一、minist数据集
minist数据集分为两个部分,训练集和测试集,然后在不同的集合中分为两个文件,数据Images文件和Labels文件。在数据集中一个有60000个训练数据和10000个测试数据,图片的大小是28*28。
下载数据集
import numpy as np
from sklearn.datasets import fetch_openml
X, y = fetch_openml('mnist_784', return_X_y=True)
在X中,每一条数据是一个长为28×28=78428×28=784的数组,数组的数据是图片的像素值。每一条y数据就是一个标签,代表这张图片表示哪一个数字(从0到9)。
然后我们将数据进行二值化,像素值大于0的置为1,并将数据保存到文件夹中:
X[X > 0] = 1
np.save('./data/dataset', X)
np.save('./data/class', y)
加载数据集
X = np.load('./data/dataset.npy')
y = np.load('./data/class.npy')
One-Hot编码,又称为一位有效编码,主要是采用N位状态寄存器来对N个状态进行编码,每个状态都由他独立的寄存器位,并且在任意时候只有一位有效。
使用one hot encoding将y变成输出10个数字。
# 使用one hot encoding将y变成输出10个数字
from sklearn.preprocessing import OneHotEncoder
oh = OneHotEncoder(sparse=False)
y = oh.fit_transform(y.reshpe(y.shape[0], 1))
划分数据集
# 将数据集划分为训练集和测试集
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(X, y, random_state=14)
在神经网络中,我们使用pybrain框架去构建一个神经网络。但是呢,对于pybrain库,他很与众不同,他要使用自己的数据集格式,因此,我们需要将数据转成它规定的格式。
如果pybrain弹出“No module named ‘structure‘”错误,解决方法。
from pybrain.datasets import SupervisedDataSet
train_data = SupervisedDataSet(x_train.shape[1], y.shape[1])
test_data = SupervisedDataSet(x_test.shape[1], y.shape[1])
for i in range(x_train.shape[0]):
train_data.addSample(x_train[i], y_train[i])
for i in range(x_test.shape[0]):
test_data.addSample(x_test[i], y_test[i])
二、构建神经网络
from pybrain.tools.shortcuts import buildNetwork
# X.shape[1]代表属性的个数,100代表隐层中神经元的个数,y.shape[1]代表输出
net = buildNetwork(X.shape[1], 100, y.shape[1], bias=True)
三、反向传播算法
利用反向传播(BP)算法去更新网络的权重。
from pybrain.supervised.trainers import BackpropTrainer
trainer = BackpropTrainer(net, train_data, learningrate=0.01, weightdecay=0.01)
trainer.trainEpochs(epochs=100)
四、评估
predictions = trainer.testOnClassData(dataset=test_data)
y_test_arry = y_test.argmax(axis=1)
from sklearn.metrics import f1_score
print("F-score:{0:.2f}".format(f1_score(predictions, y_test_arry, average='micro')))