从数组、列表对象创建
tf.constant()和tf.convert_to_tensor()都能够自动的把Numpy()数组或者Python列表数据类型转化为Tensor类型。
import tensorflow as tf
import numpy as np
a = tf.constant([1.2, 2.3])
b = tf.convert_to_tensor([1.2, 2.3])
c = tf.constant(np.array([1.2, 2.3]))
d = tf.convert_to_tensor(np.array([1.2, 2.3]))
print("python list >> constant >> tensor:", a)
print("python list >> convert_to_tensor >> tensor:", b)
print("numpy array >> constant >> tensor:", c)
print("numpt array >> convert_to_tensor >> tensor:", d)
输出结果:
python list >> constant >> tensor: tf.Tensor([1.2 2.3], shape=(2,), dtype=float32)
python list >> convert_to_tensor >> tensor: tf.Tensor([1.2 2.3], shape=(2,), dtype=float32)
numpy array >> constant >> tensor: tf.Tensor([1.2 2.3], shape=(2,), dtype=float64)
numpt array >> convert_to_tensor >> tensor: tf.Tensor([1.2 2.3], shape=(2,), dtype=float64)
注意:Numpy浮点数数组默认使用64为精度保存数据,转换到Tensor类型是精度为tf.float64,可以在需要的时候将其转换为tf.float32类型。
函数 | 说明 | 例子 |
---|---|---|
tf.zeros() | 创建全0张量 | 标量:tf.zeros([]),向量:tf.zeros([2]),矩阵:tf.zeros([2,2]),张量:tf.zeros([2, 3, 2]) |
tf.ones() | 创建全1张量 | 标量:tf.ones([]),向量:tf.ones([2]),矩阵:tf.ones([2,2]),张量:tf.ones([2, 3, 2]) |
tf.zeros_like() | 新建与某个张量shape一样,且内部全0的张量 | a=tf.ones([2,3]) b=tf.zeros_like(a) |
tf.ones_like() | 新建与某个张量shape一样,且内部全1的张量 | a=tf.zeros([2,3]) b=tf.ones_like(a) |
tf.fill(shape, value) | 全部初始化为某个自定义value的张量 | tf.fill([2,2], 4) |
tf.random.normal(shape, mean=0.0, stddev=1.0) | 创建形状为shape,均值为mean,标准差为stddev的高斯分布 | tf.random.normal([2,3]) |
tf.random.uniform(shape, minval=0, maxval=None, dtype=tf.float32) | 创建采样自[minval,maxval]区间的均匀分布的张量 | tf.random.uniform([2,2])如果需要均匀采样整型类型的数据,必须指定采样区间的最大值maxval参数,同时指定数据类型为tf.int*型 |
tf.range(limit, delta=1) | 创建[0, limit)之间,步长为delta的序列,不包括limit本身 | tf.range(10) |
tf.range(start, limit, delta=1) | 创建[start, limit)之间,步长为delta的序列,不包括limit本身 | tf.range(1, 10) |