TensorFlow基础API

看网课视频老师讲的一些,实际上官方文档有非常详细的介绍

import numpy as np
import tensorflow as tf

# tf基础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))
print(t @ tf.transpose(t))  # 乘转置
#%%
# numpy conversion
print(t.numpy())
print(np.square(t))
np_t = np.array([[1., 2., 3.], [4., 5., 6.]])
print(tf.constant(np_t))
#%%
# Scalars tensor可以使0维、1维...
t = tf.constant(2.718)
print(t.numpy())
print(t.shape)
#%%
# strings
t = tf.constant('cafe')
print(t)
print(tf.strings.length(t))
print(tf.strings.length(t, unit='UTF8_CHAR'))
print(tf.strings.unicode_decode(t, 'UTF8'))
#%%
# string array
t = tf.constant(['cafe', 'coffee', '咖啡'])
print(tf.strings.length(t, unit='UTF8_CHAR'))
r = tf.strings.unicode_decode(t, 'UTF8')
print(r)
#%%
# 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]])
print(tf.concat([r, r2], axis=0))
r3 = tf.ragged.constant([[13, 14], [15], [], [41, 42, 43]])
print(tf.concat([r, r3], axis=1))
# ragged tensor 变成 普通tensor 空位用0补齐,注意0永远在正常值的后面
print(r.to_tensor())
#%%
# sparse tensor 0可以在正常值前面
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))  # 稀疏矩阵转密集矩阵,这样的稀疏矩阵不能用ragged tensor来表示
#%%
# ops on sparse tensors
s2 = s * 2.0
print(s2)

try:
    s3 = s + 1
except TypeError as ex:
    print(ex)

s4 = tf.constant([[10., 20.],
                  [30., 40.],
                  [50., 60.],
                  [70., 80.]])
print(tf.sparse.sparse_dense_matmul(s, s4))
#%%
s5 = tf.SparseTensor(indices=[[0, 2], [0, 1], [2, 3]],  # 没有排好序的稀疏矩阵无法被转换为密集矩阵
                    values=[1., 2., 3.],
                    dense_shape=[3, 4])
print(s5)
s6 = tf.sparse.reorder(s5)  # 对s5进行排序
print(tf.sparse.to_dense(s6))


#%%
# Variable 变量
v = tf.Variable([[1., 2., 3.], [4., 5., 6.]])
print(v)
print(v.value())
print(v.numpy())
#%%
# assign value 变量重新赋值
v.assign(2*v)
print(v.numpy())
v[0, 1].assign(42)
print(v.numpy())
v[1].assign([7., 8., 9.])
print(v.numpy())
#%%
# 不能用=号,只能用assign()重新赋值
try:
    v[1] = [7., 8., 9.]
except TypeError as ex:
    print(ex)
# 'ResourceVariable' object does not support item assignment

留下评论

您的电子邮箱地址不会被公开。