我手动安装了CUDA v9.2和对应的cuDNN来安装tensorflow gpu
但我意识到 tensorflow 1.8.0 需要 CUDA 9.0 所以我跑了
pip install tensorflow-gpu
从 anaconda 提示(基本环境)开始,它自动安装了 CUDA 9.0 和相应的 cuDNN。我从同一个命令提示符启动了 Spyder。
所以这是我在 Python 3.6 中的代码,其中我使用 keras 和 tensorflow 来训练使用 8000 张奇数图像 -
# Convolutional Neural Networks
# Part 1 - Building the CNN
# Not important
# Part 2- Fitting the CNN to the images -
from keras.preprocessing.image import ImageDataGenerator
train_datagen = ImageDataGenerator(
rescale=1./255,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True)
test_datagen = ImageDataGenerator(rescale=1./255)
training_set = train_datagen.flow_from_directory(
'dataset/training_set',
target_size=(64, 64),
batch_size=32,
class_mode='binary')
test_set = test_datagen.flow_from_directory(
'dataset/test_set',
target_size=(64, 64),
batch_size=32,
class_mode='binary')
with tf.device("/gpu:0"): # Notice THIS
classifier.fit_generator(
training_set,
steps_per_epoch=8000,
epochs=25,
validation_data=test_set,
validation_steps=2000)
请注意,在最后拟合数据集之前,我将其放入
with tf.device("/gpu:0"):
我认为这应该确保它使用 GPU 进行训练?我不确定,因为将“gpu:0 ”更改为“cpu:0 ”可以提供完全相同的训练时间(每个时期 18-20 分钟)。如何确保 Spyder 中的 tensorflow 使用我的 GPU?
我有一个 NVIDIA GTX 970,所以它兼容 CUDA。
另外我使用的是 python 3.6,这是一个问题吗?
我应该创建一个单独的 Python 3.5 环境并在其中安装 tensorflow-gpu 并尝试吗?
最佳答案
创建图表。
with tf.device('/device:GPU:0'):
a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a')
b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2], name='b')
c = tf.matmul(a, b)
# Creates a session with log_device_placement set to True.
sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))
# Runs the op.
r = sess.run(c)
print(r)
import numpy as np
assert np.all(r == np.array([[22., 28.], [49., 64.]]))
或者去 tensorflow 网站 ( https://www.tensorflow.org/programmers_guide/using_gpu )
import tensorflow as tf
if tf.test.gpu_device_name():
print('Default GPU Device: {}'.format(tf.test.gpu_device_name()))
else:
print("Please install GPU version of TF")
或这个 :
from tensorflow.python.client import device_lib
print(device_lib.list_local_devices())
关于python - 如何确保 tensorflow 正在使用 GPU,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51114771/