"""Create, reshape, broadcast and reduce deterministic TensorFlow tensors."""
import numpy as np
import json
import platform
import tensorflow as tf
def finish(cases):
print(json.dumps(dict(version=platform.python_version(),tensorflow=tf.__version__,keras=tf.keras.__version__,
system=platform.system(),devices=[d.name for d in tf.config.list_physical_devices()],cases=cases)))
def observe(cases,name,operation,inputs,expected,actual):
assert expected==actual,(name,expected,actual)
cases.append(dict(name=name,operation=operation,inputs=inputs,expected=expected,actual=actual,passed=True))
def main():
cases=[]
t=[tf.constant(5),tf.constant([1,2,3]),tf.constant([[1,2],[3,4]]),tf.ones((2,3,4))]
observe(cases,"rank_dtype_and_placement","compare the four tensor ranks and CPU placement",
{"shape":[2,3,4]},[[0,1,2,3],["int32","float32"],True],
[[int(tf.rank(v)) for v in t],[t[0].dtype.name,t[3].dtype.name],t[0].device.endswith("CPU:0")])
b=tf.constant(np.array([[5,6],[7,8]],dtype=np.int64))
observe(cases,"create_from_list_and_array","construct one explicit int64 tensor from a NumPy matrix",
b.numpy().tolist(),["int64",[[1,2],[3,4]],[[5,6],[7,8]]],[b.dtype.name,t[2].numpy().tolist(),b.numpy().tolist()])
observe(cases,"special_value_generators","check zero, one, identity and filled matrices",
[2,3], [0.,6.,3.,[[7,7],[7,7]]],
[float(tf.reduce_sum(tf.zeros((2,3)))),float(tf.reduce_sum(tf.ones((3,2)))),
float(tf.linalg.trace(tf.eye(3))),tf.fill((2,2),7).numpy().tolist()])
seed=[72,4]
uniform=tf.random.stateless_uniform((2,2),seed)
normal=tf.random.stateless_normal((3,3),seed)
shuffle=tf.random.experimental.stateless_shuffle(tf.range(1,6),seed)
observe(cases,"reproducible_random_and_permutation","repeat a stateless draw and inspect three random forms",
seed,[True,True,[3,3],[1,2,3,4,5]],
[bool(tf.reduce_all((uniform>=0)&(uniform<1))),
bool(tf.reduce_all(uniform==tf.random.stateless_uniform((2,2),seed))),
list(normal.shape),sorted(shuffle.numpy().tolist())])
a=tf.constant([[1,2],[3,4]])
c=tf.cast(b,tf.int32)
observe(cases,"elementwise_vs_matrix","compare sums, products and a floating-point square root",
[a.numpy().tolist(),c.numpy().tolist()], [[[6,8],[10,12]],[[5,12],[21,32]],[[19,22],[43,50]],2.],
[(a+c).numpy().tolist(),(a*c).numpy().tolist(),(a@c).numpy().tolist(),float(tf.sqrt(tf.cast(a[1,1],tf.float32)))])
grid=tf.reshape(tf.range(1,7),(2,3))
observe(cases,"reshape_transpose_expand","alter shape while tracking element order",
grid.numpy().tolist(),[[[1,2],[3,4],[5,6]],[[1,4],[2,5],[3,6]],[1,2,3]],
[tf.reshape(grid,(3,2)).numpy().tolist(), tf.transpose(grid).numpy().tolist(),list(tf.expand_dims(grid,0).shape)])
big=tf.reshape(tf.range(1,10),(3,3))
observe(cases,"indexed_slice_values","index a scalar, a row, a column and a two-by-two slice",
big.numpy().tolist(),[6,[4,5,6],[2,5,8],[[2,3],[5,6]]],
[int(big[1,2]),big[1,:].numpy().tolist(),big[:,1].numpy().tolist(),big[0:2,1:].numpy().tolist()])
vector=tf.constant([10,20,30])
column=tf.constant([[1],[2],[3]])
observe(cases,"scalar_and_matrix_broadcast","broadcast scalar and trailing axes",
[column.numpy().tolist(),vector.numpy().tolist()],[[12,22,32],[[11,21,31],[12,22,32],[13,23,33]]],
[(2+vector).numpy().tolist(),(column+vector).numpy().tolist()])
try:
tf.ones((2,3))+tf.ones((2,2))
except tf.errors.InvalidArgumentError:
rejected=True
else:
rejected=False
observe(cases,"incompatible_shapes_rejected","try summing arrays with different trailing axes",[[2,3],[2,2]],True,rejected)
observe(cases,"reductions_and_integer_mean","check axis sums, means, extrema and booleans",
grid.numpy().tolist(),[21,[5,7,9],[6,15],3,3.5,1,6,True,True],
[int(tf.reduce_sum(grid)),tf.reduce_sum(grid,axis=0).numpy().tolist(),tf.reduce_sum(grid,axis=1).numpy().tolist(),
int(tf.reduce_mean(grid)),float(tf.reduce_mean(tf.cast(grid,tf.float32))),int(tf.reduce_min(grid)),
int(tf.reduce_max(grid)),bool(tf.reduce_any(grid>4)),bool(tf.reduce_all(grid>0))])
raw=tf.random.stateless_uniform((3,3),seed,0,10,dtype=tf.int32)
gram=raw@tf.transpose(raw)
observe(cases,"gram_trace_exercise","compare random Gram trace with elementwise squares",
raw.numpy().tolist(),[True,True],[bool(tf.reduce_all(gram==tf.transpose(gram))),
int(tf.linalg.trace(gram))==int(tf.reduce_sum(raw**2))])
values=tf.reshape(tf.range(1,5),(4,1))+tf.constant([10,20,30,40])
observe(cases,"outer_sum_exercise","add a column to a vector and check edge cells",
{"left_shape":[4,1],"right_shape":[4]},[[4,4],[11,21,31,41],44],
[list(values.shape),values[0].numpy().tolist(),int(values[-1,-1])])
finish(cases)
if __name__=="__main__":
main()
本例需在 Windows CPU、Python 3.12.14、TensorFlow 2.21.0、Keras 3.15.1。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows CPU、Python 3.12.14、TensorFlow 2.21.0、Keras 3.15.1。
入口文件:projects/tensorflow-tensor-operations-lab/build-and-transform-tensors.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
build-and-transform-tensors.py,或下载右侧课程工程包。 - 确认本地已准备 Windows CPU、Python 3.12.14、TensorFlow 2.21.0、Keras 3.15.1。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联24章) · 含当前章节或实例 · mbskycom202612a359.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a380.zip