如何在Python中修复'Dim ValueError'

时间:2019-07-25 13:10:35

标签: python python-3.x lstm recurrent-neural-network

我是Keras的新手,我正在尝试实现一个简单的LSTM模型。特别是,我有一个25类的数据集,我想训练模型。

from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import LSTM, Dense
from keras.models import load_model
import numpy as np


class imageLSTMClassifier(object):
    def __init__(self):

        self.time_steps=64 # timesteps to unroll
        self.n_units=128 # hidden LSTM units
        self.n_inputs=64 # rows of 28 pixels (an img is 64x64)
        self.n_classes=25 
        self.batch_size=32
        self.n_epochs=5
        self.train_data_dir='walking'

        self._data_loaded = False
        self._trained = False

    def __create_model(self):
        self.model = Sequential()
        self.model.add(LSTM(self.n_units, input_shape=(self.time_steps, self.n_inputs)))
        self.model.add(Dense(self.n_classes, activation='softmax'))

        self.model.compile(loss='categorical_crossentropy',
                      optimizer='adam',
                      metrics=['accuracy'])

    def __load_data(self):
        self.train_datagen = ImageDataGenerator(rescale=1./255,
                                                shear_range=0.2,
                                                zoom_range=0.2,
                                                horizontal_flip=True,
                                                validation_split=0.2)

        self.train_generator = self.train_datagen.flow_from_directory(
                                                    self.train_data_dir,
                                                    target_size=(self.n_inputs,self.n_inputs),
                                                    batch_size=self.batch_size,
                                                    class_mode='categorical',
                                                    subset='training')

        self.validation_generator = self.train_datagen.flow_from_directory(
                                                    self.train_data_dir,
                                                    target_size=(self.n_inputs,self.n_inputs),
                                                    batch_size=self.batch_size,
                                                    class_mode='categorical',
                                                    subset='validation')
        self._data_loaded = True

ValueError:

ValueError: Input 0 is incompatible with layer lstm_9: expected ndim=3, found ndim=4

我认为问题源于flow_from_directory函数的返回值(批处理,大小1,大小2),但我无法修复它。

感谢帮助。

0 个答案:

没有答案