简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM