用Python实现神经网络(一)
Python实现神经网络有多种方法。这里我们使用keras框架。你必须安装 tensorflow或theano, 和 keras然后才能实现神经网络。
1. 下载数据集并提取训练和测试集(见“NN.ipynb”)
from keras.datasets import mnist
import matplotlib.pyplot as plt
%matplotlib inline
# load (downloaded if needed) the MNIST dataset
(X_train, y_train), (X_test, y_test) = mnist.load_data()
# plot 4 images as gray scale
plt.subplot(221)
plt.imshow(X_train[0], cmap=plt.get_cmap('gray'))
plt.subplot(222)
plt.imshow(X_train[1], cmap=plt.get_cmap('gray'))
plt.subplot(223)
plt.imshow(X_train[2], cmap=plt.get_cmap('gray'))
plt.subplot(224)
plt.imshow(X_train[3], cmap=plt.get_cmap('gray'))
# show the plot
plt.show()
图 4-18. 输出
2. 导入相关包:
import numpy as np
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.utils import np_utils
3. 预处理数据集:
num_pixels = X_train.shape[1] * X_train.shape[2]
# reshape the inputs so that they can be passed to the
vanilla NN
X_train = X_train.reshape(X_train.shape[0],num_pixels
).astype('float32')
X_test = X_test.reshape(X_test.shape[0],num_pixels).
astype('float32')
# scale inputs
X_train = X_train / 255
X_test = X_test / 255
# one hot encode the output
y_train = np_utils.to_categorical(y_train)
y_test = np_utils.to_categorical(y_test)
num_classes = y_test.shape[1]
4. 构建模型:
# building the model
model = Sequential()
# add 1000 units in the hidden layer
# apply relu activation in hidden layer
model.add(Dense(1000, input_dim=num_pixels,activation='relu'))
# initialize the output layer
model.add(Dense(num_classes, activation='softmax'))
# compile the model
model.compile(loss='categorical_crossentropy',optimizer='adam', metrics=['accuracy'])
# extract the summary of model
model.summary()
5. 运行模型:
model.fit(X_train, y_train, validation_data=(X_test,
y_test), epochs=5, batch_size=1024, verbose=1)
注意随着epochs增加, 测试集的准确率也增加。另外在keras里我们只要在第一层指明输入的维,它会自己动的推出余下各层的维。