In [1]:
import pandas as pd
In [2]:
df = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/wdbc.data', header=None)
In [4]:
df.head()
Out[4]:
In [8]:
from sklearn.preprocessing import LabelEncoder
X = df.loc[:, 2:].values
y = df.loc[:, 1].values
In [10]:
le = LabelEncoder()
y = le.fit_transform(y)
In [14]:
# M: 悪性 B: 良性
le.transform(['M', 'B'])
Out[14]:
In [15]:
le.classes_
Out[15]:
In [16]:
from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20, random_state=1)
In [19]:
print(X_train.shape)
print(X_test.shape)
print(y_train.shape)
print(y_test.shape)
In [20]:
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
In [21]:
pipe_lr = Pipeline([('sc1', StandardScaler()),
('pca', PCA(n_components=2)),
('clf', LogisticRegression(random_state=1))])
In [22]:
pipe_lr
Out[22]:
In [23]:
pipe_lr.fit(X_train, y_train)
Out[23]:
In [24]:
print('Test Accuracy: %.3f' % pipe_lr.score(X_test, y_test))
In [25]:
import numpy as np
from sklearn.cross_validation import StratifiedKFold
In [44]:
kfold = StratifiedKFold(y=y_train, n_folds=10, random_state=1)
In [45]:
scores = []
for k, (train, test) in enumerate(kfold):
pipe_lr.fit(X_train[train], y_train[train])
score = pipe_lr.score(X_train[test], y_train[test])
scores.append(score)
print('Fold: %s, Class dist: %s, Acc: %.3f' % (k + 1, np.bincount(y_train[train]), score))
In [46]:
print('CV accuracy: %.3f +/- %.3f' % (np.mean(scores), np.std(scores)))
In [50]:
from sklearn.cross_validation import cross_val_score
scores = cross_val_score(estimator=pipe_lr, X=X_train, y=y_train, cv=10, n_jobs=-1)
In [51]:
print('CV accuracy scores: %s' % scores)
In [52]:
print('CV accuracy: %.3f +- %.3f' % (np.mean(scores), np.std(scores)))
In [67]:
import matplotlib.pyplot as plt
from sklearn.learning_curve import learning_curve
%matplotlib inline
In [54]:
pipe_lr = Pipeline([('scl', StandardScaler()),
('clf', LogisticRegression(penalty='l2', random_state=0))])
In [57]:
train_sizes, train_scores, test_scores = learning_curve(estimator=pipe_lr,
X=X_train,
y=y_train,
train_sizes=np.linspace(0.1, 1.0, 10),
cv=10,
n_jobs=1)
In [58]:
train_sizes
Out[58]:
In [63]:
train_scores
Out[63]:
In [64]:
test_scores
Out[64]:
In [65]:
train_mean = np.mean(train_scores, axis=1)
train_std = np.std(train_scores, axis=1)
test_mean = np.mean(test_scores, axis=1)
test_std = np.std(test_scores, axis=1)
In [71]:
plt.plot(train_sizes, train_mean, color='blue', marker='o', markersize=5, label='training accuracy')
plt.fill_between(train_sizes, train_mean + train_std, train_mean - train_std, alpha=0.15, color='blue')
plt.plot(train_sizes, test_mean, color='green', linestyle='--', marker='s', markersize=5, label='validation accuracy')
plt.fill_between(train_sizes, test_mean + test_std, test_mean - test_std, alpha=0.15, color='green')
plt.grid()
plt.xlabel('Number of training samples')
plt.ylabel('Accuracy')
plt.legend(loc='lower right')
plt.ylim([0.8, 1.0])
plt.show()
In [74]:
from sklearn.metrics import confusion_matrix
from sklearn.svm import SVC
In [76]:
pipe_svc = Pipeline([('sc1', StandardScaler()),
('clf', SVC(random_state=1))])
In [77]:
pipe_svc.fit(X_train, y_train)
Out[77]:
In [78]:
y_pred = pipe_svc.predict(X_test)
In [80]:
y_test
Out[80]:
In [81]:
y_pred
Out[81]:
In [82]:
confmat = confusion_matrix(y_true=y_test, y_pred=y_pred)
In [83]:
print(confmat)
In [88]:
fig, ax = plt.subplots(figsize=(2.5, 2.5))
ax.matshow(confmat, cmap=plt.cm.Blues, alpha=0.3)
for i in range(confmat.shape[0]):
for j in range(confmat.shape[1]):
ax.text(x=j, y=i, s=confmat[i, j], va='center', ha='center')
plt.xlabel('predicted label')
plt.ylabel('true label')
Out[88]:
In [89]:
from sklearn.metrics import precision_score, recall_score, f1_score
In [92]:
print('precision: %.3f' % precision_score(y_true=y_test, y_pred=y_pred))
print(40 / 41)
In [95]:
print('recall: %.3f' % recall_score(y_true=y_test, y_pred=y_pred))
print(40 / 42)
In [97]:
print('f1: %.3f' % f1_score(y_true=y_test, y_pred=y_pred))
print(2 * 0.975609756097561 * 0.9523809523809523 / (0.975609756097561 + 0.9523809523809523))
In [99]:
from sklearn.metrics import roc_curve, auc
from scipy import interp
In [106]:
pipe_lr = Pipeline([('scl', StandardScaler()),
('pca', PCA(n_components=2)),
('clf', LogisticRegression(penalty='l2', random_state=0, C=100.0))])
X_train2 = X_train[:, [4, 14]]
In [137]:
cv = StratifiedKFold(y_train, n_folds=3, random_state=1)
fig = plt.figure(figsize=(7, 5))
mean_tpr = 0.0
mean_fpr = np.linspace(0, 1, 100)
all_tpr = []
for i, (train, test) in enumerate(cv):
probas = pipe_lr.fit(X_train2[train], y_train[train]).predict_proba(X_train2[test])
fpr, tpr, thresholds = roc_curve(y_train[test], probas[:, 1], pos_label=1)
mean_tpr += interp(mean_fpr, fpr, tpr)
mean_tpr[0] = 0.0
roc_auc = auc(fpr, tpr)
plt.plot(fpr, tpr, lw=1, label='ROC fold %d (area = %0.2f)' % (i + 1, roc_auc))
plt.plot([0, 1], [0, 1], linestyle='--', color=(0.6, 0.6, 0.6), label='random guessing')
mean_tpr /= len(cv)
mean_tpr[-1] = 1.0
mean_auc = auc(mean_fpr, mean_tpr)
plt.plot(mean_fpr, mean_tpr, 'k--', label='mean ROC (area = %0.2f)' % mean_auc, lw=2)
plt.plot([0, 0, 1], [0, 1, 1], lw=2, linestyle=':', color='black', label='prefect performance')
plt.xlim([-0.05, 1.05])
plt.ylim([-0.05, 1.05])
plt.xlabel('false positive rate')
plt.ylabel('true positive rate')
plt.title('Receiver Operator Characteristic')
plt.legend(loc='lower right')
plt.show()
In [141]:
pipe_lr = pipe_lr.fit(X_train2, y_train)
y_pred2 = pipe_lr.predict(X_test[:, [4, 14]])
from sklearn.metrics import roc_auc_score, accuracy_score
print('ROC AUC: %.3f' % (roc_auc_score(y_true=y_test, y_score=y_pred2)))
print('Accuracy: %.3f' % accuracy_score(y_true=y_test, y_pred=y_pred2))
In [ ]: