本文基于Andrew_Ng的ML课程作业
1-Logistic Regression in multi-class classification problem:One_vs_All Classifier:使用一对一全分类方法,有k个不同类的标签就有k个分类器,每个分类器在"类别i"和"不是i"之间决定;我们把分类器训练包含在一个函数中,该函数计算10个分类器中的每个分类器的权重,最终实现手写数字0~9的识别
导入库
import numpy as np
import matplotlib.pyplot as plt
from scipy.io import loadmat
import scipy.optimize as opt
from sklearn.metrics import classification_report
函数:Sigmoid函数
def sigmoid(z): #Sigmoid函数
return 1/(1+np.exp(-z))
函数:计算正则化的代价函数J(theta)
def computeRegCost(theta,X,y,lambada): #计算正则化的代价函数J(theta)
theta=np.matrix(theta)
X=np.matrix(X)
y=np.matrix(y)
first=np.multiply(-y,np.log(sigmoid(X*theta.T)))
second=np.multiply((1-y),np.log(1-sigmoid(X*theta.T)))
reg=(lambada/(2*len(X)))*np.sum(np.power(theta[:,1:theta.shape[1]],2)) #matrix[:,1:matrix.shape[1]]:取矩阵的第一列直到最后一列(左闭右闭)
return np.sum(first-second)/len(X)+reg
函数:计算正则化的梯度grad
def computeRegGradient(theta,X,y,lambada): #计算正则化的梯度grad
theta = np.matrix(theta)
X = np.matrix(X)
y = np.matrix(y)
parameters=int(theta.ravel().shape[1])
grad = np.zeros(parameters)
error=(sigmoid(X*theta.T))-y
for i in range(parameters):
term=np.multiply(error,X[:,i])
if (i==0): #theta_0的梯度单独更新
gr