多层感知机回归python实现
时间: 2023-07-18 12:06:59 浏览: 119
python实现多层感知器
5星 · 资源好评率100%
多层感知机(Multi-Layer Perceptron,简称 MLP)是一种常用的神经网络模型,用于解决回归和分类问题。下面是一个使用 Python 实现的 MLP 回归模型:
首先,导入必要的库:
```python
import numpy as np
from sklearn.neural_network import MLPRegressor
from sklearn.datasets import make_regression
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
```
接着,生成一个回归数据集:
```python
X, y = make_regression(n_samples=1000, n_features=10, noise=0.1)
```
将数据集划分为训练集和测试集:
```python
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
```
定义 MLP 模型,并训练:
```python
mlp = MLPRegressor(hidden_layer_sizes=(100, 50, 10), 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)
mlp.fit(X_train, y_train)
```
预测并计算均方误差:
```python
y_pred = mlp.predict(X_test)
mse = mean_squared_error(y_test, y_pred)
print('MSE: ', mse)
```
上述代码中,MLPRegressor 函数用于定义 MLP 模型,其中 hidden_layer_sizes 参数指定了隐藏层的神经元个数,activation 参数指定了激活函数,solver 参数指定了优化器,alpha 参数指定了正则化系数,max_iter 参数指定了最大迭代次数等。最后使用 fit 函数对模型进行训练,predict 函数对测试集进行预测,mean_squared_error 函数计算均方误差。
完整代码如下:
```python
import numpy as np
from sklearn.neural_network import MLPRegressor
from sklearn.datasets import make_regression
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
# 生成回归数据集
X, y = make_regression(n_samples=1000, n_features=10, noise=0.1)
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
# 定义 MLP 模型
mlp = MLPRegressor(hidden_layer_sizes=(100, 50, 10), 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)
# 训练模型
mlp.fit(X_train, y_train)
# 预测并计算均方误差
y_pred = mlp.predict(X_test)
mse = mean_squared_error(y_test, y_pred)
print('MSE: ', mse)
```
阅读全文