在TF中,所有的数据都通过张量Tensor
来表示
import tensorflow as tf
a = tf.constant([1,2,3], name ="a")
# <tf.Tensor 'a_1:0' shape=(3,) dtype=int32>
TF
中 tensor
主要保存三个属性:名字name
维度shape
类型type
张量维度shape
第一阶张量为向量,也就是一维数组;第二阶张量为矩阵
b = tf.constant([[1,2],[3,4]] ,name = "b")
# <tf.Tensor 'b_1:0' shape=(2, 2) dtype=int32>
张量类型type
每个张量会有一个唯一的类型。TF
会对参与运算张量类型进行匹配,如果不一样,会有类型不匹配的错误
import tensorflow as tf
a = tf.constant([1,2,3], name ="a")
b = tf.constant([1.0,2.0,3.0], name ="a")
tf.add(a, b, name = "add")
# TypeError: Input 'y' of 'Add' Op has type float32 that does not match type int32 of argument 'x'.
解决方案 a = tf.constant([1,2,3], name ="a",type=tf.float32)
常见type
类型
实数:tf.float32 tf.float64
整数:tf.int8 tf.int32 tf.uint8
布尔型:tf.bool
张量常见的方法
**获取张量的维度 **
tf.shape(input)[0]
# 获取第一个维度的值
tensor和numpy对象的转换 tf.session()中运行
with tf.Session() as sess:
res = a.eval()
print type(res)
#<type 'numpy.ndarray'>
with tf.Session() as sess:
data = tf.convert_to_tensor(x)
print data
# Tensor("Const_1:0", shape=(2, 2), dtype=float64)
网友评论