博客
关于我
tensorflow python3 minist keras简单卷积网络实现
阅读量:371 次
发布时间:2019-03-05

本文共 4319 字,大约阅读时间需要 14 分钟。

 

 

from __future__ import print_functionimport numpy as npfrom keras.datasets import mnistfrom keras.models import Sequentialfrom keras.layers.core import Dense, Dropout, Activation, Flattenfrom keras.optimizers import RMSpropfrom keras.utils import np_utilsfrom keras.layers.convolutional import Conv2D, MaxPooling2Dimport matplotlib.pyplot as pltnp.random.seed(1671)  # 为 reproducibility 设置随机种子# 网络和训练配置NB_EPOCH = 20BATCH_SIZE = 128VERBOSE = 1NB_CLASSES = 10  # 输出数量等于数字数量OPTIMIZER = RMSprop()N_HIDDEN = 128VALIDATION_SPLIT = 0.2DROPOUT = 0.3# 数据预处理:分割训练集和测试集(X_train, y_train), (X_test, y_test) = mnist.load_data()# 数据形状调整RESHAPED = 784X_train = X_train.reshape(60000, 28, 28, 1)X_test = X_test.reshape(10000, 28, 28, 1)X_train = X_train.astype('float32')X_test = X_test.astype('float32')# 数据归一化X_train /= 255X_test /= 255print(X_train.shape[0], '训练样本数量')print(X_test.shape[0], '测试样本数量')# 类别转换为二元分类矩阵Y_train = np_utils.to_categorical(y_train, NB_CLASSES)Y_test = np_utils.to_categorical(y_test, NB_CLASSES)# 定义模型model = Sequential()model.add(Conv2D(32, kernel_size=5, padding='same', input_shape=(28, 28, 1)))model.add(Activation('relu'))model.add(MaxPooling2D(pool_size=(2, 2)))model.add(Dropout(0.25))model.add(Conv2D(64, kernel_size=5, padding='same'))model.add(Activation('relu'))model.add(MaxPooling2D(pool_size=(2, 2)))model.add(Dropout(0.25))model.add(Flatten())model.add(Dense(1024))model.add(Activation('relu'))model.add(Dropout(0.5))model.add(Dense(NB_CLASSES))model.add(Activation('softmax'))model.summary()model.compile(loss='categorical_crossentropy',              optimizer=OPTIMIZER,              metrics=['accuracy'])# 训练模型history = model.fit(X_train, Y_train,                    batch_size=BATCH_SIZE,                    epochs=6,                    verbose=VERBOSE,                    validation_split=VALIDATION_SPLIT)# 评估模型性能score = model.evaluate(X_test, Y_test, verbose=VERBOSE)print("\n测试准确率:", score[1])# 可视化训练历史plt.plot(history.history['acc'])plt.plot(history.history['val_acc'])plt.title('模型准确率曲线')plt.ylabel('准确率')plt.xlabel('训练轮次')plt.legend(['训练', '验证'], loc='upper left')plt.show()plt.plot(history.history['loss'])plt.plot(history.history['val_loss'])plt.title('模型损失曲线')plt.ylabel('损失值')plt.xlabel('训练轮次')plt.legend(['训练', '验证'], loc='upper left')plt.show()

模型总结

_______________________________________________________________________

Layer (type)                 Output Shape         Param #

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

conv2d_1 (Conv2D)            (None, 28, 28, 32)        832

_______________________________________________________________

activation_1 (Activation)          (None, 28, 28, 32)        0

_______________________________________________________________

max_pooling2d_1 (MaxPooling2D)          (None, 14, 14, 32)        0

_______________________________________________________________

dropout_1 (Dropout)          (None, 14, 14, 32)        0

_______________________________________________________________

conv2d_2 (Conv2D)          (None, 14, 14, 64)        512

_______________________________________________________________

activation_2 (Activation)          (None, 14, 14, 64)        0

_______________________________________________________________

max_pooling2d_2 (MaxPooling2D)          (None, 7, 7, 64)        0

_______________________________________________________________

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

_______________________________________________________________

flatten_1 (Flatten)          (None, 3136)        0

_______________________________________________________________

dense_1 (Dense)          (None, 1024)        3212288

_______________________________________________________________

activation_3 (Activation)          (None, 1024)        0

_______________________________________________________________

dropout_3 (Dropout)          (None, 1024)        0

_______________________________________________________________

dense_2 (Dense)          (None, 10)        10250

_______________________________________________________________

activation_4 (Activation)          (None, 10)        0

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

总参数数量:3,274,634

转载地址:http://afpg.baihongyu.com/

你可能感兴趣的文章
python+locust电商全流程性能测试
查看>>
Python函数运行的可执行文件的终端输出如何以一般方式静音?
查看>>
Python+Pytest+Allure+Git+Jenkins接口自动化框架
查看>>
python+pytest接口自动化 —— 参数关联
查看>>
python+pytest接口自动化 —— 参数关联
查看>>
Python+pytest接口自动化 —— 接口测试基础
查看>>
python+pytest接口自动化 —— 自动化用例编写思路 (使用pytest编写一个测试脚本)
查看>>
Python+pytest接口自动化之cookie绕过登录(保持登录状态)
查看>>
python+pytest接口自动化:接口测试
查看>>
Python+requests+unittest执行接口自动化测试详情
查看>>
Python+requests+unittest执行接口自动化测试详情
查看>>
python+requests+unittest执行自动化接口测试!
查看>>
Python+Requests编码识别Bug
查看>>
python函数编写_[零基础学python]传说中的函数编写条规
查看>>
Python+selenium —— UI自动化之鼠标操作
查看>>
python函数注释,参数后面加冒号:,函数后面的箭头→是什么?
查看>>
Python+Selenium+Threading进行兼容性测试
查看>>
Python+selenium+unittest的GUI自动化框架实现
查看>>
python函数拟合不规则曲线_Python计算&绘图——曲线拟合问题(转)
查看>>
python函数定义的基本格式_零基础学python-2.19 定义函数、调用函数与默认参数
查看>>