python - Failed to append an element to a numpy array -
i'm trying add values generated function calc_class, not working , don't know reason. i've tried use numpy.append, numpy.insert , built-in python function append unsuccessfully.
this piece of code:
def calc_class(test): expec = [] new in test: prob_vector = np.zeros((len(voc)), dtype=bool) #define 'true' array store class probabilities words_in_new = new[0].split() #split new email words words_in_new = list(set(words_in_new)) #remove duplicated words = 0 voc_word in voc: #for each element in voc if voc_word in words_in_new: prob_vector[i] = true #set ith element of prob_vector true, if voc element in word else: prob_vector[i] = false #set ith element of prob_vector false, otherwise += 1 prob_ham = 1 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 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) the problem print(expect) printing empty array.
you can use pdb debug (or ipdb ipython).
from pdb import set_trace use "set_trace()" instead of "print('p(spam|new_email)=', p_spam_given_new[0])"(third line counted end-line), run code. pause @ line, , can run python code there, such "print(p_spam_given_new)" or "p_spam_given_new", can check "prob_spam", "p_spam" or other variable want check.
Comments
Post a Comment