基础API
常量
# 定义常量 定义二位矩阵 并初始化
t = tf.constant([[1., 2., 3.], [4., 5., 6.]])
# index
print(t)
# 取出第二列以后的数据
print(t[:, 1:])
# 取出第二列的数据
print(t[..., 1])
# ops
print(t+10)
# 平方操作
print(tf.square(t))
# 矩阵乘以矩阵的转置 2*3 x 3*2 = 2*2
print(t @ tf.transpose(t))
# numpy conversion
print(t.numpy())
print(np.square(t))
np_t = np.array([[1., 2., 3.], [4., 5., 6.]])
# numpy tensor 的转换
print(tf.constant(np_t))
标量
# strings
t = tf.constant("cafe")
print(t)
# 获得字符串长度
print(tf.strings.length(t))
# 获得utf8编码的长度
print(tf.strings.length(t, unit="UTF8_CHAR"))
# 把字符串从unicode 转化为 utf8编码
print(tf.strings.unicode_decode(t, "UTF8"))
获得三个字符串各自的长度
# ragged tensor 长度不一
r = tf.ragged.constant([[11, 12], [21, 22, 23], [], [41]])
# index op
print(r)
print(r[1])
# 左闭右开区间
print(r[1:2])
# ops on ragged tensor
r2 = tf.ragged.constant([[51, 52], [], [71]])
# 在维度0进行拼接
print(tf.concat([r, r2], axis = 0))
纵向拼接 向量维度要一致
转换为tensor,0值在正常值的后面
# sparse tensor
# 正常值index
s = tf.SparseTensor(indices = [[0, 1], [1, 0], [2, 3]],
values = [1., 2., 3.],
dense_shape = [3, 4])
print(s)
print(tf.sparse.to_dense(s))
# sparse tensor
# indices 没有排好序
s5 = tf.SparseTensor(indices = [[0, 2], [0, 1], [2, 3]],
values = [1., 2., 3.],
dense_shape = [3, 4])
print(s5)
# 调用reorder 给indecs 排序
s6 = tf.sparse.reorder(s5)
print(tf.sparse.to_dense(s6))
变量
v.value()变成tensor
v.numpy()取出v的值
重新赋值
# assign value
v.assign(2*v)
print(v.numpy())
# 对0,1位置重新赋值
v[0, 1].assign(42)
print(v.numpy())
# 给第一行重新赋值
v[1].assign([7., 8., 9.])
print(v.numpy())
不能用=号赋值