数据预处理
输入的label值转为独热式编码:
import tensorflow as tf
# indices 就是label值,
# asix=0表示按列排,asix=1 表示按行排
var0 = tf.one_hot(indices=[1, 2, 3], depth=3, axis=0)
var1 = tf.one_hot(indices=[1, 2, 3], depth=4, axis=0)
var2 = tf.one_hot(indices=[1, 2, 3], depth=4, axis=1) # axis=1 按行排
var3 = tf.one_hot(indices=[1, 2, 3], depth=4, axis=-1)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
a0 = sess.run(var0)
a1 = sess.run(var1)
a2 = sess.run(var2)
a3 = sess.run(var3)
print("var0(axis=0 depth=3)\n",a0)
print("var1(axis=0 depth=4P)\n",a1)
print("var2(axis=1)\n",a2)
print("var3(axis=-1)\n",a3)
神经网络
前向传播
# 神经网络--前向传播
import tensorflow as tf
# 2*3的矩阵 变量
w1 = tf.Variable(tf.random_normal((2,3),stddev=1,seed=1)) # 随机矩阵,标准差是1,随机种子是1,意味着w1和w2是一模一样的
# 3*1的矩阵
w2 = tf.Variable(tf.random_normal((3,1),stddev=1,seed=1))
# 1x2的矩阵 输入值,不推荐用constan常量
x = tf.placeholder(tf.float32,shape=(1,2),name="input_x")
# 前向传播
# a是中间隐藏层节点
a = tf.matmul(x,w1)
y = tf.matmul(a,w2)
# 使用会话来运行
with tf.Session() as sess:
# 统一初始化
init_op = tf.global_variables_initializer()
sess.run(init_op)
# x是placeholder,所以需要输入值
res = sess.run(y,feed_dict={
x:[[0.7,0.9]]}) # 1x2 2x3 3x1 -> 输出1x1的矩阵
print(res)
反向传播
三个步骤:
- 定义神经网络结构和前向传播的输出结果
- 定义损失函数和反向传播优化的算法
- 会话,反复训练
# 神经网络--前向传播和反向传播
import tensorflow as tf
from numpy.random import RandomState
# 一批数据8个
batch_size = 8
w1 = tf.Variable(tf.random_normal([2,3],stddev=1,seed=1))
w2 = tf.Variable(tf.random_normal([3,1],stddev=1,seed=1))
# 输入值, (None,2)表示多行,2列, 数据一批一批的传送
x = tf.placeholder(tf.float32,shape=(None,2),name="input_x")
t = tf.placeholder(tf.float32,shape=(None,1),name="output_t")
# 定义前向传播的过程
a = tf.matmul(x,w1)
y = tf.matmul(a,w2)
y = tf.sigmoid(y)
# 交叉熵:损失函数和真实值的差距
cross_entropy = -tf.reduce_mean(t*tf.log(tf.clip_by_value(