查看相同栏目文章
Tensorflow2 基础-创建tensor
1、TF的Tensor可以直接从numpy的矩阵或者符合矩阵规则的Python list中生成。
import tensorflow as tf
import numpy as np
print(tf.convert_to_tensor(np.ones([2,3])))
print(tf.convert_to_tensor(np.zeros([2,3])))
print(tf.convert_to_tensor([1,2]))
print(tf.convert_to_tensor([[2],[3.]]))
tf.Tensor(
[[1. 1. 1.]
[1. 1. 1.]], shape=(2, 3), dtype=float64)
tf.Tensor(
[[0. 0. 0.]
[0. 0. 0.]], shape=(2, 3), dtype=float64)
tf.Tensor([1 2], shape=(2,), dtype=int32)
tf.Tensor(
[[2.]
[3.]], shape=(2, 1), dtype=float32)
2、tf.zeros方法创建,接受参数为shape,创建全0的tensor。
import tensorflow as tf
print(tf.zeros([]))
print(tf.zeros([1]))
print(tf.zeros([2,2,2]))
tf.Tensor(0.0, shape=(), dtype=float32)
tf.Tensor([0.], shape=(1,), dtype=float32)
tf.Tensor(
[[[0. 0.]
[0. 0.]]
[[0. 0.]
[0. 0.]]], shape=(2, 2, 2), dtype=float32)
3、接受参数为tensor,创建根据该tensor的shape的全0的tensor。
a = tf.zeros([2,3,4])
print(tf.zeros_like(a))
tf.Tensor(
[[[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]]
[[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]]], shape=(2, 3, 4), dtype=float32)
4、tf.ones类似tf.zeros,tf.ones_like类似tf.zeros_like
5、tf.random.normal接受参数为shape,mean,stddev,创建指定shape的tensor,数据从指定均值和标准差的正态分布中采样。
6、接受参数同上,创建指定shape的tensor,数据从指定均值和标准差的正态分布截断后采样。
print(tf.random.normal([2,2],mean=1,stddev=1))
print(tf.random.truncated_normal([2,2],mean=1,stddev=1))
tf.Tensor(
[[1.0357192 2.8778548]
[0.7229105 2.5524483]], shape=(2, 2), dtype=float32)
tf.Tensor(
[[2.352232 0.54148245]
[0.663664 1.3031777 ]], shape=(2, 2), dtype=float32)
7、tf.random.uniform接受参数为shape,minval,maxval,创建指定shape的tensor,数据从指定最小值到最大值之间的均匀分布中生成。
print(tf.random.uniform([2,2],minval=0, maxval=1))
print(tf.random.uniform([2,2],minval=0,maxval=1,dtype=float))
tf.Tensor(
[[0.71651447 0.15630555]
[0.03856313 0.91570055]], shape=(2, 2), dtype=float32)
tf.Tensor(
[[0.78214204 0.99830914]
[0.3884778 0.8252417 ]], shape=(2, 2), dtype=float32)
8、tf.range接受参数为limit,创建一维的start到limit的tensor。
print(tf.range(10))
print(tf.range(10,100,delta=3,dtype=tf.int32))
tf.Tensor([0 1 2 3 4 5 6 7 8 9], shape=(10,), dtype=int32)
tf.Tensor(
[10 13 16 19 22 25 28 31 34 37 40 43 46 49 52 55 58 61 64 67 70 73 76 79
82 85 88 91 94 97], shape=(30,), dtype=int32)
9、tf.constant类似tf.convert_to_tensor。
print(tf.constant(1))
print(tf.constant([1]))
print(tf.constant([1,2.]))
tf.Tensor(1, shape=(), dtype=int32)
tf.Tensor([1], shape=(1,), dtype=int32)
tf.Tensor([1. 2.], shape=(2,), dtype=float32)