簡體   English   中英

Keras Tensorflow在時期期間重塑錯誤

[英]Keras Tensorflow reshape error during epoch

我是Keras和Tensorflow的新手,我正在嘗試使用LSTM在我擁有的某些雷達脈沖數據集上進行訓練。 在編譯過程中,我使它起作用,但是當模型開始訓練時,我無法使其起作用。 我不知道在哪里放置重塑形狀以及使用哪個尺寸,因為錯誤給出的數字不知道它們來自何處。

所以代碼是:

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)

錯誤告訴:

> 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)]]

作為輸入給您的Reshape圖層的元素數量必須等於其輸出中的元素數量( output_shape=(None, 3, 4) ,所以batch_size * 12元素),當前情況並非如此。

你的模型仍然編譯,因為你是為維度引入動態大小0模型的輸入(比照Noneinput_shape=(None, x_train.shape[1], 1) 因為只有在推斷時, None才會被實際的尺寸大小代替,所以Keras(在編譯時)信任您提供尺寸為0的適當大小的樣本,以便在Reshape之前其元素數等於3 * 4 = 12 因為你是最后與供給元件model.fit()最終被越大,推斷在失敗Reshape

具體來說,讓我們分析一下代碼。 根據跟蹤中的值,我將假設您的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)

讓我們嘗試建立模型:

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))

嘗試運行此代碼,您將在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尺寸引起的歧義)。

如果我們逐行看一下,直到出現例外,否則圖層的輸出形狀是什么:

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)))

如您所見,您正在嘗試將998 * 998 * 32 = 31872128元素的矩陣(跟蹤中的值)重塑為3 * 4 = 12元素的矩陣,因此會出現錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM