一、神经网络
在前面的练习中,你实现了神经网络的前馈传播,并利用它预测手写数字的权重。在这个练习中,你将实现反向传播算法来学习神经网络的参数。
1.1 Visualizing the data(可视化数据)
这与您在上一次练习中使用的数据集相同。在ex3data1.mat中有5000个训练示例,其中每个训练示例是20像素乘20像素的数字灰度图像。像素用浮点数表示,表示该位置的灰度强度。20×20像素网格被“展开”成400维矢量。每一次训练数据矩阵X中的一行。
它给出了一个5000×400矩阵X,其中每一行都是手写数字映像的训练示例。训练集的第二部分是包含训练集标签的5000维向量y。“0”数字被标记为“10”,而数字“1”到“9”则被标记为“1”到“9”。’’’
import matplotlib.pyplot as plt
import numpy as np
import scipy.io as scio #引入读取.mat文件的库
import scipy.optimize as opt
#import displayData as dd
plt.ion()
input_layer_size=400 #输入特征的维度 每张数字图片20*20=400
hidden_layer_size=25 #隐含层的个数为25
num_labels=10 #10个标签 注意“0”对应第十个标签 1-9一次对应第1-9个标签
data=scio.loadmat('ex4data1.mat')#读取训练集 包括两部分 输入特征和标签
X=data['X']#提取输入特征 5000*400的矩阵 5000个训练样本 每个样本特征维度为400 一行代表一个训练样本
y=data['y'].flatten() #提取标签 data['y']是一个5000*1的2维数组 利用flatten()将其转换为有5000个元素的一维数组
y_raw=data['y'].flatten()
编写可视化数据集的程序:
def display_data(x):
(m, n) = x.shape #100*400
example_width = np.round(np.sqrt(n)).astype(int) #每个样本显示宽度 round()四舍五入到个位 并转换为int
example_height = (n / example_width).astype(int) #每个样本显示高度 并转换为int
#设置显示格式 100个样本 分10行 10列显示
display_rows = np.floor(np.sqrt(m)).astype(int)#floor(x),其功能是“向下取整”,下取整是直接去掉小数部分。
display_cols = np.ceil(m / display_rows).astype(int)#ceil(x),其功能是向上取整。
# 待显示的每张图片之间的间隔
pad = 1
# 显示的布局矩阵 初始化值为-1
display_array = - np.ones((pad + display_rows * (example_height + pad),
pad + display_rows * (example_height + pad)))
# Copy each example into a patch on the display array
curr_ex = 0
for j in range(display_rows):
for i in range(display_cols):
if curr_ex > m:
break
# Copy the patch
# Get the max value of the patch
max_val = np.max(np.abs(x[curr_ex]))
display_array[pad + j * (example_height + pad) + np.arange(example_height),
pad + i * (example_width + pad) + np.arange(example_width)[:, np.newaxis]] = \
x[curr_ex].reshape((example_height, example_width)) / max_val
curr_ex += 1
if curr_ex > m:
break
# 显示图片
plt.figure()
plt.imshow(display_array, cmap='gray', extent=[-1, 1, -1, 1])
plt.axis('off')
加载数据在上面的display_data(x)函数上:
m = y.size #训练样本的数量
# 随机抽取100个训练样本 进行可视化
rand_indices = np.random.permutation(range(m)) #获取0-4999 5000个无序随机索引
selected = X[rand_indices[0:100], :] #获取前100个随机索引对应的整条数据的输入特征
display_data(selected) #调用可视化函数 进行可视化
运行结果: