前言:
自己手贱,配置环境装了一天还没弄好,最后只能求助于淘宝。我将商家安装的步骤一一记录了下来,希望可以为后面的人避坑。
安装anaconda步骤省略,官网直接下载安装即可。
conda create -n tf2x python=3.8.5
conda activate tf2x
conda install cudatoolkit=10.1 cudnn=7.6.5
pip install tensorflow-gpu==2.2 keras==2.3.1 -i https://pypi.douban.com/simple/
pip install opencv-python pillow numpy matplotlib scipy pandas scikit-learn tqdm scikit-image imutils PyYAML -i https://pypi.douban.com/simple/
在pycharm中的配置:
file--settings--project interpreter,单击右边的齿轮图标,选择add local,添加本地解释器
切换到existing environment,找到刚创建的环境tf2x,出现下图就代表环境配置成功。
最后就来跑个程序测试一下吧!
import tensorflow as tf
import time
begin = time.time()
n_classes = 10
model = tf.keras.Sequential([
tf.keras.layers.Conv2D(
32,(5,5),activation = tf.nn.relu, input_shape = (28,28,1)),
tf.keras.layers.MaxPool2D((2,2),(2,2)),
tf.keras.layers.Conv2D(64,(3,3),activation = tf.nn.relu),
tf.keras.layers.MaxPool2D((2,2),(2,2)),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(1024,activation=tf.nn.relu),
tf.keras.layers.Dropout(0.5),
tf.keras.layers.Dense(n_classes)
])
model.summary()
mnist = tf.keras.datasets.mnist
(train_x, train_y),(test_x,test_y) = mnist.load_data()
train_x = train_x/255. *2 -1
test_x = test_x/255. *2 -1
train_x = tf.expand_dims(train_x, -1).numpy()
test_x = tf.expand_dims(test_x, -1).numpy()
model.compile(
optimizer=tf.keras.optimizers.Adam(1e-5),
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
model.fit(train_x,train_y,epochs=50,batch_size = 100)
model.evaluate(test_x, test_y)
end = time.time()
print('It cost',end-begin,'s')
可以看到已经开始调用GPU,如果环境配置失败则只会调用CPU。