如何确保 Keras 使用 GPU 和 tensorflow 后端?

     2023-02-23     142

关键词:

【中文标题】如何确保 Keras 使用 GPU 和 tensorflow 后端?【英文标题】:How ensure that Keras is using GPU with tensorflow backend? 【发布时间】:2018-10-02 00:17:01 【问题描述】:

我在 Paperspace 云基础架构上创建了虚拟笔记本,后端使用了 Tensorflow GPU P5000 虚拟实例。 当我开始训练我的网络时,它的运行速度比我使用纯 CPU 运行时引擎的 MacBook Pro 慢 2 倍。 如何确保 Keras NN 在训练过程中使用 GPU 而不是 CPU?

请在下面找到我的代码:

from tensorflow.contrib.keras.api.keras.models import Sequential
from tensorflow.contrib.keras.api.keras.layers import Dense
from tensorflow.contrib.keras.api.keras.layers import Dropout
from tensorflow.contrib.keras.api.keras import utils as np_utils
import numpy as np
import pandas as pd

# Read data
pddata= pd.read_csv('data/data.csv', delimiter=';')

# Helper function (prepare & test data)
def split_to_train_test (data):
    trainLenght = len(data) - len(data)//10

    trainData = data.loc[:trainLenght].sample(frac=1).reset_index(drop=True)
    testData = data.loc[trainLenght+1:].sample(frac=1).reset_index(drop=True)

    trainLabels = trainData.loc[:,"Label"].as_matrix()
    testLabels = testData.loc[:,"Label"].as_matrix()

    trainData = trainData.loc[:,"Feature 0":].as_matrix()
    testData  = testData.loc[:,"Feature 0":].as_matrix()

    return (trainData, testData, trainLabels, testLabels)

# prepare train & test data
(X_train, X_test, y_train, y_test) = split_to_train_test (pddata)

# Convert labels to one-hot notation
Y_train = np_utils.to_categorical(y_train, 3)
Y_test  = np_utils.to_categorical(y_test, 3)

# Define model in Keras
def create_model(init):
    model = Sequential()
    model.add(Dense(101, input_shape=(101,), kernel_initializer=init, activation='tanh'))
    model.add(Dense(101, kernel_initializer=init, activation='tanh'))
    model.add(Dense(101, kernel_initializer=init, activation='tanh'))
    model.add(Dense(101, kernel_initializer=init, activation='tanh'))
    model.add(Dense(3, kernel_initializer=init, activation='softmax'))
    return model

# Train the model
uniform_model = create_model("glorot_normal")
uniform_model.compile(loss='categorical_crossentropy', optimizer='sgd', metrics=['accuracy'])
uniform_model.fit(X_train, Y_train, batch_size=1, epochs=300, verbose=1, validation_data=(X_test, Y_test)) 

【问题讨论】:

How to tell if tensorflow is using gpu acceleration from inside python shell?的可能重复 不确定是否是最好的方法,但创建一个巨大的批次并用它进行训练。如果它带来 OOM 错误,它是 GPU,如果它冻结你的机器,它是 CPU 您可以尝试的另一件事是在声明您的模型之前强制使用:with tf.device('/gpu:0'): 的 GPU 设备。 相同的行为 - 执行速度较慢,当我创建 batch_size=32 甚至 64 时。在纯 CPU 上,比具有相同设置的 MacBook Pro 低两倍 更改代码以使用with tf.device('/gpu:0'): 运行,但与我的 MacBook pro 相比,执行时间仍然很慢... 【参考方案1】:

您需要在 TensorFlow 会话中设置 log_device_placement = True 来运行您的网络(下面示例代码中最后一行之前的行。)有趣的是,如果您在会话中设置它,当 Keras 执行配件。所以下面的这段代码(经过测试)确实输出了每个张量的位置。请注意,我已将数据读取短路,因为您的数据不可用,所以我只是用随机数据运行网络。这种方式的代码是独立的,任何人都可以运行。另一个注意事项:如果您从 Jupyter Notebook 运行此程序,log_device_placement 的输出将转到 Jupyter Notebook 启动的终端,而不是笔记本单元格的输出。

from tensorflow.contrib.keras.api.keras.models import Sequential
from tensorflow.contrib.keras.api.keras.layers import Dense
from tensorflow.contrib.keras.api.keras.layers import Dropout
from tensorflow.contrib.keras.api.keras import utils as np_utils
import numpy as np
import pandas as pd
import tensorflow as tf

# Read data
#pddata=pd.read_csv('data/data.csv', delimiter=';')
pddata = "foobar"

# Helper function (prepare & test data)
def split_to_train_test (data):

    return (
        np.random.uniform( size = ( 100, 101 ) ),
        np.random.uniform( size = ( 100, 101 ) ),
        np.random.randint( 0, size = ( 100 ), high = 3 ),
        np.random.randint( 0, size = ( 100 ), high = 3 )
    )

    trainLenght = len(data) - len(data)//10

    trainData = data.loc[:trainLenght].sample(frac=1).reset_index(drop=True)
    testData = data.loc[trainLenght+1:].sample(frac=1).reset_index(drop=True)

    trainLabels = trainData.loc[:,"Label"].as_matrix()
    testLabels = testData.loc[:,"Label"].as_matrix()

    trainData = trainData.loc[:,"Feature 0":].as_matrix()
    testData  = testData.loc[:,"Feature 0":].as_matrix()

    return (trainData, testData, trainLabels, testLabels)

# prepare train & test data
(X_train, X_test, y_train, y_test) = split_to_train_test (pddata)

# Convert labels to one-hot notation
Y_train = np_utils.to_categorical(y_train, 3)
Y_test  = np_utils.to_categorical(y_test, 3)

# Define model in Keras
def create_model(init):
    model = Sequential()
    model.add(Dense(101, input_shape=(101,), kernel_initializer=init, activation='tanh'))
    model.add(Dense(101, kernel_initializer=init, activation='tanh'))
    model.add(Dense(101, kernel_initializer=init, activation='tanh'))
    model.add(Dense(101, kernel_initializer=init, activation='tanh'))
    model.add(Dense(3, kernel_initializer=init, activation='softmax'))
    return model

# Train the model
uniform_model = create_model("glorot_normal")
uniform_model.compile(loss='categorical_crossentropy', optimizer='sgd', metrics=['accuracy'])
with tf.Session( config = tf.ConfigProto( log_device_placement = True ) ):
    uniform_model.fit(X_train, Y_train, batch_size=1, epochs=300, verbose=1, validation_data=(X_test, Y_test)) 

终端输出(部分,太长了):

... VarIsInitializedOp_13: (VarIsInitializedOp): /job:localhost/replica:0/task:0/device:GPU:0 2018-04-21 21:54:33.485870: 我 tensorflow/core/common_runtime/placer.cc:884] VarIsInitializedOp_13: (VarIsInitializedOp)/job:localhost/replica:0/task:0/device:GPU:0 训练/SGD/mul_18/ReadVariableOp: (ReadVariableOp): /job:localhost/replica:0/task:0/device:GPU:0 2018-04-21 21:54:33.485895: 我 tensorflow/core/common_runtime/placer.cc:884] 训练/SGD/mul_18/ReadVariableOp: (ReadVariableOp)/job:localhost/replica:0/task:0/device:GPU:0 训练/SGD/Variable_9/Read/ReadVariableOp: (ReadVariableOp): /job:localhost/replica:0/task:0/device:GPU:0 2018-04-21 21:54:33.485903: 我 tensorflow/core/common_runtime/placer.cc:884] 训练/SGD/Variable_9/Read/ReadVariableOp: (ReadVariableOp)/job:localhost/replica:0/task:0/device:GPU:0 ...

注意多行末尾的 GPU:0

Tensorflow 手册相关页面:Using GPU: Logging Device Placement.

【讨论】:

是的,你说得对 - log_device_placement - 表明我的训练在 GPU 上运行...奇怪的是,在 GPU 上每个 Epoch 需要 230 秒,而在 MacBook 上每个 epoch 只需要 120 秒... 也可以在colab.research.google.com 上试试。确保转到“运行时”,“更改运行时类型”,并将“硬件加速器”设置为 GPU。看看会不会快一点。如果是,那么您使用的服务跟不上速度... 谢谢 Peter,我的代码实际上使用 GPU,但奇怪的是 - GPU 执行速度比 CPU 慢... 也许可以尝试使用与 Paperspace 不同的云提供商,看看是否更好。顺便说一句,Colab 是免费的。可能是 Paperspace 的客户太多,他们的 GPU 负担过重。【参考方案2】:

把它放在你的 jupyter notebook 的顶部附近。把不需要的东西注释掉。

# confirm TensorFlow sees the GPU
from tensorflow.python.client import device_lib
assert 'GPU' in str(device_lib.list_local_devices())

# confirm Keras sees the GPU (for TensorFlow 1.X + Keras)
from keras import backend
assert len(backend.tensorflow_backend._get_available_gpus()) > 0

# confirm PyTorch sees the GPU
from torch import cuda
assert cuda.is_available()
assert cuda.device_count() > 0
print(cuda.get_device_name(cuda.current_device()))

注意:随着 TensorFlow 2.0 的发布,Keras 现在被包含在 TF API 中。

最初回答是here。

【讨论】:

【参考方案3】:

考虑到keras是tensorflow从2.0版本开始的内置:

import tensorflow as tf
tf.test.is_built_with_cuda()  
tf.test.is_gpu_available(cuda_only = True)  

注意:后一种方法可能需要几分钟才能运行。

【讨论】:

如何使用 Tensorflow-GPU 和 Keras 修复低挥发性 GPU-Util?

】如何使用Tensorflow-GPU和Keras修复低挥发性GPU-Util?【英文标题】:HowtofixlowvolatileGPU-UtilwithTensorflow-GPUandKeras?【发布时间】:2018-04-2803:34:48【问题描述】:我有一台4GPU机器,我在上面运行带有Keras的Tensorflow(GPU)。我的一些分类问题... 查看详情

如何使用 Theano 启用 Keras 以利用多个 GPU

】如何使用Theano启用Keras以利用多个GPU【英文标题】:HowtoenableKeraswithTheanotoutilizemultipleGPUs【发布时间】:2016-08-2719:32:52【问题描述】:设置:使用带有NvidiaGPU的AmazonLinux系统我使用的是Keras1.0.1运行Theanov0.8.2后端使用CUDA和CuDNNTHEAN... 查看详情

如何强制 keras 使用 tensorflow GPU 后端

】如何强制keras使用tensorflowGPU后端【英文标题】:HowtoforcekerastousetensorflowGPUbackend【发布时间】:2021-11-2804:09:22【问题描述】:我知道这是热门问题之一,但到目前为止,没有一个解决方案对我有用。我正在运行用tensorflowv1.13.1和... 查看详情

将 Keras 和 Tensorflow 与 AMD GPU 结合使用

...Theano之上的一层。但是,我只能使用AMDGPU,例如AMDR9280X。如何设置我的Python环境,以便我可以通过Keras/Tensorflow对OpenCL的支持来使用 查看详情

Keras 不使用 GPU - 如何排除故障?

】Keras不使用GPU-如何排除故障?【英文标题】:KerasdoesnotuseGPU-howtotroubleshoot?【发布时间】:2018-10-2502:35:19【问题描述】:我正在尝试在GPU上训练一个Keras模型,使用Tensorflow作为后端。我已经按照https://www.tensorflow.org/install/install_w... 查看详情

如何在 GPU 上使用 Keras?

】如何在GPU上使用Keras?【英文标题】:HowtouseKeraswithGPU?【发布时间】:2018-09-0410:18:59【问题描述】:我已经成功安装了带有GPU的TensorFlow。当我运行以下脚本时,我得到了这个结果:fromtensorflow.python.clientimportdevice_libprint(device_lib... 查看详情

如何在 Tensorflow 2.0 + Keras 中进行并行 GPU 推理?

】如何在Tensorflow2.0+Keras中进行并行GPU推理?【英文标题】:HowtodoparallelGPUinferencinginTensorflow2.0+Keras?【发布时间】:2020-03-1523:49:56【问题描述】:让我们从我刚开始接触TensorFlow和一般深度学习的前提开始。我有使用tf.Model.train()、... 查看详情

如何使用 GPU 构建 Keras (TF) 模型?

】如何使用GPU构建Keras(TF)模型?【英文标题】:HowtoUseBuildaKeras(TF)modelusingGPU?【发布时间】:2021-08-3006:16:47【问题描述】:这个问题很简单,但没有真正得到答案。很简单,我怎么知道当我通过Keras在tensorflow中构建Sequential()模型... 查看详情

如何检查 keras 是不是使用 gpu 版本的 tensorflow?

】如何检查keras是不是使用gpu版本的tensorflow?【英文标题】:HowdoIcheckifkerasisusinggpuversionoftensorflow?如何检查keras是否使用gpu版本的tensorflow?【发布时间】:2017-11-1614:31:54【问题描述】:当我运行keras脚本时,我得到以下输出:Usin... 查看详情

小白学习keras教程九keras使用gpu和callbacks模型保存(代码片段)

...U在gpu上训练使训练神经网络比在cpu上运行快得多Keras支持使用Tensorflow和Theano后端对gpu进行培训文档:https://keras.io/getting-started/faq/#how-can-i-run-keras-on-gpu安装GPU首先,下载并安装CUDA&CuDNN(假设您使用的是NVIDIAgpu)安装url:http 查看详情

使用 Keras 和 Tensorflow 降低 NVIDIA GPU 使用率

】使用Keras和Tensorflow降低NVIDIAGPU使用率【英文标题】:LowNVIDIAGPUUsagewithKerasandTensorflow【发布时间】:2020-02-0522:55:21【问题描述】:我在Windows10上使用keras-gpu和tensorflow-gpu和NVIDIAGeForceRTX2080Ti运行CNN。我的计算机有IntelXeone5-2683v4CPU(2.... 查看详情

如何安装支持 gpu 的 Keras?

】如何安装支持gpu的Keras?【英文标题】:HowtoinstallKeraswithgpusupport?【发布时间】:2019-07-0809:39:57【问题描述】:我为GPU安装了Tensorflow:pipinstalltensorflow-gpu但是当我为Keraspipinstallkeras-gpu尝试相同的操作时,它给我一个错误:找不... 查看详情

无论如何在带有 AMD GPU 的 Mac 中使用 Keras?

】无论如何在带有AMDGPU的Mac中使用Keras?【英文标题】:AnywaytoworkwithKerasinMacwithAMDGPU?【发布时间】:2020-05-1721:20:35【问题描述】:我有一台配备AMD处理器的MacBookPro,我想在这个GPU中运行Keras(Tensorflow后端)。我开始知道Keras仅适... 查看详情

使用 GPU 而不是 CPU 与 Keras 和 Linux 的 Tensorflow 后端

】使用GPU而不是CPU与Keras和Linux的Tensorflow后端【英文标题】:UsingGPUinsteadofCPUwithKeraswithTensorflowBackendforLinux【发布时间】:2017-10-1104:17:08【问题描述】:我无法让Keras使用GPU版本的Tensorflow而不是CPU。每次我导入keras时,它都会说:&... 查看详情

keras-gpu的安装与配置

...,利用gpu的特性可显著提高训练的效率。先升级显卡驱动确保后面不会因为显卡驱动版本低这个问题被卡住。NVIDIACUDA是一种由NVIDIA推出的通用并行计算架构,该架构使GPU能够解决复杂的计算问题。NVIDIAcuDNN是用于深度神经网络的... 查看详情

如何配置我的 jupyter notebook 以便它在使用 keras 时使用可用的 GPU?

】如何配置我的jupyternotebook以便它在使用keras时使用可用的GPU?【英文标题】:HowdoIconfiguremyjupyternotebooksothatitusestheavailableGPUwhileworkingwithkeras?【发布时间】:2021-05-1702:10:40【问题描述】:我搜索了解决方案并使用pip安装了tensorflow... 查看详情

新人求教gpu的使用和keras调用

参考技术A最近一直在用keras,说点个人感受。1、keras根植于python及theano,人气比较旺。2、提供较为上层的框架,搞个深度学习的原型非常方便。3、更新很快,记得几个月前还没有multi-task的能力,最近再查就提供了graph的对象。4... 查看详情

如何使用 gpu 并行训练 tensorflow.keras 模型? TensorFlow 版本 2.5.0

】如何使用gpu并行训练tensorflow.keras模型?TensorFlow版本2.5.0【英文标题】:Howtotraintensorflow.kerasmodelsinparallelusinggpu?Tensorflowversion2.5.0【发布时间】:2021-09-2409:04:17【问题描述】:我有以下代码运行我在不同模块中拥有的自定义模型... 查看详情