第一部分:sklearn主要模塊和使用方法
1. sklearn的六大板塊:
- 分類: Classification
- 回歸: Regression
- 聚類:Clustering
- 維數(shù)約簡:Dimensional Reduction
- 模型選擇:Model Selection
- 數(shù)據(jù)預處理:Preprocessing
2. 監(jiān)督學習/無監(jiān)督學習下的各個模塊及調(diào)用方法
2.1 監(jiān)督學習的各個模塊
- neighbors: 近鄰算法
- SVM: 支持向量機
- kernal_ridge: 核嶺回歸
- discriminant_analysis: 判別分析
- linear_model: 廣義線性模型
- ensemble: 集成方法
- tree: 決策樹
- naive_bayes: 樸素貝葉斯
- cross_decomposition: 交叉分解
- gaussion_process: 高斯過程
- neural_network: 多層神經(jīng)網(wǎng)絡
- calibration: 概率校準
- isotonic: 保序回歸
- feature_selection: 監(jiān)督特征選擇
- multiclass: 多類多標簽算法
2.2 無監(jiān)督學習各個模塊
- decomposition: 矩陣因子分解
- cluster: 聚類分析
- manifold: 流行學習
- mixture: 高斯混合模型
- neural_network: 無監(jiān)督神經(jīng)網(wǎng)絡
- density: 密度估計
- covariance: 協(xié)方差估計
2.3 數(shù)據(jù)變換模塊
- feature_extraction: 特征提取
- feature_selection: 特征選擇
- preprocessing: 數(shù)據(jù)預處理
- random_projection: 隨機投影
- kernal_approximation: 核逼近
- pipline: 管道流
調(diào)用方法:from sklearn import model(model 表示對應的模型)
例如:調(diào)用決策樹回歸分析模塊
from sklearn import tree
model = tree.DecisionTreeRegressor()
3. API調(diào)用方法
3.1 統(tǒng)一調(diào)用
estimator.fit(x_train,[y_train]) | [ ]表示無監(jiān)督模塊無y |
---|---|
estimator.predict(x_test) | estimator.transform(x_test) |
Classification | Preprocessing |
Regression | Dimensionally Reduction |
clustering | Feature Extraction |
Feature Selection |
3.2 數(shù)據(jù)集的加載方式 Dataset Loading
- sklearn自帶的小數(shù)據(jù)集的加載(Packaged Dataset)
sklearn.datasets.load_datanema(對應的數(shù)據(jù)集名稱道偷,可在官方API介紹中查看)
以導入波士頓房價數(shù)據(jù)集為例:
sklearn.datasets.load_boston
- 在線下載的數(shù)據(jù)集(Downloadable Dataset)
sklearn.datasets.fetch_dataname(下載的數(shù)據(jù)集名稱)
- 計算機生成的數(shù)據(jù)集(Generated_Dataset)
sklearn.datasets.make_dataname(生成的數(shù)據(jù)集名稱)
- svmlight/libsvm 格式的數(shù)據(jù)集
sklearn.datasets.load_svmlight_file(對應文件在磁盤中的地址)
- 從mldata.org(一個機器學習數(shù)據(jù)集網(wǎng)站)在線下載獲取數(shù)據(jù)集
注:更多API接口在需要的時候從官方API介紹查看使用。
4.利用sklearn進行分析的基本流程
- 準備我們所需要的數(shù)據(jù)集即加載數(shù)據(jù)集 (Loading datasets)
--選擇合適的方式將我們要處理的數(shù)據(jù)集加載到內(nèi)存中,這里以從UCI下載的數(shù)據(jù)集為例
#python3.6
import numpy as np
import urllib
# 導入數(shù)據(jù)集所在網(wǎng)址
url = "http://archive.ics.uci.edu/ml/machine-learning-databases/pima-indians-diabetes/pima-indians-diabetes.data"
# 借用urlopen 將數(shù)據(jù)集導入
raw_data = urllib.urlopen(url)
# 以矩陣形式存儲數(shù)據(jù)
dataset = np.loadtxt(raw_data, delimiter=",")
# 觀察數(shù)據(jù)特征并進行適當?shù)那蟹?X = dataset[:,0:7]
y = dataset[:,8]
- 數(shù)據(jù)處理 (Preprocessing)
-- 由于我們所用到的大多數(shù)機器學習回歸算法以梯度下降法為主,且對數(shù)據(jù)的縮放和尺度較為敏感,所以我們在使用數(shù)據(jù)前應該進行數(shù)據(jù)歸一化薛闪,歸至(-1,1)或者(0,1)之間。
-- 不過sklearn作為強大的機器學習模塊,已經(jīng)內(nèi)置了normalize(),scale()等函數(shù)肾档,便于我們對數(shù)據(jù)的歸一化。
#歸一化在數(shù)據(jù)預處理板塊中
from sklearn import preprocessing
# normalize the data attributes
normalized_X = preprocessing.normalize(X)
# standardize the data attributes
standardized_X = preprocessing.scale(X)
- 特征選擇 (Feature selection)
-- 根據(jù)已有數(shù)據(jù)要想擬合出我們需要的回歸曲線辫继,最重要的就是特征選擇怒见,到底數(shù)據(jù)集中的哪些規(guī)律值得我們重視呢?
-- 往往在面對不同的實際問題時姑宽,對應的特征復雜程度也不同遣耍,這需要很強的專業(yè)知識,但做為初學者炮车,sklearn內(nèi)置的函數(shù)就夠我們進行分析使用舵变。
#以決策樹的特征提取為例
from sklearn import metrics
from sklearn.ensemble import ExtraTreesClassifier
model = ExtraTreesClassifier()
model.fit(X, y)
- 算法的選擇(Choose the algorithm)
-- 針對不同的問題我們可以選擇不同的回歸方法進行分析,具體展示在下面一欄瘦穆。
5. 常用回歸分析的實現(xiàn)及對比
5.1 首先我們準備下所需要的數(shù)據(jù)集纪隙,這里的數(shù)據(jù)采用計算機隨機生成。
import numpy as np
import matplotlib.pyplot as plt
#Prepare the data we need
def f(x1,x2):
y = 0.5 * np.sin(x1) + 0.5 * np.cos(x2) + 0.1 * x1 + 3
return y
#creat training data and test data
def LoadData():
x1_train = np.linspace(0, 50,500)
x2_train = np.linspace(-10, 10,500)
data_train = np.array([[x1,x2,f(x1, x2) + (np.random.random(1)-0.5)] for x1,x2 in zip(x1_train, x2_train)])
x1_test = np.linspace(0, 50,100) + 0.5 * np.random.random(100)
x2_test = np.linspace(-10, 10,100) + 0.02 * np.random.random(100)
data_test = np.array([[x1,x2,f(x1, x2)] for x1,x2 in zip(x1_test, x2_test)])
return data_train,data_test
train,test = LoadData()
x_train,y_train = train[:,:2],train[:,2]
x_test,y_test = test[:,:2],test[:,2]
5.2 定義擬合函數(shù)扛或,以便重復調(diào)用實現(xiàn)不同的回歸方法
def TryDifferentMethod(model):
model.fit(x_train,y_train)
score = model.score(x_test,y_test)
result = model.predict(x_test)
plt.figure()
plt.plot(np.arange(len(result)),y_test,'go-',label='true value')
plt.plot(np.arange(len(result)),result,'ro-',label='predict value')
plt.title('score:%f'%score)
plt.legend()
plt.show()
5.3 這里使用經(jīng)常用到的五種回歸方法進行展示
# 1.DecisionTree Regression
from sklearn import tree
model_DecisionTreeRegressor = tree.DecisionTreeRegressor()
#TryDifferentMethod(model_DecisionTreeRegressor)
# 2.LinearRegression
from sklearn import linear_model
model_LinearRegression = linear_model.LinearRegression()
#TryDifferentMethod(model_LinearRegression)
# 3.SVM Regression
from sklearn import svm
model_SVMRegression = svm.SVR()
#TryDifferentMethod(model_SVMRegression)
# 4.KNN Regression
from sklearn import neighbors
model_KNeighborsRegressor = neighbors.KNeighborsRegressor()
#TryDifferentMethod(model_KNeighborsRegressor)
# 5.RandomForest Regression
from sklearn import ensemble
model_RandomForestRegressor = ensemble.RandomForestRegressor(n_estimators=22) # Use 22 Decision Trees
#TryDifferentMethod(model_RandomForestRegressor)
為了更明顯的對比初差距绵咱,將可視化后的圖像呈現(xiàn)出來:
1.線性回歸方法
LinearRegression.png
2.決策樹回歸方法
DecisionTree.png
3.支持向量機回歸方法
SVMRegression.png
4.KNN回歸方法
KNN_Regression.png
5.隨機森林回歸方法
RandomForestRegression.png
接下來,就開始一個個搞了熙兔,先從這些回歸方法的內(nèi)置函數(shù)搞起悲伶。。黔姜。拢切。