简体   繁体   English

无法在数组元素中分配“np.random.normal 之和”

[英]Can't assign the "sum of np.random.normal" in a element of array

I am trying to produce random number by random.normal and take the summary of them.我正在尝试通过random.normal生成随机数并对其进行汇总。 Then, I tried to assgin the value to each element in the array sum .然后,我尝试将值分配给数组sum中的每个元素。 I made a zero array (float type) by np.zeros and then assign the value in following way.我通过np.zeros创建了一个零数组(浮点型),然后按以下方式分配值。
I attempted to utilize numpy and matlibplot.pyplot as libraries to do this.我试图利用 numpy 和 matlibplot.pyplot 作为库来执行此操作。
My code:我的代码:

np.random.seed(0)
sum=np.zeros(10,dtype=float)
for i in np.arange(1,11):
    X = np.random.normal(size=(10,1))
    Y=np.sum(X,axis=1)
    sum[i-1]=Y
print(sum)

When I conduct this code on Google Colab, following errors happened.当我在 Google Colab 上执行此代码时,发生了以下错误。

TypeError                                 Traceback (most recent call last)
TypeError: only size-1 arrays can be converted to Python scalars

The above exception was the direct cause of the following exception:

ValueError                                Traceback (most recent call last)
<ipython-input-14-33fba8ac5d90> in <module>
      6     X = np.random.normal(size=(10,1))
      7     Y=np.sum(X,axis=1)
----> 8     sum[i-1]=Y
      9 print(sum)

ValueError: setting an array element with a sequence.

Could you please tell me how to solve this error?你能告诉我如何解决这个错误吗?

The X array you create has a size of 10 x 1. When you do anumpy sum , the axis you select is 0-based, so you are doing a sum over the "1" dimension (the second dimension) and getting an array that is still 10 x 1 for Y .您创建的X数组的大小为 10 x 1。当您执行numpy sum时,轴 select 是基于 0 的,因此您正在对“1”维度(第二维度)进行求和并获得一个数组Y仍然是 10 x 1。

To fix it, you want to either set the axis to 0要修复它,您需要将轴设置为 0

X = np.random.normal(size=(10,1))
Y = np.sum(X,axis=0)

or just omit the axis argument entirely to return a scalar instead of a size-1 array或者完全省略轴参数以返回标量而不是大小为 1 的数组

X = np.random.normal(size=(10,1))
Y = np.sum(X)

As a side note, using sum as a variable name is not recommended since that is the name of a built-in python method and can cause errors if you later try to use the built-in sum function - but this isn't the root of the problem here.作为旁注,不建议使用sum作为变量名,因为这是内置 python 方法的名称,如果您稍后尝试使用内置 sum function 可能会导致错误 - 但这不是根这里的问题。

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

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