n_jobs = -1 等效于 keras

数据挖掘 Python 深度学习 喀拉斯 scikit-学习 张量流
2022-02-25 04:35:23

我最近开始学习深度学习。在使用 n_jobs = -1 的 sklearn 库的机器学习中,使用了我所有的 cpu 内核,这加快了网格搜索。现在我正在尝试在训练数据上拟合一个 rnn 模型,这需要很多时间。有什么方法可以加快训练速度吗?

# Initialising the RNN
regressor = Sequential()

# Adding the first LSTM layer and some Dropout regularisation
regressor.add(LSTM(units = 50, return_sequences = True, input_shape = (X_train.shape[1], 7)))
regressor.add(Dropout(0.2))

# Adding a second LSTM layer and some Dropout regularisation
regressor.add(LSTM(units = 50, return_sequences = True))
regressor.add(Dropout(0.2))

# Adding a third LSTM layer and some Dropout regularisation
regressor.add(LSTM(units = 50, return_sequences = True))
regressor.add(Dropout(0.2))

# Adding a fourth LSTM layer and some Dropout regularisation
regressor.add(LSTM(units = 50))
regressor.add(Dropout(0.2))

# Adding the output layer
regressor.add(Dense(units = 1))

# Compiling the RNN
regressor.compile(optimizer = 'adam', loss = 'mean_squared_error')

# Fitting the RNN to the Training set
regressor.fit(X_train, y_train, epochs = 100, batch_size = 32,shuffle=False)
1个回答

在这里,您对模型进行了一次 fit(),其名称本身就说明了 - Sequential。

除非您正在使用多个模型进行交叉验证或某种分布式学习,否则并行运行多个拟合没有任何好处。

但是您可以在迭代级别上显着加快速度,具体取决于 Keras 后端如何配置为与您的硬件一起使用。

假设您使用带有 tensorflow 后端的 Keras(默认):

  • 如果你在 CPU 上运行,默认情况下 tensorflow 应该已经选择了所有可用的内核(如果没有,它可能有助于检查如何在多个内核上运行 Keras?);

  • 如果您在 GPU 上运行:

    (1) 确保 Keras 后端可以看到你的 GPU

    from keras import backend
    print(backend.tensorflow_backend._get_available_gpus())
    

    如果您的 GPU 没有显示在这里,您的系统可能需要进行一些配置(它值得另一个主题);

    (2) 看看CuDNNLSTM——它是针对 GPU 优化的 Keras LSTM 实现。