This repository has been archived by the owner on May 15, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathUnionHypothesisSpace.py
179 lines (154 loc) · 5.24 KB
/
UnionHypothesisSpace.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
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
# python3
# -*- coding: utf-8 -*-
# @File : UnionHypothesisSpace.py
# @Desc : Book 1-2
# @Project : Melon-book-puzzles
# @Time : 9/10/19 6:05 PM
# @Author : Loopy
# @Contact : [email protected]
# @License : CC BY-NC-SA 4.0 (subject to project license)
from DatasetSpace import DatasetSpace
import json
import pandas as pd
import matplotlib.pyplot as plt
class UnionHypothesisSpace:
"""
Figure out how the number of hypothsis change with the disjunction become longer
"""
def __init__(self, dataset=None):
if dataset is None:
return
self.__data = dataset
self.__space = DatasetSpace(dataset)
self.__features = list(self.__data.columns)
self.__features.remove("target")
self.sample_space = self.get_sample_space()
# history hypothsis_code
self.his_hypothsis_code = dict()
self.his_hypothsis_code["k=1"] = self.get_conj_hypothesis()
for i, h in enumerate(self.his_hypothsis_code["k=1"]):
self.his_hypothsis_code["k=1"][i] = self.encode(h)
# shown hypothsis_codes
self.hypothsis_code_pool = [False] * 2 ** (len(self.sample_space))
def get_conj_hypothesis(self):
return self.__space.get_hypothesis_space()
def get_sample_space(self):
return self.__space.get_sample_space()
def encode(self, hypothesis):
"""
Encode a hypothsis to a unique code
:param hypothesis: list
:return: int the unique code
"""
code = ""
for s in self.sample_space:
flag = "1"
for i in range(len(self.__features)):
if s[i] != hypothesis[i] and hypothesis[i] != "*":
flag = "0"
code += flag
return int(code, 2)
def union(self, k):
"""
Try union the hypothsis and skip redundant ones
:param k:
:return:
"""
self.his_hypothsis_code["k=" + str(k + 1)] = []
for i, h_l in enumerate(self.his_hypothsis_code["k=" + str(k)]):
for j, h_r in enumerate(self.his_hypothsis_code["k=1"]):
if not self.hypothsis_code_pool[(h_l | h_r)]:
self.hypothsis_code_pool[(h_l | h_r)] = True
self.his_hypothsis_code["k=" + str(k + 1)].append((h_l | h_r))
print("k={} i={} j={}".format(k, i, j), end="\r")
def run(self, k=1):
"""
runner
:param k: int the k to start
:return: None
"""
max_hypothsis_number = 2 ** (len(self.sample_space))
count = 0
while count < max_hypothsis_number:
self.union(k)
self.save_report(k)
k += 1
count = 0
for h in self.hypothsis_code_pool:
if h:
count += 1
self.plot(k)
def load(self):
"""
load result from res.json
:return:
"""
with open("../temp/res.json", "r") as f:
res = json.loads(f.read())
self.__data = res["dataset"]
self.__space = DatasetSpace(res["dataset"])
self.his_hypothsis_code = res["his_hypothsis_code"]
self.hypothsis_code_pool = res["hypothsis_code_pool"]
self.sample_space = self.get_sample_space()
self.__features = list(self.__data.columns)
self.__features.remove("target")
def save_report(self, k):
"""
save result to res.json and report
:param k: int current k
:return: None
"""
with open("../temp/res.json", "w") as f:
res = str(
{
"dataset": self.__data,
"his_hypothsis_code": self.his_hypothsis_code,
"hypothsis_code_pool": self.hypothsis_code_pool,
}
)
f.write(res)
count = 0
for h in self.hypothsis_code_pool:
if h:
count += 1
print(
"{}\n"
"Working on {}-term-disjunction:\n"
"Number of {}-term-disjunction hypothsis:{}\n"
"Number of hypothsis:{}/{} = {}%".format(
"=" * 79,
k + 1,
k,
len(self.his_hypothsis_code["k=" + str(k)]),
count,
2 ** (len(self.sample_space)),
round(count / 2 ** (len(self.sample_space)) * 100, 2),
)
)
def plot(self, k):
"""
plot k-number of hypothsis
:param k: int max number of disjunction term
:return: None
"""
x = list(range(k))
y = [len(self.his_hypothsis_code["k=" + str(i + 1)]) for i in range(k)]
plt.plot(x, y)
plt.show()
plt.savefig("../temp/1.png")
if __name__ == "__main__":
melon_data = pd.DataFrame(
[
["青绿", "蜷缩", "浊响", True],
["乌黑", "蜷缩", "浊响", True],
["青绿", "硬挺", "清脆", False],
["乌黑", "稍蜷", "沉闷", False],
],
columns=["色泽", "根蒂", "敲声", "target"],
)
space = UnionHypothesisSpace(melon_data)
space.run()
# when you have to continue
# space = UnionHypothesisSpace()
# space.load()
# space.run(10)