MLP,神经网络算法,又称为多层感知机神经网络算法。
代码:
import pandas as pd
import numpy as np
from sklearn import metrics
from sklearn.svm import SVC
from sklearn.neural_network import MLPClassifier
from sklearn.neural_network import MLPRegressor
# MLP神经网络算法
def mx_MLP(train_x, train_y):
#mx = MLPClassifier(solver='lbfgs', alpha=1e-5,hidden_layer_sizes=(5, 2), random_state=1)
mx = MLPClassifier()
mx.fit(train_x, train_y)
return mx
#结果验证函数
def ai_acc_xed(df9,ky0=5,fgDebug=True):
#1
#ny_test,ny_pred=len(df9['y_test']),len(df9['y_pred'])
ny_test=len(df9['y_test'])
df9['ysub']=df9['y_test']-df9['y_pred']
df9['ysub2']=np.abs(df9['ysub'])
#2
df9['y_test_div']=df9['y_test']
df9.loc[df9['y_test'] == 0, 'y_test_div'] =0.00001
df9['ysubk']=(df9['ysub2']/df9['y_test_div'])*100
dfk=df9[df9['ysubk']<ky0]
dsum=len(dfk['y_pred'])
dacc=dsum/ny_test*100
#
#3
if fgDebug:
print('\nai_acc_xed')
print(df9.head())
y_test,y_pred=df9['y_test'],df9['y_pred']
print('\nn_df9,{0},n_dfk,{1}'.format(ny_test,dsum))
dmae=metrics.mean_absolute_error(y_test, y_pred)
dmse=metrics.mean_squared_error(y_test, y_pred)
drmse=np.sqrt(metrics.mean_squared_error(y_test, y_pred))
print('acc-kok: {0:.2f}%, MAE:{1:.2f}, MSE:{2:.2f}, RMSE:{3:.2f}'.format(dacc,dmae,dmse,drmse))
#
#4
return dacc
# 1
fs0 = 'dat/iris_'
print('\n#1 init, fs0,', fs0)
x_train = pd.read_csv(fs0 + 'xtrain.csv', index_col = False)
y_train = pd.read_csv(fs0 + 'ytrain.csv', index_col = False)
x_test = pd.read_csv(fs0 + 'xtest.csv', index_col = False)
y_test = pd.read_csv(fs0 + 'ytest.csv', index_col = False)
df9 = x_test.copy()
#2
print('\n#2 model')
mx = mx_MLP(x_train.values, y_train.values)
# 3
print('\n#3 predict')
y_pred = mx.predict(x_test.values)
df9['y_predsr'] = y_pred
df9['y_test'], df9['y_pred'] = y_test, y_pred
df9['y_pred'] = round(df9['y_predsr']).astype(int)
# 4
df9.to_csv('dat/iris_9.csv', index = False)
print('\n#4 d9')
print(df9.tail())
# 5
dacc = ai_acc_xed(df9, 1, False)
print('\n#5 mx:mx_sum, kok: {0:.2f}%'.format(dacc))
输出:
#4 d9
x1 x2 x3 x4 y_predsr y_test y_pred
33 6.4 2.8 5.6 2.1 1 1 1
34 5.8 2.8 5.1 2.4 1 1 1
35 5.3 3.7 1.5 0.2 2 2 2
36 5.5 2.3 4.0 1.3 3 3 3
37 5.2 3.4 1.4 0.2 2 2 2
#5 mx:mx_sum, kok: 97.37%