import numpy as np
from scipy.io import loadmat
def sigmoid(z):
z=np.matrix(z)
return 1/(1+np.exp(-z))
def predict(theta1,theta2,x):
#theta1:25*401 输入层多一个偏置项
#theta2:10*26 隐藏层多一个偏置项
m=x.shape[0] #样本数
num_labels=theta2.shape[0] #类别数
theta1=np.matrix(theta1)
theta2=np.matrix(theta2)
x=np.matrix(x)
x=np.c_[np.ones((m,1)),x]
z1=x*theta1.T
a1=sigmoid(z1)
a1=np.c_[np.ones((m,1)),a1]
z2=a1*theta2.T
a2=sigmoid(z2)
p=np.argmax(a2,axis=1)
p+=1
return p;
def predictOfPercent(theta1,theta2,X,y):
p=predict(theta1,theta2,X)
count=0
size=len(X)
for i in range(size):
if(p[i]==y[i]):
count+=1
print(count/float(len(y))*100)
theta=loadmat('E:\\machine learning\\homework3\\ex3weights.mat')
theta1=theta['Theta1']
theta2=theta['Theta2']
data=loadmat('E:\\machine learning\\homework3\\ex3data1.mat')
X=data['X']
y=data['y']
predictOfPercent(theta1,theta2,X,y)