Anaconda/Jupyter/Keras LSTM: «Ошибка значения: Ошибка при проверке цели: ожидалось, что dense_1 будет иметь 3 измерения, но получил массив с формой (183, 1)»

#tensorflow #keras #jupyter-notebook #lstm

Вопрос:

Я пытаюсь заставить модель нейронной сети Keras работать в ноутбуке Jupyter. Вот код, который я написал:

 import numpy as np import matplotlib.pyplot as plt import pandas as pd import datetime  dataset = pd.read_csv(r'MC.PA.csv',index_col='Date',parse_dates=True)  training_set=dataset['Open'] training_set=pd.DataFrame(training_set)  dataset.isna().any()  from sklearn.preprocessing import MinMaxScaler sc = MinMaxScaler(feature_range = (0,1)) training_set_scaled = sc.fit_transform(training_set)  X_train = [] y_train = [] for i in range(69, 252):  X_train.append(training_set_scaled[i-60:i,0])  y_train.append(training_set_scaled[i,0]) X_train, y_train = np.array(X_train), np.array(y_train)  X_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1))  from keras.models import Sequential from keras.layers import Dense from keras.layers import LSTM from keras.layers import Dropout  regressor = Sequential()  regressor.add(LSTM(units = 50, return_sequences = True, input_shape = (X_train.shape[1], 1))) regressor.add(Dropout(0.2))  regressor.add(LSTM(units = 50, return_sequences = True)) regressor.add(Dropout(0.2))  regressor.add(LSTM(units = 50, return_sequences = True)) regressor.add(Dropout(0.2))  regressor.add(LSTM(units = 50, return_sequences = True)) regressor.add(Dropout(0.2))  regressor.add(Dense(units = 1))  regressor.compile(optimizer = 'adam', loss = 'mean_squared_error')  regressor.fit(X_train, y_train, epochs = 100, batch_size = 32)  

Однако при запуске функции подгонки последнего регрессора я получаю это сообщение об ошибке: Перед последней функцией подгонки все работает нормально:

 --------------------------------------------------------------------------- ValueError Traceback (most recent call last) lt;ipython-input-15-b2143a820b6bgt; in lt;modulegt;  1 regressor.compile(optimizer = 'adam', loss = 'mean_squared_error')  2  ----gt; 3 regressor.fit(X_train, y_train, epochs = 100, batch_size = 32)  ~/opt/anaconda3/envs/Tensorflowtest/lib/python3.6/site-packages/keras/engine/training.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, validation_freq, max_queue_size, workers, use_multiprocessing, **kwargs)  1152 sample_weight=sample_weight,  1153 class_weight=class_weight, -gt; 1154 batch_size=batch_size)  1155   1156 # Prepare validation data.  ~/opt/anaconda3/envs/Tensorflowtest/lib/python3.6/site-packages/keras/engine/training.py in _standardize_user_data(self, x, y, sample_weight, class_weight, check_array_lengths, batch_size)  619 feed_output_shapes,  620 check_batch_axis=False, # Don't enforce the batch size. --gt; 621 exception_prefix='target')  622   623 # Generate sample-wise weight values given the `sample_weight` and  ~/opt/anaconda3/envs/Tensorflowtest/lib/python3.6/site-packages/keras/engine/training_utils.py in standardize_input_data(data, names, shapes, check_batch_axis, exception_prefix)  133 ': expected '   names[i]   ' to have '    134 str(len(shape))   ' dimensions, but got array ' --gt; 135 'with shape '   str(data_shape))  136 if not check_batch_axis:  137 data_shape = data_shape[1:]  ValueError: Error when checking target: expected dense_1 to have 3 dimensions, but got array with shape (183, 1)