sklearn.MLPClassifierを使用しての簡単な例

トレーニング

MLPClassifier hidden_​​layer_sizesはニューロンの数で提供することができる隠された層の数を必要とし、そのような(3,2)として、各ニューラルネットワークの隠れ層は、ニューラルネットワークは、2つの隠れ層、第一隠れ層のニューロンを有することを示す3第2の層2隠れニューロン。他の特定のパラメータは、参照の公式ドキュメント
以下の例では、またKFoldが、結果として、最終的な結果は次の共存に数回倒し分類器の保存最高になり、クロスチェックを行って使用しています。

# two-layer neural network 
# train part

import numpy as np
from sklearn.neural_network import MLPClassifier
from sklearn.model_selection import KFold
from joblib import dump

#get training data
X = train_data[:,1:]
y = train_data[:,0]  

#neural network classifier of structure (3,2)
kf = KFold(n_splits=3) # 3-fold cross-validation
best_clf = None
best_score = 0
train_scores = []
test_scores = []
print("kfold-------")
for train_index, test_index in kf.split(X):
    # create neural network using MLPClassifer
    clf = MLPClassifier(solver = 'sgd', activation = 'logistic', max_iter = 1000, hidden_layer_sizes = (3,2),random_state = 1)
    X_train, X_test = X[train_index], X[test_index]
    y_train, y_test = y[train_index], y[test_index]
    clf.fit(X_train, y_train)
    train_score = clf.score(X_train, y_train)
    train_scores.append(train_score)
 
    test_score = clf.score(X_test, y_test)
    test_scores.append(test_score)

    #compare score of the tree models and get the best one
    if test_score > best_score:
        best_score = test_score
        best_clf = clf
    
    #print(clf.n_outputs_)
in_sample_error = [1 - score for score in train_scores]
test_set_error = [1 - score for score in test_scores]
print("in_sample_error: ")
print(in_sample_error)
print("test_set_error: ")
print(test_set_error)

#store the classifier
if best_clf != None:
    dump(best_clf, "train_model.m")

テスト

分類器のトレーニングとテストを直接ロードし、より良い保存する前

# test part

import numpy as np
from sklearn.neural_network import MLPClassifier
from joblib import load

X_test = test_data[:,1:]
y_test = test_data[:,0]

clf = load("train_model.m")
y_pred = clf.predict(X_test)
np.savetxt("label_pred.txt", np.array(y_pred)) #save predict result
#print(y_pred)
test_score = clf.score(X_test, y_test)
test_error = 1 - test_score
print('test_score:%s' % test_score)
print('test_error:%s' % test_error)

おすすめ

転載: www.cnblogs.com/liuxin0430/p/12130346.html