粒子群优化BP神经网络代码 完整代码 带有测试数据和训练流程的

import numpy as np
import random

# 生成示例数据
np.random.seed(42)
X_train = np.random.rand(100, 5)  # 示例特征数据,假设有100个样本,5个特征
y_train = np.random.randint(0, 2, size=(100, 1))  # 示例标签数据,二分类问题

# 定义BP神经网络
class NeuralNetwork:
    def __init__(self, input_size, hidden_size, output_size):
        self.input_size = input_size
        self.hidden_size = hidden_size
        self.output_size = output_size
        self.weights_input_hidden = np.random.rand(self.input_size, self.hidden_size)
        self.weights_hidden_output = np.random.rand(self.hidden_size, self.output_size)

    def sigmoid(self, x):
        return 1 / (1 + np.exp(-x))

    def forward(self, X):
        self.hidden = self.sigmoid(np.dot(X, self.weights_input_hidden))
        self.output = self.sigmoid(np.dot(self.hidden, self.weights_hidden_output))
        return self.output

    def calculate_loss(self, X, y):
        y_pred = self.forward(X)
        return np.mean((y - y_pred) ** 2)

# 粒子群优化算法
class PSO:
    def __init__(self, population_size, max_iter, nn):
        self.population_size = population_size
        self.max_iter = max_iter
        self.nn = nn
        self.particles = []
        self.global_best_position = np.random.rand(nn.input_size * nn.hidden_size + nn.hidden_size * nn.output_size)
        self.global_best_loss = float('inf')

    def train(self, X, y):
        for _ in range(self.population_size):
            particle = np.random.rand(self.nn.input_size * self.nn.hidden_size + self.nn.hidden_size * self.nn.output_size)
            self.particles.append(particle)

        for i in range(self.max_iter):
            for particle in self.particles:
                self.nn.weights_input_hidden = particle[:self.nn.input_size * self.nn.hidden_size].reshape(self.nn.input_size, self.nn.hidden_size)
                self.nn.weights_hidden_output = particle[self.nn.input_size * self.nn.hidden_size:].reshape(self.nn.hidden_size, self.nn.output_size)
                loss = self.nn.calculate_loss(X, y)

                if loss < self.global_best_loss:
                    self.global_best_loss = loss
                    self.global_best_position = particle.copy()

            w = 0.5
            c1 = 2
            c2 = 2
            for j, particle in enumerate(self.particles):
                r1 = np.random.rand(len(particle))
                r2 = np.random.rand(len(particle))
                inertia = w * particle
                cognitive = c1 * r1 * (self.global_best_position - particle)
                social = c2 * r2 * (self.global_best_position - particle)
                self.particles[j] = inertia + cognitive + social

        best_weights_input_hidden = self.global_best_position[:self.nn.input_size * self.nn.hidden_size].reshape(self.nn.input_size, self.nn.hidden_size)
        best_weights_hidden_output = self.global_best_position[self.nn.input_size * self.nn.hidden_size:].reshape(self.nn.hidden_size, self.nn.output_size)
        return best_weights_input_hidden, best_weights_hidden_output

# 定义模型和PSO训练
input_size = 5
hidden_size = 4
output_size = 1
nn = NeuralNetwork(input_size, hidden_size, output_size)
pso = PSO(population_size=10, max_iter=100, nn=nn)
best_weights_input_hidden, best_weights_hidden_output = pso.train(X_train, y_train)

# 使用训练得到的权重参数构建最终BP神经网络模型
nn.weights_input_hidden = best_weights_input_hidden
nn.weights_hidden_output = best_weights_hidden_output

# 测试数据
X_test = np.random.rand(10, 5)  # 示例测试数据,10个样本,5个特征
predictions = nn.forward(X_test)
print(predictions)

猜你喜欢

转载自blog.csdn.net/qq_38735017/article/details/134966735