sklearn是基于numpy和scipy的一個機器學(xué)習(xí)算法庫,設(shè)計的非常優(yōu)雅,它讓我們能夠使用同樣的接口來實現(xiàn)所有不同的算法調(diào)用。
一、數(shù)據(jù)獲取
*****************
"""
##1.1 導(dǎo)入sklearn數(shù)據(jù)集
from sklearn import datasets
iris = datasets.load.iris() #導(dǎo)入數(shù)據(jù)集
X = iris.data #獲得其特征向量
y = iris.target # 獲得樣本label
##1.2 創(chuàng)建數(shù)據(jù)集
from sklearn.datasets.samples_generator import make_classification
X, y = make_classification(n_samples=6, n_features=5, n_informative=2,
n_redundant=2, n_classes=2, n_clusters_per_class=2, scale=1.0,
random_state=20)
# n_samples:指定樣本數(shù)
# n_features:指定特征數(shù)
# n_classes:指定幾分類
# random_state:隨機種子,使得隨機狀可重
# 查看數(shù)據(jù)集
for x_,y_ in zip(X,y):
print(y_,end=': ')
print(x_)
"""
0: [-0.6600737 -0.0558978 0.82286793 1.1003977 -0.93493796]
1: [ 0.4113583 0.06249216 -0.90760075 -1.41296696 2.059838 ]
1: [ 1.52452016 -0.01867812 0.20900899 1.34422289 -1.61299022]
0: [-1.25725859 0.02347952 -0.28764782 -1.32091378 -0.88549315]
0: [-3.28323172 0.03899168 -0.43251277 -2.86249859 -1.10457948]
1: [ 1.68841011 0.06754955 -1.02805579 -0.83132182 0.93286635]
"""
"""
*****************
二、數(shù)據(jù)預(yù)處理
*****************
"""
from sklearn import preprocessing
##2.1 數(shù)據(jù)歸一化
data = [[0, 0], [0, 0], [1, 1], [1, 1]]
# 1. 基于mean和std的標準化
scaler = preprocessing.StandardScaler().fit(train_data)
scaler.transform(train_data)
scaler.transform(test_data)
# 2. 將每個特征值歸一化到一個固定范圍
scaler = preprocessing.MinMaxScaler(feature_range=(0, 1)).fit(train_data)
scaler.transform(train_data)
scaler.transform(test_data)
#feature_range: 定義歸一化范圍,注用()括起來
#2.2 正則化
X = [[ 1., -1., 2.],
[ 2., 0., 0.],
[ 0., 1., -1.]]
X_normalized = preprocessing.normalize(X, norm='l2')
print(X_normalized)
"""
array([[ 0.40..., -0.40..., 0.81...],
[ 1. ..., 0. ..., 0. ...],
[ 0. ..., 0.70..., -0.70...]])
"""
## 2.3 One-Hot編碼
data = [[0, 0, 3], [1, 1, 0], [0, 2, 1], [1, 0, 2]]
encoder = preprocessing.OneHotEncoder().fit(data)
enc.transform(data).toarray()
"""
*****************
三、數(shù)據(jù)集拆分
*****************
"""
# 作用:將數(shù)據(jù)集劃分為 訓(xùn)練集和測試集
# 格式:train_test_split(*arrays, **options)
from sklearn.mode_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
"""
參數(shù)
---
arrays:樣本數(shù)組,包含特征向量和標簽
test_size:
float-獲得多大比重的測試樣本 (默認:0.25)
int - 獲得多少個測試樣本
train_size: 同test_size
random_state:
int - 隨機種子(種子固定,實驗可復(fù)現(xiàn))
shuffle - 是否在分割之前對數(shù)據(jù)進行洗牌(默認True)
返回
---
分割后的列表,長度=2*len(arrays),
(train-test split)
"""
"""
*****************
四、定義模型
*****************
"""
## 模型常用屬性和工鞥呢
# 擬合模型
model.fit(X_train, y_train)
# 模型預(yù)測
model.predict(X_test)
# 獲得這個模型的參數(shù)
model.get_params()
# 為模型進行打分
model.score(data_X, data_y) # 線性回歸:R square; 分類問題: acc
## 4.1 線性回歸
from sklearn.linear_model import LinearRegression
# 定義線性回歸模型
model = LinearRegression(fit_intercept=True, normalize=False,
copy_X=True, n_jobs=1)
"""
參數(shù)
---
fit_intercept:是否計算截距。False-模型沒有截距
normalize: 當fit_intercept設(shè)置為False時,該參數(shù)將被忽略。 如果為真,則回歸前的回歸系數(shù)X將通過減去平均值并除以l2-范數(shù)而歸一化。
n_jobs:指定線程數(shù)
"""
## 4.2 邏輯回歸
from sklearn.linear_model import LogisticRegression
# 定義邏輯回歸模型
model = LogisticRegression(penalty='l2', dual=False, tol=0.0001, C=1.0,
fit_intercept=True, intercept_scaling=1, class_weight=None,
random_state=None, solver='liblinear', max_iter=100, multi_class='ovr',
verbose=0, warm_start=False, n_jobs=1)
"""參數(shù)
---
penalty:使用指定正則化項(默認:l2)
dual: n_samples > n_features取False(默認)
C:正則化強度的反,值越小正則化強度越大
n_jobs: 指定線程數(shù)
random_state:隨機數(shù)生成器
fit_intercept: 是否需要常量
"""
## 4.3 樸素貝葉斯算法NB
from sklearn import naive_bayes
model = naive_bayes.GaussianNB() # 高斯貝葉斯
model = naive_bayes.MultinomialNB(alpha=1.0, fit_prior=True, class_prior=None)
model = naive_bayes.BernoulliNB(alpha=1.0, binarize=0.0, fit_prior=True, class_prior=None)
"""
文本分類問題常用MultinomialNB
參數(shù)
---
alpha:平滑參數(shù)
fit_prior:是否要學(xué)習(xí)類的先驗概率;false-使用統(tǒng)一的先驗概率
class_prior: 是否指定類的先驗概率;若指定則不能根據(jù)參數(shù)調(diào)整
binarize: 二值化的閾值,若為None,則假設(shè)輸入由二進制向量組成
"""
## 4.4 決策樹DT
from sklearn import tree
model = tree.DecisionTreeClassifier(criterion='gini', max_depth=None,
min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0.0,
max_features=None, random_state=None, max_leaf_nodes=None,
min_impurity_decrease=0.0, min_impurity_split=None,
class_weight=None, presort=False)
"""參數(shù)
---
criterion :特征選擇準則gini/entropy
max_depth:樹的最大深度,None-盡量下分
min_samples_split:分裂內(nèi)部節(jié)點,所需要的最小樣本樹
min_samples_leaf:葉子節(jié)點所需要的最小樣本數(shù)
max_features: 尋找最優(yōu)分割點時的最大特征數(shù)
max_leaf_nodes:優(yōu)先增長到最大葉子節(jié)點數(shù)
min_impurity_decrease:如果這種分離導(dǎo)致雜質(zhì)的減少大于或等于這個值,則節(jié)點將被拆分。
"""
## 4.5 支持向量機
from sklearn.svm import SVC
model = SVC(C=1.0, kernel='rbf', gamma='auto')
"""參數(shù)
---
C:誤差項的懲罰參數(shù)C
gamma: 核相關(guān)系數(shù)。浮點數(shù),If gamma is ‘a(chǎn)uto' then 1/n_features will be used instead.
"""
## 4.6 k近鄰算法 KNN
from sklearn import neighbors
#定義kNN分類模型
model = neighbors.KNeighborsClassifier(n_neighbors=5, n_jobs=1) # 分類
model = neighbors.KNeighborsRegressor(n_neighbors=5, n_jobs=1) # 回歸
"""參數(shù)
---
n_neighbors: 使用鄰居的數(shù)目
n_jobs:并行任務(wù)數(shù)
"""
## 4.7 多層感知機
from sklearn.neural_network import MLPClassifier
# 定義多層感知機分類算法
model = MLPClassifier(activation='relu', solver='adam', alpha=0.0001)
"""參數(shù)
---
hidden_layer_sizes: 元祖
activation:激活函數(shù)
solver :優(yōu)化算法{‘lbfgs', ‘sgd', ‘a(chǎn)dam'}
alpha:L2懲罰(正則化項)參數(shù)。
"""
"""
*****************
五、模型評估與選擇
*****************
"""
## 5.1 交叉驗證
from sklearn.model_selection import cross_val_score
cross_val_score(model, X, y=None, scoring=None, cv=None, n_jobs=1)
"""參數(shù)
---
model:擬合數(shù)據(jù)的模型
cv : k-fold
scoring: 打分參數(shù)-‘a(chǎn)ccuracy'、‘f1'、‘precision'、‘recall' 、‘roc_auc'、'neg_log_loss'等等
"""
## 5.2 檢驗曲線
from sklearn.model_selection import validation_curve
train_score, test_score = validation_curve(model, X, y, param_name, param_range, cv=None, scoring=None, n_jobs=1)
"""參數(shù)
---
model:用于fit和predict的對象
X, y: 訓(xùn)練集的特征和標簽
param_name:將被改變的參數(shù)的名字
param_range: 參數(shù)的改變范圍
cv:k-fold
返回值
---
train_score: 訓(xùn)練集得分(array)
test_score: 驗證集得分(array)
"""
"""
*****************
六、保存模型
*****************
"""
## 6.1 保存為pickle文件
import pickle
# 保存模型
with open('model.pickle', 'wb') as f:
pickle.dump(model, f)
# 讀取模型
with open('model.pickle', 'rb') as f:
model = pickle.load(f)
model.predict(X_test)
## 6.2 sklearn方法自帶joblib
from sklearn.externals import joblib
# 保存模型
joblib.dump(model, 'model.pickle')
#載入模型
model = joblib.load('model.pickle')
以上就是Python機器學(xué)習(xí)工具scikit-learn的使用筆記的詳細內(nèi)容,更多關(guān)于Python機器學(xué)習(xí)工具scikit-learn的資料請關(guān)注腳本之家其它相關(guān)文章!