2.1 张量与操作
张量
TensorFlow使用一种叫张量(tensor)的数据结构去定义所有的数据,我们可以把 tensor 看成是 n 维的 array 或者 list。在 TensorFlow 的各部分图形间流动传递的只能是tensor。
编写TensorFlow程序时,操纵并传递的主要对象是tf.Tensor:
一个数据类型(例如 float32,int32,或string)
以及shape
array(numpy)和Tensor(Tensorflow)对比
Numpy
TensorFlow
a = np.zeros((2,2)); b = np.ones((2,2))
a = tf.zeros((2,2)); b = tf.ones((2,2))
np.sum(b,axis=1)
tf.reduce_sum(a,axis=1)
a.shape
a.get_shape()
np.reshape(a,(1,4))
tf.reshape(a,(1,4))
b*5+1
b*5+1
np.dot(a,b)
tf.matmul(a,b)
a[0,0]; a[:,0]; a[0,:]
a[0,0]; a[:,0]; a[0,:]
操作
tf.strings (常用于推荐算法场景、**NLP场景**)
tf.debugging
tf.dtypes
tf.math
tf.random
tf.feature_column (常用于结构化数据特征处理)
tf.strings
#字符切割
tf.strings.bytes_split('hello')
#单词切割
tf.strings.split('hello world')
#string hash
tf.strings.to_hash_bucket(['hello','world'], num_buckets=10)
tf.debugging
#tf自带debug函数
a=tf.random.uniform((10,10))
tf.debugging.assert_equal(x=a.shape,y=(10,10))
#错误示范
tf.debugging.assert_equal(x=a.shape,y=(20,10))
tf.random
a = tf.random.uniform(shape=(10,5),minval=0,maxval=10)
tf.math
a = tf.constant([[1,2],[3,4]])
b = tf.constant([[5,6],[7,8]])
tf.print(tf.math.add(a,b))
tf.print(tf.math.subtract(a,b))
tf.print(tf.math.multiply(a,b))
tf.print(tf.math.divide(a,b))
tf.dtypes
x =tf.constant([1.8,2.2],dtype=tf.float32)
x1=tf.dtypes.cast(x,tf.int32)
最后更新于
这有帮助吗?