Failed to append an element to a numpy array
<p>I'm trying to add the values generated by the function <code>calc_class</code>, but it is not working and I don't know the reason. I've tried to use the <code>numpy.append</code>, <code>numpy.insert</code> and the built-in Python function <code>append</code> unsuccessfully.</p>

<p>This is my piece of code:</p>

<pre><code>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)
</code></pre>

<p>The problem is that <code>print(expect)</code> is printing an empty array.</p>

<p>You can use pdb do debug (or ipdb for ipython).</p>

<pre><code>from pdb import set_trace
</code></pre>

<p>use "set_trace()" instead of  "print('p(spam|new_email)=', p_spam_given_new[0])"(third line counted from end-line), than run your code. It will pause at this line, and you can run any python code there, such as "print(p_spam_given_new)" or just "p_spam_given_new", you can also check "prob_spam", "p_spam" or any other variable you want to check.</p>

python arrays numpy