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

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

逻辑回归(二)

發(fā)布時間:2023/12/4 编程问答 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 逻辑回归(二) 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

邏輯回歸

在學(xué)習(xí)邏輯回歸之前我們先回顧一下線性回歸。線性回歸解決的是回歸問題,簡單來說就是,我們需要找到一個函數(shù),這個函數(shù)需要盡可能的擬合所有訓(xùn)練集的樣本點。

邏輯回歸解決的是分類問題,它的目標(biāo)是找到一個函數(shù),利用這個函數(shù)盡可能把不同種類的數(shù)據(jù)區(qū)分開來。利用sigmod激活函數(shù)可以將前面類似線性回歸的計算結(jié)果映射為離散值。

通過激活函數(shù)我們可以將下面圖片中不同位置的點映射為不同的離散值。
需要注意:這個圖橫縱坐標(biāo)都是自變量X,跟上面的線性回歸是有區(qū)別的。
![在這里插入圖片描述](https://img-blog.csdnimg.cn/743fbcb1b1204c91be6cbd24d37fd010.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA6Zi_5p2-5Li2,size_20,color_FFFFFF,t_70,g_se,x_16

import matplotlib.pyplot as plt import numpy as np from sklearn.metrics import classification_report from sklearn import preprocessing # 數(shù)據(jù)是否需要標(biāo)準(zhǔn)化 scale = False# 畫圖正常顯示中文 plt.rcParams['font.sans-serif'] = ['SimHei'] # 用來正常顯示中文標(biāo)簽 plt.rcParams['axes.unicode_minus'] = False # 用來正常顯示負(fù)號def sigmoid(x):return 1.0 / (1 + np.exp(-x))def cost(xMat, yMat, ws):left = np.multiply(yMat, np.log(sigmoid(xMat * ws)))right = np.multiply(1 - yMat, np.log(1 - sigmoid(xMat * ws)))return np.sum(left + right) / -(len(xMat))def gradAscent(xArr, yArr):if scale == True:xArr = preprocessing.scale(xArr)xMat = np.mat(xArr)yMat = np.mat(yArr)# 學(xué)習(xí)率lr = 0.001# 迭代次數(shù)epochs = 10000# 申明一個列表用來存儲losscostList = []# 計算數(shù)據(jù)行列數(shù)# 行代表數(shù)據(jù)個數(shù),列代表權(quán)值個數(shù)m, n = np.shape(xMat)# 初始化權(quán)值ws = np.mat(np.ones((n, 1)))for i in range(epochs + 1):# xMat和weights矩陣相乘h = sigmoid(xMat * ws)# 計算誤差ws_grad = xMat.T * (h - yMat) / mws = ws - lr * ws_gradif i % 50 == 0:costList.append(cost(xMat, yMat, ws))return ws, costListdef plot(x_data, y_data):x0 = []x1 = []y0 = []y1 = []# 切分不同類別的數(shù)據(jù)for i in range(len(x_data)):if y_data[i] == 0:x0.append(x_data[i, 0])y0.append(x_data[i, 1])else:x1.append(x_data[i, 0])y1.append(x_data[i, 1])# 畫圖scatter0 = plt.scatter(x0, y0, c='b', marker='o')scatter1 = plt.scatter(x1, y1, c='r', marker='x')# 畫圖例plt.title("訓(xùn)練數(shù)據(jù)集散點分布")plt.xlabel("自變量:x0")plt.ylabel("自變量:x1")plt.legend(handles=[scatter0, scatter1], labels=['label0', 'label1'], loc='best')plt.savefig("LR_scatter.png")# plt.show()def plot_result(ws,x_data,y_data):# 畫圖決策邊界plot(x_data,y_data)x_test = [[-4],[3]]y_test = (-ws[0] - x_test*ws[1])/ws[2]plt.plot(x_test, y_test, 'k')plt.savefig("LR_result.png")plt.show()def plot_loss(costList):# 畫圖 loss值的變化x = np.linspace(0, 10000, 201)plt.plot(x, costList, c='r')plt.title('Train')plt.xlabel('Epochs')plt.ylabel('Cost')plt.savefig("LR_Loss.png")plt.show()# 預(yù)測 def predict(x_data, ws):if scale == True:x_data = preprocessing.scale(x_data)xMat = np.mat(x_data)ws = np.mat(ws)return [1 if x >= 0.5 else 0 for x in sigmoid(xMat*ws)]def train():# 載入數(shù)據(jù)data = np.genfromtxt("LR-testSet.csv", delimiter=",")x_data = data[:, :-1]y_data = data[:, -1]# 繪制散點圖plot(x_data, y_data)# 數(shù)據(jù)處理,添加偏置項x_data = data[:, :-1]y_data = data[:, -1, np.newaxis]print("x_data的數(shù)據(jù)形狀為:", np.mat(x_data).shape)print("y_data的數(shù)據(jù)形狀為:", np.mat(y_data).shape)# 給樣本添加偏置項X_data = np.concatenate((np.ones((100, 1)), x_data), axis=1)print("x_data添加偏執(zhí)后X_data的數(shù)據(jù)形狀為:", X_data.shape)# 訓(xùn)練模型,得到權(quán)值和cost值的變化ws, costList = gradAscent(X_data, y_data)print("訓(xùn)練后得到的權(quán)值列表為:", ws)print("保存決策邊界結(jié)果圖像")plot_result(ws, x_data, y_data)predictions = predict(X_data, ws)print(classification_report(y_data, predictions))print("保存loss下降結(jié)果……")plot_loss(costList)if __name__ == '__main__':train()

運行結(jié)果:
x_data的數(shù)據(jù)形狀為: (100, 2)
y_data的數(shù)據(jù)形狀為: (100, 1)
x_data添加偏執(zhí)后X_data的數(shù)據(jù)形狀為: (100, 3)
訓(xùn)練后得到的權(quán)值列表為: [[ 2.05836354]
[ 0.3510579 ]
[-0.36341304]]
保存決策邊界結(jié)果圖像
precision recall f1-score support

0.0 0.82 1.00 0.90 471.0 1.00 0.81 0.90 53accuracy 0.90 100

macro avg 0.91 0.91 0.90 100
weighted avg 0.92 0.90 0.90 100

保存loss下降結(jié)果……

輸出圖片:

總結(jié)

以上是生活随笔為你收集整理的逻辑回归(二)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。