Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 2

import java.util.

Random;

public class NeuralNetwork {


private int[] layers;
private double[][][] weights;
private double[][] biases;
private Random rand;

public NeuralNetwork(int[] layers) {


this.layers = layers;
this.rand = new Random();

// Inicializar pesos e vieses aleatoriamente


this.weights = new double[layers.length-1][][];
for (int i = 0; i < layers.length - 1; i++) {
this.weights[i] = new double[layers[i+1]][layers[i]];
for (int j = 0; j < layers[i+1]; j++) {
for (int k = 0; k < layers[i]; k++) {
this.weights[i][j][k] = rand.nextGaussian();
}
}
}
this.biases = new double[layers.length-1][];
for (int i = 0; i < layers.length - 1; i++) {
this.biases[i] = new double[layers[i+1]];
for (int j = 0; j < layers[i+1]; j++) {
this.biases[i][j] = rand.nextGaussian();
}
}
}

public double[] feedforward(double[] input) {


double[] activations = input;
for (int i = 0; i < layers.length - 1; i++) {
double[] weightedSums = new double[layers[i+1]];
for (int j = 0; j < layers[i+1]; j++) {
double weightedSum = biases[i][j];
for (int k = 0; k < layers[i]; k++) {
weightedSum += weights[i][j][k] * activations[k];
}
weightedSums[j] = weightedSum;
}
activations = sigmoid(weightedSums);
}
return activations;
}

public void stochasticGradientDescent(double[][] inputs, double[][] labels,


double learningRate, int batchSize, int epochs) {
for (int epoch = 0; epoch < epochs; epoch++) {
for (int i = 0; i < inputs.length; i += batchSize) {
double[][] batchInputs = new double[batchSize][];
double[][] batchLabels = new double[batchSize][];
for (int j = 0; j < batchSize; j++) {
batchInputs[j] = inputs[i+j];
batchLabels[j] = labels[i+j];
}
stochasticGradientDescentBatch(batchInputs, batchLabels,
learningRate);
}
}
}

private void stochasticGradientDescentBatch(double[][] inputs, double[][]


labels, double learningRate) {
double[][][] weightGradients = new double[weights.length][][];
double[][] biasGradients = new double[biases.length][];
for (int i = 0; i < weights.length; i++) {
weightGradients[i] = new double[weights[i].length][];
for (int j = 0; j < weights[i].length; j++) {
weightGradients[i][j] = new double[weights[i][j].length];
}
}

You might also like