写在前面
写这篇文章主要是为了整理一下之前配置环境埋下的坑,以及加深一下印象,为了以后当需要更改环境时,能够更快地配置好;或者当环境出问题的时候,更快地定位出问题。
1.anaonda 配置tensorflow环境(2.x) conda创建一个虚拟环境
conda create -n py37 python=3.7
2.激活环境
`conda activate py37`
3.安装tensorflow-gpu版本,注意安装的时候要添加gpu,以及注意tensorflow与python版本,以及cuda版本的对应关系。
参考以下的blog:
当然,因为是在虚拟环境中安装各种库,所以这个环境是纯净的,也就是没有包含你系统中的cuda,cudnn。所以,在这过程中,你可能需要安装cudatoolkit,cudnntoolkit这些工具,如使用以下方法:
conda install cudatoolkit=10.1
conda install cudnn=7.6.5
注意下,直接使用pip install 的速度会很慢,所以你可以使用国内的镜像进行下载,这里推荐豆瓣镜像,清华的镜像好像也变得慢了起来。
若使用这个命令:
pip install -i https://pypi.doubanio.com/simple/ tensorflow-gpu
系统则会自动安装官网最新的版本。,但是你可以安装你想要的的版本 如: pip install -i https://pypi.doubanio.com/simple/ tensorflow-gpu==1.14.0 (有人说conda和pip不用混着使用,会出错,但是我这里并没有遇到)
4.安装后测试:
import tensorflow as tf
tf.test.is_gpu_available()
若都没问题的话,tensorflow可以成功导入,虽然中间会报许多警告,但是可以不用理会。
以及倘若cuda配置正确,则会打印出True。
5.安装的过程顺利的话就很轻松,如果出现问题也不用过于担心。出现一个解决一个即可。
- 可能出现的问题,也是出现次数最多的:找不到DLL :
1.可以尝试降低numpy版本,我之前numpy为1.19,因为报错所以后来降到了1.17 。
2.降低protobuf,我使用python3.6,tensorflow1.14的版本,就将protopbuf从3.7降到3.6.0,错误就消失了。
3.你可以确认以下你的cuda,cudnn版本、路径是否正确。
tf1.x的测试程序:
import tensorflow as tf
matrix1 = tf.constant([[3., 3.]])
matrix2 = tf.constant([[2.],[2.]])
product = tf.matmul(matrix1, matrix2)
sess = tf.Session()
result = sess.run(product)
print (result)
tf2.x的测试例程:
import tensorflow as tf
mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
model = tf.keras.models.Sequential([ tf.keras.layers.Flatten(input_shape=(28, 28)),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(10, activation='softmax') ])
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
model.fit(x_train, y_train, epochs=5)
model.evaluate(x_test, y_test, verbose=2)
最后
虽然tf2.x与tf1.x有许多地方不同,但是通过设置,tf2.x还是可以运行tf1.x项目的。
1.比如如果报没有placeholder,session这些属性、函数的错误,可以使用以下语句,在tf2.x中调用tf1.x的函数来解决。
import tensorflow.compat.v1 as tf
2.如果报RuntimeError,The session is empty这个的话,这个错误的意思是:此函数只能在创建任何图、运算或张量之前调用。 我们可以使用以下语句来解决。tensorflow.compat.v1.disable_eager_execution()
3.如果出现没有log等数学运算的函数,我们可以使用numpy中的来代替。
4.如果出现这个cudart64_100.dll 解决"dlerror: cudart64_100.dll not found"的问题,那就直接把你电脑下的C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA 的cudart64_101.dll或者其他版本的文件复制一个然后再重命名改为cudart64_100.dll就可以了,就是这么简单粗暴。