第一部分是下载数据
第二部分常用函数
第三部分是神经网络类
第四部分主函数
# coding: utf-8
try:
import urllib.request
except ImportError:
raise ImportError('You should use Python 3.x')
import os.path
import gzip
import pickle
import os
import math
import numpy as np
# 以下部分为下载数据集
url_base = 'http://yann.lecun.com/exdb/mnist/'
key_file = {
'train_img': 'train-images-idx3-ubyte.gz',
'train_label': 'train-labels-idx1-ubyte.gz',
'test_img': 't10k-images-idx3-ubyte.gz',
'test_label': 't10k-labels-idx1-ubyte.gz'
}
dataset_dir = os.path.dirname(os.path.abspath(__file__))
save_file = dataset_dir + "/mnist.pkl"
train_num = 60000
test_num = 10000
img_dim = (1, 28, 28)
img_size = 784
def _download(file_name):
file_path = dataset_dir + "/" + file_name
if os.path.exists(file_path):
return
print("Downloading " + file_name + " ... ")
urllib.request.urlretrieve(url_base + file_name, file_path)
print("Done")
def download_mnist(): # 下载数据集
for v in key_file.values():
_download(v)
def _load_label(file_name):
file_path = dataset_dir + "/" + file_name
print("Converting " + file_name + " to NumPy Array ...")
with gzip.open(file_path, 'rb') as f:
labels = np.frombuffer(f.read(), np.uint8, offset=8)
print("Done")
return labels
def _load_img(file_name):
file_path = dataset_dir + "/" + file_name
print("Converting " + file_name + " to NumPy Array ...")
with gzip.open(file_path, 'rb') as f:
data = np.frombuffer(f.read(), np.uint8, offset=16)
data = data.reshape(-1, img_size)
print("Done")
return data
def _convert_numpy(): # 数据集预处理
dataset = {}
dataset['train_img'] = _load_img(key_file['train_img'])
dataset['train_label'] = _load_label(key_file['train_label'])
dataset['test_img'] = _load_img(key_file['test_img'])
dataset['test_label'] = _load_label(key_file['test_label'])
return dataset
def init_mnist():
download_mnist()
dataset = _convert_numpy()
print("Creating pickle file ...")
with open(save_file, 'wb') as f:
pickle.dump(dataset, f, -1)
print("Done!")
def _change_one_hot_label(X):
T = np.zeros((X.size, 10))
for idx, row in enumerate(T):
row[X[idx]] = 1
return T
def load_mnist(normalize=True, flatten=True, one_hot_label=False):
"""读入MNIST数据集
Parameters
----------
normalize : 将图像的像素值正规化为0.0~1.0
one_hot_label :
one_hot_label为True的情况下,标签作为one-hot数组返回
one-hot数组是指[0,0,1,0,0,0,0,0,0,0]这样的数组
flatten : 是否将图像展开为一维数组
Returns
-------
(训练图像, 训练标签), (测试图像, 测试标签)
"""
if not os.path.exists(save_file):
init_mnist()
with open(save_file, 'rb') as f:
dataset = pickle.load(f)
if normalize:
for key in ('train_img', 'test_img'):
dataset[key] = dataset[key].astype(np.float32)
print("key ")
print(dataset[key][5][5])
dataset[key] /= 255.0
print(dataset[key][5][5])
if one_hot_label:
dataset['train_label'] = _change_one_hot_label(dataset['train_label'])
dataset['test_label'] = _change_one_hot_label(dataset['test_label'])
if not flatten:
for key in ('train_img', 'test_img'):
dataset[key] = dataset[key].reshape(-1, 1, 28, 28)
return (dataset['train_img'], dataset['train_label']), (dataset['test_img'], dataset['test_label'])
# 以下内容为神经网络
def sigmoid(x):
return 1/(1+np.exp(-x))
def softmax(x):
if x.ndim == 2:
x = x.T
x = x-np.max(x, axis=0)
y = np.exp(x) / np.sum(np.exp(x), axis=0)
return y.T
x=x-np.max(x)
return np.exp(x) / np.sum(np.exp(x))
def cross_entropy_error(y, t):
if y.ndim == 1:
t = t.reshape(1, t.size)
y = y.reshape(1, y.size)
# 监督数据是one-hot-vector的情况下,转换为正确解标签的索引
if t.size == y.size:
t = t.argmax(axis=1)
batch_size = y.shape[0]
return -np.sum(np.log(y[np.arange(batch_size), t] + 1e-7)) / batch_size
def numerical_gradient(f, x):
h = 1e-4 # 0.0001
grad = np.zeros_like(x) # 初始化数组为0用来存放梯度
# 默认情况下,nditer将视待迭代遍历的数组为只读对象(read-only)
# 为了在遍历数组的同时,实现对数组元素值得修改,必须指定op_flags=['readwrite']模式。
# flags=['multi_index']表示对x进行多重索引
it = np.nditer(x, flags=['multi_index'], op_flags=['readwrite'])
while not it.finished:
# 把元素的索引(it.multi_index)赋值给idx
idx = it.multi_index
# 用来还原值
tmp_val = x[idx]
x[idx] = float(tmp_val) + h
fxh1 = f(x) # f(x+h)
x[idx] = tmp_val - h
fxh2 = f(x) # f(x-h)
grad[idx] = (fxh1 - fxh2) / (2 * h)
x[idx] = tmp_val # 还原值
it.iternext()
return grad
class TwoLayerNet:
# 模型初始化
def __init__(self, input_size, hidden_size, output_size, weight_init_std=0.01):
# 初始化权重
# 第一层的权重
# 第一层的偏置
# ##请添加网络第二层的权重和偏置的初始化代码
# 第2层的权重
# 第2层的偏置
self.params = {'W1': weight_init_std * np.random.randn(input_size, hidden_size), 'b1': weight_init_std * np.random.randn(hidden_size),
'W2': weight_init_std * np.random.randn(hidden_size, output_size), 'b2': weight_init_std * np.random.randn(output_size)}
# 模型前向传播过程
def forward(self, x):
# ##请从参数字典获取网络参数
w1 = self.params['W1']
w2 = self.params['W2']
b1 = self.params['b1']
b2 = self.params['b2']
# 实现第一层的运算
z1 = np.dot(x, w1) + b1
h1 = sigmoid(z1)
# ##请实现第二层的运算
z2 = np.dot(h1, w2) + b2
# z2 = sigmoid(z2)
return z2
# 定义损失函数
def loss(self, x, t): # x:输入数据, t:监督数据
y = self.forward(x)
z = softmax(y)
los = cross_entropy_error(z, t)
return los
# ##请补充计算并返回损失函数值的代码
# 计算预测的准确率
def accuracy(self, x, t): # 假定输入的数据x和标签t都是mini-batch形式的
# ##请补充实现模型前向输出的代码
y = self.forward(x)
y = softmax(y)
y = np.argmax(y, axis=1)
# ##请补充提取模型预测类别和标签真实类别的代码
if t.ndim != 1: t = np.argmax(t, axis=1)
# ##请补充计算并返回模型类别预测准确率的代码
acc = np.sum(y == t) / float(x.shape[0])
print('result:')
print(t)
print(y)
# print(x.shape[0])
return acc
# 通过数值微分的方式计算模型参数的梯度
'''def gradient(self, x, t):
# 定义字典形式的参数梯度
grads = {}
# ##请定义需传入numerical_gradient函数的需求梯度的函数
loss_W = lambda W: self.loss(x, t)
# ##请补充通过数值微分的方法计算参数W1、W2、b1、b2的梯度的代码
grads['W1'] = numerical_gradient(loss_W,self.params['W1'])
grads['b1'] = numerical_gradient(loss_W,self.params['b1'])
grads['W2'] = numerical_gradient(loss_W,self.params['W2'])
grads['b2'] = numerical_gradient(loss_W,self.params['b2'])
# 返回计算出的梯度
return grads'''
def gradient(self, x, t):
w1, w2 = self.params['W1'], self.params['W2']
b1, b2 = self.params['b1'], self.params['b2']
grads = {}
batch_num = x.shape[0]
# forward
a1 = np.dot(x, w1) + b1
z1 = sigmoid(a1)
a2 = np.dot(z1, w2) + b2
y = softmax(a2)
# backward
dy = (y - t) / batch_num
grads['W2'] = np.dot(z1.T, dy)
grads['b2'] = np.sum(dy, axis=0)
da1 = np.dot(dy, w2.T)
dz1 = (1.0 - sigmoid(a1)) * sigmoid(a1) * da1
grads['W1'] = np.dot(x.T, dz1)
grads['b1'] = np.sum(dz1, axis=0)
return grads
# 主函数
if __name__ == '__main__':
init_mnist()
(x_train, t_train), (x_test, t_test) = load_mnist(flatten=True,normalize=True,one_hot_label=True)
# print(t_train[0])
print(t_test[0])
# ##请补充实例化TwoLayerNet类创建network对象的代码
network = TwoLayerNet(input_size=784, hidden_size=100, output_size=10) # 在这里调整参数
# 定义训练循环迭代次数
iters_num = 1000
# 获取训练数据规模
train_size = x_train.shape[0]
# 定义训练批次大小
batch_size = 100
# 定义学习率
learning_rate = 0.1
# 创建记录模型训练损失值的列表
train_loss_list = []
# 创建记录模型在训练数据集上预测精度的列表
train_acc_list = []
# 创建记录模型在测试数据集上预测精度的列表
test_acc_list = []
# 计算一个epoch所需的训练迭代次数(一个epoch定义为所有训练数据都遍历过一次所需的迭代次数)
iter_per_epoch = max(train_size / batch_size, 1)
# print(train_size)
# ##请补充创建训练循环的代码
for i in range(int(iters_num)):
for j in range(int(iter_per_epoch)):
# 在每次训练迭代内部选择一个批次的数据
batch_mask = np.random.choice(train_size, batch_size)
x_batch = x_train[batch_mask]
t_batch = t_train[batch_mask]
# ##请补充计算梯度的代码
grad = network.gradient(x_batch, t_batch)
# ##请补充更新模型参数的代码
for key in ('W1', 'b1', 'W2', 'b2'): # 梯度更新
network.params[key] -= learning_rate * grad[key]
# ##请补充向train_loss_list列表添加本轮迭代的模型损失值的代码
loss = network.loss(x_batch, t_batch)
train_loss_list.append(loss)
# ##请补充向train_acc_list列表添加当前模型对于训练集预测精度的代码
train_acc = network.accuracy(x_train, t_train)
train_acc_list.append(train_acc)
# ##请补充向test_acc_list列表添加当前模型对于测试集预测精度的代码
test_acc = network.accuracy(x_test, t_test)
test_acc_list.append(test_acc)
# 输出一个epoch完成后模型分别在训练集和测试集上的预测精度以及损失值
print("iteration:{} ,train acc:{}, test acc:{} ,loss:{}|".format(i, train_acc, test_acc, loss))