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)

参数辨识结果

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值