tensorflow多层感知机+mnist数据集

本博客参考:《tensorflow+keras深度学习人工智能实践应用 林大贵著》

keras与tensorflow建立模型的不同

kerastensorflow
模型建立model=Sqeuential():建立线性堆叠模型,
model.add():将各个神经网络层加入网络即可
自定义layer函数,使用layer建立多层感知机模型
模型优化在model.compile()函数中,模型预编译阶段完成自定义loss损失函数以及optimizer优化器
模型训练在model.fit()函数中,传入x_train,y_train,epochs,batch_size,验证集比例等参数后由函数自动完成,返回history对象其中包含模型训练过程中的loss和acc变化训练过程需要自定义,通过循环定义模型在每个epoch中需要执行的操作,每次epoch通过自定义的loss_fun和acc函数计算模型的loss和acc存入数组中作为训练过程的"history"

加载mnist

import tensorflow.examples.tutorials.mnist.input_data as input_data
path=r'E:\mydataset\data\LeYun_mnist'
mnist=input_data.read_data_sets(path,one_hot=True)
mnist对象的属性值数据分类属性属性值
mnist.train.num_examples训练集图片数量55000
.images.shape-数据形状(55000, 784)
.labels.shape-数据形状(55000, 10)
mnist.test.num_examples测试集图片数量10000
.images.shape-数据形状(10000, 784)
.images.shape-数据形状(10000, 10)
mnist.validation.num_examples交叉验证集图片数量5000
.images.shape-数据形状(5000,784)
.labels.shape-数据形状(5000,10)

注:path文件夹下面需要包含mnist数据集压缩包(共4个文件),否则函数将先从网络上下载,如图在这里插入图片描述

tensorflow多层感知机构建

全连接层函数定义

import tensorflow as tf
def layer(output_dim,input_dim,inputs,activation=None):
	w=tf.Variable(tf.random_normal([input_dim,output_dim]))
	b=tf.Variable(tf.random_normal([1,output_dim]))
	y=tf.matmul(inputs,w)+b
	if activation is None:
		return y
	else:
		return activation(y)

感知机各层的输入和输出

# 感知机各层输入和输出
x=tf.placeholder('float',[None,784])
h1=layer(output_dim=256,input_dim=784,inputs=x,activation=tf.nn.relu)
y_predict=layer(output_dim=10,input_dim=256,inputs=h1,activation=None)
y_label=tf.placeholder('float',[None,10])

损失函数、优化器

loss=tf.nn.softmax_cross_entropy_with_logits(logits=y_predict,labels=y_label)
loss_fun=tf.reduce_mean(loss)
optimizer=tf.train.AdamOptimizer(learning_rate=0.001).minimize(loss_fun)

模型准确率计算

correct_prediction=tf.equal(tf.argmax(y_label,1),tf.argmax(y_predict,1))
accuracy=tf.reduce_mean(tf.cast(correct_prediction,'float'))

模型训练参数定义

epochs=15
batch_size=100
total_epoch=int(mnist.train.num_examples/batch_size)
loss_list=[]
accuracy_list=[]
sess=tf.Session()
sess.run(tf.global_variables_initializer())

训练开始

for epoch in range(epochs):
	for i in range(total_epoch):
		batch_x,batch_y=mnist.train.next_batch(batch_size)
		sess.run(optimizer,feed_dict={x:batch_x,y_label:batch_y})
	loss,acc=sess.run([loss_fun,accuracy],feed_dict={x:mnist.validation.images,y_label:mnist.validation.labels})
	loss_list.append(loss)
	accuracy_list.append(acc)
	print((epoch+1,loss,acc))

运行结果
在这里插入图片描述

模型训练效果可视化

import matplotlib.pyplot as plt

fig=plt.gcf()
plt.plot(range(1,16),accuracy_list,label='accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(loc='upper left')

运行结果
在这里插入图片描述

fig=plt.gcf()
plt.plot(range(1,16),loss_list,label='loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(loc='upper left')

运行结果
在这里插入图片描述

模型评分

score=sess.run(accuracy,feed_dict={x:mnist.test.images,y_label:mnist.test.labels})
>>> 0.9427

利用模型进行预测

import numpy as np
pred=sess.run(tf.argmax(y_predict,1),feed_dict={x:mnist.test.images})
pred[:10]
>>> array([7, 2, 1, 0, 4, 1, 4, 9, 6, 9], dtype=int64)
real_label=np.argmax(mnist.test.labels,axis=-1)
real_label[:10]
>>> array([7, 2, 1, 0, 4, 1, 4, 9, 5, 9], dtype=int64)

运行结果
在这里插入图片描述

显示混淆矩阵

import pandas as pd
real_label=real_label.reshape(-1)
pd.crosstab(real_label,pred,rownames=['label'],colnames=['predict'])

运行结果
在这里插入图片描述

总体来看效果还算不错

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

夺笋123

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值