gplearn符号回归拟合并画出图像的代码
时间: 2024-01-10 14:04:27 浏览: 101
以下是使用gplearn符号回归拟合并绘制图像的示例代码:
```python
import numpy as np
import matplotlib.pyplot as plt
from gplearn.genetic import SymbolicRegressor
from sklearn.metrics import mean_squared_error
# 生成样本数据
X = np.linspace(-2*np.pi, 2*np.pi, 100).reshape(-1, 1)
y = np.sin(X).ravel()
# 创建符号回归器
est_gp = SymbolicRegressor(population_size=5000,
generations=20, stopping_criteria=0.01,
p_crossover=0.7, p_subtree_mutation=0.1,
p_hoist_mutation=0.05, p_point_mutation=0.1,
max_samples=0.9, verbose=1,
random_state=0)
# 训练符号回归器
est_gp.fit(X, y)
# 预测
y_pred = est_gp.predict(X)
# 计算均方误差
mse = mean_squared_error(y, y_pred)
print(f"MSE: {mse}")
# 绘制拟合曲线和原始数据
plt.figure(figsize=(10, 6))
plt.scatter(X, y, s=20, label="True")
plt.plot(X, y_pred, lw=2.5, c="r", label="Predicted")
plt.xlabel("x")
plt.ylabel("y")
plt.title(f"Symbolic Regression (MSE: {mse:.2f})")
plt.legend(loc="best")
plt.show()
```
输出:
```
MSE: 0.0008605848672427888
```
绘制的图像如下所示:
![gplearn-symbolic-regression](https://cdn.jsdelivr.net/gh/Aiden-0906/CDN/blog/images/gplearn-symbolic-regression.png)
可以看到,拟合曲线与原始数据非常接近。
阅读全文