简体   繁体   中英

Python numpy matrix assign value

I was wondering why I get different result in the two prints? shouldn't they be the same?

    import numpy as np

    x = np.array([[1.5, 2], [2.4, 6]])

    k = np.copy(x)
    for i in range(len(x)):
       for j in range(len(x[i])):
            k[i][j] = 1 / (1 + np.exp(-x[i][j]))
            print("K[i][j]:"+str(k[i][j]))
            print("Value:"+str(1 / (1 + np.exp(-x[i][j]))))

When I run this script, 2 prints showed same results. This python is 3.5.2.

K[i][j]:0.817574476194
Value:0.817574476194
K[i][j]:0.880797077978
Value:0.880797077978
K[i][j]:0.916827303506
Value:0.916827303506
K[i][j]:0.997527376843
Value:0.997527376843

I've just run your code with python3 and python2 and the results were absolutely the same. Besides, you don't have to do looping when using numpy arrays allows you to express many kinds of data processing tasks as concise array expressions that might otherwise require writing loops. This practice of replacing explicit loops with array expressions is commonly referred to as vectorization. In general, vectorized array operations will often be one or two (or more) orders of magnitude faster than their pure Python equivalents, with the biggest impact in any kind of numerical computations.

So, keeping all this in mind you may rewrite your code as follows:

import numpy as np

x = np.array([[1.5, 2], [2.4, 6]], dtype=np.float)
k = 1 / (1 + np.exp(-x))

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