Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Tensorflow Keras中的数据并行_Tensorflow_Keras - Fatal编程技术网

Tensorflow Keras中的数据并行

Tensorflow Keras中的数据并行,tensorflow,keras,Tensorflow,Keras,我在keras(tensorflow后端)中寻找数据并行性,而不是模型并行性。 我正在对视频文件执行视频分类,因此在GPU中只能容纳一批大小为2的视频。因此,我想知道一种使用多个GPU的方法,以增加批量大小,从而更好地估计和更快地训练。 你能给我一个有效的方法吗 我正在使用一个12gb的TitanX和一个6gb的Titan Black 谢谢这是一种方法: 此方法to_multi_gpu获取模型(在单个gpu上使用Keras 2.0定义),并返回在多个gpu上复制的相同模型(使用共享参数)。新模型

我在keras(tensorflow后端)中寻找数据并行性,而不是模型并行性。 我正在对视频文件执行视频分类,因此在GPU中只能容纳一批大小为2的视频。因此,我想知道一种使用多个GPU的方法,以增加批量大小,从而更好地估计和更快地训练。 你能给我一个有效的方法吗

我正在使用一个12gb的TitanX和一个6gb的Titan Black


谢谢

这是一种方法:

此方法
to_multi_gpu
获取
模型(在单个gpu上使用Keras 2.0定义),并返回在多个gpu上复制的相同模型(使用共享参数)。新模型的输入将被均匀地分割,每个切片将传递给一个复制模型。所有复制模型的输出在最后连接起来

from keras import backend as K
from keras.models import Model
from keras.layers import Input
from keras.layers.core import Lambda
from keras.layers.merge import Concatenate

def slice_batch(x, n_gpus, part):
    """
    Divide the input batch into [n_gpus] slices, and obtain slice number [part].
    i.e. if len(x)=10, then slice_batch(x, 2, 1) will return x[5:].
    """
    sh = K.shape(x)
    L = sh[0] // n_gpus
    if part == n_gpus - 1:
        return x[part*L:]
    return x[part*L:(part+1)*L]


def to_multi_gpu(model, n_gpus=2):
    """
    Given a keras [model], return an equivalent model which parallelizes
    the computation over [n_gpus] GPUs.

    Each GPU gets a slice of the input batch, applies the model on that slice
    and later the outputs of the models are concatenated to a single tensor, 
    hence the user sees a model that behaves the same as the original.
    """
    with tf.device('/cpu:0'):
        x = Input(model.input_shape[1:], name=model.input_names[0])

    towers = []
    for g in range(n_gpus):
        with tf.device('/gpu:' + str(g)):
            slice_g = Lambda(slice_batch, 
                             lambda shape: shape, 
                             arguments={'n_gpus':n_gpus, 'part':g})(x)
            towers.append(model(slice_g))

    with tf.device('/cpu:0'):
        merged = Concatenate(axis=0)(towers)

    return Model(inputs=[x], outputs=[merged])