【问题标题】:Running Tensorflow.Keras Model.Predict on Only One CPU仅在一个 CPU 上运行 Tensorflow.Keras Model.Predict
【发布时间】:2022-01-24 10:58:44
【问题描述】:

我有一个有 60 个 CPU 的系统。我想在 60 个内核上并行应用 Keras 神经网络模型预测。我应该如何强制每个并行进程只使用 60 个内核中的 1 个?

from pandarallel import pandarallel
pandarallel.initialize(nb_workers=60)

def my_func(path):
   # probably something should be added here to restrict tensorflow.keras model.predict to only one CPU
   return my_model.predict(load_and_preprocess(path))

df['prediction'] = df.parallel_apply(lambda x: my_func(x['image_path']))

问题在于,目前,对于长度为 10 的 DataFrame,此代码在 10 秒内完成时永远不停地运行。

【问题讨论】:

标签: pandas session multiprocessing tf.keras predict


【解决方案1】:

为了社区的利益,在此处添加@H4iku 答案

import tensorflow as tf
import numpy as np
from multiprocessing import Pool


def _apply_df(data):
    model = tf.keras.models.load_model("my_fashion_mnist_model.h5")
    return model.predict(data)


def apply_by_multiprocessing(data, workers):

    pool = Pool(processes=workers)
    result = pool.map(_apply_df, np.array_split(data, workers))
    pool.close()
    return list(result)


def main():
    fashion_mnist = tf.keras.datasets.fashion_mnist
    _, (test_images, test_labels) = fashion_mnist.load_data()

    test_images = test_images / 255.0
    results = apply_by_multiprocessing(test_images, workers=3)
    print(test_images.shape)           # (10000, 28, 28)
    print(len(results))                # 3
    print([x.shape for x in results])  # [(3334, 10), (3333, 10), (3333, 10)]


if __name__ == "__main__":
    main()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-24
    相关资源
    最近更新 更多