tensorflow创建Tensor基础操作,代码如下:
import tensorflow as tf # 版本 print(tf.__version__) # 2.2.0 # 基础类型 a = tf.constant(1.23, dtype=tf.float64) print(type(a)) # <class 'tensorflow.python.framework.ops.EagerTensor'> print(a) # tf.Tensor(1.23, shape=(), dtype=float64) print(tf.constant('hello world')) # tf.Tensor(b'hello world', shape=(), dtype=string) print(tf.constant(True)) # tf.Tensor(True, shape=(), dtype=bool) # 一维数据 b = tf.constant([1, 2, 3]) print(b.numpy()) # [1 2 3] print(b.dtype) # <dtype: 'int32'> # 类型转换 b = tf.cast(b, tf.float64) print(b) # tf.Tensor([1. 2. 3.], shape=(3,), dtype=float64) # 二维数据 c = tf.constant([[1, 2, 3], [4, 5, 6]]) print(c) # tf.Tensor([[1 2 3] [4 5 6]], shape=(2, 3), dtype=int32) # 变量 d = tf.Variable([1, 2, 3], dtype=tf.float16) print(d) # <tf.Variable 'Variable:0' shape=(3,) dtype=float16, numpy=array([1., 2., 3.], dtype=float16)> e = tf.convert_to_tensor([[1, 2, 3], [4, 5, 6]]) print(e) # tf.Tensor([[1 2 3][4 5 6]], shape=(2, 3), dtype=int32) print(tf.zeros([2, 2])) # tf.Tensor( # [[0. 0.] # [0. 0.]], shape=(2, 2), dtype=float32) print(tf.ones([2, 3])) # tf.Tensor( # [[1. 1. 1.] # [1. 1. 1.]], shape=(2, 3), dtype=float32) print(tf.fill([2, 3], 5)) # tf.Tensor( # [[5 5 5] # [5 5 5]], shape=(2, 3), dtype=int32) print(tf.range(10)) # tf.Tensor([0 1 2 3 4 5 6 7 8 9], shape=(10,), dtype=int32) print(tf.random.normal((2, 3), mean=0, stddev=1)) # tf.Tensor( # [[-1.1571267 -0.13292214 1.2395346 ] # [-0.6756243 -1.0658612 -1.3149271 ]], shape=(2, 3), dtype=float32)