前提是已经安装好Anaconda,本文基于1.9.2
- 创建一个新的environment 可以选择python的版本创建,也是anaconda的优势,可以根据python的不同版本创建环境
conda create -n tf-env python=3.6
- 查看已经创建的环境
conda env list
- 删除环境
conda env remove -n tfenv
- 激活环境
activate tf-env
- 导出当前环境的配置到yml,实际上就是复制自己的环境,这样即使更换电脑后也可以与之前的自己环境一致
conda env export > environment.yml
使用此环境配置:
conda env create -f environment.yaml
以上就创建并激活tf-env这个环境,python version=3.6
安装tensorflow
Anaconda 在安装python package时比较方便,这也是建议初学者使用它的原因,这样就避免了中间过程要安装很多依赖包的麻烦
- 这里我选择安装的是tensorflow-gpu版本,看到右侧的安装依赖包顺便帮你安装好了CUDA9.0和cuDNN7.1,这省了你很大很大麻烦,当然前提你的电脑显卡是支持的
- 到这里就已经安装好了tensorflow了,是不是很简单,用anaconda很方便。现在我们去操作下
- 在anaconda可以使用Spyder编写python,如果你喜欢使用VS,可能需要额外配置,这里就以Spyder为例
- 既然安装时tensorflow-gup版本,按道理说肯定比cpu运算快点,现在测试下
-
查看电脑GPU和CPU
import os
from tensorflow.python.client import device_lib
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "99"
if __name__ == "__main__":
print(device_lib.list_local_devices())
这是我电脑的cup和gpu的情况
runfile('C:/Users/Administrator/.spyder-py3/temp.py', wdir='C:/Users/Administrator/.spyder-py3')
[name: "/device:CPU:0"
device_type: "CPU"
memory_limit: 268435456
locality {
}
incarnation: 15435477216407839396
, name: "/device:GPU:0"
device_type: "GPU"
memory_limit: 3082768384
locality {
bus_id: 1
links {
}
}
incarnation: 7754051037352108455
physical_device_desc: "device: 0, name: GeForce GTX 1050 Ti, pci bus id: 0000:01:00.0, compute capability: 6.1"
]
- 在Spyder运行.py文件时需要输入参数,运算结果看出,gpu要比cpu快8倍左右,默认是先选择gpu运算
import sys
import numpy as np
import tensorflow as tf
from datetime import datetime
device_name = sys.argv[1] # Choose device from cmd line. Options: gpu or cpu
shape = (int(sys.argv[2]), int(sys.argv[2]))
if device_name == "gpu":
device_name = "/gpu:0"
else:
device_name = "/cpu:0"
with tf.device(device_name):
random_matrix = tf.random_uniform(shape=shape, minval=0, maxval=1)
dot_operation = tf.matmul(random_matrix, tf.transpose(random_matrix))
sum_operation = tf.reduce_sum(dot_operation)
startTime = datetime.now()
with tf.Session(config=tf.ConfigProto(log_device_placement=True)) as session:
result = session.run(sum_operation)
print(result)
# It can be hard to see the results on the terminal with lots of output -- add some newlines to improve readability.
print("\n" * 5)
print("Shape:", shape, "Device:", device_name)
print("Time taken:", datetime.now() - startTime)
print("\n" * 5)
--------------------------------------------
runfile('C:/Users/Administrator/.spyder-py3/temp.py', args='cpu 1500',wdir='C:/Users/Administrator/.spyder-py3')
844857860.0
Shape: (1500, 1500) Device: /cpu:0
Time taken: 0:00:00.093600
runfile('C:/Users/Administrator/.spyder-py3/temp.py', args='gpu 1500',wdir='C:/Users/Administrator/.spyder-py3')
844695940.0
Shape: (1500, 1500) Device: /gpu:0
Time taken: 0:00:00.015600