首页 文章

如何使用Keras与GPU?

提问于
浏览
1

我用GPU成功安装了TensorFlow . 当我运行以下脚本时,我得到了这个结果:

from tensorflow.python.client import device_lib
print(device_lib.list_local_devices())

C:\ tf_jenkins \ workspace \ rel-win \ M \ windows -gpu \ PY \ 36 \ tensorflow \ core \ platform \ cpu_feature_guard.cc:140]您的CPU支持未编译此TensorFlow二进制文件的指令:AVX2 2018 -03-26找到具有属性的设备0:名称:GeForce GTX 970 major:5 minor:2 memoryClockRate(GHz):1.253 pciBusID:0000:01:00.0 totalMemory:4.00GiB freeMemory:3.31GiB 2018-03-26 11:47 :03.186046:IC:\ tf_jenkins \ workspace \ rel-win \ M \ windows-gpu \ PY \ 36 \ tensorflow \ core \ common_runtime \ gpu \ gpu_device.cc:1312]添加可见的gpu设备:0 2018-03-26 11 :47:04.062049:IC:\ tf_jenkins \ workspace \ rel-win \ M \ windows-gpu \ PY \ 36 \ tensorflow \ core \ common_runtime \ gpu \ gpu_device.cc:993]创建TensorFlow设备(/ device:GPU:0 3043 MB内存) - >物理GPU(设备:0,名称:GeForce GTX 970,pci总线ID:0000:01:00.0,计算能力:5.2)[名称:“/ device:CPU:0”device_type:“CPU “memory_limit:268435456 locality {}化身:8082333747214375667,name:”/ device:GPU:0“device_type:”GPU“memory_l imit:3190865920 locality {bus_id:1}化身:1190887510488091263 physical_device_desc:“device:0,name:GeForce GTX 970,pci bus id:0000:01:00.0,compute capability:5.2”]

例如,如果我在Keras运行CNN,它会自动使用GPU吗?或者我是否必须编写一些代码来强制Keras使用GPU?

例如,使用MNIST数据集,我将如何使用GPU?

model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3),
                 activation='relu',
                 input_shape=input_shape))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(num_classes, activation='softmax'))

model.compile(loss=keras.losses.categorical_crossentropy,
              optimizer=keras.optimizers.Adadelta(),
              metrics=['accuracy'])

model.fit(x_train, y_train,
          batch_size=batch_size,
          epochs=epochs,
          verbose=1,
          validation_data=(x_test, y_test))

1 回答

  • 3

    您无需明确告诉Keras使用GPU . 如果GPU可用(并且从您的输出我可以看到它的情况)它将使用它 .

    您还可以通过在模型培训期间查看GPU的使用情况来凭经验检查:如果您是're on Windows 10 you only need to open the task manager and look under the ' Performance'选项卡(请参阅here) .

相关问题