python - 在 Keras 中使用带有生成器的多处理时,如何为每个 fork 建立单独的数据库连接?
问题描述
我将 Keras 与fit_generator()
. 我的生成器连接到数据库(在我的例子中是 MongoDB)以获取每个批次的数据。如果我使用fit_generator()
我得到这个警告的多处理标志:
UserWarning: MongoClient opened before fork. Create MongoClient only after forking.
我在以下期间连接到数据库__init__()
:
class MyCustomGenerator(tf.keras.utils.Sequence):
def __init__(self, ...):
collection = MagicMongoDBConnector()
def __len__(self):
...
def __getitem__(self, idx):
# Using collection to fetch data from mongoDB
...
def on_epoch_end(self):
...
我假设我需要为每个纪元建立一个单独的连接,但不幸的是,没有on_epoch_begin(self)
可用的回调(如此处所示)。
所以有两个问题:
如果使用多处理,Keras 如何以及何时分叉生成器?如何摆脱 MongoClient 警告并在每个分叉内连接?
解决方案
我没有要测试的 mongo 数据库,但这可能有效 - 您可以在每个进程的第一个 get-item 上获取集合(连接?)。
class MyCustomGenerator(tf.keras.utils.Sequence):
def __init__(self, ...):
self.collection = None
def __len__(self):
...
def __getitem__(self, idx):
if self.collection is None:
self.collection = MagicMongoDBConnector()
# Continue with your code
# Using collection to fetch data from mongoDB
...
def on_epoch_end(self):
...
推荐阅读
- laravel-5 - 自定义域不适用于宅基地
- javascript - 时间返回的格式不正确
- r - 在 ggplot2 字幕的 plotmath 表达式中包含条件元素
- javascript - JavaScript 幻灯片未按预期工作
- time-series - 重现 ARIMA 预测(熊猫)
- c - 使用结构和指针时如何释放分配的内存?
- php - 如何为 PHP 多维数组中的每个对象添加新的键值对?
- react-native - 返回时未触发 ReactNative WebView onNavigationStateChange
- java - Hibernate ORA-00932: 不一致的数据类型: 预期 NUMBER 得到 BINARY
- javascript - 通过 Javascript 调用自定义操作时出现错误的请求错误