Keras实现卷积神经网络

 1 # -*- coding: utf-8 -*-
 2 """
 3 Created on Sun Jan 20 11:25:29 2019
 4 
 5 @author: zhen
 6 """
 7 
 8 import numpy as np
 9 from keras.datasets import mnist
10 from keras.models import Sequential
11 from keras.layers import Dense
12 from keras.layers import Dropout
13 from keras.layers import Flatten
14 from keras.layers.convolutional import Conv2D
15 from keras.layers.convolutional import MaxPooling2D
16 
17 # 加载数据
18 (x_train, y_train), (x_test, y_test) = mnist.load_data("../test_data_home")
19 # 转化训练数据为四维张量形式
20 x_train = x_train.reshape(x_train.shape[0], 28, 28, 1).astype("float32")
21 x_test = x_test.reshape(x_test.shape[0], 28, 28, 1).astype("float32")
22 # 归一化
23 x_train /= 255
24 x_test /= 255
25 
26 #转化为one hot 编码
27 def to_one_hot(y):
28     y_one_hot = np.zeros(10) # 生成全零向量
29     y_one_hot[y] = 1
30     return y_one_hot
31 
32 # 重置标签
33 y_train_one_hot = np.array([to_one_hot(y_train[i]) for i in range(len(y_train))])
34 y_test_one_hot = np.array([to_one_hot(y_test[i]) for i in range(len(y_test))])
35 # 搭建卷积神经网络
36 model = Sequential()
37 model.add(Conv2D(filters=32, kernel_size=(3, 3), strides=(1, 1), padding='same', input_shape=(28, 28, 1), 
38                  activation='relu'))
39 # 添加最大池化层
40 model.add(MaxPooling2D(pool_size=(2, 2)))
41 # 添加Dropout层
42 model.add(Dropout(0.2))
43 # 构建深度网络
44 model.add(Conv2D(64, kernel_size=(3, 3), strides=(1, 1), padding='same', activation='relu'))
45 model.add(MaxPooling2D(pool_size=(2, 2)))
46 model.add(Dropout(0.2))
47 model.add(Conv2D(128, kernel_size=(3, 3), strides=(1, 1), padding='same', activation='relu'))
48 model.add(MaxPooling2D(pool_size=(2, 2)))
49 model.add(Dropout(0.2))
50 # 展开
51 model.add(Flatten())
52 # 构造全连接层
53 model.add(Dense(128, activation='relu'))
54 model.add(Dense(64, activation='relu'))
55 model.add(Dense(32, activation='relu'))
56 model.add(Dense(10, activation='softmax'))
57 # 定义损失函数
58 model.compile(loss='categorical_crossentropy', optimizer='adagrad',
59               metrics=['accuracy'])
60 # 训练
61 model.fit(x_train, y_train_one_hot, validation_data=(x_test, y_test_one_hot),
62           epochs=2, batch_size=128)
63 # 评估
64 # verbose : 0表示不显示数据,1表示显示进度
65 scores = model.evaluate(x_test, y_test_one_hot, verbose=0)
66 print(scores)

结果:

Keras实现卷积神经网络_第1张图片

 

转载于:https://www.cnblogs.com/yszd/p/10294536.html

你可能感兴趣的:(Keras实现卷积神经网络)