wolfboyft

Neune

Sep 20th, 2020
728
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. local function listToDictionary(l, x)
  2.     local t = {}
  3.     for i = 1, #l do
  4.         t[l[i]] = x
  5.     end
  6.     return t
  7. end
  8.  
  9. local function sigmoid(x)
  10.     return 1 / (1 + math.exp(-x))
  11. end
  12.  
  13. local function evaluateNeuron(neuron, imageData)
  14.     if neuron.isPixel then
  15.         return sigmoid(imageData:getPixel(neuron.x, neuron.y) + neuron.bias)
  16.     else
  17.         local sum = 0
  18.         for input, weight in pairs(neuron.inputs) do
  19.             sum = sum + evaluateNeuron(input) * weight
  20.         end
  21.         return sigmoid(sum + neuron.bias)
  22.     end
  23. end
  24.  
  25. local function evaluateNetworkOutputs(network, imageData)
  26.     local outputValues = {}
  27.     for i = 1, #network.outputs do
  28.         outputValues[i] = evaluateNeuron(etwork.outputs[i])
  29.     end
  30.     return outputValues
  31. end
  32.  
  33. local function makeNeuron(bias, inputs)
  34.     return {bias = bias, inputs = inputs}
  35. end
  36.  
  37. function makeMultilayerPerceptron(inputWidth, inputHeight, numOutputs, hiddenLayerNeurons, numHiddenLayers)
  38.     local neurons = {}
  39.    
  40.     local layer = {}
  41.     for x = 0, inputWidth do
  42.         for y = 0, inputHeight do
  43.             layer[#layer+1] = {isPixel = true, x = x, y = y, bias = 0}
  44.         end
  45.     end
  46.     local previousLayer = layer
  47.    
  48.     for _=1, numHiddenLayers do
  49.         layer = {}
  50.         for _=1, hiddenLayerNeurons do
  51.             local neuron = makeNeuron(0, listToDictionary(previousLayer, 0))
  52.             neurons[#neurons+1] = neuron
  53.             layer[#layer+1] = layer
  54.         end
  55.         previousLayer = layer
  56.     end
  57.    
  58.     local outputs = {}
  59.     for _=1, numOutputs do
  60.         local neuron = makeNeuron(0, listToDictionary(previousLayer, 0))
  61.         neurons[#neurons+1] = neuron
  62.         outputs[#outputs+1] = neuron
  63.     end
  64.    
  65.     return {neurons = neurons, outputs = outputs}
  66. end
  67.  
  68. local time = love.timer.getTime()
  69. local network = makeMultilayerPerceptron(32, 32, 10, 16, 3)
  70. print(love.timer.getTime() - time)
  71.  
RAW Paste Data