Skip to content

About

Modular neural networks from scratch in Java — independent layers, parallel CPU training, interactive visualization and Kaggle execution.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

34 Commits

Folders and files

Repository files navigation

NeuralCore

A modular neural network engine built from scratch in Java.

NeuralCore began as a personal project to understand and implement neural networks from first principles. The original Java implementation contains the network mathematics and modular components. Later, AI-assisted development helped extend, test, and optimize the engine. The interactive website is a separate branch, not part of the original Java project.

Three versions

Version Branch Scope
Original Java original-java Historical source snapshot before the later fixes and AI-assisted engine improvements
Enhanced Java engine master (this branch) Original foundation plus AI-assisted correctness fixes, independent layer configuration, mini-batch training and reusable CPU workers
Website & Kaggle website-kaggle Interactive Network Lab, visualization, browser training and remote Java training on Kaggle

Live Network Lab — the optional website is maintained separately from the Java engine.

The original version is preserved at 4e1d397. The Java engine in this branch is the pre-website version at 423f64a, immediately after reusable mini-batch worker threads were added. This distinction makes the evolution of the personal project and the later AI-assisted changes explicit.

Java engine

Illustrative dense neural network and gradient flow

The core implements forward propagation, backpropagation, loss calculation, weight initialization, learning-rate scheduling and parameter updates without an external machine-learning framework.

Original foundation

  • Configurable dense neural networks, including hidden and output layers.
  • Forward propagation and backpropagation.
  • Activation functions, weight and bias initializers, losses and learning-rate schedules.
  • Model persistence and CSV data utilities.
  • Experimental classification examples.

Later AI-assisted improvements

  • Corrections to prediction, initializer dimensions, loss calculations and activation derivatives.
  • Structured exceptions with numerical and shape validation.
  • Independent configuration for every hidden layer and the output layer.
  • Removal of unnecessary CSV writes and artificial initialization delays.
  • Separate calculation state from model parameters.
  • Memory-efficient mini-batch gradient accumulation.
  • Reusable worker threads using wait() and notifyAll(), with parameter updates after each batch.
  • Regression and performance tests.

Supported components

Component Implementations
Hidden activations ReLU, Leaky ReLU, sigmoid, linear
Output activations Softmax, sigmoid, linear
Loss functions Mean squared error, cross-entropy, binary cross-entropy
Weight initialization He, Xavier and random (uniform and normal variants)
Bias initialization Zero, small constant and custom constant
Learning rates Constant, step decay, exponential decay, polynomial decay
Training Sample-wise and mini-batch gradient descent; parallel CPU workers
Persistence Java model save/load and explicit CSV snapshots

The output activation and loss must be compatible. The engine currently supports dense networks; CNNs, RNNs, transformers and GPU execution are not implemented.

Quick start

Requires Java 21 for the documented regression suite. Clone this Java-only branch:

git clone --branch master https://github.com/RaveroCreates/NeuralCore.git
cd NeuralCore
mkdir -p out
javac -d out $(find src/NeuralNetwork src/Save -name '*.java')

Create Example.java:

import NeuralNetwork.NeuralNetworkCore;
import NeuralNetwork.config.HiddenLayerConfig;
import NeuralNetwork.config.OutputLayerConfig;
import NeuralNetwork.ActivationFunctions.hidden.*;
import NeuralNetwork.ActivationFunctions.output.SoftMax;
import NeuralNetwork.Initializer.CompositeInitializer;
import NeuralNetwork.Initializer.Weight.Uniform.*;
import NeuralNetwork.Initializer.Bias.ZeroInitializer;
import NeuralNetwork.LearningRate.Constant;
import NeuralNetwork.lossfunction.CrossEntropy;

public class Example {
    public static void main(String[] args) {
        var model = new NeuralNetworkCore(
            2,
            new HiddenLayerConfig[] {
                new HiddenLayerConfig(8, new Relu(),
                    new CompositeInitializer(new HeInitialization(),
                                             new ZeroInitializer())),
                new HiddenLayerConfig(4, new Sigmoid(),
                    new CompositeInitializer(new XavierInitialization(),
                                             new ZeroInitializer()))
            },
            new OutputLayerConfig(2, new SoftMax(),
                new CompositeInitializer(new XavierInitialization(),
                                         new ZeroInitializer())),
            new CrossEntropy()
        );

        double[][] inputs = {{0, 0}, {0, 1}, {1, 0}, {1, 1}};
        double[][] targets = {{1, 0}, {0, 1}, {0, 1}, {1, 0}};

        // Epochs, learning-rate schedule, initial rate, batch size, workers
        model.train(inputs, targets, 200, new Constant(), 0.05, 4, 2);
        System.out.println(model.predict(new double[]{0, 1}));
    }
}
javac -cp out -d out Example.java
java -cp out Example

This illustrates the training API; accuracy depends on architecture, initialization and training settings.

Mini-batch and multithreaded training

Parallel mini-batch computation and synchronized weight update

Each batch uses a shared snapshot of model parameters. Workers calculate sample-level results using independent calculation state; the engine combines gradients and applies the parameter update before starting the next batch. Worker threads are reused instead of created for every batch.

// Single worker
model.train(inputs, targets, 100, new Constant(), 0.01, 32, 1);

// Four workers (limited by the available batch/data size)
model.train(inputs, targets, 100, new Constant(), 0.01, 32, 4);

Repository structure

src/
├── NeuralNetwork/    # Java neural-network engine
├── Save/             # Model persistence
├── ImageResizer/     # Image and dataset utilities
└── utils/            # Utilities
tests/                # Java regression and performance tests
docs/                 # Engine documentation
Data/                 # Historical model/data artifacts

Documentation and tests

mkdir -p out
javac -d out $(find src/NeuralNetwork src/Save src/ImageResizer tests -name '*.java')
for test in LayerConfigurationTest ExceptionFlowTest GradientRegressionTest PerformanceRegressionTest BatchTrainingTest; do
  java -cp out "$test" || exit 1
done

Run these commands in a disposable working directory when testing persistence or snapshot exports.

Roadmap

  • Additional optimizers, including momentum, Adam and RMSProp.
  • Convolutional and recurrent layer types.
  • Dropout and normalization.
  • Further correctness testing and reproducible CPU benchmarks.

Contributing

Feedback, reproducible bug reports, tests and ideas for Java machine learning are welcome. For changes to the numerical engine, explain the expected mathematical behavior and include a regression test. Website changes belong on website-kaggle.

The original implementation is kept separate so the historical personal work is not confused with subsequent AI-assisted development.

About

Modular neural networks from scratch in Java — independent layers, parallel CPU training, interactive visualization and Kaggle execution.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages