简体   繁体   English

Keras Tensorflow在时期期间重塑错误

[英]Keras Tensorflow reshape error during epoch

I am new to Keras and Tensorflow and I am trying to use the LSTM to train on some radar pulse dataset I have. 我是Keras和Tensorflow的新手,我正在尝试使用LSTM在我拥有的某些雷达脉冲数据集上进行训练。 During compilation I have made it work, but when the model starts to train I cannot get it working. 在编译过程中,我使它起作用,但是当模型开始训练时,我无法使其起作用。 I don't know where to place the reshape and which dimensions to use since the numbers that the error gives I don't know where they come from. 我不知道在哪里放置重塑形状以及使用哪个尺寸,因为错误给出的数字不知道它们来自何处。

So the code is: 所以代码是:

x_train = load_data("D:\\Software_Herramienta\\Datasets\\sweep_switch_train.csv")
y_train = load_data("D:\\Software_Herramienta\\Datasets\\sweep_switch_labels_train.csv")
x_train = x_train.reshape(-1, x_train.shape[0], x_train.shape[1], 1)
y_train.astype(int)
y_train = y_train.reshape(1,1000)

batch = 10

model = Sequential()
model.add(Convolution2D(32, 3, 3, activation='relu', input_shape=(None, x_train.shape[1], 1)))
model.add(TimeDistributed(Activation('relu')))
model.add(TimeDistributed(Dense(32, name="first_dense")))
model.add(Reshape((3, 4)))
model.add(LSTM(x_train.shape[1], dropout_U=0.2, dropout_W=0.2))
# model.add(Dense(1, activation='softmax'))

model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
model.fit(x_train, y_train, epochs=15, batch_size=batch)

And the error tells: 错误告诉:

> Epoch 1/15
2018-06-13 13:40:17.225066: I T:\src\github\tensorflow\tensorflow\core\platform\cpu_feature_guard.cc:140] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2
Traceback (most recent call last):
  File "D:\Software_Utils\Python_3.6.5\lib\site-packages\tensorflow\python\client\session.py", line 1322, in _do_call
    return fn(*args)
  File "D:\Software_Utils\Python_3.6.5\lib\site-packages\tensorflow\python\client\session.py", line 1307, in _run_fn
    options, feed_dict, fetch_list, target_list, run_metadata)
  File "D:\Software_Utils\Python_3.6.5\lib\site-packages\tensorflow\python\client\session.py", line 1409, in _call_tf_sessionrun
    run_metadata)
tensorflow.python.framework.errors_impl.InvalidArgumentError: Input to reshape is a tensor with 31872128 values, but the requested shape has 12
     [[Node: reshape_1/Reshape = Reshape[T=DT_FLOAT, Tshape=DT_INT32, _device="/job:localhost/replica:0/task:0/device:CPU:0"](time_distributed_2/add, reshape_1/Reshape/shape)]]
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "D:/Software_Herramienta/Pulse_Generator/pulse_model_keras_tf.py", line 74, in <module>
    model.fit(x_train, y_train, epochs=15, batch_size=batch)
  File "D:\Software_Utils\Python_3.6.5\lib\site-packages\keras\models.py", line 1002, in fit
    validation_steps=validation_steps)
  File "D:\Software_Utils\Python_3.6.5\lib\site-packages\keras\engine\training.py", line 1705, in fit
    validation_steps=validation_steps)
  File "D:\Software_Utils\Python_3.6.5\lib\site-packages\keras\engine\training.py", line 1236, in _fit_loop
    outs = f(ins_batch)
  File "D:\Software_Utils\Python_3.6.5\lib\site-packages\keras\backend\tensorflow_backend.py", line 2482, in __call__
    **self.session_kwargs)
  File "D:\Software_Utils\Python_3.6.5\lib\site-packages\tensorflow\python\client\session.py", line 900, in run
    run_metadata_ptr)
  File "D:\Software_Utils\Python_3.6.5\lib\site-packages\tensorflow\python\client\session.py", line 1135, in _run
    feed_dict_tensor, options, run_metadata)
  File "D:\Software_Utils\Python_3.6.5\lib\site-packages\tensorflow\python\client\session.py", line 1316, in _do_run
    run_metadata)
  File "D:\Software_Utils\Python_3.6.5\lib\site-packages\tensorflow\python\client\session.py", line 1335, in _do_call
    raise type(e)(node_def, op, message)
tensorflow.python.framework.errors_impl.InvalidArgumentError: Input to reshape is a tensor with 31872128 values, but the requested shape has 12
     [[Node: reshape_1/Reshape = Reshape[T=DT_FLOAT, Tshape=DT_INT32, _device="/job:localhost/replica:0/task:0/device:CPU:0"](time_distributed_2/add, reshape_1/Reshape/shape)]]
Caused by op 'reshape_1/Reshape', defined at:
  File "D:/Software_Herramienta/Pulse_Generator/pulse_model_keras_tf.py", line 69, in <module>
    model.add(Reshape((3, 4)))
  File "D:\Software_Utils\Python_3.6.5\lib\site-packages\keras\models.py", line 522, in add
    output_tensor = layer(self.outputs[0])
  File "D:\Software_Utils\Python_3.6.5\lib\site-packages\keras\engine\topology.py", line 619, in __call__
    output = self.call(inputs, **kwargs)
  File "D:\Software_Utils\Python_3.6.5\lib\site-packages\keras\layers\core.py", line 406, in call
    return K.reshape(inputs, (K.shape(inputs)[0],) + self.target_shape)
  File "D:\Software_Utils\Python_3.6.5\lib\site-packages\keras\backend\tensorflow_backend.py", line 1898, in reshape
    return tf.reshape(x, shape)
  File "D:\Software_Utils\Python_3.6.5\lib\site-packages\tensorflow\python\ops\gen_array_ops.py", line 7323, in reshape
    "Reshape", tensor=tensor, shape=shape, name=name)
  File "D:\Software_Utils\Python_3.6.5\lib\site-packages\tensorflow\python\framework\op_def_library.py", line 787, in _apply_op_helper
    op_def=op_def)
  File "D:\Software_Utils\Python_3.6.5\lib\site-packages\tensorflow\python\framework\ops.py", line 3392, in create_op
    op_def=op_def)
  File "D:\Software_Utils\Python_3.6.5\lib\site-packages\tensorflow\python\framework\ops.py", line 1718, in __init__
    self._traceback = self._graph._extract_stack()  # pylint: disable=protected-access
InvalidArgumentError (see above for traceback): Input to reshape is a tensor with 31872128 values, but the requested shape has 12
     [[Node: reshape_1/Reshape = Reshape[T=DT_FLOAT, Tshape=DT_INT32, _device="/job:localhost/replica:0/task:0/device:CPU:0"](time_distributed_2/add, reshape_1/Reshape/shape)]]

The number of elements given as input to your Reshape layer must be equal to the number of elements in its output ( output_shape=(None, 3, 4) , so batch_size * 12 elements), which is not currently the case. 作为输入给您的Reshape图层的元素数量必须等于其输出中的元素数量( output_shape=(None, 3, 4) ,所以batch_size * 12元素),当前情况并非如此。

Your model is still compiling because you are introducing a dynamic size for the dimension 0 of your model's input (cf the None in input_shape=(None, x_train.shape[1], 1) ). 你的模型仍然编译,因为你是为维度引入动态大小0模型的输入(比照Noneinput_shape=(None, x_train.shape[1], 1) Because None will be replaced by the actual dimension size only at inference time, Keras - at compilation time - is trusting you to feed samples with a dimension 0 of proper size so that their number of elements before the Reshape equals 3 * 4 = 12 . 因为只有在推断时, None才会被实际的尺寸大小代替,所以Keras(在编译时)信任您提供尺寸为0的适当大小的样本,以便在Reshape之前其元素数等于3 * 4 = 12 Since the elements you are finally feeding with model.fit() end up being larger, the inference fails at the Reshape . 因为你是最后与供给元件model.fit()最终被越大,推断在失败Reshape

Concretely, let's take your code and analyze it. 具体来说,让我们分析一下代码。 According to the value in your trace, I will assume your sweep_switch_train.csv contains samples of shape 1000x1000x1 each: 根据跟踪中的值,我将假设您的sweep_switch_train.csv包含每个形状为1000x1000x1样本:

# Mocking 50 samples of size 1000x1000x1 and their labels:
x_train = np.random.rand(50, 1000, 1000, 1)
y_train = np.random.randint(2, size=50)

Let's try to build your model: 让我们尝试建立模型:

model = Sequential()
model.add(Convolution2D(32, 3, 3, activation='relu', input_shape=x_train.shape[1:]))
# notice we set input_shape to (1000, 1000, 1) instead of (None, 1000, 1) the way you were.
# This makes the example clearer as Keras directly knows all dimensions.
model.add(TimeDistributed(Activation('relu')))
model.add(TimeDistributed(Dense(32, name="first_dense")))
model.add(Reshape((3, 4)))
model.add(LSTM(x_train.shape[1], dropout_U=0.2, dropout_W=0.2))

Trying to run this code, you will have an Exception " ValueError: total size of new array must be unchanged " at model.add(Reshape((3, 4))) , as Keras would directly notice the number of elements doesn't match for the reshape (as there's no more ambiguity caused by a None dimension size here). 尝试运行此代码,您将在model.add(Reshape((3, 4)))model.add(Reshape((3, 4)))异常“ ValueError: total size of new array must be unchanged ”, model.add(Reshape((3, 4)))会直接注意到元素数量并没有匹配重塑形状(因为这里不再存在由None尺寸引起的歧义)。

If we look look line by line what your layers' output shapes are until the exception: 如果我们逐行看一下,直到出现例外,否则图层的输出形状是什么:

model = Sequential()
model.add(Convolution2D(32, 3, 3, activation='relu', input_shape=x_train.shape[1:]))
print(model.layers[0].output_shape)
# (None, 998, 998, 32)
model.add(TimeDistributed(Activation('relu')))
print(model.layers[1].output_shape)
# (None, 998, 998, 32)
model.add(TimeDistributed(Dense(32, name="first_dense")))
print(model.layers[2].output_shape)
# (None, 998, 998, 32)
model.add(Reshape((3, 4)))

As you can see, you are trying to reshape matrices of 998 * 998 * 32 = 31872128 elements (the value in your trace) into matrices of 3 * 4 = 12 elements, hence the error. 如您所见,您正在尝试将998 * 998 * 32 = 31872128元素的矩阵(跟踪中的值)重塑为3 * 4 = 12元素的矩阵,因此会出现错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM