/**
* 神经网络
*/
class NeuralNetwork {
public layerinfo:number[];//神经层结构
public neuralLayerList: List;
public gene: number[];//偏执
public get Gene(): number[] {
return this.gene;
}
// public set Gene(any: number[]) {
// //this.gene = any;
// this.LoadGene(any);
// }
public constructor(layerinfo: number[]) {
this.layerinfo=layerinfo;
this.neuralLayerList = new List();
for (let i = 0; i < layerinfo.length; i++) {
this.neuralLayerList.AddValue(new NeuralLayer(i, layerinfo));//初始化所有层神经元
}
//输入层无偏执和权重
for (let i = 1; i < this.neuralLayerList.Count; i++) {
for (var j in this.neuralLayerList[i].neurals) {
this.gene.push[this.neuralLayerList[i].neurals[j].stubborn];//加偏执
for (var k in this.neuralLayerList[i].neurals[j].weights) {
this.gene.push[this.neuralLayerList[i].neurals[j].weights[k]];//加权重
}
}
}
}
//是否load保存好的权重
public LoadGene(gene: number[]) {
var index = 0;
for (let i = 1; i < this.neuralLayerList.Count; i++) {
for (var j in this.neuralLayerList[i].neurals) {
this.neuralLayerList[i].neurals[j].stubborn = gene[index];//偏执
this.gene[index]=gene[index];
index++;
for (var k in this.neuralLayerList[i].neurals[j].weights) {
this.neuralLayerList[i].neurals[j].weights[k] = gene[index];//权重
this.gene[index]=gene[index];
index++;
}
}
}
}
//输入-->输出
public Pushout(inputs: number[]): number[] {
return this.Compute(inputs);
}
private Compute(inputs: number[]): number[] {
//输入层
var inputneurals: NeuralLayer = this.neuralLayerList[0].neurals;
for (var i in inputneurals) {
inputneurals[i].value = inputs[i];
}
//隐藏层
for (let i = 1; i < this.neuralLayerList.Count; i++) {
var upperneurals: List = this.neuralLayerList[i - 1].neurals;
var curneurals: List = this.neuralLayerList[i].neurals;
for (var j in curneurals) {
curneurals[j].value = 0;
for (var k in upperneurals) {
curneurals[j].value += MathTool.ActivationFunction(curneurals[j].weights[k] * upperneurals[k].value + curneurals[j].stubborn);
}
}
}
//输出层
var outputneurals: List = this.neuralLayerList[this.neuralLayerList.Count - 1].neurals;
var outputs: number[];
for (var i in outputneurals) {
outputs.push(outputneurals[i]);
}
return outputs;
}
}
/**
* 神经层
*/
class NeuralLayer {
public neurals: List;
public constructor(index: number, layerinfo: number[]) {
this.neurals = new List();
var weightcount = 0;
if (index == 0)
weightcount = 0;
else
weightcount = layerinfo[index - 1];
for (let i = 0; i < layerinfo[index]; i++) {
this.neurals.AddValue(new Neural(weightcount));
}
}
}
/**
* 神经元
*/
class Neural {
public stubborn: number;//偏执
public weights: number[];//权重
public value: number;//计算后的值
public constructor(weightcount: number) {
for (let i = 0; i < weightcount; i++) {
this.weights.push(MathTool.Random());
}
}
}