【问题标题】:Can't Reshape Numpy Array, even with multiple methods即使使用多种方法也无法重塑 Numpy 数组
【发布时间】:2019-07-22 01:42:03
【问题描述】:

我收到一个非常奇怪的错误:

print(np.asarray(X[i%len(y)]).shape)
x_train = X[i%len(y)]
x_train.shape = (1, x_train.shape[0], x_train.shape[1]) 

(39, 4096)
Traceback (most recent call last):
  File "scripts/train_new.py", line 172, in <module>
    model.fit_generator(train_generator(), steps_per_epoch=len(y), epochs=1, verbose=1)
  File "/home/ubuntu/anaconda3/envs/python2/lib/python2.7/site-packages/keras/legacy/interfaces.py", line 91, in wrapper
    return func(*args, **kwargs)
  File "/home/ubuntu/anaconda3/envs/python2/lib/python2.7/site-packages/keras/engine/training.py", line 1418, in fit_generator
    initial_epoch=initial_epoch)
  File "/home/ubuntu/anaconda3/envs/python2/lib/python2.7/site-packages/keras/engine/training_generator.py", line 181, in fit_generator
    generator_output = next(output_generator)
  File "/home/ubuntu/anaconda3/envs/python2/lib/python2.7/site-packages/keras/utils/data_utils.py", line 709, in get
    six.reraise(*sys.exc_info())
  File "/home/ubuntu/anaconda3/envs/python2/lib/python2.7/site-packages/keras/utils/data_utils.py", line 685, in get
    inputs = self.queue.get(block=True).get()
  File "/home/ubuntu/anaconda3/envs/python2/lib/python2.7/multiprocessing/pool.py", line 572, in get
    raise self._value
ValueError: total size of new array must be unchanged

我尝试了 expand_dims,尝试了 np.new_axis,尝试了 reshape 以将数组的形状更改为 (1, 39, 4096) 而不是 (39, 4096),并且一切都给出了相同的错误。甚至尝试将数组条目复制到变量中,仍然是相同的错误。

为什么会发生错误,我该如何解决?

【问题讨论】:

  • 这显然不是完整的代码,因为错误发生在未显示的model.fit_generator 调用中。请显示所有相关代码。
  • x_train ndarray 还是 keras 对象?

标签: python python-2.7 numpy numpy-ndarray


【解决方案1】:

使用reshape 而不是shape

arr = np.zeros((39, 4096))
dim1, dim2 = arr.shape
arr.reshape((1,dim1,dim2)).shape
(1, 39, 4096)

【讨论】:

  • 没有出现同样的错误 ValueError: total size of new array must be changed
  • @Rafael 您可以随时分配您的值。我会更新我的答案
  • @Rafael 错误是抱怨您的train_generator 生成的数据大小不一致。您必须指定哪个暗淡可以根据您的 keras 模型而变化。
猜你喜欢
  • 1970-01-01
  • 2013-12-13
  • 1970-01-01
  • 2016-05-22
  • 2020-08-29
  • 2019-09-08
  • 1970-01-01
  • 2020-07-11
相关资源
最近更新 更多