本文参考资源:eat_tensorflow_in_30_days
程序=数据结构+算法
TensorFlow程序=张量数据结构+计算图算法语言
张量和计算图是TensorFlow的核心概念
TensorFlow的基本数据结构是张量Tensor。张量即多维数组;TensorFlow的张量和numpy中的array很类似。
从行为特性来看,有两种类型的张量,常量constant和变量Variable。
常量的值在计算图中不可以被重新赋值,变量可以在计算图中用assign等算子进行重新赋值。
一、常量张量
张量的数据类型和numpy.array基本一一对应。
import numpy as np
import tensorflow as tf
i = tf.constant(1) # tf.int32 类型常量
l = tf.constant(1, dtype=tf.int64) # tf.int64
f = tf.constant(1.23) # tf.float32类型常量
d = tf.constant("hello world") # tf.string 类型常量
b = tf.constant(True) # tf.bool 类型常量
print(tf.int64 == np.int64)
print(tf.bool == np.bool)
print(tf.double == np.float64)
print(tf.string == np.unicode) # tf.string类型和np.unicode类型不等价
不同类型的数据可以用不同的维度(rank)的张量来表示
标量为0维的张量,向量为1维的张量,矩阵为2维张量
彩色图像有rgb三个通道,可以表示为3维张量
视频还有时间维,可以表示为 4 维张量
可以简单的总结为:有几层中括号,就是一个多少维的张量
scalar = tf.constant(True) # 0维张量
print(tf.rank(scalar))
print(scalar.numpy().ndim)
vector = tf.constant([1.0, 2.0, 3.0, 4.0]) # 2维张量
print(tf.rank(vector))
print(np.ndim(vector.numpy()))
matrix = tf.constant([[1.0, 2.0], [3.0, 4.0]]) # 2维张量
print(tf.rank(matrix).numpy())
print(np.ndim(matrix))
tensor3 = tf.constant([[[1.0, 2.0], [3.0, 4.0]], [[5.0, 6.0], [7.0, 8.0]]]) # 3维张量
print(tensor3)
print(tf.rank(tensor3))
tensor4 = tf.constant([[[[1.0, 1.0], [2.0, 2.0]], [[3.0, 3.0], [4.0, 4.0]]],
[[[5.0, 5.0], [6.0, 6.0]], [[7.0, 7.0], [8.0, 8.0]]]]) # 4维张量
print(tensor4)
print(tf.rank(tensor4))
可以用tf.cast改变张量的数据类型。
可以用numpy方法将tensorflow中的张量转化为numpy中的张量。
可以用shape方法查看张量的尺寸。
# 改变张量的数据类型
h = tf.constant([123, 456], dtype=tf.int32)
f = tf.cast(h, tf.float32)
print(h.dtype, f.dtype)
二、变量张量
模型中需要被训练的参数一般设置成常量
(1)常量的值不可改变,常量的重新赋值相当于创造新的内存空间
# 常量值不可以改变,常量的重新赋值相当于创造新的内存空间
c = tf.constant([1.0, 2.0])
print(c)
print(id(c))
c = c + tf.constant([1.0, 1.0])
print(c)
print(id(c))
(2)变量的值可以改变,可以通过assign, assign_add 等方法给变量重新赋值
# 变量的值可以改变,可以通过assign, assign_add等方法给变量重新赋值
v = tf.Variable([1.0, 1.0], name='v')
print(v)
print(id(v))
v.assign_add([1.0, 2.0])
print(v)
print(id(v))