张量 tensor

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qxqxqzzz/article/details/86682938

一、标量:0阶张量

目标:定义一个变量,值为1

定义:a = tf.Variable(tf.constant(1))

输出:1

 

二、矢量(向量):1阶张量

目标:定义一个3维向量(或一行列表),值为[1, 1, 1] 

定义:a = tf.Variable(tf.constant(1, shape=[3]))

输出:[1, 1, 1]

 

三、矩阵:2阶张量

目标:定义一个3行1列矩阵,值全部为1 

定义:a = tf.Variable(tf.constant(1, shape=[3, 1]))

输出:

       [[1],

       [1],

       [1]]

 

目标:定义一个1行3列的矩阵,值全部为1 

定义:a = tf.Variable(tf.constant(1, shape=[1, 3]))

输出:[[1, 1, 1]]

 

以上内容的完整代码:

import tensorflow as tf

a1 = tf.Variable(tf.constant(1))
a2 = tf.Variable(tf.constant(1, shape=[3]))
a3 = tf.Variable(tf.constant(1, shape=[3, 1]))
a4 = tf.Variable(tf.constant(1, shape=[1, 3]))

# important step
init = tf.initialize_all_variables()

with tf.Session() as sess:
    sess.run(init) # important step
    for _ in (a1, a2, a3, a4):
        print(sess.run(_))

 

四、不同阶数张量的表示方法:

0阶:1

1阶:[1, 2, 3]

2阶:

1行3列:[[1,2,3]]

2行3列:[[1,2,3], [4,5,6]]

3行1列:[[1], [2], [3]]

 

五、如何看张量的维数(shape):

import tensorflow as tf
a = tf.constant([[1,2,3]])
print(a)

输出:

Tensor("Const_2:0", shape=(1, 3), dtype=int32)

所以,这是一个一行三列的矩阵(二阶张量)

 

猜你喜欢

转载自blog.csdn.net/qxqxqzzz/article/details/86682938