简体   繁体   English

Python Numpy矩阵分配值

[英]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. 当我运行此脚本时,有2张照片显示了相同的结果。 This python is 3.5.2. 这个python是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. 我刚刚使用python3和python2运行您的代码,结果绝对相同。 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. 此外,当使用numpy数组时,您不必执行循环,从而可以将许多数据处理任务表示为简洁的数组表达式,否则可能需要编写循环。 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. 通常,向量化数组运算通常会比其纯Python等效运算快一个或两个(或更多)个数量级,在任何类型的数值计算中影响最大。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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