Python Sklearn.metrics 簡介及應用示例
利用Python進行各種機器學習算法的實現時,經常會用到sklearn(scikit-learn)這個模塊/庫。
無論利用機器學習算法進行回歸、分類或者聚類時,評價指標,即檢驗機器學習模型效果的定量指標,都是一個不可避免且十分重要的問題。因此,結合scikit-learn主頁上的介紹,以及網上大神整理的一些資料,對常用的評價指標及其實現、應用進行簡單介紹。
一、 scikit-learn安裝
網上教程很多,此處不再贅述,具體可以參照:
https://www.cnblogs.com/zhangqunshi/p/6646987.html
此外,如果安裝了Anoconda,可以直接從Anoconda Navigator——Environment里面搜索添加。
pip install -U scikit-learn
二、 scikit-learn.metrics導入與調用
有兩種方式導入:
方式一:
from sklearn.metrics import 評價指標函數名稱
例如:
from sklearn.metrics import mean_squared_error
from sklearn.metrics import r2_score
調用方式為:直接使用函數名調用
計算均方誤差mean squared error
mse = mean_squared_error(y_test, y_pre)
計算回歸的決定系數R2
R2 = r2_score(y_test,y_pre)
方式二:
from sklearn import metrics
調用方式為:metrics.評價指標函數名稱(parameter)
例如:
計算均方誤差mean squared error
mse = metrics.mean_squared_error(y_test, y_pre)
計算回歸的決定系數R2
R2 = metrics.r2_score(y_test,y_pre)
三、 scikit-learn.metrics里各種指標簡介
簡單介紹參見:
https://www.cnblogs.com/mdevelopment/p/9456486.html
詳細介紹參見:
https://www.cnblogs.com/harvey888/p/6964741.html
官網介紹:
https://scikit-learn.org/stable/modules/classes.html#module-sklearn.metrics
轉自第一個鏈接的內容,簡單介紹內容如下:
回歸指標
explained_variance_score(y_true, y_pred, sample_weight=None, multioutput=‘uniform_average’):回歸方差(反應自變量與因變量之間的相關程度)
mean_absolute_error(y_true,y_pred,sample_weight=None,
multioutput=‘uniform_average’):
平均絕對誤差
mean_squared_error(y_true, y_pred, sample_weight=None, multioutput=‘uniform_average’):均方差
median_absolute_error(y_true, y_pred) 中值絕對誤差
r2_score(y_true, y_pred,sample_weight=None,multioutput=‘uniform_average’) :R平方值
分類指標
accuracy_score(y_true,y_pre) : 精度
auc(x, y, reorder=False) : ROC曲線下的面積;較大的AUC代表了較好的performance。
average_precision_score(y_true, y_score, average=‘macro’, sample_weight=None):根據預測得分計算平均精度(AP)
brier_score_loss(y_true, y_prob, sample_weight=None, pos_label=None):The smaller the Brier score, the better.
confusion_matrix(y_true, y_pred, labels=None, sample_weight=None):通過計算混淆矩陣來評估分類的准確性 返回混淆矩陣
f1_score(y_true, y_pred, labels=None, pos_label=1, average=‘binary’, sample_weight=None): F1值
F1 = 2 * (precision * recall) / (precision + recall) precision(查准率)=TP/(TP+FP) recall(查全率)=TP/(TP+FN)
log_loss(y_true, y_pred, eps=1e-15, normalize=True, sample_weight=None, labels=None):對數損耗,又稱邏輯損耗或交叉熵損耗
precision_score(y_true, y_pred, labels=None, pos_label=1, average=‘binary’,) :查准率或者精度; precision(查准率)=TP/(TP+FP)
recall_score(y_true, y_pred, labels=None, pos_label=1, average=‘binary’, sample_weight=None):查全率 ;recall(查全率)=TP/(TP+FN)
roc_auc_score(y_true, y_score, average=‘macro’, sample_weight=None):計算ROC曲線下的面積就是AUC的值,the larger the better
roc_curve(y_true, y_score, pos_label=None, sample_weight=None, drop_intermediate=True);計算ROC曲線的橫縱坐標值,TPR,FPR
TPR = TP/(TP+FN) = recall(真正例率,敏感度) FPR = FP/(FP+TN)(假正例率,1-特異性)
四、 一個應用實例
結合官網的案例,利用自己的數據,實現的一個應用實例:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn import ensemble
from sklearn import metrics
##############################################################################
# Load data
data = pd.read_csv('Data for train_0.003D.csv')
y = data.iloc[:,0]
X = data.iloc[:,1:]
offset = int(X.shape[0] * 0.9)
X_train, y_train = X[:offset], y[:offset]
X_test, y_test = X[offset:], y[offset:]
##############################################################################
# Fit regression model
params = {'n_estimators': 500, 'max_depth': 4, 'min_samples_split': 2,
'learning_rate': 0.01, 'loss': 'ls'}
clf = ensemble.GradientBoostingRegressor(**params)
clf.fit(X_train, y_train)
y_pre = clf.predict(X_test)
# Calculate metrics
mse = metrics.mean_squared_error(y_test, y_pre)
print("MSE: %.4f" % mse)
mae = metrics.mean_absolute_error(y_test, y_pre)
print("MAE: %.4f" % mae)
R2 = metrics.r2_score(y_test,y_pre)
print("R2: %.4f" % R2)
##############################################################################
# Plot training deviance
# compute test set deviance
test_score = np.zeros((params['n_estimators'],), dtype=np.float64)
for i, y_pred in enumerate(clf.staged_predict(X_test)):
test_score[i] = clf.loss_(y_test, y_pred)
plt.figure(figsize=(12, 6))
plt.subplot(1, 2, 1)
plt.title('Deviance')
plt.plot(np.arange(params['n_estimators']) + 1, clf.train_score_, 'b-',
label='Training Set Deviance')
plt.plot(np.arange(params['n_estimators']) + 1, test_score, 'r-',
label='Test Set Deviance')
plt.legend(loc='upper right')
plt.xlabel('Boosting Iterations')
plt.ylabel('Deviance')
##############################################################################
# Plot feature importance
feature_importance = clf.feature_importances_
# make importances relative to max importance
feature_importance = 100.0 * (feature_importance / feature_importance.max())
sorted_idx = np.argsort(feature_importance)
pos = np.arange(sorted_idx.shape[0]) + .5
plt.subplot(1, 2, 2)
plt.barh(pos, feature_importance[sorted_idx], align='center')
plt.yticks(pos, X.columns[sorted_idx])
plt.xlabel('Relative Importance')
plt.title('Variable Importance')
plt.show()