ValueError: setting an array element with a sequence...

2023-12-16 20:48:41

报错:ValueError: setting an array element with a sequence…

案例1:numpy库使用numpy.array转换list

a是一个list,其包含两个元组,使用np.array进行转换,会报错:

import numpy as np
a = ([([1, 2, 3], 0, 1.0, [3, 4], 0), ([1, 2, 3], 0, 1.0, [3, 4], 0)])
a = np.array(a)
ValueError: setting an array element with a sequence. The requested array has an inhomogeneous shape after 2 dimensions. The detected shape was (2, 5) + inhomogeneous part.

有的numpy版本不报错而是警告:

VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify ‘dtype=object’ when creating the ndarray.

加上 dtype=object 就不会再报错或警告:

import numpy as np
a = ([([1, 2, 3], 0, 1.0, [3, 4], 0), ([1, 2, 3], 0, 1.0, [3, 4], 0)])
a = np.array(a, dtype=object)

简单介绍一下此处的背景,在python中,list无法被数组进行索引:

a = ([([1, 2, 3], 0, 1.0, [3, 4], 0), ([1, 2, 3], 0, 1.0, [3, 4], 0)])
index = [1, 0]
b = a[index]
print(f'{b}')
TypeError: list indices must be integers or slices, not list

将list转换成numpy,然后就可以使用数组进行索引了:

import numpy as np
a = ([([1, 2, 3], 0, 1.0, [3, 4], 0), ([1, 2, 3], 0, 1.0, [3, 4], 0)])
a = np.array(a, dtype=object)
index = [1, 0]
b = a[index]
print(f'{b}')

输出为:
在这里插入图片描述

案例2:新版gym库使用state = env.reset()

新版本gym库的env.reset()返回是两个元组,其中第二个为dict,一般不包含数据。若直接使用state = env.reset()返回的数值如下所示:
在这里插入图片描述
因此,继续原来的操作(状态分析转换等等)就会报错ValueError: setting an array element with a sequence,正确的写法如下所示,这样就能直接得到agent所对应的状态了:

state, _ = env.reset()

同理,env.step(action)的返回值也有所改变,返回参数由原来的四个改为了五个,如果使用下面代码则会报错(ValueError: too many values to unpack (expected 4)):

next_state, reward, done, _ = env.step(action)

需要使用如下的修改代码:

next_state, reward, done, _, _ = env.step(action)

新版gym库返回参数的详细定义可以参考官方网站:
https://www.gymlibrary.dev/api/core/

文章来源:https://blog.csdn.net/weixin_44584198/article/details/135036376
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。