Keras学习(四)—— Classify分类简单实例

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/weixin_42886817/article/details/99967208

代码

import numpy as np
np.random.seed(1337)
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
# X shape(60000,28x28) ,y shape (10000, )

( X_train, y_train),(X_test, y_test) = mnist.load_data()

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

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

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

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

# train
print('Training------')
model.fit(X_train,y_train,nb_epoch=2,batch_size=32)

print('\nTesting------')
loss,accuracy = model.evaluate(X_test,y_test)

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

运行结果

52704/60000 [=>…] - ETA: 0s - loss: 0.1966 - acc: 0.9435
53440/60000 [
=>…] - ETA: 0s - loss: 0.1969 - acc: 0.9434
54208/60000 [>…] - ETA: 0s - loss: 0.1972 - acc: 0.9433
54912/60000 [
>…] - ETA: 0s - loss: 0.1972 - acc: 0.9432
55712/60000 [>…] - ETA: 0s - loss: 0.1967 - acc: 0.9433
56576/60000 [
=>…] - ETA: 0s - loss: 0.1972 - acc: 0.9434
57344/60000 [=>…] - ETA: 0s - loss: 0.1966 - acc: 0.9435
58176/60000 [
>.] - ETA: 0s - loss: 0.1964 - acc: 0.9435
59040/60000 [
>.] - ETA: 0s - loss: 0.1956 - acc: 0.9436
59840/60000 [
>.] - ETA: 0s - loss: 0.1956 - acc: 0.9437
60000/60000 [
============================] - 4s 69us/step - loss: 0.1955 - acc: 0.9437

Testing------

32/10000 […] - ETA: 16s
1600/10000 [=>…] - ETA: 0s
3296/10000 [
>…] - ETA: 0s
5376/10000 [
=>…] - ETA: 0s
7520/10000 [
=>…] - ETA: 0s
9344/10000 [
=>…] - ETA: 0s
10000/10000 [
================] - 0s 32us/step
test loss: 0.17461771187186242
test accuracy: 0.9506

Process finished with exit code 0

猜你喜欢

转载自blog.csdn.net/weixin_42886817/article/details/99967208