基于sklearn的感知机python3

首先,本文还是选用python里面自带的digits数据集

from sklearn.datasets import load_digits
digits=load_digits()

大家都知道这个数据集是一些图片,我们对数据进行处理:

#数据标准化
from sklearn.preprocessing import StandardScaler
scaler=StandardScaler()
scaler.fit(digits.data)
x_scaled=scaler.transform(digits.data)

将数据和类别分别赋予x,y:

x=x_scaled
y=digits.target

划分训练集、测试集:

from sklearn.model_selection import train_test_split
x_train,x_test,y_train,y_test=train_test_split(x,y)

调用sklearn,使用感知机预测:

from sklearn.neural_network import MLPClassifier
mlp=MLPClassifier(hidden_layer_sizes=(30,30,30),activation='logistic',max_iter=100)
mlp.fit(x_train,y_train)

进行预测,并观察效果:


from sklearn.metrics import classification_report
predicted=mlp.predict(x_test)
print(classification_report(y_test, predicted))
基于sklearn的感知机python3_第1张图片
下面我们进行调参,并观察参数改变对预测效果的影响:

from sklearn.pipeline import Pipeline
from sklearn.model_selection import GridSearchCV
if __name__ == '__main__':
    pipeline = Pipeline([
        ('mlp',MLPClassifier(hidden_layer_sizes=(30,30,30),max_iter=100))
    ])
    parameters = {
        'mlp__activation': ('identity','logistic','tanh','relu'),
         'mlp__solver': ('lbfgs','sgd','adam')
    }
    grid_search = GridSearchCV(pipeline, parameters,verbose=1,n_jobs=-1)
    grid_search.fit(x_train, y_train)
    print('最佳效果:%0.3f' % grid_search.best_score_)
    print('最优参数:')
    best_parameters = grid_search.best_estimator_.get_params()
    for param_name in sorted(parameters.keys()):
        print('\t%s: %r' % (param_name, best_parameters[param_name]))

    predictions = grid_search.predict(x_test)
    print(classification_report(y_test, predictions))

基于sklearn的感知机python3_第2张图片
可以看到预测效果有显著提升!

你可能感兴趣的:(python3,机器学习)