GRNN预测模型Python实现
时间: 2023-11-05 10:08:06 浏览: 199
GRNN预测基于广义神经网络GRNN实现数据预测附Python代码和数据集.zip
5星 · 资源好评率100%
下面给出GRNN(General Regression Neural Network)神经网络的Python实现代码:
```python
import numpy as np
class GRNN:
def __init__(self, sigma):
self.sigma = sigma
def gaussian_kernel(self, x, y):
diff = x - y
return np.exp(-np.dot(diff, diff) / (2 * self.sigma ** 2))
def fit(self, X, y):
self.X_train = X
self.y_train = y
def predict(self, X):
y_pred = []
for i in range(X.shape[0]):
numerator = 0
denominator = 0
for j in range(self.X_train.shape[0]):
kernel = self.gaussian_kernel(X[i], self.X_train[j])
numerator += kernel * self.y_train[j]
denominator += kernel
y_pred.append(numerator / denominator)
return np.array(y_pred)
```
使用示例:
```python
import numpy as np
from sklearn.datasets import make_regression
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
from grnn import GRNN
# 生成样本数据
X, y = make_regression(n_samples=100, n_features=10, noise=0.1, random_state=42)
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 创建GRNN模型
grnn = GRNN(sigma=1.0)
# 训练模型
grnn.fit(X_train, y_train)
# 预测测试集结果
y_pred = grnn.predict(X_test)
# 计算均方误差
mse = mean_squared_error(y_test, y_pred)
print("均方误差:", mse)
```
这里使用了Scikit-learn库的`make_regression`函数生成100个样本,每个样本包含10个特征,使用GRNN模型进行回归预测,并计算均方误差作为评估指标。
阅读全文