多层感知机可用于解决分类和回归问题
导入常用的包和数据
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.neural_network import MLPClassifier
from sklearn.neural_network import MLPRegressor
from sklearn.metrics import accuracy_score
from sklearn.metrics import mean_absolute_error, mean_squared_error
from sklearn.datasets import load_breast_cancer, load_wine
from sklearn.datasets import load_boston
import warnings
warnings.simplefilter("ignore")
class sklearn.neural_network.MLPClassifier(hidden_layer_sizes=(100,), activation='relu', *, solver='adam', alpha=0.0001, batch_size='auto', learning_rate='constant', learning_rate_init=0.001, power_t=0.5, max_iter=200, shuffle=True, random_state=None, tol=0.0001, verbose=False, warm_start=False, momentum=0.9, nesterovs_momentum=True, early_stopping=False, validation_fraction=0.1, beta_1=0.9, beta_2=0.999, epsilon=1e-08, n_iter_no_change=10, max_fun=15000)
多层感知机MLP解决分类问题
mlpc = MLPClassifier()
mlpc.fit(X_train, y_train['LABEL'])
train_score = mlpc.score(X_train, y_train['LABEL'])
test_score = mlpc.score(X_test, y_test['LABEL'])
print('train_score',train_score)
print('test_score',test_score)
y_pred = mlpc.predict(X_test)
acc_score = accuracy_score(y_pred, y_test)
print('mse_score',acc_score)
class sklearn.neural_network.MLPRegressor(hidden_layer_sizes=(100,), activation='relu', *, solver='adam', alpha=0.0001, batch_size='auto', learning_rate='constant', learning_rate_init=0.001, power_t=0.5, max_iter=200, shuffle=True, random_state=None, tol=0.0001, verbose=False, warm_start=False, momentum=0.9, nesterovs_momentum=True, early_stopping=False, validation_fraction=0.1, beta_1=0.9, beta_2=0.999, epsilon=1e-08, n_iter_no_change=10, max_fun=15000)
多层感知机解决回归问题
boston = load_boston()
df_data = pd.DataFrame(boston.data)
df_data.columns = boston.feature_names
df_target = pd.DataFrame(boston.target)
df_target.columns = ['LABEL']
df = pd.concat([df_data, df_target], axis=1)
from sklearn.neural_network import MLPRegressor
mlp_model = MLPRegressor()
mlp_model.fit(X_train, y_train)
train_score = mlp_model.score(X_train, y_train['LABEL'])
test_score = mlp_model.score(X_test, y_test['LABEL'])
print('train_score',train_score)
print('test_score',test_score)
y_pred = mlp_model.predict(X_test)
mae = mean_absolute_error(y_pred, y_test)
mse = mean_squared_error(y_pred, y_test)
print('mae_score',mae)
print('mse_score',mse)
回归预测结果可视化
plt.figure(figsize=(20,5),dpi=80)
x = np.arange(0,50,1)
y = y_test[0:50]
z = y_pred[0:50]
plt.scatter(x, y, s=20, color='blue', label='y_test')
plt.scatter(x, z, s=20, color='red', label='y_pred')
# 添加描述信息
plt.xlabel('index')
plt.ylabel('value')
plt.title('y_test and y_pred')
plt.legend(loc='upper left')
plt.show()