keras学习实例(二):mnist 手写体分类

版权声明:本样板的所有内容,包括文字、图片,均为原创。对未经许可擅自使用者,本人保留追究其法律责任的权利。 https://blog.csdn.net/qq_29893385/article/details/82106937

承接上次笔记,这次进行mnist 的手写体目标识别实例,先说明一下出现的问题。

如上图,源程序类似keras的mnist_example实例,数据源是通过 url = https://s3.amazonaws.com/img-datasets/mnist.npz 进行下载的。访问该 url 地址被墙了,导致 MNIST 相关的案例都卡在数据下载的环节。

所以小编选择事先下载好mnist的数据集,然后修改程序,直接调用本地的数据集。这里给出一个博主给的链接,可以下载mnist.npz 数据集:

下载链接:https://pan.baidu.com/s/1jH6uFFC 密码: dw3d

程序如下:

#-*- coding: UTF-8 -*-
"""
To know more or get code samples, please visit my website:
https://morvanzhou.github.io/tutorials/
Or search: 莫烦Python
Thank you for supporting!
"""

# please note, all tutorial code are running under python3.5.
# If you use the version like python2.7, please modify the code accordingly

# 5 - Classifier example

import numpy as np
np.random.seed(1337)  # for reproducibility
from keras.datasets import mnist
from keras.utils import np_utils
from keras.models import Sequential
from keras.layers import Dense, Activation
from keras.optimizers import RMSprop

# download the mnist to the path '~/.keras/datasets/' if it is the first time to be called
# X shape (60,000 28x28), y shape (10,000, )
#(X_train, y_train), (X_test, y_test) = mnist.load_data()


###调用本地mnist数据集
import numpy as np
path='/home/ren_dong/文档/mnist.npz'
f = np.load(path)
X_train, y_train = f['x_train'], f['y_train']
X_test, y_test = f['x_test'], f['y_test']
f.close()

# data pre-processing
X_train = X_train.reshape(X_train.shape[0], -1) / 255.   # normalize
X_test = X_test.reshape(X_test.shape[0], -1) / 255.      # normalize
y_train = np_utils.to_categorical(y_train, num_classes=10)
y_test = np_utils.to_categorical(y_test, num_classes=10)

# Another way to build your neural net

model = Sequential([
    Dense(32, input_dim=784),
    Activation('relu'),
    Dense(10),
    Activation('softmax'),
])

# Another way to define your optimizer
rmsprop = RMSprop(lr=0.001, rho=0.9, epsilon=1e-08, decay=0.0)

# We add metrics to get more results you want to see
model.compile(optimizer=rmsprop,
              loss='categorical_crossentropy',
              metrics=['accuracy'])

print('Training ------------')
# Another way to train the model
model.fit(X_train, y_train, epochs=2, batch_size=32)

print('\nTesting ------------')
# Evaluate the model with the metrics we defined earlier
loss, accuracy = model.evaluate(X_test, y_test)

print('test loss: ', loss)
print('test accuracy: ', accuracy)

运行结果:

 

一共迭代两个epoch,最后loss为0.19,accurary为0.94,在测试阶段loss为0.17,accurary为0.95,可以说迭代还是学到了很多东西的。

参考博客:

https://blog.csdn.net/houchaoqun_xmu/article/details/78492718

https://study.163.com/course/courseLearn.htm?courseId=1003340023#/learn/video?lessonId=1003803531&courseId=1003340023

猜你喜欢

转载自blog.csdn.net/qq_29893385/article/details/82106937