1

I'n new to Python, and there is a syntax problem I'm trying to understand. I have a numpy matrix:

x = np.array([[1, 2, 3, 6],
              [2, 4, 5, 6], 
              [3, 8, 7, 6]])

An I want to apply a Softmax function to each column of it. The code is pretty straightforward. Without reporting the whole loop, let's say I make it for the first column:

w = x[:,0]  # select a column
w = np.exp(w)  # compute softmax in two steps
w = w/sum(w)
x[:,0] = w   # reassign the values to the original matrix

However, instead of the values of w: array([0.09003057, 0.24472847, 0.66524096]) , only a column of zeros is assigned to the matrix, that returns:

 np.array([[0, 2, 3, 6],
           [0, 4, 5, 6], 
           [0, 8, 7, 6]])

Why is that? How can I correct this problem? Thank you

1
  • 2
    Change the dataype to float and then assign. Commented Oct 28, 2018 at 11:41

1 Answer 1

3

The type of values of your matrix is int, and at the time of assigning, the softmax values are converted to int, hence the zeros.

Create your matrix like this:

x = np.array([[1, 2, 3, 6],
              [2, 4, 5, 6], 
              [3, 8, 7, 6]]).astype(float)

Now, after assigning softmax values:

w = x[:,0]  # select a column
w = np.exp(w)  # compute softmax in two steps
w = w/sum(w)
x[:,0] = w   # reassign the values to the original matrix

x comes out to be:

array([[0.09003057, 2., 3., 6.],
       [0.24472847, 4., 5., 6.],
       [0.66524096, 8., 7., 6.]])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.