【Python】keras卷积神经网络识别mnist

栏目: 编程工具 · 发布时间: 6年前

内容简介:卷积神经网络的结构我随意设了一个。结构大概是下面这个样子:_________________________________________________________________

卷积神经网络的结构我随意设了一个。

结构大概是下面这个样子:

_________________________________________________________________

Layer (type) Output Shape Param #

=================================================================

conv2d_1 (Conv2D) (None, 26, 26, 32) 320

_________________________________________________________________

conv2d_2 (Conv2D) (None, 24, 24, 64) 18496

_________________________________________________________________

max_pooling2d_1 (MaxPooling2 (None, 12, 12, 64) 0

_________________________________________________________________

dropout_1 (Dropout) (None, 12, 12, 64) 0

_________________________________________________________________

conv2d_3 (Conv2D) (None, 10, 10, 64) 36928

_________________________________________________________________

conv2d_4 (Conv2D) (None, 8, 8, 64) 36928

_________________________________________________________________

dropout_2 (Dropout) (None, 8, 8, 64) 0

_________________________________________________________________

flatten_1 (Flatten) (None, 4096) 0

_________________________________________________________________

dense_1 (Dense) (None, 81) 331857

_________________________________________________________________

dropout_3 (Dropout) (None, 81) 0

_________________________________________________________________

dense_2 (Dense) (None, 10) 820

_________________________________________________________________

activation_1 (Activation) (None, 10) 0

=================================================================

代码如下:

import numpy as np
from keras.preprocessing import image
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten, Activation
from keras.layers import Conv2D, MaxPooling2D

# 从文件夹图像与标签文件载入数据
def create_x(filenum, file_dir):
    train_x = []
    for i in range(filenum):
        img = image.load_img(file_dir + str(i) + ".bmp", target_size=(28, 28))
        img = img.convert('L')
        x = image.img_to_array(img)
        train_x.append(x)
    train_x = np.array(train_x)
    train_x = train_x.astype('float32')
    train_x /= 255
    return train_x


def create_y(classes, filename):
    train_y = []
    file = open(filename, "r")
    for line in file.readlines():
        tmp = []
        for j in range(classes):
            if j == int(line):
                tmp.append(1)
            else:
                tmp.append(0)
        train_y.append(tmp)
    file.close()
    train_y = np.array(train_y).astype('float32')
    return train_y

classes = 10
X_train = create_x(55000, './train/')
X_test = create_x(10000, './test/')

Y_train = create_y(classes, 'train.txt')
Y_test = create_y(classes, 'test.txt')

# 从网络下载的数据集直接解析数据
'''
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
X_train, Y_train = mnist.train.images, mnist.train.labels
X_test, Y_test = mnist.test.images, mnist.test.labels
X_train = X_train.astype('float32')
X_test = X_test.astype('float32')
'''
model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=(28, 28, 1)))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(Dropout(0.25))

model.add(Flatten())
model.add(Dense(81, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(10))
model.add(Activation('softmax'))
model.summary()

model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])
history = model.fit(X_train, Y_train, batch_size=500, epochs=10, verbose=1, validation_data=(X_test, Y_test))
score = model.evaluate(X_test, Y_test, verbose=0)

test_result = model.predict(X_test)
result = np.argmax(test_result, axis=1)

print(result)
print('Test score:', score[0])
print('Test accuracy:', score[1])

最终在测试集上识别率在99%左右。

【Python】keras卷积神经网络识别mnist

相关测试数据可以在这里 下载 到。


以上所述就是小编给大家介绍的《【Python】keras卷积神经网络识别mnist》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

科技投资新时代:TMT投资方法、趋势与热点聚焦

科技投资新时代:TMT投资方法、趋势与热点聚焦

马军、宋辉、段迎晟 / 人民邮电出版社 / 2018-3 / 69.00

中国 TMT 行业(科技、媒体及通信)起步较晚但充满朝气。2017 年,TMT 板块的IPO 数量占到了总数的四分之一;对于投资者来说,投资 TMT 的收益非常可观。那么,TMT 的投资趋势如何? TMT 行业又有哪些投资热点? 本书立足于 TMT 投资现状,在介绍了 TMT 投资的基本概念之后,作者详细讲述了TMT 投资的基本研究方法、分析视角、整体行情及趋势分析,同时从行业视角分析了包括......一起来看看 《科技投资新时代:TMT投资方法、趋势与热点聚焦》 这本书的介绍吧!

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

html转js在线工具
html转js在线工具

html转js在线工具