1. 创建TensorFlow
一、
x1 = tf.constant(range(12))
x2 = tf.constant([1,2,3],[1,2,3])
x3 = tf.reshape(x1,(3,4))
x4 = tf.zeros((2,3,4))
x5 = tf.ones((2,3,4))
<tf.Tensor: id=5, shape=(2, 3, 4), dtype=float32, numpy=
array([[[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.]],
[[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.]]], dtype=float32)>
二、
有些情况下,我们需要随机生成tensor中每个元素的值。下面我们创建一个形状为(3, 4)的tensor。它的每个元素都随机采样于均值为0、标准差为1的正态分布。
tf.random.normal(shape=[3,4], mean=0, stddev=1)
三、较简单tensor属性查询:
len(x)
x.shape
2. 运算
- 加乘除(点运算,非矩阵乘法)
x+y
x*y
x/y
- 指数运算,需先转换类型(Y原为int类型,转换成float32类型)
Y = tf.cast(Y, tf.float32)
tf.exp(Y)
- matmul函数做矩阵乘法(先转换类型,再转置,最后相乘)
Y = tf.cast(Y, tf.int32)
#此函数是类型转换函数:tf.cast(x, dtype, name=None)
tf.matmul(X, tf.transpose(Y))
- 连接concat函数
tf.concat([X,Y],axis = 0), tf.concat([X,Y],axis = 1)
- 判断两tensor对应位置元素是否相等,结果为true or false
tf.equal(X,Y)
- tensor所有元素求和
tf.reduce_sum(X)
- 求解范数
X = tf.cast(X, tf.float32)
tf.norm(X)
3、广播机制
- 当两tensor的shape不同时,相加,会先把A B扩展成shape相同,复制已有的行/列
A = tf.reshape(tf.constant(range(3)), (3,1))
B = tf.reshape(tf.constant(range(2)), (1,2))
A+B
4、索引(从0开始)
- X[1:3]表示第二行至第三行
- 改变某索引值
X = tf.Variable(X)
X[1,2].assign(9)
#把第二行第三列元素置为9
X[1:2,:].assign(tf.ones(X[1:2,:].shape, dtype = tf.float32)*12)
#把第二行换为12
<tf.Variable 'UnreadVariable' shape=(3, 4) dtype=float32, numpy=
array([[ 0., 1., 2., 3.],
[12., 12., 12., 12.],
[ 8., 9., 10., 11.]], dtype=float32)>
- tensor 与 numpy 互相转换
import numpy as np
P = np.ones((2,3))
#numpy 转 tensor
D = tf.constant(P)
#tensor 转 numpy
P = np.array(D)