TensorFlow Action(开山使用篇)

1、TensorFlow安装:

  使用pip install tensorflow安装CPU版;

  或使用pip install tensorflow-gpu==1.2.1指定版本安装GPU版。

2、TensorFlow测试样例:

import tensorflow as tf
a = tf.constant([1.0, 2.0], name="a")
b = tf.constant([3.0, 4.0], name="b")
add = a + b
sess = tf.Session()
sess.run(add)

  使用python的import操作加载TensorFlow;

  使用tf.constant函数定义两个常量tensor,并将两个tensor相加;

  使用tf.Session函数生成一个会话(session)并通过这个session来计算结果;

  以上若运行无误,则说明TensorFlow安装成功。

3、TensorFlow指定GPU占用 示例:

import os
import tensorflow as tf
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = "2"
config = tf.ConfigProto()
# 设置定量的GPU使用量,占用GPU50%的显存
# config.gpu_options.per_process_gpu_memory_fraction = 0.5
# 设置最小的GPU使用量,自动增长:按需求分配显存
config.gpu_options.allow_growth = True
# 打印详细日志信息
config.log_device_placement = True
a = tf.constant([1.0, 2.0], name="a")
b = tf.constant([3.0, 4.0], name="b")
add = a + b
with tf.Session(config=config) as sess:
    sess.run(add)

  使用os.environ指定具体的GPU,指定GPU占用可参考TensorFlow指定GPU使用及监控GPU占用情况

  使用tf.ConfigProto()函数设置config设定GPU使用量及tf的其他属性参数,并在tf.Session()中指定该config。

 

原文地址:https://www.cnblogs.com/helloyy/p/8191054.html