版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_877667836/article/details/83073903
1-目标
- 使用tensorflow创建感知机模型
- 使用感知机对手写数字识别
2-模型分析及构建
- 感知机
y = f(Wx + b)
由输入层神经元和输出层神经元组成,输入的数据矩阵是n_samples x m_features ,输出是n_samples x p_labels, 参数W矩阵形式是m x p,偏置b的形式为p维向量。 - 搭建前向传播网络。创建输入x(n,784),权重w(784,10),偏置b(10,),激活函数f使用softmax函数实现多分类,输出y = Softmax(x*w+b)。还要创建标签y_(n,10)用于反向传播。
- 实现BP反向传播。定义损失函数loss(交叉熵 or 均方差 or …),定义学习率LR,使用梯度下降调整模型误差。
- 创建会话,读入数据,训练模型
3-主要函数用法
tf.matmul()
:矩阵乘法
tf.nn.softmax()
:调用softmax激活函数,输入一个logists ,类型tensor,默认是对最高维度计算softmax。
tf.reduce_mean() / tf.reduce_sum()
:针对某个axis降维求均值或求和,默认是所有。
类似的tf.reduce_xxx()
都是对数组降维后在执行运算。
Args:
input_tensor: The tensor to reduce. Should have numeric type.
axis: The dimensions to reduce. IfNone
(the default),
reduces all dimensions.
keep_dims: If true, retains reduced dimensions with length 1.
name: A name for the operation (optional).
reduction_indices: The old (deprecated) name for axis.
For example:
# 'x' is [[1, 1, 1]
# [1, 1, 1]]
tf.reduce_sum(x) ==> 6
tf.reduce_sum(x, 0) ==> [2, 2, 2]
tf.reduce_sum(x, 1) ==> [3, 3]
tf.reduce_sum(x, 1, keep_dims=True) ==> [[3], [3]]
tf.reduce_sum(x, [0, 1]) ==> 6
tf.argmax()
返回一个数组某个维度上(默认axis=0)最大值的索引
# 'x' is [[1, 2, 3]
# [4, 5, 6]]
tf.argmax(x) ==> [1, 1, 1]
tf.argmax(x , 1) ==> [2, 2]
tf.equal()
逐个比较两个数组中的元素是否相等,返回真值表。
tf.cast()
将数据格式转化成指定类型
4-代码实现
import os
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
# 消除不支持SSE/AVX的警告
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
# 读入mnist数据 (relative workdir)
mnist = input_data.read_data_sets('MNIST_data/', one_hot=True)
# 创建输入x, 权重w, 偏置b, 输出y = Softmax(x*w+b)
x = tf.placeholder(tf.float32, [None, 784])
w = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
y = tf.nn.softmax(tf.matmul(x, w) + b)
# 创建图片的实际标签y_
y_ = tf.placeholder(tf.float32, [None, 10])
# 根据y与y_构造交叉熵损失
cross_entropy_loss = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y)))
# 使用梯度下降法减小损失,学习率为LR
LR = 0.01
train_step = tf.train.GradientDescentOptimizer(LR).minimize(cross_entropy_loss)
# 正确的预测结果
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
# 计算预测准确率
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
# 创建会话,训练模型
with tf.Session() as sess:
# 初始化所有变量
tf.global_variables_initializer().run()
# 进行1000步梯度下降
for _ in range(1000):
# 随机从mnist.train中取100个训练数据
# batch_xs是形状为(100,784)的图像数据, batch_ys是形状为(100,10)的图片标签
batch_xs, batch_ys = mnist.train.next_batch(100)
sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
# 最终模型的正确率
print(sess.run(accuracy, feed_dict={
x: mnist.test.images, y_: mnist.test.labels})) # 0.91