第四范式,秋招笔试,贝叶斯分类
import math if __name__ == "__main__": m = int(input()) train = [] for i in range(m): t = [int(x) for x in input().strip().split(' ')] train.append(t) # 计算先验概率 py_ = [] label = [t[-1] for t in train] py_1 = sum(label) / m py_0 = 1 - py_1 py_.append(py_0) py_.append(py_1) # 计算似然函数 py = [] for c in range(2): t1 = [t[0] for t in train if t[-1] == c] t2 = [t[1] for t in train if t[-1] == c] t3 = [t[2] for t in train if t[-1] == c] t4 = [t[3] for t in train if t[-1] == c] p_t1 = [] for i in range(3): p = len([x for x in t1 if x == i+1]) / m if p == 0: p_t1.append(0.0001) continue p_t1.append(p) p_t2 = [] for i in range(3): p = len([x for x in t2 if x == i+1]) / m if p == 0: p_t1.append(0.0001) continue p_t2.append(p) p_t3 = [] for i in range(2): p = len([x for x in t3 if x == i]) / m if p == 0: p_t1.append(0.0001) continue p_t3.append(p) p_t4 = [] for i in range(2): p = len([x for x in t4 if x == i]) / m if p == 0: p_t1.append(0.0001) continue p_t4.append(p) py.append((p_t1, p_t2, p_t3, p_t4)) # 测试阶段 n = int(input()) res = [] # gamma = 0.00001 for i in range(n): test = [int(x) for x in input().strip().split(' ')] ans = [] for c in range(2): p_t1, p_t2, p_t3, p_t4 = py[c] pt = math.log(p_t1[test[0]-1]) + math.log(p_t2[test[1]-1]) + math.log(p_t3[test[2]]) + math.log(p_t4[test[3]]) + math.log(py_[c]) ans.append(pt) if ans[0] > ans[1]: res.append(0) else: res.append(1) res1 = [str(x) for x in res] print(' '.join(res1))
#笔试题目##第四范式#