吴裕雄--天生自然TensorFlow2教程:创建Tensor

import numpy as np
import tensorflow as tf

tf.convert_to_tensor(np.ones([2, 3]))
tf.convert_to_tensor(np.zeros([2, 3]))
list
tf.convert_to_tensor([1, 2])
tf.convert_to_tensor([1, 2.])
tf.convert_to_tensor([[1], [2.]])
zeros
tf.zeros([])
tf.zeros([1])
tf.zeros([2, 2])
tf.zeros([2, 3, 3])
a = tf.constant([0])
tf.zeros_like(a)  # 等同于tf.zeros(a.shape)
ones
tf.ones(1)
tf.ones([])
tf.ones([2])
tf.ones([2, 3])

a = tf.constant([0])
tf.ones_like(a)  # # 等同于tf.ones(a.shape)
fill
tf.fill([2, 2], 0)
tf.fill([2, 2], 0)
tf.fill([2, 2], 1)
tf.fill([2, 2], 9)
random
# 正态分布,均值为1,方差为1
tf.random.normal([2, 2], mean=1, stddev=1)

tf.random.normal([2, 2])

# 截断的正态分布,
tf.random.truncated_normal([2, 2], mean=0, stddev=1)

# 均匀分布
tf.random.uniform([2, 2], minval=0, maxval=1)

tf.random.uniform([2, 2], minval=0, maxval=100, dtype=tf.int32)
打乱idx后,a和b的索引不变

idx = tf.range(10)
idx = tf.random.shuffle(idx)
idx

a = tf.random.normal([10, 784])
b = tf.random.uniform([10], maxval=10, dtype=tf.int32)
b

a = tf.gather(a, idx)
b = tf.gather(b, idx)
b
constant

tf.constant(1)
tf.constant([1])
tf.constant([1, 2.])
tf.constant([[1, 2], [3., 2]])
loss计算
无bias的loss
out = tf.random.uniform([4, 10])
out

y = tf.range(4)
y = tf.one_hot(y, depth=10)
y

loss = tf.keras.losses.mse(y, out)
loss

loss = tf.reduce_mean(loss)
loss
原文地址:https://www.cnblogs.com/tszr/p/12104496.html