import tensorflow as tf
tensor = tf.constant(0) #产生常数
tf.rank(tensor) #0,常数的秩为0
#直接打印tensor
print(tensor) #tf.Tensor(0, shape=(), dtype=int32), 会出现值,shape和dtype
#tensor 转换为numpy,只需要tensor后加 '.numpy()'即可
tensor.numpy()
x = tf.constant([[1,1],
[1,1]])
y = tf.constant([[2,4],
[6,8]])
#矩阵加法
print(tf.add(x, y))
#矩阵乘法
print(tf.matmul(x,y))
#创建一个全为1的矩阵,注意要标明数据类型(dtype)
x = tf.ones(shape = [2,3,5], dtype = tf.float32)
#查看tensor的shape,dtype
x.shape
x.dtype
#查看tensor的最后一维大小
x.shape[-1]
#查看tensor所有元素的个数
tf.size(x).numpy()
#查看tensor的维数
x.ndim #number of dimension
#tensorflow取元素的规则与python一致
#取所有元素
x.numpy() or x[:].numpy() # ':'表示取所有元素
#取某一行元素
x[1,:].numpy() #取第一行所有元素
#取某一个元素
x[1,2].numpy() #取第一行第二列元素
#取部分元素
x[1:, 2:].numpy() #取第一行之后,第二列之后所有元素
#改变tensor数据类型的方法(dtype),使用cast
y = tf.cast(x, dtype = tf.float32)
tensor
最新推荐文章于 2022-09-10 08:00:00 发布