Tensor属性
Tensor有以下属性:
- name
- shape
- dtype
a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a')
d = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a')
b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2], name='b')
c = tf.matmul(a, b)
print(a) # Tensor("a:0", shape=(2, 3), dtype=float32)
print(a.name) # a:0 type: str
print(a.shape) # (2, 3)
print(a.shape[0]) # 2
print(a.dtype) # <dtype: 'float32'>
print(d) # Tensor("a_1:0", shape=(2, 3), dtype=float32)
print(d.name) # a_1:0
print(b) # <tf.Variable 'b:0' shape=(3, 2) dtype=float32_ref>
print(c) # Tensor("MatMul:0", shape=(2, 2), dtype=float32)
基本函数
算术运算
- tf.square
对每个元素求平方
tf.get_collection
从集合中获取变量,集合一般为 tf.GraphKeys.LOCAL_VARIABLES和 tf.GraphKeys.GLOBAL_VARIABLES
running_vars = tf.get_collection(tf.GraphKeys.LOCAL_VARIABLES, scope="my_metric")
tf.reduce_mean
用于计算张量tensor沿着指定的数轴(tensor的某一维度)上的的平均值,主要用作降维或者计算tensor(图像)的平均值。
tf.reduce_mean(input_tensor,
axis=None,
keep_dims=False,
name=None,
reduction_indices=None)
类似函数:
- tf.reduce_sum :计算tensor指定轴方向上的所有元素的累加和;
- tf.reduce_max : 计算tensor指定轴方向上的各个元素的最大值;
- tf.reduce_all : 计算tensor指定轴方向上的各个元素的逻辑和(and运算);
- tf.reduce_any: 计算tensor指定轴方向上的各个元素的逻辑或(or运算);
tf.cast
作用是执行 tensorflow 中张量数据类型转换,比如读入的图片如果是int8类型的,一般在要在训练前把图像的数据格式转换为float32
t1 = tf.Variable([1,2,3,4,5])
t2 = tf.cast(t1,dtype=tf.float32)
t1: <tf.Variable 'Variable:0' shape=(5,) dtype=int32_ref>
t2: Tensor("Cast:0", shape=(5,), dtype=float32)