Leevo
Leevo

Reputation: 1753

Python, Numpy: Cannot assign the values of a numpy array to a column of a matrix

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

Upvotes: 1

Views: 1276

Answers (1)

Ahmad Khan
Ahmad Khan

Reputation: 2693

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.]])

Upvotes: 3

Related Questions