sklearn學習之LR算法實踐

scikit-learn是python的一個機器學習算法集成模塊,功能強大,包含了常見的邏輯迴歸,決策樹,樸素貝葉斯,SVM等常見的機器學習算法。對於日常科研和工作上的處理,基本都可以滿足要求。

這裏,用最簡單的LR算法來做一下分類。算法細節不在文中介紹,大家參考網上資料,太多了。

import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.linear_model import stochastic_gradient
from sklearn.metrics import classification_report


# 數據總共8列,第一列是用戶id, 2-7列爲對應的特徵,第8列是label, 0或1
column_names = ['uin', 'gender', 'age', 'play_cnt', 'influence_pv', 'ds2', 'ds3', 'label']
data = pd.read_csv('lr_feature1.csv', names=column_names)

# 打印數據的信息、前十條數據、數據的維度
print(data.info())
print(data.head(10))
print(data.shape)

# 隨機採用25%的數據用於測試,剩下的75%的數據用於訓練集
# random_state是隨機數的種子,不同的種子會造成不同的隨機採樣結果,相同的種子採樣結果相同
X_train, X_test, y_train, y_test = train_test_split(data[column_names[1:6]], data[column_names[7]], test_size=0.25)

# 標準化數據,保證每個維度的特徵數據方差爲1,均值爲0。使得預測結果不會被某些維度過大的特徵值而主導。
ss = StandardScaler()
X_train = ss.fit_transform(X_train)
X_test = ss.transform(X_test)
print(pd.DataFrame(X_train).head(10))

# 3.使用邏輯斯蒂迴歸
lr = LogisticRegression()  # 初始化LogisticRegression
lr.fit(X_train, y_train)  # 使用訓練集對測試集進行訓練

print('Accuracy of LR Classifier:%f' % lr.score(X_test, y_test))  # 使得邏輯迴歸模型自帶的評分函數score獲得模型在測試集上的準確性結果
# print(classification_report(y_test, lr_y_predit, target_names=['high', 'low']))

# 4.使用邏輯斯蒂迴歸(基於隨機梯度下降法SGD)
sgdc = stochastic_gradient.SGDClassifier(max_iter=5)  # 初始化分類器
sgdc.fit(X_train, y_train)
sgdc_y_predit = sgdc.predict(X_test)
sgdc_y_predit_t = sgdc.predict(X_train)
print('Accuarcy of test data of SGD Classifier:', sgdc.score(X_test, y_test))
print(classification_report(y_test, sgdc_y_predit, target_names=['pos', 'neg']))

print('Accuracy of train data of SGD Classifier:', sgdc.score(X_train, y_train))
print(classification_report(y_train, sgdc_y_predit_t, target_names=['pos', 'neg']))

運行結果:

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 574030 entries, 0 to 574029
Data columns (total 8 columns):
uin             574030 non-null int64
gender          574030 non-null int64
age             574030 non-null int64
play_cnt        574030 non-null int64
influence_pv    574030 non-null int64
ds2             574030 non-null int64
ds3             574030 non-null int64
label           574030 non-null float64
dtypes: float64(1), int64(7)
memory usage: 35.0 MB
None
       uin  gender  age  play_cnt  influence_pv  ds2  ds3  label
0  1889812       2   67         2             0    2    2    0.0
1  1966339       2   69       747           194   15   30    1.0
2  1982539       2   66      1165            40   12   24    1.0
3  2131170       3   78        53           117    3   12    1.0
4  4471700       3   81         2             0    3    4    0.0
5  4921331       3   79      1634           178   15   30    1.0
6  5441180       3   68         0             0    4    4    0.0
7  6144422       2   79       109            25   14   24    1.0
8  6807020       3   72       418            90   11   22    1.0
9  7015648       3   76       144            15    7   18    1.0
(574030, 8)

          0         1         2
0  1.112735 -2.103642  0.710866
1 -0.887578  0.549115  0.210986
2 -0.887578  0.549115 -0.110037
3  1.112735  0.200068 -0.586987
4  1.112735 -0.498026 -0.653484
5 -0.887578 -0.009360  0.309586
6 -0.887578 -0.079170 -0.577815
7 -0.887578  0.967971  0.018372
8 -0.887578  0.269877  0.133023
9  1.112735  0.479305 -0.323289

Accuracy of LR Classifier:0.914088
Accuarcy of test data of SGD Classifier: 0.9194260947124899
              precision    recall  f1-score   support

         pos       0.89      0.94      0.91     63907
         neg       0.95      0.90      0.93     79601

   micro avg       0.92      0.92      0.92    143508
   macro avg       0.92      0.92      0.92    143508
weighted avg       0.92      0.92      0.92    143508

Accuracy of train data of SGD Classifier: 0.9211561778492156
              precision    recall  f1-score   support

         pos       0.89      0.94      0.91    192833
         neg       0.95      0.91      0.93    237689

   micro avg       0.92      0.92      0.92    430522
   macro avg       0.92      0.92      0.92    430522
weighted avg       0.92      0.92      0.92    430522

可以看到,訓練集和測試集的準確率和召回率都挺高的,sklearn模塊將算法都封裝好,只要簡單幾行代碼就可以處理億級別的樣本,這裏我們用的特徵比較少,前期對缺失值也都做了補0處理,實際有很多特徵是沒有值的,在訓練時需要對空值所特殊處理,捨棄或者填充其他值,這裏不再贅述,網上很多資料都有講。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章