机器学习-西瓜书-课后题-第一章
习题1.1 表1.1中若只包含编号为1和4的两个样例,试给出相应的版本空间。
如果只包含1和4样例,那么三个属性的取值都只有两个
色泽:青绿,乌黑
根蒂:蜷缩,稍蜷
敲声:浊响,沉闷
如果我们用A来每种属性的第一个值,B来表示每种属性的第二个值,正例用Y表示,反例用N来表示。那么训练集的就可以用 AAAY,BBBN来表示。
根据假设空间规模的计算方法,每种属性除了A,B外,还有一个属性表示不管取A或者B对结果都没有影响,这里用通配符.来表示。所以每种属性有三个取值即:A,B,.。
然后假设空间的规模就是:3 * 3 * 3 + 1 = 28
接下来,就是计算假设空间中的所有假设,然后根据正例和反例来在假设空间上对不符合的假设做删除,最后得到符合训练集样例的假设空间即是版本空间。
注意:对于...这样的假设,虽然匹配正例,但同时也匹配反例,所以要删除。
即匹配优先级是:遍历所有假设空间,如果当前假设与反例匹配,则删除当前假设,如果不匹配,则去判断该假设是否和所有正例匹配,只要有一个正例不匹配,就删除该假设。
python代码如下:代码的实现参考这位大佬的博客:https://blog.csdn.net/qq_40273675/article/details/89856447
import re
def get_all_hypothesis(list_attr):
set_hyp = set()
for val_attr0 in list_attr[0]:
for val_attr1 in list_attr[1]:
for val_attr2 in list_attr[2]:
hyp = val_attr0 + val_attr1 + val_attr2
set_hyp.add(hyp)
return set_hyp
def classify(list_ins):
positive_class = []
negative_class = []
for instance in list_ins:
ins = instance[0:3]
if instance[3] is "Y":
positive_class.append(ins)
else:
negative_class.append(ins)
return positive_class, negative_class
def get_version_space(list_ins, set_hypothesis):
pos_class, neg_class = classify(list_ins)
del_items = set()
for hypothesis in set_hypothesis:
for negative in neg_class:
re_hyp_n = re.match(hypothesis, negative)
if re_hyp_n is None:
for positive in pos_class:
re_hyp_p = re.match(hypothesis, positive)
if re_hyp_p is None:
del_items.add(hypothesis)
else:
del_items.add(hypothesis)
version_space = set_hypothesis - del_items
return version_space
def main():
list_attr = [["A","B","."],["A","B","."],["A","B","."]]
list_ins = ["AAAY","BBBN"]
all_hypothesis = get_all_hypothesis(list_attr)
version_space = get_version_space(list_ins, all_hypothesis)
print(version_space, len(version_space))
if __name__ == '__main__':
main()