tensorflow2.0 基本操作——学习笔记1
文章是个人自学深度学习时的学习记录,代码在jupyter notebook上运行的,在后续学习过程中会继续积累更新
import tensorflow as tf
import numpy as np
创建tensor
tf.convert_to_tensor,其他数据类型转换为tensor格式
tf.convert_to_tensor(np.ones([2, 3]))
tf.convert_to_tensor([[2], [3.0]])
tf.zeros/zeros_like/ones/ones_like, 传入shape或like需数据,按数据的shape生成
tf.zeros([2, 3, 3])
a = tf.zeros([2, 3, 3])
tf.zeros_like(a)
tf.fill([2, 3], 5)
tf.random, 随机生成tensor
tf.random.normal([2, 3], mean=1, stddev=2)
tf.random.truncated_normal([2, 3], mean=1, stddev=2, )
tf.random.uniform([2, 3], minval=0, maxval=10)
idx = tf.range(5)
idx1 = tf.random.shuffle(idx)
a = tf.random.normal([5, 10])
b = tf.random.uniform([5], minval=1, maxval=10, dtype=tf.int32)
a1 = tf.gather(a, idx1)
b1 = tf.gather(b, idx1)
constant/variable 常量与变量
tf.constant([1, 2])
tf.Variable([[2,3], [4, 5]])
out = tf.random.uniform([4, 10])
y = tf.range(4)
y = tf.one_hot(y, depth=10)
loss = tf.keras.losses.mse(y, out)
loss = tf.reduce_mean(loss)
loss
net = tf.keras.layers.Dense(10)
net.build((4, 8))
net.kernel, net.bias
索引与切片
index取值
b = tf.random.normal([4, 28, 28, 3])
b[0][0][0]
b[1, 2, 3]
b[0, :, :, :]
b[:, :, :, 0]
b[:, 0:28:2, 0:28:2, :]
b[2::-2]
gather/gather_nd/boolean_mask, 需要用到indices
ts = tf.random.normal([4, 35, 8])
tf.gather(ts, axis=0, indices=[2, 3])
tf.gather(ts, axis=0, indices=[2, 1, 3, 0])
tf.gather(ts, axis=1, indices=[2, 3, 7, 9, 16])
tf.gather(ts, axis=2, indices=[2, 5, 6])
tf.gather_nd(ts, [0])
tf.gather_nd(ts, [0, 1])
tf.print(tf.gather_nd(ts, [0, 1, 2]))
tf.gather_nd(ts, [[0, 1, 2]])
tf.gather_nd(ts, [[0, 0], [1, 1]])
tf.gather_nd(ts, [[0, 0, 0], [1, 1, 1]])
tf.gather_nd(ts, [[[0, 0, 0], [1, 1, 1]]])
img = tf.random.normal([2, 4, 4, 3])
tf.boolean_mask(img, mask=[True, False])
tf.boolean_mask(img, mask=[[True, False, False, False],
[False, False, False, True]])
维度变换
img = tf.random.normal([4, 28, 28, 3])
img.shape, img.ndim
tf.reshape(img, [4, 784, 3])
tf.reshape(img, [4, -1, 3])
tf.reshape(img, [4, 784 * 3])
tf.reshape(img, [4, -1])
tf.transpose(img)
tf.transpose(img, perm=[0, 3, 1, 2])
a = tf.random.normal([4, 35, 8])
tf.expand_dims(a, axis=0)
tf.expand_dims(a, axis=1)
tf.expand_dims(a, axis=-1)
a = tf.zeros([1, 2, 1, 3])
tf.squeeze(a)
tf.squeeze(a, axis=0)
tf.squeeze(a, axis=2)
a = tf.ones([3, 4])
a1 = tf.broadcast_to(a, [2, 3, 4])
数学运算
tf.pow(2, 3)
tf.exp(2.)
tf.math.log(2.)
tf.math.log(8.) / tf.math.log(2.)
a = tf.random.normal([3, 3, 4])
b = tf.random.normal([3, 4, 5])
b1 = tf.random.normal([4, 5])
tf.matmul(a, b)
tf.matmul(a, b1)
合并与分割
a = tf.ones([4, 35, 8])
b = tf.ones([2, 35, 8])
c = tf.concat([a, b], axis=0)
a = tf.ones([4, 35, 8])
b = tf.ones([4, 35, 8])
c = tf.stack([a, b], axis=0)
aa, bb = tf.unstack(c, axis=0)
tf.unstack(c, axis=3)
tf.split(c, axis=3, num_or_size_splits=2)
tf.split(c, axis=3, num_or_size_splits=[2, 2, 4])
数据统计
a = tf.ones([4, 28, 28, 3])
tf.norm(a)
tf.sqrt(tf.reduce_sum(tf.square(a)))
tf.norm(a, ord=2, axis=1)
tf.norm(a, ord=1, axis=0)
tf.reduce_min(a)
tf.reduce_min(a, axis=1)
a = tf.random.normal([4, 28, 28, 3])
tf.argmax(a)
a = tf.constant([1, 2, 3, 2, 5])
b = tf.range(5)
tf.reduce_sum(tf.cast(tf.equal(a, b), dtype=tf.int32))
x = tf.constant([[0.1, 0.2, 0.7], [0.9, 0.05, 0.05]])
y = tf.constant([2, 1])
pred = tf.cast(tf.argmax(x, axis=1), dtype=tf.int32)
correct = tf.reduce_sum(tf.cast(tf.equal(y, pred), dtype=tf.int32)) / len(y)
print(correct)
b = tf.constant([4, 2, 2, 4, 3])
tf.unique(b).y, tf.unique(b).idx
张量排序
a = tf.random.shuffle(tf.reshape(tf.range(6), [2, 3]))
tf.sort(a, direction='DESCENDING')
tf.argsort(a, direction='DESCENDING')
res = tf.math.top_k(a, 2)
res.indices
res.values
prob = tf.constant([[0.1, 0.2, 0.7], [0.2, 0.7, 0.1]])
target = tf.constant([2, 0])
k_b = tf.math.top_k(prob, 3).indices
k_b = tf.transpose(k_b, [1, 0])
k_b
target = tf.broadcast_to(target, [3, 2])
def accuracy(out, target, topk=(1,)):
maxk = max(topk)
batch_size = target.shape[0]
pred = tf.math.top_k(out, maxk).indices
print(pred.numpy())
pred = tf.transpose(pred, perm=[1, 0])
target_ = tf.broadcast_to(target, pred.shape)
correct = tf.equal(pred, target_)
res = []
for k in topk:
correct_k = tf.cast(tf.reshape(correct[:k], [-1]), dtype=tf.float32)
correct_k = tf.reduce_sum(correct_k)
acc = float(correct_k / batch_size)
res.append(acc)
return res
out = tf.random.normal([10, 6])
out = tf.math.softmax(out, axis=1)
target = tf.random.uniform([10], maxval=6, dtype=tf.int32)
pred = tf.argmax(out, axis=1)
print('pred', pred.numpy())
print('label', target.numpy())
acc = accuracy(out, target, topk=(1, 2, 3, 4, 5, 6))
print('top-1-6 acc', acc)
填充与复制
a = tf.ones([2, 3])
tf.pad(a, [[1, 1], [2, 2]])
a = tf.constant([[1, 2, 0], [3, 4, 5]])
tf.tile(a, [1, 2])
tf.tile(a, [2, 2])
张量的限幅
tf.maximum(a, 3)
tf.clip_by_value(a, 1, 3)
tf.nn.relu(a)
tf.clip_by_norm(a, 3)
高阶操作
where
a = tf.random.normal([3, 3])
mask = a > 0
tf.boolean_mask(a, mask)
indices = tf.where(mask)
tf.gather_nd(a, indices)
A = tf.ones([3, 3])
B = tf.zeros([3, 3])
tf.where(mask, A, B)
tf.where(tf.greater(A, B), A, B)
scatter_nd
indices = tf.constant([[4], [3], [1], [7]])
updates = tf.constant([9, 10, 11, 12])
shape = tf.constant([8])
tf.scatter_nd(indices, updates, shape)
meshgrid 生成网格的坐标
x = tf.linspace(-1., 1., 3)
y = tf.linspace(-2., 2., 5)
point_x, point_y = tf.meshgrid(x, y)
points = tf.stack([point_x, point_y], axis=2)
point_x,point_y, points