首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >获取numpy错误(ValueError:使用序列设置数组元素)

获取numpy错误(ValueError:使用序列设置数组元素)
EN

Stack Overflow用户
提问于 2018-06-29 07:32:10
回答 1查看 333关注 0票数 3

下面的代码是使用python 3.6编写的。它应该创建一个包含二进制向量的最终矩阵。在循环期间,从方法simulate_output()使用的连续向量中获取每个批次,但最终将批次展平为单个向量:

代码语言:javascript
复制
tmp_list = []
output = []
num_components = 4
dim = 16
total_vectors = 100000

X = np.random.choice(np.array([0, 1], dtype=np.uint8), size=(total_vectors, dim))
num_vectors = np.unique(X, axis=0)

for i in range(0, len(num_vectors), num_components):
    batch = num_vectors[i:(i + num_components)]
    # output.append(simulate_output(batch)) # Comment this line will not solve the error.
    batch = np.hstack(batch)  # to flatten the list into a single vector
    tmp_list.append(batch)

final_matrix = np.array(tmp_list, dtype=np.int8)
print(final_matrix)

对于某些运行,我得到这个错误:

代码语言:javascript
复制
Traceback (most recent call last):
  File "test.py", line 65, in <module>
    final_matrix = np.array(tmp_list, dtype=np.int8)
ValueError: setting an array element with a sequence.

我相信错误在最后一行final_matrix = np.array(tmp_list, dtype=np.int8),但我不知道为什么以及如何修复它,因为在一些运行中它可以工作,而在其他运行中它不能。

谢谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-06-29 08:22:54

我找到你的问题了。在这一行中:

final_matrix = np.array(tmp_list, dtype=np.int8)

您希望final_matrix是一个二维numpy数组。如果所有的行都有相同的长度,这是可能的,但这并不完全是您的情况。上一个展平批次向量较短,因为len(num_vectors)没有被num_components(4)除。

如果你简单地说:

代码语言:javascript
复制
tmp_list = tmp_list[:-1]

在for循环之后,一切都会好起来的。我认为数千种元素中的一种可以忽略不计。如果您仍然不想删除它,请尝试用零填充到所需的大小- num_components * dim

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51092426

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档