Python To Lua Translation

Im currently trying to translate the code in this video: Create a Simple Neural Network in Python from Scratch - YouTube
to lua however I’m stuck as I don’t know python and lua lacks most of the functions python has.

Heres my code as of now:

local random = Random.new(1)

function sigmoid(x)
	return 1 / (1 + math.exp(-x))
end

function sigmoid_derivative(x)
	return x * (1 - x)
end

function sigmoidDotTable(a,b)
	local output = {}
	
	for _,v in ipairs(a) do
		local aVector = Vector3.new(v[1],v[2],v[3])
		local bVector = Vector3.new(b[1],b[2],b[3])
		
		table.insert(output,aVector:Dot(bVector))
	end
	
	for i,v in ipairs(output) do
		output[i] = sigmoid(v)
	end
	
	return output
end

function calculateError(a,b)
	local output = {}
	
	for i,v in ipairs(a) do
		local bv = b[i]
		
		table.insert(output,v-bv)
	end
	
	return output
end

function calculateAdjustment(e,o)
	local output = {}
	
	for i,v in pairs(o) do
		table.insert(output,e[i]*sigmoid_derivative(v))
	end
	
	return output
end

function adjustWeights(inp,a)
	local output = {}

	for _,v in ipairs(inp) do
		local aVector = Vector3.new(v[1],v[2],v[3])
		local bVector = Vector3.new(a[1],a[2],a[3])

		table.insert(output,aVector:Dot(bVector))
	end

	return output
end

local training_inputs = {
	{0,0,1},
	{1,1,1},
	{1,0,1},
	{0,1,1},
}

local training_outputs = {0,1,1,0}

local synaptic_weights = {
	2 * random:NextNumber(0,1) - 1,
	2 * random:NextNumber(0,1) - 1,
	2 * random:NextNumber(0,1) - 1,
}

print("Random Starting Weights", synaptic_weights)

for i = 0,20000 do
	local input_layer = training_inputs
	
	outputs = sigmoidDotTable(input_layer,synaptic_weights)
	
	local error = calculateError(training_outputs,outputs)
	
	local adjustments = calculateAdjustment(error,outputs)
	
	local Adjusted = adjustWeights(input_layer,adjustments)
	
	for index,weight in ipairs(synaptic_weights) do
		synaptic_weights[i] = weight + Adjusted[index]
	end
end

print("Synaptic Weights after training",synaptic_weights)

print("Outputs after training", outputs)

The error I’m getting is this at the part where the weights are adjusted in the for loop:
image

Based on your code, the error is on the line synaptic_weights[i] = weight + Adjusted[index], and the error says number and nil, meaning that Adjusted[index] is nil. This probably means that the number of items in the synaptic_weights table is more than the items in the Adjusted table.

I would start on looking through why there might be a mismatch there.

I know that the issue is that I don’t know how to rectify such issue.

Another issue might be:

synaptic_weights[i] = weight + Adjusted[index]

That i should (maybe) be index.

that seemed to of fixed the issue