Certainly! Below is a LuaU template for a simple neural network suitable for Roblox. This template allows you to easily edit the network's structure, train it on your data, and evaluate its accuracy through console logs. The template includes:
- Neural Network Module: A basic feedforward neural network with one hidden layer.
- Main Script: An example of how to use the neural network module, including training and evaluating its accuracy.
1. Neural Network Module (NeuralNetworkTemplate.lua)
Create a ModuleScript in Roblox named NeuralNetworkTemplate and paste the following code:
-- NeuralNetworkTemplate.lua
-- A simple feedforward neural network in LuaU for Roblox
local NeuralNetwork = {}
NeuralNetwork.__index = NeuralNetwork
-- Activation function and its derivative (Sigmoid)
local function sigmoid(x)
return 1 / (1 + math.exp(-x))
end
local function sigmoidDerivative(x)
return x * (1 - x)
end
-- Initialize a new Neural Network
function NeuralNetwork.new(inputSize, hiddenSize, outputSize, learningRate)
local self = setmetatable({}, NeuralNetwork)
self.inputSize = inputSize
self.hiddenSize = hiddenSize
self.outputSize = outputSize
self.learningRate = learningRate or 0.1
-- Initialize weights with small random values
self.weightsInputHidden = {}
for i = 1, self.hiddenSize do
self.weightsInputHidden[i] = {}
for j = 1, self.inputSize do
self.weightsInputHidden[i][j] = math.random() * 0.2 - 0.1 -- Range [-0.1, 0.1]
end
end
self.weightsHiddenOutput = {}
for i = 1, self.outputSize do
self.weightsHiddenOutput[i] = {}
for j = 1, self.hiddenSize do
self.weightsHiddenOutput[i][j] = math.random() * 0.2 - 0.1
end
end
-- Initialize biases
self.biasHidden = {}
for i = 1, self.hiddenSize do
self.biasHidden[i] = math.random() * 0.2 - 0.1
end
self.biasOutput = {}
for i = 1, self.outputSize do
self.biasOutput[i] = math.random() * 0.2 - 0.1
end
return self
end
-- Feedforward operation
function NeuralNetwork:feedforward(input)
self.hiddenLayer = {}
-- Calculate hidden layer activations
for i = 1, self.hiddenSize do
local activation = self.biasHidden[i]
for j = 1, self.inputSize do
activation = activation + input[j] * self.weightsInputHidden[i][j]
end
self.hiddenLayer[i] = sigmoid(activation)
end
self.outputLayer = {}
-- Calculate output layer activations
for i = 1, self.outputSize do
local activation = self.biasOutput[i]
for j = 1, self.hiddenSize do
activation = activation + self.hiddenLayer[j] * self.weightsHiddenOutput[i][j]
end
self.outputLayer[i] = sigmoid(activation)
end
return self.outputLayer
end
-- Train the network using backpropagation
function NeuralNetwork:train(input, target)
-- Feedforward
self:feedforward(input)
-- Calculate output errors (target - actual)
local outputErrors = {}
for i = 1, self.outputSize do
outputErrors[i] = target[i] - self.outputLayer[i]
end
-- Calculate gradients for weightsHiddenOutput
local outputGradients = {}
for i = 1, self.outputSize do
outputGradients[i] = outputErrors[i] * sigmoidDerivative(self.outputLayer[i])
-- Update weightsHiddenOutput
for j = 1, self.hiddenSize do
self.weightsHiddenOutput[i][j] = self.weightsHiddenOutput[i][j] + self.learningRate * outputGradients[i] * self.hiddenLayer[j]
end
-- Update biasOutput
self.biasOutput[i] = self.biasOutput[i] + self.learningRate * outputGradients[i]
end
-- Calculate hidden layer errors
local hiddenErrors = {}
for i = 1, self.hiddenSize do
hiddenErrors[i] = 0
for j = 1, self.outputSize do
hiddenErrors[i] = hiddenErrors[i] + outputGradients[j] * self.weightsHiddenOutput[j][i]
end
end
-- Calculate gradients for weightsInputHidden
local hiddenGradients = {}
for i = 1, self.hiddenSize do
hiddenGradients[i] = hiddenErrors[i] * sigmoidDerivative(self.hiddenLayer[i])
-- Update weightsInputHidden
for j = 1, self.inputSize do
self.weightsInputHidden[i][j] = self.weightsInputHidden[i][j] + self.learningRate * hiddenGradients[i] * input[j]
end
-- Update biasHidden
self.biasHidden[i] = self.biasHidden[i] + self.learningRate * hiddenGradients[i]
end
end
-- Predict output for a given input
function NeuralNetwork:predict(input)
return self:feedforward(input)
end
-- Evaluate accuracy on a dataset
function NeuralNetwork:evaluate(dataset)
local correct = 0
for _, sample in ipairs(dataset) do
local output = self:predict(sample.input)
local predicted = self:argMax(output)
local actual = self:argMax(sample.target)
if predicted == actual then
correct = correct + 1
end
end
local accuracy = (correct / #dataset) * 100
print(string.format("Accuracy: %.2f%% (%d/%d)", accuracy, correct, #dataset))
return accuracy
end
-- Helper function to find index of maximum value
function NeuralNetwork:argMax(tbl)
local max = tbl[1]
local index = 1
for i = 2, #tbl do
if tbl[i] > max then
max = tbl[i]
index = i
end
end
return index
end
return NeuralNetwork
Explanation:
-
Initialization (new): Sets up the network with random weights and biases. You can adjust inputSize, hiddenSize, outputSize, and learningRate as needed.
-
Activation Functions (sigmoid, sigmoidDerivative): Implements the sigmoid activation function and its derivative, essential for backpropagation.
-
Feedforward (feedforward): Processes the input through the network to produce an output.
-
Training (train): Implements basic backpropagation to adjust weights based on the error between predicted and target outputs.
-
Prediction (predict): Outputs the network's prediction for a given input.
-
Evaluation (evaluate): Tests the network on a dataset and prints the accuracy to the console.
-
Helper (argMax): Determines the index of the highest value in a table, useful for classification tasks.
2. Main Script (MainScript.lua)
Create a Script in Roblox and name it MainScript. This script will utilize the neural network module to train and evaluate its performance.
-- MainScript.lua
local NeuralNetwork = require(script.NeuralNetworkTemplate)
-- Define network architecture
local inputSize = 3 -- Number of input neurons
local hiddenSize = 4 -- Number of hidden neurons
local outputSize = 2 -- Number of output neurons
local learningRate = 0.5 -- Learning rate
-- Initialize the neural network
local nn = NeuralNetwork.new(inputSize, hiddenSize, outputSize, learningRate)
-- Example dataset: Simple classification
-- Modify this dataset based on your specific problem
local dataset = {
{input = {0, 0, 1}, target = {1, 0}},
{input = {0, 1, 1}, target = {0, 1}},
{input = {1, 0, 1}, target = {0, 1}},
{input = {1, 1, 1}, target = {1, 0}},
}
-- Training parameters
local epochs = 10000
-- Training loop
for epoch = 1, epochs do
for _, sample in ipairs(dataset) do
nn:train(sample.input, sample.target)
end
-- Optionally, print progress every 1000 epochs
if epoch % 1000 == 0 then
print("Epoch:", epoch)
end
end
-- After training, evaluate the network's accuracy
print("Evaluating Network Accuracy on Dataset:")
nn:evaluate(dataset)
-- Example prediction
print("Example Predictions:")
for _, sample in ipairs(dataset) do
local output = nn:predict(sample.input)
print(string.format("Input: {%d, %d, %d} => Output: {%0.2f, %0.2f} (Predicted Class: %d)",
sample.input[1], sample.input[2], sample.input[3], output[1], output[2], nn:argMax(output)))
end
Explanation:
-
Importing the Module:
- The script starts by requiring the
NeuralNetworkTemplate module.
-
Defining Network Architecture:
inputSize: Number of features in your input data.
hiddenSize: Number of neurons in the hidden layer.
outputSize: Number of classes or outputs.
learningRate: Determines how much the weights are updated during training.
-
Initializing the Network:
- Creates an instance of the neural network with the specified architecture.
-
Dataset:
- An example dataset is provided. Each sample has
input and target.
- Modify this dataset according to the problem you want the network to solve.
-
Training:
- The network is trained over a defined number of
epochs.
- During each epoch, the network processes each sample in the dataset.
- Progress Logging: Every 1000 epochs, it prints the current epoch number.
-
Evaluation:
- After training, the network's accuracy on the dataset is evaluated and printed to the console.
-
Example Predictions:
- Demonstrates how to use the trained network to make predictions on the dataset.
- Prints the raw output and the predicted class for each input.
3. Customization and Usage
a. Adjusting Network Structure:
- Input Size: Change
inputSize based on the number of features in your input data.
- Hidden Size: Adjust
hiddenSize to increase or decrease the network's capacity.
- Output Size: Set
outputSize according to the number of classes or outputs you need.
- Learning Rate: Modify
learningRate to control the speed of learning. A typical range is between 0.1 and 1.0.
b. Modifying the Dataset:
- Inputs: Each
input should be a table of numbers corresponding to feature values.
- Targets: Each
target should be a table representing the expected output, typically one-hot encoded for classification.
Example for a Binary Classification Problem:
local dataset = {
{input = {1, 0, 0}, target = {1, 0}},
{input = {0, 1, 0}, target = {0, 1}},
-- Add more samples as needed
}
c. Changing the Activation Function:
- The current activation function is Sigmoid. To use a different activation function (e.g., ReLU, Tanh), modify the
sigmoid and sigmoidDerivative functions accordingly.
Example for Tanh Activation:
local function tanh(x)
return (math.exp(x) - math.exp(-x)) / (math.exp(x) + math.exp(-x))
end
local function tanhDerivative(x)
return 1 - x * x
end
-- Replace `sigmoid` with `tanh` and `sigmoidDerivative` with `tanhDerivative` in the module.
d. Enhancing the Network:
- Multiple Hidden Layers: To add more hidden layers, extend the network's architecture by adding more weight matrices and biases.
- Different Optimization Techniques: Implement algorithms like Momentum, Adam, or RMSProp for more efficient training.
- Regularization: Add dropout or weight decay to prevent overfitting.
e. Handling Larger Datasets:
Roblox has limitations in terms of performance and memory. For larger datasets, consider:
- Batch Training: Train on batches of data instead of the entire dataset at once.
- Limiting Network Size: Keep the number of neurons and layers manageable to ensure smooth performance.
4. Testing the Template
To test the neural network:
-
Set Up the Scripts:
- Add
NeuralNetworkTemplate as a ModuleScript.
- Add
MainScript as a Script in Roblox Studio.
-
Customize the Dataset:
- Modify the
dataset table in MainScript with your own data.
-
Run the Game:
- Play the game in Roblox Studio.
- Open the Output window to view training progress and accuracy results.
-
Observe the Console:
- The console will display training progress every 1000 epochs.
- After training, it will show the accuracy and example predictions.
5. Example Output
Epoch: 1000
Epoch: 2000
...
Accuracy: 100.00% (4/4)
Example Predictions:
Input: {0, 0, 1} => Output: {0.99, 0.01} (Predicted Class: 1)
Input: {0, 1, 1} => Output: {0.02, 0.98} (Predicted Class: 2)
Input: {1, 0, 1} => Output: {0.03, 0.97} (Predicted Class: 2)
Input: {1, 1, 1} => Output: {0.98, 0.02} (Predicted Class: 1)
6. Final Notes
-
Performance: LuaU is not optimized for heavy neural network computations. Keep the network size and dataset small for smooth performance in Roblox.
-
Learning Rate Tuning: A learning rate that's too high can cause the network to diverge, while too low can make training excessively slow. Experiment to find a suitable value.
-
Dataset Quality: Ensure your dataset is clean, properly normalized, and representative of the problem you're trying to solve.
-
Advanced Features: For more complex tasks, consider integrating external machine learning services or pre-trained models accessed via APIs, as Roblox's scripting environment has limitations.
Feel free to expand upon this template to suit your specific needs. Happy coding!