NKUMachineLearning-lab3.1-神经网络前向传播

题设

题设如本文章所带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)
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值