-
Notifications
You must be signed in to change notification settings - Fork 8
Getting Started
echo edited this page May 1, 2025
·
21 revisions
This guide will walk you through the basic features of Brain4J, from setting up your first model to making predictions.
Let's create a simple model to simulate the XOR operator.
If you haven't checked it yet, follow the Installation Guide.
Create a basic model using Brain4J:
Model model = new Sequential(
new DenseLayer(2, Activations.LINEAR), // 2 Input neurons
new DenseLayer(32, Activations.MISH), // 32 Hidden neurons
new DenseLayer(32, Activations.MISH), // 32 Hidden neurons
new DenseLayer(1, Activations.SIGMOID) // 1 Output neuron for classification
);
model.compile(Loss.BINARY_CROSS_ENTROPY, new AdamW(0.1));
To train the model we need some data, for the XOR we can generate it:
List<Sample> samples = new ArrayList<>();
for (int x = 0; x < 2; x++) {
for (int y = 0; y < 2; y++) {
Tensor input = Tensors.vector(x, y);
Tensor output = Tensors.vector(x ^ y);
samples.add(new Sample(input, output));
}
}
// Samples, no shuffle, 4 of batch size
ListDataSource dataSource = new ListDataSource(samples, false, 4);
// Fit the model for 50 epoches, evaluate every 10
model.fit(dataSource, 50, 10);
Once trained, you can use the model to make predictions.
// You can evaluate the model like this
EvaluationResult evaluation = model.evaluate(dataSource);
System.out.println(evaluation.confusionMatrix());
Additionally, if you have test data, you can have Brain4J evaluate the model on it:
ListDataSource trainSource = ...;
ListDataSource testSource = ...;
// Trains with trainSource, evaluates with testSource
model.fit(trainSource, testSource, 50, 10);
Check out Advanced Usage
This wiki is still under construction. If you feel that you can contribute, please do so! Thanks.