0

I am a beginner in python . I am trying to modify a numpy array but somehow it is not getting modify. Here is my program

def test_numpy(x):
    count = 0
    for i in x:
        i-=np.max(i)
        i=(np.exp(i)/np.sum(np.exp(i)))
        print "The value of i is "
        print i
        x[count] = i
        count+=1
        print "the value of x is "
        print x

if __name__ == "__main__":
    test_numpy(np.array([[1,2],[3,4]])). 

The output it prints is :

The value of i is [0.26894142 0.73105858] the value of x is [[0 0] [3 4]] The value of i is [0.26894142 0.73105858] the value of x is [[0 0] [0 0]]

I am assuming the value of x should be overridden by the value of i . So after looping twice the value of x should become ([0.26894142 0.73105858],[0.26894142 0.73105858]) But somehow the value is not getting overridden. Can anyone please point out my mistake here

2 Answers 2

2

When you do:

i=(np.exp(i)/np.sum(np.exp(i)))

You are creating a new variable, you are not changing the data in place. You forgot to tell Python to modify the data:

i[:]=(np.exp(i)/np.sum(np.exp(i)))
Sign up to request clarification or add additional context in comments.

Comments

0

Your input array is of type int, so no floating point numbers can be saved. You have to provide a float array:

q=np.array([[1,2],[3,4]], dtype=float)
test_numpy(q)
print q

or you don't change the array, but create a new one, then the resulting type is automatically chosen correctly:

def test_numpy(x):
    x = np.exp(x - x.max(axis=1)[:, None])
    return x / x.sum(axis=1)[:, None]

q = np.array([[1,2],[3,4]])
a = test_numpy(q)
print(a)

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.