3.1前馈神经网络
使用前馈神经网络来识别手写数字(从0到9)。数据集MNIST手写体数据集,这里包含了5000个训练样本。之前用逻辑回归进行多元分类,这次用前馈神经网络进行预测。shen
神经网络:
类似于神经元细胞体,通过类似于树突的输入通道传递给神经元信息让它工作,再通过类似于轴突的输出通道输出结果。h在这里称为激活函数(activation function),我们称这个逻辑单元(logistic unit)是一个带激活函数的人工神经元(artificial neuron)。在激活函数中的参数又叫模型的权重。
Layer1 输入层,Layer2隐藏层 Layer3输出层 X0偏置神经元(值为1)
:权重矩阵:控制j->j+1的映射, :激活项
前向传播:输入特征值,a1 = , =a1 , 激活项=,每一层重复此过程,直到得到预测值
扫描二维码关注公众号,回复:
17186227 查看本文章
神经网络中没有用输入特征来训练逻辑回归,而是用自己训练出更加复杂的特征项作为输入
1 读取数据集,调取数据
# 案例:手写数字识别
# 说明:利用神经网络(前向传播)来实现ex_2里的问题。已经给定了最优的权重参数
import numpy as np
import matplotlib.pyplot as plt
import scipy.io as sio
path = 'ex3data1.mat'
data = sio.loadmat(path)
raw_X = data['X']
raw_y = data['y']
data.keys()
#dict_keys(['__header__', '__version__', '__globals__', 'X', 'y'])
X = np.insert(raw_X, 0, values=1, axis=1)#加入一列偏执单元,数值为1
print(X.shape)# (5000,401)
y = raw_y.flatten()
print(y.shape)# (5000,)
# 权重
theta = sio.loadmat('ex3weights.mat')
theta
print(theta.keys())
#dict_keys(['__header__', '__version__', '__globals__', 'Theta1', 'Theta2'])
theta1 = theta['Theta1']
theta2 = theta['Theta2']
# (25, 401) (10, 26)
print(theta1.shape, theta2.shape)
2 实现前向传播
def sigmoid(z):
return 1 / (1 + np.exp(-z))
a1 = X # 第一层
z2 = X @ theta1.T
a2 = sigmoid(z2)
print(a2.shape) # (5000, 25)
a2 = np.insert(a2, 0, values=1, axis=1)
print(a2.shape) # (5000, 26)
z3 = a2 @ theta2.T
a3 = sigmoid(z3)
print(a3.shape) # (5000, 10)
3 预测和精度
# np.argmax 排序索引(max方向)
y_pred = np.argmax(a3, axis=1)#按行方向搜索最大值 并返回其索引位置
y_pred = y_pred + 1#再加1就是对应的类别
acc = np.mean(y_pred == y)
#1、 x == y表示两个数组中的值相同时,输出True;否则输出False
#2、对y_pred == y结果取平均值,其中True=1,False=0;
print(acc) # 0.9752