'float' 对象不可分割
'float' object is unsliceable
我正在尝试生成两个 类 随机二维点,一个的平均值为 [1,1],另一个的平均值为 [-1,-1]。我写了一个函数,但我得到了一个无法弄清楚的错误。我用谷歌搜索但没有找到任何东西。这是我的功能:
def gen_arti_Bis(nbex=10,centerx=1,centery=1,sigma=0.1,epsilon=0.02):
xpos=np.random.multivariate_normal([centerx,centery],np.diag([sigma,sigma]),nbex/2)
xneg=np.random.multivariate_normal([-centerx,-centery],np.diag([sigma,sigma]),nbex/2)
data=np.vstack((xpos,xneg))
y=np.hstack((np.ones(nbex/2),-np.ones(nbex/2)))
return data,y
这是我键入 gen_arti() 时的错误消息:
Traceback (most recent call last):
File "<ipython-input-64-a173cf922dac>", line 1, in <module>
gen_arti_Bis()
File "<ipython-input-63-da8720093c11>", line 2, in gen_arti_Bis
xpos=np.random.multivariate_normal([centerx,centery],np.diag([sigma,sigma]),nbex/2)
File "mtrand.pyx", line 4308, in mtrand.RandomState.multivariate_normal (numpy/random/mtrand/mtrand.c:23108)
TypeError: 'float' object is unsliceable
在Python 3中,使用/
运算符的除法总是进行浮点除法,即使运算符两边的数字都是整数。在几个地方,您正在计算 nbex / 2
,并将结果作为参数传递给 numpy,其中 numpy 需要一个整数。
具体来说,np.random.multivariate
的最后一个参数应该是 int
或 tuple
的 int
。你传递的是一个 float
,它不会接受,即使浮点数的值实际上是一个整数(例如 5.0
)。您还将 float
传递给 np.ones
,但该函数似乎可以正常处理它(它会忽略输入数字的任何小数部分)。
最基本的修复方法是使用 //
运算符显式执行整数除法。将 nbex / 2
的每个位置替换为 nbex // 2
,它应该可以按预期工作。
请注意,//
执行的整数除法将始终选择下限值(即向下舍入,朝向负无穷大)。如果您想在某些情况下进行不同的舍入,您可能需要使用 /
进行除法,然后使用 round
将浮点数结果转换为整数(这将舍入两个值的一半)偶数的整数)或 math.ceil
(总是四舍五入)。
我正在尝试生成两个 类 随机二维点,一个的平均值为 [1,1],另一个的平均值为 [-1,-1]。我写了一个函数,但我得到了一个无法弄清楚的错误。我用谷歌搜索但没有找到任何东西。这是我的功能:
def gen_arti_Bis(nbex=10,centerx=1,centery=1,sigma=0.1,epsilon=0.02):
xpos=np.random.multivariate_normal([centerx,centery],np.diag([sigma,sigma]),nbex/2)
xneg=np.random.multivariate_normal([-centerx,-centery],np.diag([sigma,sigma]),nbex/2)
data=np.vstack((xpos,xneg))
y=np.hstack((np.ones(nbex/2),-np.ones(nbex/2)))
return data,y
这是我键入 gen_arti() 时的错误消息:
Traceback (most recent call last):
File "<ipython-input-64-a173cf922dac>", line 1, in <module>
gen_arti_Bis()
File "<ipython-input-63-da8720093c11>", line 2, in gen_arti_Bis
xpos=np.random.multivariate_normal([centerx,centery],np.diag([sigma,sigma]),nbex/2)
File "mtrand.pyx", line 4308, in mtrand.RandomState.multivariate_normal (numpy/random/mtrand/mtrand.c:23108)
TypeError: 'float' object is unsliceable
在Python 3中,使用/
运算符的除法总是进行浮点除法,即使运算符两边的数字都是整数。在几个地方,您正在计算 nbex / 2
,并将结果作为参数传递给 numpy,其中 numpy 需要一个整数。
具体来说,np.random.multivariate
的最后一个参数应该是 int
或 tuple
的 int
。你传递的是一个 float
,它不会接受,即使浮点数的值实际上是一个整数(例如 5.0
)。您还将 float
传递给 np.ones
,但该函数似乎可以正常处理它(它会忽略输入数字的任何小数部分)。
最基本的修复方法是使用 //
运算符显式执行整数除法。将 nbex / 2
的每个位置替换为 nbex // 2
,它应该可以按预期工作。
请注意,//
执行的整数除法将始终选择下限值(即向下舍入,朝向负无穷大)。如果您想在某些情况下进行不同的舍入,您可能需要使用 /
进行除法,然后使用 round
将浮点数结果转换为整数(这将舍入两个值的一半)偶数的整数)或 math.ceil
(总是四舍五入)。