1.安裝scikit-learn
1.1Scikit-learn 依賴
- Python (>= 2.7 or >= 3.3),
- NumPy (>= 1.8.2),
- SciPy (>= 0.13.3).
分別查看上述三個依賴的版本,
python -V 結果:Python 2.7.3
python -c 'import scipy; print scipy.version.version' scipy版本結果:0.9.0
python -c "import numpy; print numpy.version.version" numpy結果:1.10.2
查看包安裝路徑:python -c 'import scipy; print scipy.__file__'
1.2 Scikit-learn安裝
如果你已經安裝了NumPy、SciPy和python並且均滿足1.1中所需的條件,那么可以直接運行sudo pip install -U scikit-learn 執行安裝,這個命令安裝的是最新版本的scikit-learn。
如果你的Scipy版本和我的一樣,是0.9.0版本,在不升級scipy版本的情況下,可以指定安裝scikit-learn低版本(例如:0.17版本):sudo pip --default-timeout=500 install -U scikit-learn==0.17.0。這樣就不會造成高版本的scikit-learn不兼容低版本的Scipy問題。
在pip安裝的過程中,--default-timeout=500設定可以解決網絡問題引起的ssl認證失敗的問題,通過pip install -h命令得知默認超時時間是15s。
2.計算auc指標
1 import numpy as np 2 from sklearn.metrics import roc_auc_score 3 y_true = np.array([0, 0, 1, 1]) 4 y_scores = np.array([0.1, 0.4, 0.35, 0.8]) 5 roc_auc_score(y_true, y_scores)
輸出:0.75
3.計算roc曲線
1 import numpy as np 2 from sklearn import metrics 3 y = np.array([1, 1, 2, 2]) #實際值 4 scores = np.array([0.1, 0.4, 0.35, 0.8]) #預測值 5 fpr, tpr, thresholds = metrics.roc_curve(y, scores, pos_label=2) #pos_label=2,表示值為2的實際值為正樣本 6 print fpr 7 print tpr 8 print thresholds
輸出:
array([ 0. , 0.5, 0.5, 1. ])
array([ 0.5, 0.5, 1. , 1. ])
array([ 0.8 , 0.4 , 0.35, 0.1 ])