sklearn通常流程

sklearn

Key_Wordpython

數據獲取: sklearn, datasets, DataFrame, load_*數組

數據標準化: preprocessing, MinMaxScaler, scaler, fit, transform, data, target函數

劃分測試集: model_selection, train_test_split, test_size測試

訓練模型: fit ,predict, kernel="linear"probability=True優化

模型評估: score, predict_proba編碼

使用metrics模塊評估: classification_reportspa

使用交叉驗證方法評估: cross_val_scorecode

模型的優化: GridSearchCV, C, kernel, gamma, param_grid, svc, cvorm

模型持久化: pikle, joblib, dump, loadblog

sklearn數據獲取

# In[1]:
import sklearn

# In[2]:
sklearn.__version__

# In[6]:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
get_ipython().run_line_magic('matplotlib', 'inline')
#在jupyter中可視化的展現圖形
from sklearn import datasets    #從sklearn導入數據集

iris = datasets.load_iris()


# In[10]:
iris
iris.data
iris['target']


# In[17]:
# 利用dataframe作簡單的可視化分析
df = pd.DataFrame(iris.data, columns = iris.feature_names)    # 是一個表格 
df['target'] = iris.target    # 表頭字段就是key
df.plot(figsize = (12, 8))

 

數據的預處理

數據的標準化: 將每個數值調整到某一個數量級下

from sklearn import preprocessing
# sklearn的數據標準化都在preprocessing下

數據的歸一化

數據的二值化

非線性轉換

數據特徵編碼

處理缺失值

 

數據標準化

Key_Word

preprocessing, MinMaxScaler, scaler, fit, transform, data, target

from sklearn import preprocessing
scaler = preprocessing.MinMaxScaler()    # scaler: 定標器  
# MinMaxScaler將樣本特徵值線性縮放到0,1之間
scaler.fit(iris.data)    # 先fit
data = scaler.transform(iris.data)    # 再transform    也能夠二合一寫成fit_transform
target = iris.target

 

模型選擇

帶標籤的屬於分類問題, 樣本數量爲150小於100K, 選擇Linear SVC模型進行分類

 

模型訓練

Key_Word

劃分測試集: model_selection, train_test_split, test_size

訓練模型: fit ,predict, kernel="linear", probability=True

模型評估: score, predict_proba

劃分測試集與訓練集

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(data, target, test_size = 1/3)
# train_test_split(數據集, 目標集, 將多少數據劃分紅測試集)
len(X_train), len(X_test)

 

導入並訓練模型

from sklearn import svm    # 導入支持向量機
clf = svm.SVC(kernel = "linear", C = 1, probability = True)    # 建立一個線性支持向量機的模型
clf.fit(X_train, y_train)    # 導入訓練集與訓練集的標籤
clf.predict(X_test) - y_test    # 檢驗預測結果

 

查看模型參數

clf.C    # 查看模型 的某一個參數,用點語法
clf.get_params()    # 參看模型的全部參數

 

查看預測結果

clf.predict_proba(X_test)    # 測試集落在3個label上的機率
clf.score(X_test, y_test)    # 查看模型得分

 

模型的評估

Key_Word

使用metrics模塊評估: classification_report

使用交叉驗證方法評估: cross_val_score

1.在sklearn.metrics模塊針對不一樣問題類型提供了各類評估指標而且能夠建立用戶自定義的評估指標

from sklearn.metrics import classification_report
print(classification_report(target, clf.predict(data), 
                            target_names = iris.target_names))

2.能夠採用交叉驗證方法評估模型的泛化能力

from sklearn.model_selection import cross_val_score
scores = cross_val_score(clf, data, target, cv=5)  # 採用5折交叉驗證
print(scores)
# 平均得分和95%的置信區間
print("Accuracy: %0.2f(+/-%0.2f)"%(scores.mean(), scores.std()*2))
# 95%的置信區間在平均值兩倍標準差以內

 

K折交叉驗證(K=10)示意圖

 

 模型的優化

網格搜索法: 在指定的超參數空間中對每一種可能的狀況進行交叉驗證評分並選出最好的超參數

  就是暴力枚舉超參數空間中全部可能出現的超參數,

  而後生成全部的模型,

  以後使用交叉驗證去評分每一種模型

  選出最好的超參數組合

隨機搜索法

模型特定交叉驗證

信息準則優化

Key_Word

模型的優化: GridSearchCV, C, kernel, gamma, param_grid, svc, cv

from sklearn import svm
from sklearn.model_selection import GridSearchCV
# 估計器
svc = svm.SVC()
# 超參數空間
param_grid = [{'C': [0.1, 1, 10, 100, 1000], 'kernel':['linear',]},
             {'C': [0.1, 1, 10, 100, 1000], 'gamma':[0.001, 0.01], "kernel":['rbf',]},
             ]
# 打分函數
scoring = 'accuracy'
# 指定採樣方法
clf = GridSearchCV(svc, param_grid = param_grid, scoring = scoring, cv = 10)
clf.fit(data, target)    # 獲得的clf是一個優化了的分類器
clf.predict(data)    # 用優化了的分類器進行分類
print(clf.get_params())    # 查看所有參數
print(clf.best_params_)    # 查看最優參數

clf.best_score_

 

 

模型持久化

Key_Word

模型持久化: pikle, joblib, dump, load

使用pickle模塊保存模型

對於sklearn, 使用joblib會更有效

import pickle
s = pickle.dumps(clf) # 保存模型成字符串
clf2 = pickle.loads(s)    # 從字符串加載模型
from sklearn.externals import joblib
joblib.dump(clf, 'filename.pkl')    # 保存模型到文件
clf3 = joblib.load('filename.pkl')    #加載模型
相關文章
相關標籤/搜索