我正在尝试添加函数calc_class
生成的值,但它不起作用,我不知道原因。我试图使用numpy.append
,numpy.insert
和内置Python函数append
失败。
这是我的代码:
def calc_class(test):
expec = []
for new in test:
prob_vector = np.zeros((len(voc)), dtype=bool) #define a 'True' array to store class probabilities
words_in_new = new[0].split() #split the new email into words
words_in_new = list(set(words_in_new)) #remove duplicated words
i = 0
for voc_word in voc: #for each element in voc
if voc_word in words_in_new:
prob_vector[i] = True #set the ith element of prob_vector to True, if voc element is in word
else:
prob_vector[i] = False #set the ith element of prob_vector to False, otherwise
i += 1
prob_ham = 1
for i in range(len(prob_vector)):
if prob_vector[i] == True:
prob_ham *= ham_class_prob[i]
else:
prob_ham *= (1 - ham_class_prob[i])
# alternative: np.prod(ham_class_prob[np.where(prob_vector==True)]) * np.prod(1- ham_class_prob[np.where(prob_vector==False)])
prob_spam = 1
for i in range(len(prob_vector)):
if prob_vector[i] == True:
prob_spam *= spam_class_prob[i]
else:
prob_spam *= (1 - spam_class_prob[i])
p_spam = 0.3
p_ham = 1 - p_spam
p_spam_given_new = (prob_spam * p_spam) / (prob_spam * p_spam + prob_ham * p_ham) # Bayes theorem
print('p(spam|new_email)=', p_spam_given_new[0])
expec.append(p_spam_given_new[0])
print(expec)
问题是print(expect)
正在打印一个空数组。
答案 0 :(得分:0)
您可以使用pdb do debug(或ipdb for ipython)。
from pdb import set_trace
使用“set_trace()”而不是“print('p(spam | new_email)=',p_spam_given_new [0])”(从行尾计算的第三行),而不是运行您的代码。它将在此行暂停,您可以在那里运行任何python代码,例如“print(p_spam_given_new)”或只是“p_spam_given_new”,您还可以检查“prob_spam”,“p_spam”或您要检查的任何其他变量。