tensor创建可以基于numpy,list或者tensorflow本身的API。
笔记直接上代码:
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
tf.__version__
#通过numpy创建tensor
tensor0 = tf.convert_to_tensor(np.ones([2,3]))
print(tensor0)
tensor1 = tf.convert_to_tensor(np.zeros([2,3]), dtype=tf.int32)
print(tensor1)
#通过list创建tensor
tensor2 = tf.convert_to_tensor([1,2,3])
print(tensor2)
tensor3 = tf.convert_to_tensor([[1,2,3],[4,5,6.]])
print(tensor3)
#通过tensorflow的API创建
tensor4 = tf.zeros([3,3])
print(tensor4)
tensor5 = tf.ones([2,5], dtype=tf.float32)
print(tensor5)
#zeros_like以传入的tensor的shape为模版,但是值为全0
#类似的还有ones_like
tensor6 = tf.zeros_like(tensor5)
#和tensor6 = tf.zeros(tensor5.shape)是一样的
print(tensor6)
#fill填充任意值
tensor7 = tf.fill([2,2], 1.5)
print(tensor7)
#随机正态分布
tensor8 = tf.random.normal([5,5], mean=1, stddev=1)
print(tensor8)
#带截断的随机正态分布
tensor9 = tf.random.truncated_normal([3,3], mean=0, stddev=1)
print(tensor9)
#均匀分布
tensor10 = tf.random.uniform([3,3], minval=-2, maxval=2)
print(tensor10)
#随机排列,shuffle
ids = tf.range(10)
ids = tf.random.shuffle(ids)
print(ids)
#下面假设trainData和trainLabel是训练数据和训练标签
#trainData包含10张28*28的图片,trainLabel是每张图片对应的标签
trainData = tf.random.normal([10, 28*28*1])
trainLabel = tf.random.uniform([10], minval=0, maxval=10, dtype=tf.int32)
print("TrainData:",trainData)
print("TrainLabel:", trainLabel)
#通过传入shuffle后的index,调用gather来打散训练数据和训练标签
#同时保证训练数据和训练标签都能用同一个下表索引到
trainData = tf.gather(trainData, ids)
trainLabel = tf.gather(trainLabel, ids)
print("Shuffled Train Data:", trainData)
print("Shuffled Train Label:", trainLabel)
notebook运行结果截图: