将生成markov链的python代码转换为lua

时间:2019-01-04 20:44:19

标签: python dictionary lua translate markov

作为一个初学者项目,我尝试将此python代码转换为lua代码 https://eli.thegreenplace.net/2018/elegant-python-code-for-a-markov-chain-text-generator/。我在正确翻译python“ random.choices”时遇到问题。马可夫矩阵本身应该起作用。感谢您使用此lua代码生成markov链的任何帮助。 这是马尔可夫矩阵3的马尔可夫矩阵的输出,输入为“ 1111111111111110000006000000000006600”。

600 0   1
111 1   12
111 0   1
060 0   1
660 0   1
006 6   1
006 0   1
100 0   1
000 6   2
000 0   11
110 0   1
066 0   1

使用该信息,我需要计算下一步,但是我不知道如何使用lua进行操作。 对于序列600,0后跟100%, 对于序列111,1跟随12 / 13,0跟随1/13, 对于序列060,0后跟100%,依此类推。

这是我的lua代码:

math.randomseed(os.time()- os.clock() * 1000);
-- make dictionary;
function defaultdict(default_value_factory);
local t = {};
local metatable = {};
metatable.__index = function(t, key);
if not rawget(t, key) then;
rawset(t, key, default_value_factory(key));
end;
return rawget(t, key);
end;
return setmetatable(t, metatable);
end;
;
;
-- make markov matrix;
STATE_LEN = 3;
model = defaultdict(function() return {} end)
data = "1111111111111110000006000000000006600";
print("datasize: ", #data)
print('Learning model...')
for i = 1, (#data - STATE_LEN) do;
state = data:sub(i, i + STATE_LEN-1);
print("state: ", state)    
local next = data:sub(i + STATE_LEN, i + STATE_LEN);
print("next: ", next);
model[state][next] = (model[state][next] or 0)+1;
end;
;
;
-- make markov chain;
print('Sampling...');
;
-- make key list;
local keyset={};
local n=0;
for k,v in pairs(model) do;
n=n+1;
keyset[n]=k;
end;
-- make random key;
local randomKey = keyset[math.random(#keyset)];
print("RandomKey: ", randomKey)
state = randomKey;
;
-- make table from random key;
local str = state;
local stateTable = {};
for i = 1, #str do;
stateTable[i] = str:sub(i, i);
end;
;
out = stateTable;
print ("random key as table: ", table.unpack(stateTable));
;
-- make value list;
local valueset={};
local n=0;
for key, value in pairs(model) do;
for k, v in pairs(value) do;
n=n+1;
valueset[n]=v;
end;
end;
;
print("Keys: ", table.unpack(keyset));
print("Vals: ", table.unpack(valueset));
;
for key, value in pairs(model) do;
for k, v in pairs(value) do;
print(key, k, v);
end;
end;
;
;
-- make markov chain;
for i = 1, 400 do;
table.insert(out, #out + 1, math.random(10)); 
state = string.sub(state, 2, #state) .. out[#out];
end;
-- print markov chain;
print(table.concat(out));
;

1 个答案:

答案 0 :(得分:0)

我想我自己弄清楚了。 无论如何,我不知道是否应该删除我的问题,这是代码和答案:

select (aips.Item(NULL, 'Test 1')).*;