导入数据
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from scipy.io import loadmat
data=loadmat('ex4data1.mat')
data
{'__header__': b'MATLAB 5.0 MAT-file, Platform: GLNXA64, Created on: Sun Oct 16 13:09:09 2011',
'__version__': '1.0',
'__globals__': [],
'X': array([[0., 0., 0., ..., 0., 0., 0.],
[0., 0., 0., ..., 0., 0., 0.],
[0., 0., 0., ..., 0., 0., 0.],
...,
[0., 0., 0., ..., 0., 0., 0.],
[0., 0., 0., ..., 0., 0., 0.],
[0., 0., 0., ..., 0., 0., 0.]]),
'y': array([[10],
[10],
[10],
...,
[ 9],
[ 9],
[ 9]], dtype=uint8)}
X=data['X']
y=data['y']
X.shape,y.shape
((5000, 400), (5000, 1))
对y进行onehot编码
from sklearn.preprocessing import OneHotEncoder
encoder=OneHotEncoder(sparse=False)
y_onehot=encoder.fit_transform(y)
y_onehot.shape
(5000, 10)
y[0]
array([10], dtype=uint8)
y_onehot[0,:]
array([0., 0., 0., 0., 0., 0., 0., 0., 0., 1.])
模型实现
我们要为此练习构建的神经网络具有与我们的实例数据(400 +偏置单元)大小匹配的输入层,25个单位的隐藏层(带有偏置单元的26个),以及一个输出层, 10个单位对应我们的一个one-hot编码类标签。
#定义sigmoid函数
def sigmoid(z):
return 1.0/(1.0+np.exp(-z))
#定义前向传播函数
def forward_propagate(X,theta1,theta2):
#获取样本数
m=X.shape[0]
#实现正向传播
a1=np.insert(X,0,values=np.ones(m),axis=1)#插入1列全为1的元素
z2=a1*theta1.T
a2=np.insert(sigmoid(z2),0,values=np.ones(m),axis=1)
z3=a2*theta2.T
h=sigmoid(z3)
return a1,z2,a2,z3,h
#定义代价函数
def cost(params,input_size,hidden_size,num_labels,X,y,lamda):
# INPUT:神经网络参数,输入层维度,隐藏层维度,训练数据及标签,正则化参数
# OUTPUT