You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Keras中使用LSTM时触发TypeError: Expected int32错误的解决方法

解决Keras LSTM中TypeError: Expected int32, got tf.Variable的问题

你遇到的这个错误核心原因是输入层的 dtype 设置与 LSTM 层的权重 dtype 不匹配,下面给你拆解问题和解决方案:

问题分析

你的代码里把输入层的 dtype 设为了 'int32',但 Keras 的 LSTM 层默认会使用浮点类型(比如 float32)的权重参数。当 LSTM 尝试用浮点权重和 int32 类型的输入做计算时,就会触发类型不匹配的 TypeError。

解决方案

1. 修正输入层的 dtype 设置

你的训练数据是包含100个特征的连续值向量(从 training_data.shape=(600,2500,100) 可以判断),完全不需要设置 dtype='int32',直接去掉这个参数即可(Keras 默认输入 dtype 为 float32,正好匹配 LSTM 的权重类型):

rnn_inputs = Input(shape=(2500, 100))  # 默认dtype为float32,符合要求
simple_rnn = LSTM(3, return_sequences=True, activation='relu')(rnn_inputs)

或者你也可以显式指定浮点 dtype,效果一样:

rnn_inputs = Input(shape=(2500, 100), dtype='float32')

2. 确认训练数据的类型

如果你的 training_data 当前是 int32 类型,需要先转换为浮点类型再输入模型:

training_data = training_data.astype('float32')

额外提示(针对整数输入场景)

如果你的输入是整数索引(比如词嵌入的词汇索引),那不能直接把 int32 输入喂给 LSTM,需要先通过 Embedding 层把整数索引转换成浮点向量,再输入到 LSTM:

# 示例:整数索引输入的正确流程
rnn_inputs = Input(shape=(2500,), dtype='int32')
# 把整数索引转成100维浮点向量
embedding_layer = Embedding(input_dim=你的词汇表大小, output_dim=100)(rnn_inputs)
simple_rnn = LSTM(3, return_sequences=True, activation='relu')(embedding_layer)

内容的提问来源于stack exchange,提问作者Teodorico Levoff

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:28:31