张量、计算图、会话
基于Tensorflow的NN:用张量表示数据,用计算图搭建神经网络,用会话执行计算图,优化线上的权重(参数),得到模型。
一、张量:
1、张量(tensor):多维数组(列表)。阶:张量的维数。
维数 | 阶 | 名字 | 例子 |
---|---|---|---|
0-D | 0 | 标量 scalar | s = 123 |
1-D | 1 | 向量 vector | v = [1, 2, 3] |
2-D | 2 | 矩阵 matrix | m = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] |
n-D | n | 张量 tensor | t = [[1, 2, 3], [4, 5, 6], [7, 8, 9]...] [[[[....(n个) |
张量可以表示0阶到n阶数组(列表)
2、vim编辑器设置:
vim ~/.vimrc 写入:
set ts=4 # 使Tab等效于四个空格
set nu # 使vim显示行号
3、数据类型:
(1) 有符号整型:
数据类型 | 描述 |
---|---|
tf.int8 | 8位有符号整型 |
tf.int16 | 16位有符号整型 |
tf.int32 | 32位有符号整型 |
tf.int64 | 64位有符号整型 |
tf.qint8 | 量化的8位有符号整型 |
tf.qint16 | 量化的16位有符号整型 |
tf.qint32 | 量化的32位有符号整型 |
(2) 无符号整型:
数据类型 | 描述 |
---|---|
tf.uint8 | 8位无符号整型 |
tf.uint16 | 16位无符号整型 |
tf.uint32 | 32位无符号整型 |
tf.uint64 | 64位无符号整型 |
tf.quint8 | 量化的8位无符号整型 |
tf.quint16 | 量化的16位无符号整型 |
tf.quint32 | 量化的32位无符号整型 |
(3) 浮点型:
数据类型 | 描述 |
---|---|
tf.float16 | 16位半精度浮点数 |
tf.float32 | 32位单精度浮点数 |
tf.float64 | 64位双精度浮点数 |
tf.bfloat16 | 16位截断浮点数 |
(4) 字符串型:
(5) 布尔型:
(6) 复数型:
(7) 句柄:
(8) 任意类型的值:
4、张量计算:
import tensorflow as tf
a = tf.constant([1.0, 2.0])
b = tf.constant([3.0, 4.0])
result = a + b
print(result)
# 1.0运行结果:
Tensor("add:0", shape=(2,), dtype=float32)
# 2.0运行结果:
tf.Tensor([4. 6.], shape=(2,), dtype=float32)
对应数学计算:
二、计算图:
1、计算图(Graph):搭建神经网络的计算过程,只搭建,不运算。
y = =
2、实例:
import tensorflow as tf
x = tf.constant([[1.0, 2.0]])
w = tf.constant([[3.0], [4.0]])
y = tf.matmul(x, w)
print(y)
# 1.0运行结果:
Tensor("MatMul:0", shape=(1, 1), dtype=float32)
# 2.0运行结果:
tf.Tensor([[11.]], shape=(1, 1), dtype=float32)
# 注释:
tf.matmul:矩阵相乘
对应数学公式:
三、会话:
1、会话(Session):执行计算图中的节点运算。2.0版本取消了会话
语法:
with tf.Session() as sess:
print(sess.run(y))
2、示例:
import tensorflow as tf
x = tf.constant([[1.0, 2.0]])
w = tf.constant([[3.0], [4.0]])
y = tf.matmul(x, w)
print(y)
with tf.Session() as sess:
print(sess.run(y))
# 运行结果:
Tensor("MatMul:0", shape=(1, 1), dtype=float32)
[[11.]]