这里写目录标题
本博客参考:《tensorflow+keras深度学习人工智能实践应用 林大贵著》
keras与tensorflow建立模型的不同
keras | tensorflow | |
---|---|---|
模型建立 | 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'])
运行结果
总体来看效果还算不错