47 lines
1.6 KiB
C#
47 lines
1.6 KiB
C#
using System;
|
|
using UnityEngine;
|
|
using Random = UnityEngine.Random;
|
|
|
|
namespace NeuralNetwork {
|
|
public class Layer {
|
|
|
|
public readonly float[][] Matrix;
|
|
public readonly string Activation;
|
|
|
|
public Layer(int inputDimension, int outputDimension, string activationFunction = "tanh") {
|
|
Activation = activationFunction;
|
|
Matrix = new float[outputDimension][];
|
|
|
|
for (int i = 0; i < outputDimension; i++) {
|
|
Matrix[i] = new float[inputDimension];
|
|
|
|
for (int j = 0; j < inputDimension; j++) {
|
|
Matrix[i][j] = Random.Range(-1.0f, 1.0f);
|
|
}
|
|
}
|
|
}
|
|
|
|
public Vector LayerOutput(Vector input) {
|
|
Vector output = new Vector(Matrix.Length);
|
|
|
|
for (int i = 0; i < Matrix.Length; i++) {
|
|
if (Matrix[i].Length - 1 == input.Length) {
|
|
|
|
for (int j = 0; j < Matrix[i].Length; j++) {
|
|
float weightedValue = input.Values[j] * Matrix[i][j];
|
|
if (Single.IsNaN(weightedValue)) weightedValue = 0;
|
|
|
|
output.Values[i] += weightedValue;
|
|
}
|
|
|
|
output.Values[i] += 1.0f * Matrix[i][Matrix[i].Length - 1];
|
|
output.Values[i] = Activations.Tanh(output.Values[i]);
|
|
|
|
}else Debug.LogError($"Matrix[{i}] has {Matrix[i].Length} elements, but input has {input.Length} elements");
|
|
}
|
|
|
|
return output;
|
|
}
|
|
|
|
}
|
|
} |