本小节主要介绍Tensorflow常用函数
1)强制类型转换及最大值最小值计算
import tensorflow as tf
sess = tf.Session()
x1 = tf.constant([1.,2.,3.],dtype=tf.float64)
print("x1:",sess.run(x1))
# 强制类型转换
x2 = tf.cast(x1,tf.int32)
print("x2:",sess.run(x2))
# 计算张量上元素最小值
print("minimum of x2:",sess.run(tf.reduce_min(x2)))
# 计算张量上元素最大值
print("maximum of x2:",sess.run(tf.reduce_max(x2)))
输出结果如下:
x1: [1. 2. 3.]
x2: [1 2 3]
minimum of x2: 1
maximum of x2: 3
2)计算张量沿指定维度的平均值及和
import tensorflow as tf
sess = tf.Session()
x1 = tf.constant([[1,2,3],[3,4,5]])
print("x1:",sess.run(x1))
# 计算张量两个维度的均值
print(sess.run(tf.reduce_mean(x1)))
# 计算张量经度上的均值
print(sess.run(tf.reduce_mean(x1,axis=0)))
# 计算张量纬度上的均值
print(sess.run(tf.reduce_mean(x1,axis=1)))
# 计算张量两个维度的总和
print(sess.run(tf.reduce_sum(x1)))
# 计算张量经度上的总和
print(sess.run(tf.reduce_sum(x1,axis=0)))
# 计算张量纬度上的总和
print(sess.run(tf.reduce_sum(x1,axis=1)))
输出结果:
x1: [[1 2 3]
[3 4 5]]
3
[2 3 4]
[2 4]
18
[4 6 8]
[ 6 12]
注:axis = 0 代表纵向,即经度;axis = 1 代表横向,即纬度
3)将变量标记为可训练,被标记后可以在反向传播中更新参数w
w = tf.Variable(tf.random.normal([2,2],mean=0,stddev=1))
4)简单的数学运算
import tensorflow as tf
sess = tf.Session()
a = tf.ones([1, 3])
b = tf.fill([1, 3], 3.)
c = tf.fill([1, 3], 2.)
d = tf.fill([1, 3], 4.)
e = d = tf.fill([3, 1], 2.)
print("a:", sess.run(a))
print("b:", sess.run(b))
print("a+b:", sess.run(tf.add(a, b)))
print("a-b:", sess.run(tf.subtract(a, b)))
print("a*b:", sess.run(tf.multiply(a, b)))
print("b/a:", sess.run(tf.divide(b, a)))
print("c平方:", sess.run(tf.square(c)))
print("c立方:", sess.run(tf.pow(c, 3)))
print("d开方:", sess.run(tf.sqrt(d)))
print("矩阵c和矩阵e的乘法:", sess.run(tf.matmul(c, e)))
注:只有维度相同的张量才能进行四则运算
5)喂入张量和标签,生成输入特征/标签对
features = tf.constant([12, 23, 10, 17])
labels = tf.constant([0, 1, 1, 0])
dataset = tf.data.Dataset.from_tensor_slices((features, labels))