基于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))
预测效果
下面我们进行调参,并观察参数改变对预测效果的影响:

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))

参数结果
可以看到预测效果有显著提升!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值