即使使用多种方法也无法重塑Numpy数组

时间:2019-02-28 07:39:24

标签: python python-2.7 numpy numpy-ndarray

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

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,尝试了整形,只是将数组的形状更改为(1,39,4096)而不是(39,4096),并且所有内容都给出了相同的错误。甚至尝试将数组项复制到变量,仍然是erorr。

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

1 个答案:

答案 0 :(得分:1)

使用reshape而不是shape

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