欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Sklearn习题 [python]

程序员文章站 2022-07-14 12:46:06
...

题目:

Sklearn习题 [python]

代码:

from sklearn import datasets  
from sklearn import cross_validation  
from sklearn.naive_bayes import GaussianNB  
from sklearn.svm import SVC  
from sklearn.ensemble import RandomForestClassifier  
from sklearn import metrics  

dataset = datasets.make_classification(n_samples=1000, n_features=10)  
kf = cross_validation.KFold(len(dataset[0]), n_folds = 10, shuffle = True)

for train_index, test_index in kf:  
    X_train, y_train = dataset[0][train_index], dataset[1][train_index]  
    X_test, y_test = dataset[0][test_index], dataset[1][test_index]


clf = GaussianNB()
clf.fit(X_train, y_train)
pred = clf.predict(X_test)

print("GaussianNB:")
acc = metrics.accuracy_score(y_test, pred)
print('Accuracy:', acc)
f1 = metrics.f1_score(y_test, pred)
print('F1_score:', f1)
auc = metrics.roc_auc_score(y_test, pred)
print('ACU ROC:', auc)
print("")

print("SVC")
for C in [1e-02, 1e-01, 1e00, 1e01, 1e02]:
    clf = SVC(C, kernel='rbf', gamma=0.1)
    clf.fit(X_train, y_train)
    pred = clf.predict(X_test)
    
    print(str(C)+":")
    acc = metrics.accuracy_score(y_test, pred)
    print('Accuracy:', acc)
    f1 = metrics.f1_score(y_test, pred)
    print('F1_score:', f1)
    auc = metrics.roc_auc_score(y_test, pred)
    print('ACU ROC:', auc)
print("")

print("RandomForestClassifier:")
for n_estimators in [10, 100, 1000]:
    clf = RandomForestClassifier(n_estimators)
    clf.fit(X_train, y_train)
    pred = clf.predict(X_test)

    print(str(n_estimators) + ":")
    acc = metrics.accuracy_score(y_test, pred)
    print('Accuracy:', acc)
    f1 = metrics.f1_score(y_test, pred)
    print('F1_score:', f1)
    auc = metrics.roc_auc_score(y_test, pred)
    print('ACU ROC:', auc)

输出:

Sklearn习题 [python]