张量的创建

一、什么是张量?

张量是一个数学对象,它是对标量、向量和矩阵的泛化。张量可以表示为一个多维数组。 零秩张量就是标量。向量或者数组是秩为 1 的张量,而矩阵是秩为 2 的张量。简而言之,张 量可以被认为是一个 n 维数组。
TensorFlow 用张量这种数据结构来表示所有的数据。可以把一个张量想象成一个 n 维的 数组或列表。张量可以在图中的节点之间流通。其实张量代表的就是一种多维数组。在 TensorFlow 系统中,张量的维数来被描述为阶。

二、创建张量

import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
import tensorflow as tf 
def tensor_demo():
    print('固定张量的创建')
    tensor1 = tf.constant(3)
    print('tensor1:',tensor1)
    tensor2 = tf.constant([2,4,6,8,9])
    print('tensor2:',tensor2)
    tensor3 = tf.constant([[1,2,4],[3,5,7]])
    print('tensor3:',tensor3)
    print('随机张量的创建')
    t_ones = tf.ones(shape=[2,3])
    print('t_ones:',t_ones)
    t_zeros = tf.zeros(shape=[3,4])
    print('t_zeros:',t_zeros)
    print('创建均匀分布随机值')
    t_uniform = tf.random_uniform(shape=[1,2],minval=1,maxval=4)
    print('t_uniform:',t_uniform)
    t_normal = tf.random_normal(shape=[2,2],mean=1.0,stddev=3)
    print('t_normal:',t_normal)
    # 开启会话
    with tf.Session() as sess:
        t_ones_value = sess.run(t_ones)
        print('***********t_ones_value*************')
        print(t_ones_value)
        t_zeros_value = sess.run(t_zeros)
        print('***********t_zeros_value************')
        print(t_zeros_value)
        t_uniform_value = sess.run(t_uniform)
        print('***********t_uniform_value**********')
        print(t_uniform_value)
        t_normal_value = sess.run(t_normal)
        print('***********t_normal_value***********')
        print(t_normal_value)

if __name__ == '__main__':
    tensor_demo()
    

三、代码运行结果

正是江南好风景
原文地址:https://www.cnblogs.com/monsterhy123/p/13062452.html