Python 实现PSO粒子群算法优化

西门子实习内容

氨基酸发酵建模参数辨识

建模部分代码

def error(parameters):
    rowdata = [
        [1, 0, 128],
        [1.7, 0, 127],
        [2.9, 0.2, 124],
        [4.7, 0.6, 121],
        [6.7, 1.3, 116],
        [8.9, 2.3, 111],
        [11.3, 3.6, 104],
        [13.8, 5.2, 97],
        [15.6, 6.9, 88],
        [16.5, 8.7, 79],
        [16.9, 10.6, 68],
        [17.1, 12.6, 58],
        [17.2, 14.7, 46],
        [17.2, 16.9, 36],
        [17.1, 19.1, 26],
        [17.0, 21, 16],
        [16.7, 22.7, 6]]
    par = np.array([0.323, 17.21, 95, 0.016, 0.131, 51.6, 49.1, 3.2, 0.278, 0.045]).reshape(1, 10)
    model = Model(parameters)
    x0 = 1
    p0 = 0
    s0 = 128
    t = np.linspace(0, 64, 17000)
    y = odeint(model.mode, [x0, p0, s0], t)
    y_out = torch.tensor(y[0:17001:1000, :])  # y_out[i] 表示第i小时的数据
    rowdata = torch.tensor(rowdata)
    lossFun = torch.nn.MSELoss(reduction='sum')
    loss = lossFun(y_out, rowdata)
    # print('loss={0}'.format(loss))
    return loss

粒子群PSO优化算法部分代码

def PSO(objective):
    global gbestx, gbesty, num_iterations, num_particles, num_dims, w_initial, decay_rate
    particles = []
    current_error = 0
    prev_error = np.inf
    count = 1
    # initialise particles
    for i in range(num_particles):
        p = Particle(objective)
        particles.append(p)
        if p.y < gbesty:
            gbesty = p.y  # Set initial Global bests
            gbestx = copy.deepcopy(p.x)

    # Run Optimization
    w = w_initial
    for i in range(num_iterations):
        # calculate outputs for particles and update pbest,gbest
        output = []
        w *= (1.0 - decay_rate)
        # print(w)
        for p in range(num_particles):
            # p是实例化的粒子,particles[p]表示第p个粒子当前的值
            particles[p].y = objective(particles[p].x)  # Evaluate objective function for each particle
            output.append(particles[p].y)
            if output[p] < particles[p].pbesty:  # Set personal best for particle
                particles[p].pbesty = output[p]
                particles[p].pbestx = copy.deepcopy(particles[p].x)
            if output[p] < gbesty or len(gbestx) == 0:  # Update Global best
                gbesty = output[p]
                gbestx = copy.deepcopy(particles[p].x)

            # 更新每个例子的位置和速度
            particles[p].update_velocity(w=w, gbestx=gbestx)

参数辨识结果

在这里插入图片描述

你可能感兴趣的:(python,算法,开发语言)