我想对时间序列数据进行多类别分类。这里我所拥有的数据集需要进行大量预处理。为了了解如何实现模型,我使用了 IRIS 数据集(不适合 LSTM),因为它与我拥有的时间序列数据具有相同的结构(4 个输入特征,1 个输出特征,120 个样本)。我已经实现了以下代码,但在使用批量大小为 5 拟合模型时遇到了无效形状错误(我多次更改了批量大小,但似乎没有任何变化)
# 加载数据集 dataframe = pandas.read_csv("iris.csv",header=None) dataset = dataframe.values X=dataset[:,0:4].astype(float) Y=dataset[:,4]
# 编码输出变量 encoder = LabelEncoder() encoder.fit(Y) # 将输出变量转换为数字 encoded_Y = encoder.transform(Y) # 将整数转换为虚拟变量(独热编码) dummy_Y = np_utils.to_categorical(encoded_Y)
from sklearn.model_selection import train_test_splitX_train,X_test,y_train,y_test=train_test_split(X,dummy_Y,test_size=0.2) # 20% 用于测试
X_train = X_train.reshape(60, 2, 4)y_train = y_train.reshape(60, 2, 3)y_train.shape,X_train.shape
((60, 2, 3), (60, 2, 4))
# 创建神经网络模型def create_nn_model():# 创建顺序模型 model = Sequential() model.add(LSTM(100,dropout=0.2, input_shape=(X_train.shape[1],X_train.shape[2]))) model.add(Dense(100, activation='relu')) model.add(Dense(3,activation='softmax')) # 编译模型 model.compile(loss='categorical_crossentropy',optimizer='adam', metrics=['accuracy']) return model
model = create_nn_model()model.summary()
> 模型: "sequential_1"_________________________________________________________________层 (类型) 输出形状 参数数量 =================================================================lstm_1 (LSTM) (None, 100) 42000 _________________________________________________________________dense_2 (Dense) (None, 100) 10100 _________________________________________________________________dense_3 (Dense) (None, 3) 303 =================================================================总参数: 52,403可训练参数: 52,403不可训练参数: 0
model.fit(X_train,y_train,epochs=200,batch_size=5)
> ValueError Traceback (most recent call last)<ipython-input-26-0aef33c299f0> in <module>()----> 1 model.fit(X_train,y_train,epochs=200,batch_size=5) #X_train 是独立变量。根据数据集的大小,数据集将被分批训练9 frames/usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs) 984 except Exception as e: # pylint:disable=broad-except 985 if hasattr(e, "ag_error_metadata"):--> 986 raise e.ag_error_metadata.to_exception(e) 987 else: 988 raiseValueError: in user code: /usr/local/lib/python3.7/dist-packages/keras/engine/training.py:830 train_function * return step_function(self, iterator) /usr/local/lib/python3.7/dist-packages/keras/engine/training.py:813 run_step * outputs = model.train_step(data) /usr/local/lib/python3.7/dist-packages/keras/engine/training.py:771 train_step * loss = self.compiled_loss( /usr/local/lib/python3.7/dist-packages/keras/engine/compile_utils.py:201 __call__ * loss_value = loss_obj(y_t, y_p, sample_weight=sw) /usr/local/lib/python3.7/dist-packages/keras/losses.py:142 __call__ * losses = call_fn(y_true, y_pred) /usr/local/lib/python3.7/dist-packages/keras/losses.py:246 call * return ag_fn(y_true, y_pred, **self._fn_kwargs) /usr/local/lib/python3.7/dist-packages/tensorflow/python/util/dispatch.py:206 wrapper ** return target(*args, **kwargs) /usr/local/lib/python3.7/dist-packages/keras/losses.py:1631 categorical_crossentropy y_true, y_pred, from_logits=from_logits) /usr/local/lib/python3.7/dist-packages/tensorflow/python/util/dispatch.py:206 wrapper return target(*args, **kwargs) /usr/local/lib/python3.7/dist-packages/keras/backend.py:4827 categorical_crossentropy target.shape.assert_is_compatible_with(output.shape) /usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/tensor_shape.py:1161 assert_is_compatible_with raise ValueError("形状 %s 和 %s 不兼容" % (self, other)) ValueError: 形状 (5, 2, 3) 和 (5, 3) 不兼容
回答:
你的 y_true
和 y_pred
形状不一致。你可能需要以以下方式定义你的 LSTM
model.add(LSTM(100,dropout=0.2, input_shape=(2,4), return_sequences=True))....
模型: "sequential_1"_________________________________________________________________层 (类型) 输出形状 参数数量 =================================================================....dense_3 (Dense) (None, 2, 3) 303 < ---=================================================================
更新
使用 return_sequences = True
将会起作用,因为你以这种方式定义了你的训练对:
X_train = X_train.reshape(60, 2, 4)y_train = y_train.reshape(60, 2, 3)
这代表 (批量大小, 时间步长, 输入长度)
;但请注意,你需要重塑或满足上面的模型中 LSTM 层的输入要求,而不是 y_train
。然而,当你定义模型时,你没有使用返回序列,这使得最后一层只有三个分类器而没有时间步长,但你的 y_train
是以这种方式定义的。但是如果你将返回序列设置为 True 并输出你的模型摘要,你会看到最后一层的输出形状为 (None, 2, 3
),这正好与 y_train
的形状相匹配。
在理解 return_sequence
在这里的作用之前,你可能需要知道 LSTM 模型中的时间步长是什么意思,查看 这个 回答。据我所知,这取决于你需要为输入设置多少个时间步长;我可以设置 LSTM 单元的单次出现或多次出现 (n-th
时间步长)。对于 n-th
时间步长 (n: {1,2,3..N
),如果我希望 LSTM 返回所有时间步长的输出 (n
个数),那么我将设置 return_sequence = True
,否则设置 return_sequence = False
。根据 文档,
return_sequences: 布尔值。是否返回输出序列中的最后一个输出,或完整序列。默认值: False。
简而言之,如果设置为 True,将返回所有序列,但如果设置为 False,则只返回最后一个输出。例如:
inputs = tf.random.normal([32, 8])inputs = tf.reshape(inputs, [-1, 2, 4 ]) # 或 [-1, 4, 2] # 或 [-1, 1, 8]inputs.shape TensorShape([32, 2, 4]) # (批量大小, 时间步长, 输入长度)lstm = tf.keras.layers.LSTM(10, return_sequences=True)whole_seq_output = lstm(inputs)print(whole_seq_output.shape)(32, 2, 10) # (批量大小, 时间步长, 输出长度)lstm = tf.keras.layers.LSTM(10, return_sequences=False)last_seq_output = lstm(inputs)print(last_seq_output.shape)(32, 10) # (批量大小, 输出长度)