forked from rspeer/dominionstats
-
Notifications
You must be signed in to change notification settings - Fork 17
/
sofia_predict.py
58 lines (47 loc) · 1.81 KB
/
sofia_predict.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import subprocess
import pymongo
import game
import game_state_features
import math
def log_odds_to_prob(logodds):
odds = math.exp(logodds)
return odds / (1 + odds)
def encode_features_for_all_turns(game_val):
return [game_state_features.state_to_features(game_val, game_state)
for game_state in game_val.game_state_iterator()]
class SofiaWinPredictor:
def __init__(self, model_name, prediction_type='logistic',
hash_mask_bits=None):
self.use_sofia = not subprocess.call(['which', 'sofia-ml'], stdout=subprocess.PIPE)
if not self.use_sofia:
return
args = ['sofia-ml',
'--model_in', model_name,
'--test_stream',
'--prediction_type', prediction_type]
if hash_mask_bits is not None:
args.extend(['--hash_mask_bits', str(hash_mask_bits)])
p = subprocess.PIPE
self.sofia_proc = subprocess.Popen(args, stdin=p, stdout=p)
def predict_all_turns(self, game_val):
ret = []
all_turns_features = encode_features_for_all_turns(game_val)
if self.use_sofia:
for features in all_turns_features:
game_state_features.output_libsvm_state(features,
self.sofia_proc.stdin)
for _ in all_turns_features:
line = self.sofia_proc.stdout.readline()
# print line,
ret.append(log_odds_to_prob(float(line)))
else:
for _ in all_turns_features:
ret.append(0.5)
return ret
def main():
c = pymongo.Connection()
g = game.Game(c.test.games.find_one())
predictor = SofiaWinPredictor('data/logreg-peg.model')
print predictor.predict_all_turns(g)
if __name__ == '__main__':
main()