本文實例講述了Python實現(xiàn)的邏輯回歸算法。分享給大家供大家參考,具體如下:
創(chuàng)新互聯(lián)成立10余年來,這條路我們正越走越好,積累了技術(shù)與客戶資源,形成了良好的口碑。為客戶提供成都網(wǎng)站建設(shè)、成都做網(wǎng)站、網(wǎng)站策劃、網(wǎng)頁設(shè)計、域名注冊、網(wǎng)絡(luò)營銷、VI設(shè)計、網(wǎng)站改版、漏洞修補等服務(wù)。網(wǎng)站是否美觀、功能強大、用戶體驗好、性價比高、打開快等等,這些對于網(wǎng)站建設(shè)都非常重要,創(chuàng)新互聯(lián)通過對建站技術(shù)性的掌握、對創(chuàng)意設(shè)計的研究為客戶提供一站式互聯(lián)網(wǎng)解決方案,攜手廣大客戶,共同發(fā)展進步。使用python實現(xiàn)邏輯回歸
Using Python to Implement Logistic Regression Algorithm
菜鳥寫的邏輯回歸,記錄一下學(xué)習(xí)過程
代碼:
#encoding:utf-8 """ Author: njulpy Version: 1.0 Data: 2018/04/10 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)