题设
题设如本文章所带PDF文件所示,训练数据集以及Theta不予提供。实现平台:Jupyter notebook。
代码实现
import numpy as np
import pandas as pd
import os
import matplotlib.pyplot as plt
from scipy.io import loadmat
#进行数据读取
data = np.loadtxt('D:\Softwares\Git\ML-2024Spring\Lab3-NN\ex3data1.txt',delimiter=',')
X=data[:,0:400]
y=data[:,[400]]
theta1=np.loadtxt('D:\Softwares\Git\ML-2024Spring\Lab3-NN\\theta1.txt',delimiter=',')
theta2=np.loadtxt('D:\Softwares\Git\ML-2024Spring\Lab3-NN\\theta2.txt',delimiter=',')
print(X.shape, y.shape, theta1.shape, theta2.shape)
def displayData(x):
indexs = np.random.choice(X.shape[0],100)
images=x[indexs]
fig,axs=plt.subplots(10,10,figsize=(20,20))
for row in range(10):
for col in range(10):
axs[row,col].matshow(images[row*10+col].reshape(20,20).T,cmap='gray_r')
plt.show()
displayData(X)
#定义sigmoid函数
def sigmoid(z):
return (1.0/(1.0+np.exp(-z)))
#定义前向传播函数
def feedforward_propagation(X,Theta1,Theta2):
# a1 part
a0=np.ones(1)
a1=np.hstack((a0,X))
# a2 part
z2=Theta1@a1
a2=sigmoid(z2)
a2=np.hstack((a0,a2))
# a3 part
z3=Theta2@a2
a3=sigmoid(z3)
return a3
#定义预测函数
def predict(a3):
#特别注意,label的范围是1~10,要记得给索引+1
return np.argmax(a3)+1
#完成实际标签与预测标签的准确度对比的统计
def accuracy(X,y):
sum_num = 0
for i in range(y.size):
if(y[i] == predict(feedforward_propagation(X[i],theta1,theta2))):
sum_num += 1
return sum_num/y.size
accuracy(X,y)