吴恩达机器学习ex3任务2代码

import numpy as np
import matplotlib.pyplot as plt
from scipy.io import loadmat
from sklearn.metrics import classification_report

'''函数部分'''

'''激活函数'''
def sigmoid(z):
    return 1 / (1 + np.exp(-z))





'''计算部分'''

'''数据导入X,y'''
data = loadmat('D:\新大陆\吴恩达机器学习\ex3\ex3data1')
X = data['X']
y = data['y']


'''数据导入theta'''
weight = loadmat('D:\新大陆\吴恩达机器学习\ex3\ex3weights.mat')
print(weight)
theta1 = weight['Theta1']
theta2 = weight['Theta2']
print(theta1.shape)   #25*401
print(theta2.shape)   #10*26
#以上两项都已经插入了偏置神经元


'''插入常数项'''
X = np.matrix(np.insert(X,0,values=np.ones(X.shape[0]),axis=1))
y = np.matrix(y)
print(X.shape)   #5000*401
print(y.shape)   #5000*1


'''计算隐藏层'''
a1 = X
z2 = a1 * theta1.T
a2 = sigmoid(z2)
a2 = np.insert(a2,0,values=np.ones(a2.shape[0]),axis=1)   #注意,每次换层都要加一个偏置神经元
z3 = a2 * theta2.T
a3 = sigmoid(z3)   #a3的值即由假设函数推出的h(x)
print(a3)

y_pred2 = np.argmax(a3,axis=1)+1   #5000*1
print(classification_report(y,y_pred2))   #真实值和预测值之间的比较
'''
        precision    recall  f1-score   support

           1       0.97      0.98      0.98       500
           2       0.98      0.97      0.98       500
           3       0.98      0.96      0.97       500
           4       0.97      0.97      0.97       500
           5       0.97      0.98      0.98       500
           6       0.98      0.99      0.98       500
           7       0.98      0.97      0.97       500
           8       0.98      0.98      0.98       500
           9       0.97      0.96      0.96       500
          10       0.98      0.99      0.99       500

    accuracy                           0.98      5000
   macro avg       0.98      0.98      0.98      5000
weighted avg       0.98      0.98      0.98      5000
'''
'''
precision表示精度=TP/(TP+FP)
recall表示召回率或者敏感度,sensitivity=TP/(TP+FN)
'''

部分代码参考大佬:顾道长生'。感谢所有机器学习道路上的引路人。

你可能感兴趣的:(吴恩达机器学习作业,python)