下面的代码是使用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)
,但我不知道为什么以及如何修复它,因为在一些运行中它可以工作,而在其他运行中它不能。
谢谢
发布于 2018-06-29 08:22:54
我找到你的问题了。在这一行中:
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
。
https://stackoverflow.com/questions/51092426
复制相似问题