Python实现实现Keras搭建神经网络训练分类模型教程搭建神经网络训练分类模型教程
主要介绍了Python实现Keras搭建神经网络训练分类模型教程,具有很好的参考价值,希望对大家有所帮助。一
起跟随小编过来看看吧
我就废话不多说了,大家还是直接看代码吧~
注释讲解版:注释讲解版:
# Classifier example
import numpy as np
# for reproducibility
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
# 程序中用到的数据是经典的手写体识别mnist数据集
# download the mnist to the path if it is the first time to be called
# X shape (60,000 28x28), y
# (X_train, y_train), (X_test, y_test) = mnist.load_data()
# 下载minst.npz:
# 链接: https://pan.baidu.com/s/1b2ppKDOdzDJxivgmyOoQsA
# 提取码: y5ir
# 将下载好的minst.npz放到当前目录下
path='./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
# 数据预处理
# normalize
# X shape (60,000 28x28),表示输入数据 X 是个三维的数据
# 可以理解为 60000行数据,每一行是一张28 x 28 的灰度图片
# X_train.reshape(X_train.shape[0], -1)表示:只保留第一维,其余的纬度,不管多少纬度,重新排列为一维
# 参数-1就是不知道行数或者列数多少的情况下使用的参数
# 所以先确定除了参数-1之外的其他参数,然后通过(总参数的计算) / (确定除了参数-1之外的其他参数) = 该位置应该是多少的参数
# 这里用-1是偷懒的做法,等同于 28*28
# reshape后的数据是:共60000行,每一行是784个数据点(feature)
# 输入的 x 变成 60,000*784 的数据,然后除以 255 进行标准化
# 因为每个像素都是在 0 到 255 之间的,标准化之后就变成了 0 到 1 之间
X_train = X_train.reshape(X_train.shape[0], -1) / 255
X_test = X_test.reshape(X_test.shape[0], -1) / 255
# 分类标签编码
# 将y转化为one-hot vector
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
# 建立神经网络
# 应用了2层的神经网络,前一层的激活函数用的是relu,后一层的激活函数用的是softmax
#32是输出的维数
model = Sequential([
Dense(32, input_dim=784),
Activation('relu'),
Dense(10),
Activation('softmax')
])
# Another way to define your optimizer
# 优化函数
# 优化算法用的是RMSprop
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
# 不自己定义,直接用内置的优化器也行,optimizer='rmsprop'
#激活模型:接下来用 model.compile 激励神经网络
model.compile(
optimizer=rmsprop,
loss='categorical_crossentropy',
metrics=['accuracy']
)
评论0