神经网络的搭建八股:
- 用张量表示数据
- 用计算图搭建神经网络
- 用会话执行计算图
- 优化线上的权重
- 得到模型
张量(tensor):多维数组(列表) 阶:张量的维数
维数 | 阶 | 名字 | 例子 |
---|---|---|---|
0-D | 0 | 标量 scalar | s = 1 2 3 |
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 = [[[ ... |
数据类型:tf.float32 tf.int32 ...
用tensorflow实现两个向量的加法:
import tensorflow as tf
a = tf.constant([1.0,2.0])#定义常数
b = tf.constant([3.0,4.0])
result = a+b
print(result)
'''
Tensor("add:0",shape=(2,),dtype=float32)
result是一个名叫“add:0”的张量,维度为1,第一个维度中有两个元素,数据类型为32位浮点
'''
会话(Session):执行计算图中的节点运算。
用tensorflow实现向量的乘法:
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))
参数:即计算图中线上的权重,用变量表示,随机给初值。
w = tf.Variable(tf.random_normal([2,3],stddev=2,mean=0,seed=1))
tf.random_normal([2,3]) #产生基于正态分布的2x3矩阵
stddev=2 #标准差为2
mean=1 #均值为0
seed=1 #随机种子=1
tf.truncated_normal() #去掉过大偏离点的正态分布,一般超过两个标准差则重新生成
tf.random_uniform() #平均分布
tf.zeros() #全零数组 tf.zeros([3,2],int32)生成[[0,0],[0,0],[0,0]]
tf.ones() #全1数组 tf.ones([3,2],int32) 生成[[1,1],[1,1],[1,1]]
tf.fill #全定值数组 tf.fill([3,2],6) 生成[[6,6],[6,6],[6,6]]
tf.constant #直接给值 tf.constant([3,2,1])生成[3,2,1]