BP神经网络预测模型及其Python和MATLAB实现
在Python中,可以使用numpy
和scikit-learn
库来实现BP神经网络。以下是一个简单的例子:
import numpy as np
from sklearn.neural_network import MLPClassifier
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import accuracy_score
# 假设X是特征数据,y是目标变量
X = np.array([...])
y = np.array([...])
# 划分数据集为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 特征缩放
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
# 创建并训练BP神经网络
mlp = MLPClassifier(hidden_layer_sizes=(10,), max_iter=1000, random_state=42)
mlp.fit(X_train_scaled, y_train)
# 进行预测
y_pred = mlp.predict(X_test_scaled)
# 评估模型
accuracy = accuracy_score(y_test, y_pred)
print(f"Accuracy: {accuracy}")
在MATLAB中,可以使用newff
函数创建前向神经网络,并用train
函数进行训练。以下是一个简单的例子:
% 假设X是特征数据,y是目标变量
X = [...];
y = [...];
% 数据归一化
[Xn, ps] = mapminmax(X);
% 创建并训练BP神经网络
net = newff(minmax(Xn), [10, 1], {'tansig', 'purelin'}, 'traingdx');
net.trainParam.showWindow = false;
net.trainParam.epochs = 1000;
net = train(net, Xn, y);
% 进行预测
y_pred = sim(net, Xn);
% 评估模型
accuracy = sum(y_pred == y) / length(y);
disp(['Accuracy: ', num2str(accuracy)]);
这两个例子展示了如何在Python和MATLAB中创建和训练BP神经网络,并评估其性能。
评论已关闭