I need to check if first value is >= 'from' and second value is <= 'to', if true then my function retun number. It's working but I don't know if this is the best and most optimized way to get value(number from table).
local table = {
{from = -1, to = 12483, number = 0},
{from = 12484, to = 31211, number = 1},
{from = 31212, to = 53057, number = 2},
{from = 53058, to = 90200, number = 3},
{from = 90201, to = 153341, number = 4},
{from = 153342, to = 443162, number = 5},
{from = 443163, to = 753380, number = 6},
{from = 753381, to = 1280747, number = 7},
{from = 1280748, to = 2689570, number = 8},
{from = 2689571, to = 6723927, number = 9},
{from = 6723928, to = 6723928, number = 10}
}
local exampleFromValue = 31244
local exampleToValue = 42057
local function getNumber()
local number = 0
for k, v in pairs(table) do
if (v.from and exampleFromValue >= v.from) and (v.to and exampleToValue <= v.to) then
number = v.number
break
end
end
return number
end
print(getNumber())
With this small amount of data, such function doesn't seem like a performace issue. However, you can compress the data a bit:
local t = {
12484, 31212, 53058, 90201, 153342, 443163, 753381, 1280748, 2689571, 6723928
}
local exampleFromValue = 31244
local exampleToValue = 42057
local function getNumber()
local last = -1
for i, v in ipairs(t) do
if exampleFromValue >= last and exampleToValue < v then
return i - 1
end
last = v
end
return 0
end
Related
I need a little help here
Let's suppose I have a table with numbers.
tbl = {'item1' = 6, 'item2' = 1, 'item3' = 6, 'item4' = 3, 'item5' = 2, 'item5' = 3}
I wanna put all repeated numbers in the same table (with key and value) like this:
repeated = {'item1' = 6, 'item3' = 6, 'item4' = 3, 'item5' = 3}
and creat a new one with the "not repeated" numbers:
notrepeated = {'item2' = 1, 'item5' = 2}
Can someone help? Thank you so much.
-- Count the items for each number
local itemsByNum = {}
for item, num in pairs(tbl) do
itemsByNum[num] = (itemsByNum[num] or 0) + 1
end
-- Now move objects to the respective tables
local rep, noRep = {}, {} -- can't use "repeat" as that's a Lua keyword
for item, num in pairs(tbl) do
if itemsByNum[num] > 1 then -- repeated at least once
rep[item] = num
else -- unique number
norep[item] = num
end
end
I've been trying figure out what I have done wrong for many hours, but just can't figure out. I've even looked at other basic Neural Network libraries to make sure that my gradient descent algorithms were correct, but it still isn't working.
I'm trying to teach it XOR but it outputs -
input (0 0) | 0.011441891321516094
input (1 0) | 0.6558508610135193
input (0 1) | 0.6558003273099053
input (1 1) | 0.6563021185296245
after 1000 trainings, so clearly there's something wrong.
The code is written in lua and I created the Neural Network from raw data so you can easily understand how the data is formatted.
- Training code -
math.randomseed(os.time())
local nn = require("NeuralNetwork")
local network = nn.newFromRawData({
["activationFunction"] = "sigmoid",
["learningRate"] = 0.3,
["net"] = {
[1] = {
[1] = {
["value"] = 0
},
[2] = {
["value"] = 0
}
},
[2] = {
[1] = {
["bias"] = 1,
["netInput"] = 0,
["value"] = 0,
["weights"] = {
[1] = 1,
[2] = 1
}
},
[2] = {
["bias"] = 1,
["netInput"] = 0,
["value"] = 0,
["weights"] = {
[1] = 1,
[2] = 1
}
},
[3] = {
["bias"] = 1,
["netInput"] = 0,
["value"] = 0,
["weights"] = {
[1] = 1,
[2] = 1
}
},
[4] = {
["bias"] = 1,
["netInput"] = 0,
["value"] = 0,
["weights"] = {
[1] = 1,
[2] = 1
}
}
},
[3] = {
[1] = {
["bias"] = 1,
["netInput"] = 0,
["value"] = 0,
["weights"] = {
[1] = 1,
[2] = 1,
[3] = 1,
[4] = 1
}
}
}
}
})
attempts = 1000
for i = 1,attempts do
network:backPropagate({0,0},{0})
network:backPropagate({1,0},{1})
network:backPropagate({0,1},{1})
network:backPropagate({1,1},{0})
end
print("Results:")
print("input (0 0) | "..network:feedForward({0,0})[1])
print("input (1 0) | "..network:feedForward({1,0})[1])
print("input (0 1) | "..network:feedForward({0,1})[1])
print("input (1 1) | "..network:feedForward({1,1})[1])
- Library -
local nn = {}
nn.__index = nn
nn.ActivationFunctions = {
sigmoid = function(x) return 1/(1+math.exp(-x/1)) end,
ReLu = function(x) return math.max(0, x) end,
}
nn.Derivatives = {
sigmoid = function(x) return x * (1 - x) end,
ReLu = function(x) return x > 0 and 1 or 0 end,
}
nn.CostFunctions = {
MSE = function(outputs, expected)
local sum = 0
for i = 1, #outputs do
sum += 1/2*(expected[i] - outputs[i])^2
end
return sum/#outputs
end,
}
function nn.new(inputs, outputs, hiddenLayers, neurons, learningRate, activationFunction)
local self = setmetatable({}, nn)
self.learningRate = learningRate or .3
self.activationFunction = activationFunction or "ReLu"
self.net = {}
local net = self.net
local layers = hiddenLayers+2
for i = 1, layers do
net[i] = {}
end
for i = 1, inputs do
net[1][i] = {value = 0}
end
for i = 2, layers-1 do
for x = 1, neurons do
net[i][x] = {netInput = 0, value = 0, bias = math.random()*2-1, weights = {}}
for z = 1, #net[i-1] do
net[i][x].weights[z] = math.random()*2-1
end
end
end
for i = 1, outputs do
net[layers][i] = {netInput = 0, value = 0, bias = math.random()*2-1, weights = {}}
for z = 1, #net[layers-1] do
net[layers][i].weights[z] = math.random()*2-1
end
end
return self
end
function nn.newFromRawData(data)
return setmetatable(data, nn)
end
function nn:feedForward(inputs)
local net = self.net
local activation = self.activationFunction
local layers = #net
local inputLayer = net[1]
local outputLayer = net[layers]
for i = 1, #inputLayer do
inputLayer[i].value = inputs[i]
end
for i = 2, layers do
local layer = net[i]
for x = 1, #layer do
local sum = layer[x].bias
for z = 1, #net[i-1] do
sum += net[i-1][z].value * layer[x].weights[z]
end
layer[x].netInput = sum
layer[x].value = nn.ActivationFunctions[activation](sum)
end
end
local outputs = {}
for i = 1, #outputLayer do
table.insert(outputs, outputLayer[i].value)
end
return outputs
end
function nn:backPropagate(inputs, expected)
local outputs = self:feedForward(inputs)
local net = self.net
local activation = self.activationFunction
local layers = #net
local lr = self.learningRate
local inputLayer = net[1]
local outputLayer = net[layers]
for i = 1, #outputLayer do
local delta = -(expected[i] - outputs[i]) * nn.Derivatives[activation](net[layers][i].value)
outputLayer[i].delta = delta
end
for i = layers-1, 2, -1 do
local layer = net[i]
local nextLayer = net[i+1]
for x = 1, #layer do
local delta = 0
for z = 1, #nextLayer do
delta += nextLayer[z].delta * nextLayer[z].weights[x]
end
layer[x].delta = delta * nn.Derivatives[activation](layer[x].value)
end
end
for i = 2, layers do
local lastLayer = net[i-1]
for x = 1, #net[i] do
net[i][x].bias -= lr * net[i][x].delta
for z = 1, #lastLayer do
net[i][x].weights[z] -= lr * net[i][x].delta * lastLayer[z].value
end
end
end
end
return nn
Any help would be highly appreciated, thanks!
All initial weights must be DIFFERENT numbers, otherwise backpropagation will not work. For example, you can replace 1 with math.random()
Increase number of attempts to 10000
With these modifications, your code works fine:
Results:
input (0 0) | 0.028138230938126
input (1 0) | 0.97809448578087
input (0 1) | 0.97785000216126
input (1 1) | 0.023128477689456
I'm doing a Xonix game on corona sdk. As a playing field, I decided to use a grid of squares. Width 44, Height 71. As a result, I received a row consisting of 3124(44*71) squares along which the player moves. But I have problems with optimization. The engine can not cope with such a number of squares on the screen at the same time. Because of this, FPS on a smartphone is not more than 12. Help me find the best solution. All that concerns polygons and meshes, I am not strong in geometry ((((
Reducing the number of squares is a bad idea. Then the appearance is lost, and the field is captured too large pieces.
Thank you in advance!
-- Creating a playing field
M.create_pole = function()
-- init
local image = display.newImage
local rect = display.newRect
local rrect = display.newRoundedRect
local floor = math.floor
M.GR_ZONE = display.newGroup()
M.POLE = {}
-- bg
M.POLE.bg = rrect(0,0,150,150,5)
M.POLE.bg.width = M.width_pole
M.POLE.bg.height = M.height_pole
M.POLE.bg.x = _W/2
M.POLE.bg.y = _H/2
M.POLE.bg.xScale = _H*.00395
M.POLE.bg.yScale = _H*.00395
M.POLE.bg:setFillColor(API.hexToCmyk(M.color.land))
M.GR:insert(M.POLE.bg)
M.POLE.img = image(IMAGES..'picture/test.jpg')
M.POLE.img.width = M.width_pole-M.size_xonix
M.POLE.img.height = M.height_pole-M.size_xonix
M.POLE.img.x = _W/2
M.POLE.img.y = _H/2
M.POLE.img.xScale = _H*.00395
M.POLE.img.yScale = _H*.00395
M.POLE.img.strokeWidth = 1.3
M.POLE.img:setStrokeColor(API.hexToCmyk(M.color.img))
M.GR:insert(M.POLE.img)
-- control player
M.POLE.bg:addEventListener( 'touch', M.swipe )
M.POLE.bg:addEventListener( 'tap', function(e)
M.POLE.player.state = 0
end )
-- arr field
M.arr_pole = {} -- newRect
local jj = 0
for i=1,M.delta_height do -- 71 point
M.arr_pole[i] = {}
M.GUI.border[i] = {}
for k=1,M.delta_width do -- 44 point
jj = jj+1
M.arr_pole[i][k] = {nm = jj}
M.GUI.border[i][k] = {}
local xx = k*M.size_xonix
local yy = i*M.size_xonix
local _x = floor(xx-M.size_xonix/2)
local _y = floor(yy-M.size_xonix/2)
M.arr_pole[i][k][1] = image(IMAGES..'pole/land.jpg')
M.arr_pole[i][k][1] .x = _x
M.arr_pole[i][k][1] .y = _y
M.GR_ZONE:insert(M.arr_pole[i][k][1])
-- water at the edges
-- the rest is land
if (i==1 or i==M.delta_height)
or (k==1 or k==M.delta_width) then
M.arr_pole[i][k].type = 0
else
M.arr_pole[i][k].type = 2
M.arr_pole[i][k][1].isVisible = true
end
end
end
M.GR_ZONE.width = M.POLE.bg.width*M.POLE.bg.xScale
M.GR_ZONE.height = M.POLE.bg.height*M.POLE.bg.yScale
M.GR_ZONE.x = M.POLE.bg.x-M.POLE.bg.width*M.POLE.bg.xScale/2
M.GR_ZONE.y = M.POLE.bg.y-M.POLE.bg.height*M.POLE.bg.yScale/2
-- player
local _x = M.arr_pole[1][1][1].x
local _y = M.arr_pole[1][1][1].y
M.POLE.player = image(IMAGES..'ui/player.png')
M.POLE.player.x = _x
M.POLE.player.y = _y
M.POLE.player.width = M.size_xonix*1.5
M.POLE.player.height = M.size_xonix*1.5
M.POLE.player.state = 0
M.GR_ZONE:insert(M.POLE.player)
M.POLE.player:toFront()
end
-- get all free cells
- land
M.get_free = function(_i,_j,_start)
local _par = pairs
local _fill = M.filling_arr
local _arr = M.arr_pole
local _index = {
{-1,-1}, {0,-1}, {1,-1},
{-1, 0}, {1, 0},
{-1, 1}, {0, 1}, {1, 1},
}
-- mark as verified
_arr[_i][_j].is_check = true
_fill[#_fill+1] = {_i,_j}
for k,v in _par(_index) do
local i = _i+v[1]
local j = _j+v[2]
if i>1 and i<M.delta_height
and j>1 and j<M.delta_width then
if not _arr[i][j].is_check then
if _arr[i][j].type==2 then
M.get_free(i,j)
end
end
end
end
if _start then
return _fill
end
end
-- fill(capture)
M.filling = function()
-- init
local par = pairs
local tb_rem = table.remove
local arr = M.arr_pole
M.island_arr = {}
-- check indicator
for i,ii in par(arr) do
for j,jj in par(ii) do
if jj.type==2 then
jj.is_check = false
end
end
end
-- we divide land into islands
for i,ii in par(arr) do
for j,jj in par(ii) do
if jj.type==2 and not jj.is_check then
M.filling_arr = {}
M.island_arr[#M.island_arr+1] = M.get_free(i,j,true)
end
end
end
- find a larger island and delete it
local sel_max = {dir = '', count = 1}
for k,v in par(M.island_arr) do
if #v>=sel_max.count then
sel_max.dir = k
sel_max.count = #v
end
end
if #M.island_arr>0 then
tb_rem(M.island_arr,sel_max.dir)
end
-- fill
for k,v in par(M.island_arr) do
for kk,vv in par(v) do
local obj = arr[vv[1]][vv[2]]
obj.type = 0
obj[1].isVisible = false
end
end
-- turning the edges into water
for k,v in par(M.bread_crumbs) do
local arr = arr[v.arr_y][v.arr_x]
arr.type = 0
arr[1].isVisible = false
end
M.clear_history()
end
I am inserting into a table like this
Admin = {}
table.insert(Admins, {id = playerId, Count = 0})
And that works fine.
How do I remove that specific admin from that table now?
The following does not work, and Im sure its because ID is stored in an array that's inside of the table, but how would I access that then?
table.remove(Admins, playerId)
Basically,
I want to remove from the table Admins, where the ID == playerId that I input.
There are two approaches to remove an entry from the table, both are acceptable ways:
1. myTable[index] = nil Removes an entry from given index, but adds a hole in the table by maintaining the indices
local Admins = {}
table.insert(Admins, {id = 10, Count = 0})
table.insert(Admins, {id = 20, Count = 1})
table.insert(Admins, {id = 30, Count = 2})
table.insert(Admins, {id = 40, Count = 3})
local function removebyKey(tab, val)
for i, v in ipairs (tab) do
if (v.id == val) then
tab[i] = nil
end
end
end
-- Before
-- [1] = {['Count'] = 0, ['id'] = 10},
-- [2] = {['Count'] = 1, ['id'] = 20},
-- [3] = {['Count'] = 2, ['id'] = 30},
-- [4] = {['Count'] = 3, ['id'] = 40}}
removebyKey(Admins, 20)
-- After
-- [1] = {['Count'] = 0, ['id'] = 10},
-- [3] = {['Count'] = 2, ['id'] = 30},
-- [4] = {['Count'] = 3, ['id'] = 40}
2. table.remove(myTable, index)
Removes the entry from given index and renumbering the indices
local function getIndex(tab, val)
local index = nil
for i, v in ipairs (tab) do
if (v.id == val) then
index = i
end
end
return index
end
local idx = getIndex(Admins, 20) -- id = 20 found at idx = 2
if idx == nil then
print("Key does not exist")
else
table.remove(Admins, idx) -- remove Table[2] and shift remaining entries
end
-- Before is same as above
-- After entry is removed. Table indices are changed
-- [1] = {['id'] = 10, ['Count'] = 0},
-- [2] = {['id'] = 30, ['Count'] = 2},
-- [3] = {['id'] = 40, ['Count'] = 3}
Thank you for all the support with lua, I'm very new and my application is working nicely so far.
I've made an app that will take in a few thousand numbers for different items. I'm trying to find the Mean/Media/Mode for each item, I've been able to do this for a single item, but not for all items.
Here is my table structure:
for i = 0, 1500 do
local e = {}
e.seller,
e.buyer,
e.itemName,
e.soldAmount = GetSoldAmount(FromMember(i))
table.insert(allSalesTempTable, e)
end
Table output format
[1] =
{
["itemName"] = [[Salad]]
["buyer"] = [[#Mike]],
["eventType"] = 15,
["soldAmount"] = 150,
["seller"] = [[#Sarah]],
},
[2] =
{
["itemName"] = [Pizza]
["buyer"] = [[#James]],
["eventType"] = 15,
["soldAmount"] = 150,
["seller"] = [[#Sarah]],
},
[3] =
{
["itemName"] = [Salad]
["buyer"] = [[#Frank]],
["eventType"] = 15,
["soldAmount"] = 75,
["seller"] = [[#Sarah]],
},
[4] ...
},
Then I'm trying to send the table/array to this mean function
stats={}
-- Get the mean value of a table
function stats.mean( t )
local sum = 0
local count= 0
local tempTbl = {}
(This is completely not going to work, but its what I'm trying so far)
for k,v in pairs(t) do tempTbl[k] = v
if v.itemName == tempTbl.itemName then
sum = sum + v.soldAmount
count = count + 1
end
end
return (sum / count)
end
--- To get the function started
stats.mean(e)
Here is where I'm getting fuzzy, Not sure if I can add the MEAN while collecting the data into the first temp table, or if it needs to be re-calculated after I have all the data?
If it needs to be done after, then my stats.mean(e) needs a way to insert it?
I'm trying to get this output:
[1] =
{
["itemName"] = [[Salad]]
["buyer"] = [[#Mike]],
["eventType"] = 15,
["soldAmount"] = 150,
["seller"] = [[#Sarah]],
["mean"] = 112.5 - New Insert somehow
},
[2] =
{
["itemName"] = [Pizza]
["buyer"] = [[#James]],
["eventType"] = 15,
["soldAmount"] = 150,
["seller"] = [[#Sarah]],
["mean"] = 150 - New Insert somehow
},
[3] =
{
["itemName"] = [Salad]
["buyer"] = [[#Frank]],
["eventType"] = 15,
["soldAmount"] = 75,
["seller"] = [[#Sarah]],
["mean"] = 112.5 - New Insert somehow
},
[4] ...
},
I've been working on this problem for a few days, After I see how to adjust my format for the mean and insert into the existing table I'll be able to figure out mean/min/max/median/mode easy enough.