【问题标题】:Getting numpy error (ValueError: setting an array element with a sequence)出现 numpy 错误(ValueError:使用序列设置数组元素)
【发布时间】:2018-06-29 11:11:11
【问题描述】:

以下代码使用 python 3.6 编写。它应该创建一个包含二进制向量的最终矩阵。在循环过程中,每个批次都取自连续的向量,以供方法 simulate_output() 使用,但最终批次被展平为单个向量:

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)

对于某些运行,我收到此错误:

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),但我不知道为什么以及如何修复它,因为在某些运行中它可以工作,而在其他运行中却没有。

谢谢

【问题讨论】:

  • 你运行的是什么版本的 numpy?在'1.14.5' 上运行这个示例(没有output.append(...) 行)对我来说很好吗?当列表的元素是列表本身时,我通常会看到此错误。如果它再次为您中断,我会检查 tmp_list 的内容并确保它是您真正期望的。
  • @Jorden 我升级到1.14.5,但仍然遇到同样的错误。如果您尝试多次运行,您应该会收到此错误。
  • 我感觉卡住了。代码看起来不错,但无法找出错误

标签: python python-3.x numpy


【解决方案1】:

我发现了你的问题。 在这一行:

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

您希望 final_matrix 是一个二维 numpy 数组。如果所有行都具有相同的长度,则可能是这样,但这不完全是您的情况。您的最后一个展平批处理向量更短,因为len(num_vectors) 没有除以num_components(4)。

如果你简单地说:

tmp_list = tmp_list[:-1]

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

【讨论】:

  • 伟大的收获!太感谢了。有意义
猜你喜欢
  • 1970-01-01
  • 2015-12-19
  • 1970-01-01
  • 2016-01-21
  • 1970-01-01
  • 2018-04-09
  • 2018-11-10
  • 2018-05-09
  • 2017-10-20
相关资源
最近更新 更多