nn/nn.ts

57 lines
1.6 KiB
TypeScript
Raw Normal View History

2021-07-28 12:04:00 -04:00
import { default as M, Cloud } from "./m.ts";
2021-07-28 14:08:46 -04:00
export type N = Array<Array<Array<number>>>
2021-07-28 12:04:00 -04:00
2021-07-28 14:08:46 -04:00
const Label = (inSet:any, inData:Cloud.M, inLabel:Cloud.V):N =>
{
if(!inSet){inSet = [[], []];}
if(inSet.length == 0){inSet.push([]);}
if(inSet.length == 1){inSet.push([]);}
inData.forEach((row:Cloud.V) =>
{
row.push(1);
inSet[0].push(row);
inSet[1].push(inLabel);
});
return inSet;
};
2021-07-29 08:42:28 -04:00
const Forward = (inData:Cloud.M, inLayers:N):N =>
2021-07-28 12:04:00 -04:00
{
let i:number;
2021-07-29 08:42:28 -04:00
let stages = [inData];
let process = (index:number):Cloud.M => M.Batch.Sigmoid(M.Batch.Affine(stages[index], inLayers[index]));
2021-07-28 12:04:00 -04:00
for(i=0; i<inLayers.length-1; i++)
{
2021-07-29 08:42:28 -04:00
stages[i+1] = M.Mutate.Pad(process(i));
2021-07-28 12:04:00 -04:00
}
2021-07-29 08:42:28 -04:00
stages[i+1] = process(i);
return stages;
2021-07-28 12:04:00 -04:00
};
2021-07-28 16:40:58 -04:00
const Backward = (inStages:N, inLayers:N, inGoals:Cloud.M, inRate:number):N =>
2021-07-28 12:04:00 -04:00
{
let i:number;
2021-07-29 08:42:28 -04:00
let errorBack:Cloud.M = M.Batch.Subtract(inStages[inStages.length-1], inGoals);
console.log(errorBack);
2021-07-28 12:04:00 -04:00
2021-07-28 14:08:46 -04:00
for(i=inLayers.length-1; i>=0; i--)
2021-07-28 12:04:00 -04:00
{
let layerInput:Cloud.M = inStages[i];
let layerOutput:Cloud.M = inStages[i+1];
let errorScaled:Cloud.M = M.Batch.Multiply(errorBack, M.Batch.Derivative(layerOutput));
2021-07-28 16:40:58 -04:00
errorBack = M.Batch.Affine(errorScaled, M.Create.Transpose(inLayers[i]));
2021-07-28 12:04:00 -04:00
errorScaled.forEach((inScaledError:Cloud.V, inIndex:number)=> {
const deltas = M.Batch.Scale(M.Create.Outer(layerInput[inIndex], inScaledError), inRate);
2021-07-28 16:40:58 -04:00
inLayers[i] = M.Batch.Subtract(inLayers[i], deltas);
2021-07-28 12:04:00 -04:00
});
2021-07-28 16:40:58 -04:00
2021-07-28 12:04:00 -04:00
}
2021-07-28 16:40:58 -04:00
return inLayers;
2021-07-28 12:04:00 -04:00
};
2021-07-28 14:08:46 -04:00
export { Label, Forward, Backward };
2021-07-28 12:04:00 -04:00
export type { Cloud };