实数:1
一维张量(列表):[1,2,3]
二维张量(矩阵):[[1,2], [3, 4]]
三维张量:[[[1,2], [3,4], [5, 6]]]
进行张量运算时,需要注意tensor的形状
通过会话session()计算节点的值
import tensorflow as tf
# 定义a,b为常数
a = tf.constant(1)
b = tf.constant(2)
print(a + b)
print("*********************")
# 定义一维张量(列表)
A = tf.constant([1,2,3])
B = tf.constant([10, 12, 13])
print(A,"\n", B)
# 定义二维张量(矩阵)
V1 = tf.constant([[1,2], [3, 4]])
V2 = tf.constant([[1], [2]])
# 定义会话
with tf.Session() as sess:
# 初始化所有变量
init_op = tf.global_variables_initializer()
# 为变量赋初始值
sess.run(init_op)
print(sess.run(tf.matmul(V1, V2))) # 只用两个矩阵(二维张量)才能用 matmul() 函数
print(sess.run(A * B)) # 列表中对应元素相乘
Tensor("add:0", shape=(), dtype=int32)
*********************
Tensor("Const_2:0", shape=(3,), dtype=int32)
Tensor("Const_3:0", shape=(3,), dtype=int32)
[[ 5]
[11]]
[10 24 39]