简体   繁体   中英

How do I alter a variable belonging to a class in a for loop? (Java)

Attempting to write code to generate layers in a Neural Network, and i'm just trying to work out how to assign a value to a variable belonging to the Neuron itself. The structure of a standard Neuron in my code is contained in a class called XORNeuron, and i'm calling this class in a FOR loop in order to generate a certain amount of neurons depending on how many neurons the layer is assigned when it is created.

I'm using an Array to do this, however I was wondering how I would assign the number of inputs the layer is told each neuron it contains has. The number of neurons and number of inputs are both arguments provided upon the Layer Constructor being called, meaning new layers can be created easily and tweaked with regards to their size and relative number of inputs.

The weights are all automatically generated for each input in a FOR loop in the Neuron class itself, depending on a variable the Neuron class holds called "numInputs". I'm attempting to write a FOR loop that will generate a new Neuron instance for the number of neurons the layer is told it holds, and then assign the number of inputs to the "numInputs" variable the Neuron class holds, so it will be able to generate the weights correctly.

My code is as such:

public class XORlayer {

// Create a constructor to create layers of neurons.
// Means we only have to set it up once and can feed it
// settings from then on for tweaking.

XORlayer(int numNeurons,int inpNum) 
{
    XORNeuron[] layerLength = new XORNeuron[numNeurons];

    for(int neuCount = 1; neuCount <= numNeurons; neuCount++) 
    {
        layerLength[neuCount-1] = new XORNeuron();

    }
}

}

Either by calling a setter in the created neuron

XORNeuron[] layerLength = new XORNeuron[numNeurons];

    for(int neuCount = 0; neuCount < numNeurons; neuCount++) {
        layerLength[neuCount] = new XORNeuron();
        layerLength[neuCount].setNumInput(inpNum);
    }
}

or by adding the input count to the neuron constructor, so you can do

layerLength[neuCount] = new XORNeuron(inpNum);

(Note: I changed the array indexing to a 0-based for loop, since that's idiomatic for Java).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM