机器学习练习3-多类别逻辑回归和前馈神经网络

本文基于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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值