python - Keras LSTM 中的动态批量大小 (TensorFlow 2.x)

标签 python tensorflow keras lstm

我有一个数据框,其中包含 27k 条记录作为训练集,另一个测试数据集包含 4k 条记录。两个数据集各有 25 个特征。

x_train shape: (27000, 25), 
x_test shape: (4000, 25)

训练集中的数据示例:

|Subject ID|Feat_1|Feat_2|Feat_X|Hr_count|Label|
|s0001     |    89| 31   |  43  |   1    |  0  |
|s0001     |    94| 32   |  68  |   2    |  0  |
|s0001     |    38| 90   |  86  |   3    |  0  |
|s0001     |    79| 34   |  78  |   4    |  1  |
|s0001     |    85| 24   |  70  |   5    |  1  |
|s0002     |    7 | 9    |  32  |   1    |  0  |
|s0002     |    60| 56   |  72  |   2    |  0  |
|s0002     |    68| 72   |  23  |   3    |  0  |
|s0003     |    26| 88   |  1   |   1    |  0  |
|s0004     |    45| 27   |  22  |   1    |  0  |
|s0004     |    10| 80   |  67  |   2    |  0  |
|s0004     |    71| 48   |  21  |   3    |  0  |
|s0004     |    58| 9    |  60  |   4    |  1  |

Hr_count:表示每个受试者在实验中停留的时间

标签:这是我构建分类器时的目标变量。代表受试者留在实验后收到的flag

我在 LSTM RNN 模型上训练数据,其定义如下:

model = Sequential()
model.add(LSTM(100, activation='tanh', return_sequences=True, input_shape=(1, 25)))
model.add(LSTM(49, activation='tanh'))
model.add(Dense(1, activation='sigmoid'))
 
model.fit(
    x_train, y_train,
    validation_data=(x_test, y_test),
    batch_size=32,
    epochs=200)

问题:

由于数据的顺序性质,我想在拟合模型时将动态batch_size参数定义为训练中每个受试者的最大Hr_count数,以便LSTM可以拾取数据之间的关系每个受试者单独(每批仅包含每个受试者的数据)。这意味着每个批处理包含 1 个受试者的样本,按 Hr_count 排序。

动态batch_size的灵活性在Keras或TensorFlow v2.x中似乎不可用(与TensorFlow v1.x相反)...

如何将批量大小定义为动态的batch_size参数?

最佳答案

您可以创建一个循环,为每个受试者调用 model.fit() 函数,然后根据当前的 Hr_count 设置批量大小

for subject in list_of_subjects:
    hr_count,data = subject
    x_train,y_train = data
    model.fit(
    x_train, y_train,
    validation_data=(x_test, y_test),
    batch_size=hr_count,
    epochs=200)
    

此代码运行的 list_subject 必须具有形状

[[Hr_count,[x_triain,y_train]]

关于python - Keras LSTM 中的动态批量大小 (TensorFlow 2.x),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70757787/

相关文章:

python - 如何使用 https 而不是 http 启动 Dockerized Python Flask 应用程序?

python - 无法从 PyCharm python 控制台正确运行 Firefox (geckodriver)

tensorflow - 定义自定义tf.keras层时是否还需要实现 `compute_output_shape()`?

python - reshape 具有多个未知维度的张量

python - tf.keras 中的 A2C 算法 : actor loss function

python - 为什么 K.log 值在 keras 中给我 nan

python - 我如何向 Python 中的列表添加限制或规则?

python django API身份验证发布请求 - 输出变量在浏览器中显示json字符串,但在打印时不显示

tensorflow - 'conda install tensorflow-gpu' 没有安装任何 CUDNN 库

TensorFlow手动构建GraphDef