本文主要介绍Python TensorFlow相关,包括TensorFlow的CPU版和GPU版安装配置,以及使用的简单的示例代码。TensorFlow是一个用于机器学习的端到端开源平台。它拥有全面,灵活的工具, 库和 社区资源生态系统 ,可让研究人员推动ML的最新技术,开发人员可轻松构建和部署ML驱动的应用程序。

1、TensorFlow安装

安装CPU版

pip install tensorflow

安装GPU版(支持CUDA的GPU卡)

pip install tensorflow-gpu

通过Conda虚拟环境安装CPU版TensorFlow

1)创建一个新的Conda虚拟环境

conda create -n tensorflow_cpu pip python=3.6

2)激活新创建的虚拟环境

activate tensorflow_cpu

激活后的效果:

(tensorflow_cpu) C:\Users\sglvladi>

3)在虚拟环境中执行安装

pip install --ignore-installed --upgrade tensorflow==1.9

通过Conda虚拟环境安装GPU版TensorFlow

1)创建一个新的Conda虚拟环境

conda create -n tensorflow_gpu pip python=3.6

2)激活新创建的虚拟环境

activate tensorflow_gpu

激活后的效果:

(tensorflow_gpu) C:\Users\sglvladi>

3)在虚拟环境中执行安装

pip install --ignore-installed --upgrade tensorflow-gpu==1.9

2、TensorFlow示例代码

>>> import tensorflow as tf
>>> tf.enable_eager_execution()
>>> tf.add(1, 2).numpy()
3
>>> hello = tf.constant('Hello, TensorFlow!')
>>> hello.numpy()
'Hello, TensorFlow!'

# Import `tensorflow`
import tensorflow as tf
# Initialize two constants
x1 = tf.constant([1,2,3,4])
x2 = tf.constant([5,6,7,8])
# Multiply
result = tf.multiply(x1, x2)
# Print the result
print(result)

# Import `tensorflow` 
import tensorflow as tf
# Initialize two constants
x1 = tf.constant([1,2,3,4])
x2 = tf.constant([5,6,7,8])
# Multiply
result = tf.multiply(x1, x2)
# Intialize the Session
sess = tf.Session()
# Print the result
print(sess.run(result))
# Close the session
sess.close()

# Import `tensorflow`
import tensorflow as tf
# Initialize two constants
x1 = tf.constant([1,2,3,4])
x2 = tf.constant([5,6,7,8])
# Multiply
result = tf.multiply(x1, x2)
# Initialize Session and run `result`
with tf.Session() as sess:
  output = sess.run(result)
  print(output)