日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python机械编程_机器学习编程作业3——多类分类(Python版)

發布時間:2024/9/19 python 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python机械编程_机器学习编程作业3——多类分类(Python版) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

本次編程作業的實現環境是Python3、Anaconda3(64-bit)、Jupyter Notebook。是在深度之眼“機器學習訓練營”作業基礎上完成的,個別代碼有修改,供交流學習之用。

編程作業 3 - 多類分類?

對于此練習,我們將使用邏輯回歸來識別手寫數字(0到9)。 我們將擴展我們在練習2中寫的邏輯回歸的實現,并將其應用于一對一的分類。 讓我們開始加載數據集。 它是在MATLAB的本機格式,所以要加載它在Python,我們需要使用一個SciPy工具。

import numpy as np

import pandas as pd

import matplotlib.pyplot as plt

from scipy.io import loadmat

data = loadmat('ex3data1.mat')

data

Out[84]:

{'__header__': b'MATLAB 5.0 MAT-file, Platform: GLNXA64, Created on: Sun Oct 16 13:09:09 2011',

'__version__': '1.0',

'__globals__': [],

'X': array([[0., 0., 0., ..., 0., 0., 0.],

[0., 0., 0., ..., 0., 0., 0.],

[0., 0., 0., ..., 0., 0., 0.],

...,

[0., 0., 0., ..., 0., 0., 0.],

[0., 0., 0., ..., 0., 0., 0.],

[0., 0., 0., ..., 0., 0., 0.]]),

'y': array([[10],

[10],

[10],

...,

[ 9],

[ 9],

[ 9]], dtype=uint8)}

In [85]:

data['X'].shape, type(data['X']), data['y'].shape, type(data['y'])

#len(data['X'])

Out[85]:

((5000, 400), numpy.ndarray, (5000, 1), numpy.ndarray)

sigmoid 函數

def sigmoid(z):

return 1 / (1 + np.exp(-z))

代價函數

def cost(theta, X, y, learningRate):

# INPUT:參數值theta,數據X,標簽y,學習率

# OUTPUT:當前參數值下的交叉熵損失

# TODO:根據參數和輸入的數據計算交叉熵損失函數

# STEP1:將theta, X, y轉換為numpy類型的矩陣

# your code here (appro ~ 3 lines)

theta = np.matrix(theta)

X = np.matrix(X)

y = np.matrix(y)

# STEP2:根據公式計算損失函數(不含正則化)

# your code here (appro ~ 2 lines)

cross_cost = -1/len(X) * (y.T * np.log(sigmoid(X * theta.T)) + (1 - y.T) * np.log(1-sigmoid(X * theta.T)))

#cross_cost = -1/len(X) * np.sum(np.multiply(y, np.log(sigmoid(X * theta.T))) + np.multiply((1 - y), np.log(1 - sigmoid(X * theta.T))))

# STEP3:根據公式計算損失函數中的正則化部分

# your code here (appro ~ 1 lines),應使theta0為0(theta從1開始計算?)

reg = learningRate / (2*len(X)) * (np.power(theta[1:], 2).sum())

#reg = (learningRate / (2 * len(X))) * np.sum(np.power(theta[1:], 2))

# STEP4:把上兩步當中的結果加起來得到整體損失函數

# your code here (appro ~ 1 lines)

whole_cost = cross_cost + reg

return whole_cost

向量化的梯度函數

#X = np.insert(data['X'], 0, values=np.ones(5000), axis=1)

#y = data['y']

#theta = np.zeros(401)

#learningRate =1

def gradient(theta, X, y, learningRate):

# INPUT:參數值theta,數據X,標簽y,學習率

# OUTPUT:當前參數值下的梯度

# TODO:根據參數和輸入的數據計算梯度

# STEP1:將theta, X, y轉換為numpy類型的矩陣

# your code here (appro ~ 3 lines)

theta = np.matrix(theta)

X = np.matrix(X)

y = np.matrix(y)

?

# STEP2:將theta矩陣拉直(轉換為一個向量)

# your code here (appro ~ 1 lines)

#parameters = theta.ravel()

# STEP3:計算預測的誤差

# your code here (appro ~ 1 lines)

error = sigmoid(X @ theta.T) - y

# STEP4:根據上面的公式計算梯度

# your code here (appro ~ 1 lines)

grad1 = (1/len(X)) * X.T @ error

#grad = ((X.T * error) / len(X)).T + ((learningRate / len(X)) * theta)

# STEP5:由于j=0時不需要正則化,所以這里重置一下

# your code here (appro ~ 1 lines)

reg = learningRate / len(X) * theta[0,1:].T

grad1[1:,0] += reg

grad = grad1

#grad[0, 0] = np.sum(np.multiply(error, X[:,0])) / len(X)

return np.array(grad).ravel()

構建分類器:

有10個可能的類,并且由于邏輯回歸只能一次在2個類之間進行分類,我們需要多類分類的策略。 在本練習中,實現一對一全分類方法,其中具有k個不同類的標簽就有k個分類器,每個分類器在“類別 i”和“不是 i”之間決定。 我們將把分類器訓練包含在一個函數中,該函數計算10個分類器中的每個分類器的最終權重,并將權重返回為k X(n + 1)數組,其中n是參數數量。

from scipy.optimize import minimize

?

def one_vs_all(X, y, num_labels, learning_rate):

rows = X.shape[0]

params = X.shape[1]

# k X (n + 1) array for the parameters of each of the k classifiers

all_theta = np.zeros((num_labels, params + 1))

# insert a column of ones at the beginning for the intercept term

X = np.insert(X, 0, values=np.ones(rows), axis=1)

# labels are 1-indexed instead of 0-indexed

for i in range(1, num_labels + 1):

theta = np.zeros(params + 1)

y_i = np.array([1 if label == i else 0 for label in y])

y_i = np.reshape(y_i, (rows, 1)) #變為rows行1列的形式

# minimize the objective function

fmin = minimize(fun=cost, x0=theta, args=(X, y_i, learning_rate), method='TNC', jac=gradient, options={'disp': True})

all_theta[i-1,:] = fmin.x

return all_theta

實現向量化代碼的一個更具挑戰性的部分是正確地寫入所有的矩陣,保證維度正確。

rows = data['X'].shape[0]

params = data['X'].shape[1]

?

all_theta = np.zeros((10, params + 1))

?

X = np.insert(data['X'], 0, values=np.ones(rows), axis=1)

?

theta = np.zeros(params + 1)

?

y_0 = np.array([1 if label == 0 else 0 for label in data['y']])

y_0 = np.reshape(y_0, (rows, 1))

?

X.shape, type(X), y_0.shape, type(y_0), theta.shape, type(theta), all_theta.shape, type(all_theta)

Out[90]:

((5000, 401),

numpy.ndarray,

(5000, 1),

numpy.ndarray,

(401,),

numpy.ndarray,

(10, 401),

numpy.ndarray)

In [91]:

np.unique(data['y'])#看下有幾類標簽

Out[91]:

array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], dtype=uint8)

讓我們確保我們的訓練函數正確運行,并且得到合理的輸出。

data['X'].shape, type(data['X']), data['y'].shape, type(data['y'])

Out[92]:

((5000, 400), numpy.ndarray, (5000, 1), numpy.ndarray)

In [93]:

all_theta = one_vs_all(data['X'], data['y'], 10, 1)

print('theta:',all_theta.shape,)

最后一步 - 使用訓練完畢的分類器預測每個圖像的標簽。 對于這一步,我們將計算每個類的類概率,對于每個訓練樣本(使用當然的向量化代碼),并將輸出類標簽為具有最高概率的類。

def predict_all(X, all_theta):

# INPUT:參數值theta,測試數據X

# OUTPUT:預測值

# TODO:對測試數據進行預測

# STEP1:獲取矩陣的維度信息

rows = X.shape[0]

#params = X.shape[1]

#num_labels = all_theta.shape[0]

# STEP2:把矩陣X加入一列壹元素

# your code here (appro ~ 1 lines)

X = np.insert(X, 0, values=np.ones(rows), axis=1)

# STEP3:把矩陣X和all_theta轉換為numpy型矩陣

# your code here (appro ~ 2 lines)

#X = np.matrix(X)

#all_theta = np.matrix(theta)

# STEP4:計算樣本屬于每一類的概率

# your code here (appro ~ 1 lines)

h = sigmoid(X @ all_theta.T)

# STEP5:找到每個樣本中預測概率最大的值

# your code here (appro ~ 1 lines)

h_argmax = np.argmax(h, axis=1)

# STEP6:因為我們的數組是零索引的,所以我們需要為真正的標簽+1

h_argmax = h_argmax + 1

return h_argmax

現在我們可以使用predict_all函數為每個實例生成類預測,看看我們的分類器是如何工作的。

y_pred = predict_all(data['X'], all_theta)

correct = [1 if a == b else 0 for (a, b) in zip(y_pred, data['y'])]

accuracy = (sum(map(int, correct)) / float(len(correct)))

print ('accuracy = {0}%'.format(accuracy * 100))

輸出的準確率應為94.46%。

總結

以上是生活随笔為你收集整理的python机械编程_机器学习编程作业3——多类分类(Python版)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。