Archived
Private
Public Access
1
0
This repository has been archived on 2026-02-04. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
ProjectBackup/Unity/NeuralNetworkTutorial/Assets/Scripts/NeuralNetwork/Layer.cs
2022-11-12 13:10:03 +01:00

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;
}
}
}