转向感知器

2022-08-29  本文已影响0人  大龙10

书名:代码本色:用编程模拟自然系统
作者:Daniel Shiffman
译者:周晗彬
ISBN:978-7-115-36947-5
第10章目录

10.5 转向感知器

1、转向感知器

class Vehicle {
    Perceptron brain; 给小车加上大脑
    PVector location;
    PVector velocity;
    PVector acceleration;
    //……

2、场景

void seek(ArrayList<PVector> targets) {
    for (PVector target : targets) {
        PVector force = seek(targets.get(i)); 物体对每个目标都有转向力
        applyForce(force);
    }
}
void seek(ArrayList<PVector> targets) {
    PVector[] forces = new PVector[targets.size()]; 为brain对象创建一系列输入
    for (int i = 0; i < forces.length; i++) {
        forces[i] = seek(targets.get(i)); 计算每个目标对应的转向力,填充转向力数组
    }
    PVector output = brain.process(forces); 从brain对象中获取输出结果,将转向力作用在物体上
    applyForce(output);
}

3、具体实现

这两个函数实现的几乎是同一个算法,但有两点区别。

4、增强式学习

PVector desired = new PVector(width/2,height/2);
PVector error = PVector.sub(desired, location);
brain.train(forces,error);
weights[i] += c*error.x*forces[i].x;
weights[i] += c*error.y*forces[i].y;

5、示例

示例代码10-2 感知器转向

class Vehicle {
    Perceptron brain; 小车有了大脑
    PVector location; 物理运动所需的变量
    PVector velocity;
    PVector acceleration;
    float maxforce;
    float maxspeed;
    Vehicle(int n, float x, float y) { 在小车的构造函数中创建感知器对象,传入输入数量和学习brain = new Perceptron(n,0.001);
        acceleration = new PVector(0,0);
        velocity = new PVector(0,0);
        location = new PVector(x,y);
        maxspeed = 4;
        maxforce = 0.1;
    }
    void update() { update()函数和之前一样
        velocity.add(acceleration);
        velocity.limit(maxspeed);
        location.add(velocity);
        acceleration.mult(0);
    }
    void applyForce(PVector force) { applyForce()函数和之前一样
        acceleration.add(force);
    }
    void steer(ArrayList&lt;PVector> targets) {
        PVector[] forces = new PVector[targets.size()];
        for (int i = 0; i < forces.length; i++) {
            forces[i] = seek(targets.get(i));
        }
        PVector result = brain.feedforward(forces); 所有转向力都是输入
        applyForce(result); 施加计算得到的结果
        PVector desired = new PVector(width/2,height/2); 根据和中心之间的距离训练大脑
        PVector error = PVector.sub(desired, location);
        brain.train(forces,error);
    }
    PVector seek(PVector target) { seek()函数和之前一样
        PVector desired = PVector.sub(target,location);
        desired.normalize();
        desired.mult(maxspeed);
        PVector steer = PVector.sub(desired,velocity);
        steer.limit(maxforce);
        return steer;
    }
}

6、运行结果

上一篇下一篇

猜你喜欢

热点阅读