Spaces:
Runtime error
Runtime error
File size: 5,283 Bytes
dfcdf7b |
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 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 |
import os
import sys
import matplotlib.pyplot as plt
import numpy as np
import random
import jprops
from random import randint
from matumizi.util import *
from matumizi.mlutil import *
"""
Markov chain classifier
"""
class MarkovChainClassifier():
def __init__(self, configFile):
"""
constructor
Parameters
configFile: config file path
"""
defValues = {}
defValues["common.model.directory"] = ("model", None)
defValues["common.model.file"] = (None, None)
defValues["common.verbose"] = (False, None)
defValues["common.states"] = (None, "missing state list")
defValues["train.data.file"] = (None, "missing training data file")
defValues["train.data.class.labels"] = (["F", "T"], None)
defValues["train.data.key.len"] = (1, None)
defValues["train.model.save"] = (False, None)
defValues["train.score.method"] = ("accuracy", None)
defValues["predict.data.file"] = (None, None)
defValues["predict.use.saved.model"] = (True, None)
defValues["predict.log.odds.threshold"] = (0, None)
defValues["validate.data.file"] = (None, "missing validation data file")
defValues["validate.use.saved.model"] = (False, None)
defValues["valid.accuracy.metric"] = ("acc", None)
self.config = Configuration(configFile, defValues)
self.stTranPr = dict()
self.clabels = self.config.getStringListConfig("train.data.class.labels")[0]
self.states = self.config.getStringListConfig("common.states")[0]
self.nstates = len(self.states)
for cl in self.clabels:
stp = np.ones((self.nstates,self.nstates))
self.stTranPr[cl] = stp
def train(self):
"""
train model
"""
#state transition matrix
tdfPath = self.config.getStringConfig("train.data.file")[0]
klen = self.config.getIntConfig("train.data.key.len")[0]
for rec in fileRecGen(tdfPath):
cl = rec[klen]
rlen = len(rec)
for i in range(klen+1, rlen-1, 1):
fst = self.states.index(rec[i])
tst = self.states.index(rec[i+1])
self.stTranPr[cl][fst][tst] += 1
#normalize to probability
for cl in self.clabels:
stp = self.stTranPr[cl]
for i in range(self.nstates):
s = stp[i].sum()
r = stp[i] / s
stp[i] = r
#save
if self.config.getBooleanConfig("train.model.save")[0]:
mdPath = self.config.getStringConfig("common.model.directory")[0]
assert os.path.exists(mdPath), "model save directory does not exist"
mfPath = self.config.getStringConfig("common.model.file")[0]
mfPath = os.path.join(mdPath, mfPath)
with open(mfPath, "w") as fh:
for cl in self.clabels:
fh.write("label:" + cl +"\n")
stp = self.stTranPr[cl]
for r in stp:
rs = ",".join(toStrList(r, 6)) + "\n"
fh.write(rs)
def validate(self):
"""
validate using model
"""
useSavedModel = self.config.getBooleanConfig("predict.use.saved.model")[0]
if useSavedModel:
self.__restoreModel()
else:
self.train()
vdfPath = self.config.getStringConfig("validate.data.file")[0]
accMetric = self.config.getStringConfig("valid.accuracy.metric")[0]
yac, ypr = self.__getPrediction(vdfPath, True)
if type(self.clabels[0]) == str:
yac = self.__toIntClabel(yac)
ypr = self.__toIntClabel(ypr)
score = perfMetric(accMetric, yac, ypr)
print(formatFloat(3, score, "perf score"))
def predict(self):
"""
predict using model
"""
useSavedModel = self.config.getBooleanConfig("predict.use.saved.model")[0]
if useSavedModel:
self.__restoreModel()
else:
self.train()
#predict
pdfPath = self.config.getStringConfig("predict.data.file")[0]
_ , ypr = self.__getPrediction(pdfPath)
return ypr
def __restoreModel(self):
"""
restore model
"""
mdPath = self.config.getStringConfig("common.model.directory")[0]
assert os.path.exists(mdPath), "model save directory does not exist"
mfPath = self.config.getStringConfig("common.model.file")[0]
mfPath = os.path.join(mdPath, mfPath)
stp = None
cl = None
for rec in fileRecGen(mfPath):
if len(rec) == 1:
if stp is not None:
stp = np.array(stp)
self.stTranPr[cl] = stp
cl = rec[0].split(":")[1]
stp = list()
else:
frec = asFloatList(rec)
stp.append(frec)
stp = np.array(stp)
self.stTranPr[cl] = stp
def __getPrediction(self, fpath, validate=False):
"""
get predictions
Parameters
fpath : data file path
validate: True if validation
"""
nc = self.clabels[0]
pc = self.clabels[1]
thold = self.config.getFloatConfig("predict.log.odds.threshold")[0]
klen = self.config.getIntConfig("train.data.key.len")[0]
offset = klen+1 if validate else klen
ypr = list()
yac = list()
for rec in fileRecGen(fpath):
lodds = 0
rlen = len(rec)
for i in range(offset, rlen-1, 1):
fst = self.states.index(rec[i])
tst = self.states.index(rec[i+1])
odds = self.stTranPr[pc][fst][tst] / self.stTranPr[nc][fst][tst]
lodds += math.log(odds)
prc = pc if lodds > thold else nc
ypr.append(prc)
if validate:
yac.append(rec[klen])
else:
recp = prc + "\t" + ",".join(rec)
print(recp)
re = (yac, ypr)
return re
def __toIntClabel(self, labels):
"""
convert string class label to int
Parameters
labels : class label values
"""
return list(map(lambda l : self.clabels.index(l), labels)) |