Python 未能将元素附加到numpy数组
我正在尝试添加由函数Python 未能将元素附加到numpy数组,python,arrays,numpy,Python,Arrays,Numpy,我正在尝试添加由函数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 cla
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)
正在打印一个空数组。您可以使用pdb do debug(或ipdb for ipython)
使用“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”或任何其他要检查的变量。(a)问题中显示的缩进(在第三人编辑之前)是错误的。使此处的缩进与实际使用的文件中的缩进匹配。不要让我们猜测您真正使用的缩进。(b)
voc
从未定义。(c) 将来,在提问之前,请阅读:“在追加
之前打印
是否产生任何结果?代码中有4个未知变量-测试
,voc
等,函数不返回任何结果。expec.append
不是问题所在;只是在函数中达到这一点是一个问题。
from pdb import set_trace