测试显卡显存以及tensorflowGPU

查看是否有GPU可用

from tensorflow.python.client import device_lib

# 列出全部的本地机器设备
local_device_protos = device_lib.list_local_devices()
# 打印
print(local_device_protos)

# 只打印GPU设备
[print(x) for x in local_device_protos if x.device_type == 'GPU']


import tensorflow as tf
import numpy as np
import os
# tensorflow-gpu==1.15.4
os.environ['CUDA_VISIBLE_DEVICES'] = "1"
gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=1)
config = tf.ConfigProto(gpu_options=gpu_options)
session = tf.Session(config=config)

# 使用numpy生成100个随机点
x_data = np.random.rand(900000000)
y_data = x_data * 0.1 + 0.2

# 构造一个线性模型
b = tf.Variable(0.)
k = tf.Variable(0.)
y = k * x_data + b

loss = tf.reduce_mean(tf.square(y_data - y))
optimizer = tf.train.GradientDescentOptimizer(0.2)
train = optimizer.minimize(loss)
# # 初始化变量
init = tf.global_variables_initializer()

with session as sess:
    sess.run(init)
    for step in range(20100000):
        sess.run(train)
        if step % 20 == 0:
            print(step, sess.run([k, b]))

你可能感兴趣的:(tensorflow,深度学习,python)