2019-08-26 13:26:13 3699瀏覽
本篇文章扣丁學(xué)堂Python培訓(xùn)主要給小伙伴們介紹Python實(shí)現(xiàn)的邏輯回歸算法,,文中結(jié)合具體實(shí)例形式進(jìn)行分析Python邏輯回歸算法相關(guān)實(shí)現(xiàn)技巧,需要的朋友或者是對Python開發(fā)技術(shù)感興趣的小伙伴可以參考一下。
使用python實(shí)現(xiàn)邏輯回歸
Using Python to Implement Logistic Regression Algorithm
代碼:
#encoding:utf-8 """ Author: njulpy Version: 1.0 Data: 2019/08/26 Project: Using Python to Implement LogisticRegression Algorithm """ import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split #建立sigmoid函數(shù) def sigmoid(x): x = x.astype(float) return 1./(1+np.exp(-x)) #訓(xùn)練模型,采用梯度下降算法 def train(x_train,y_train,num,alpha,m,n): beta = np.ones(n) for i in range(num): h=sigmoid(np.dot(x_train,beta)) #計算預(yù)測值 error = h-y_train.T #計算預(yù)測值與訓(xùn)練集的差值 delt=alpha*(np.dot(error,x_train))/m #計算參數(shù)的梯度變化值 beta = beta - delt #print('error',error) return beta def predict(x_test,beta): y_predict=np.zeros(len(y_test))+0.5 s=sigmoid(np.dot(beta,x_test.T)) y_predict[s < 0.34] = 0 y_predict[s > 0.67] = 1 return y_predict def accurancy(y_predict,y_test): acc=1-np.sum(np.absolute(y_predict-y_test))/len(y_test) return acc if __name__ == "__main__": data = pd.read_csv('iris.csv') x = data.iloc[:,1:5] y = data.iloc[:,5].copy() y.loc[y== 'setosa'] = 0 y.loc[y== 'versicolor'] = 0.5 y.loc[y== 'virginica'] = 1 x_train,x_test,y_train,y_test = train_test_split(x,y,test_size=0.3,random_state=15) m,n=np.shape(x_train) alpha = 0.01 beta=train(x_train,y_train,1000,alpha,m,n) pre=predict(x_test,beta) t = np.arange(len(x_test)) plt.figure() p1 = plt.plot(t,pre) p2 = plt.plot(t,y_test,label='test') label = ['prediction', 'true'] plt.legend(label, loc=1) plt.show() acc=accurancy(pre,y_test) print('The predicted value is ',pre) print('The true value is ',np.array(y_test)) print('The accuracy rate is ',acc)
輸出結(jié)果:
The predicted value is [ 0. 0.5 1. 0. 0. 1. 1. 0.5 1. 1. 1. 0.5 0.5 0.5 1.
0. 0.5 1. 0. 1. 0.5 0. 0.5 0.5 0. 0. 1. 1. 1. 1.
0. 1. 1. 1. 0. 0. 1. 0. 0. 0.5 1. 0. 0. 0.5 1. ]
The true value is [0 0.5 0.5 0 0 0.5 1 0.5 0.5 1 1 0.5 0.5 0.5 1 0 0.5 1 0 1 0.5 0 0.5 0.5 0
0 1 1 1 0.5 0 1 0.5 1 0 0 1 0 0 0.5 1 0 0 0.5 1]
The accuracy rate is 0.9444444444444444
想要了解更多關(guān)于Python和人工智能方面內(nèi)容的小伙伴,請關(guān)注扣丁學(xué)堂Python培訓(xùn)官網(wǎng)、微信等平臺,扣丁學(xué)堂IT職業(yè)在線學(xué)習(xí)教育平臺為您提供權(quán)威的Python開發(fā)環(huán)境搭建視頻,Python培訓(xùn)后的前景無限,行業(yè)薪資和未來的發(fā)展會越來越好的,扣丁學(xué)堂老師精心推出的Python視頻教程定能讓你快速掌握Python從入門到精通開發(fā)實(shí)戰(zhàn)技能??鄱W(xué)堂Python技術(shù)交流群:279521237。
【關(guān)注微信公眾號獲取更多學(xué)習(xí)資料】 【掃碼進(jìn)入Python全棧開發(fā)免費(fèi)公開課】