前言
博主大三计算机科学与技术专业,培养方向为人工智能方向。大三一年开设《智能算法程序设计》,《大数据分析》两门课程,其实就是搞机器学习。大三下正在学习周志华老师的《机器学习》--西瓜书。神经网络部分学习需要Keras框架跑数据。
机器配置
机器 | 显卡版本 | CUDA版本 | CuDNN版本 | Keras版本 | Tensorflow版本 |
---|---|---|---|---|---|
小新Pro13 2020 | MX350 | V10.1.105 | v7.6.4 | 2.4.3 | 2.2.0 |
默认Python基础环境
在安装Keras支持GPU加速时,默认已经搭建好了Python基础环境。博主的基础环境为Anaconda, jupyter notebook
安装Cuda
1. 确定电脑支持的CUDA版本

这里显示cuda 版本为 10.2
2. 确定tensorflow
进入tensorflow查看tensorflow支持的CUDA和CuDNN的版本
https://tensorflow.google.cn/install/source_windows

由于博主电脑虽然是支持CUDA 10.2的,但是实际安装10.2版本后是不支持GPU加速的。
具体原因未知。所以就降了一个版本的CUDA,最后选择了10.1版本的CUDA
3. 安装CUDA 10.1
1)进入英伟达官网 https://developer.nvidia.com/cuda-toolkit-archive
2)下载10.1版本的,这三个任意一个均可。
选择local 离线安装。 选择在线安装会很慢的,毕竟2.6G。
3)安装CUDA:双击执行下载的exe文件,会先解压文件到临时目录(不是安装目录),保持默认即可
4)选择自定义安装
5)去掉Visual Studio这项
6)建议默认安装在C盘 。 这三个路径很重要,需要记住,后面配置环境变量以及安装cuDNN要用到
7)配置CUDA的环境变量
一般会自动配置环境变量,如果没有配置环境变量请手动添加。不管是否是自己手动添加,一定要重启电脑,配置环境才能生效
C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.1\lib\x64
C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.1\include
C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.1\extras\CUPTI\lib64
C:\ProgramData\NVIDIA Corporation\CUDA Samples\v10.1\bin\win64
C:\ProgramData\NVIDIA Corporation\CUDA Samples\v10.1\common\lib\x64
具体以自己安装的路径为准。
8)验证CUDA是否安装成功
nvcc -V

4. 安装cuDNN
确定CUDA版本的时候,我们看到 tensorflow-gpu 2.2.0 支持CuDNN的版本为 7.6。
tensorflow-gpu,CUDA,CuDNN三者的版本一定要对应。
博主选择的 v7.6.4。
进入英伟达 下载CuDNN, https://developer.nvidia.com/rdp/cudnn-archive
注意:需要先注册账号,填写个人信息及简单的调查文件后才能下载。
下载之后,解压缩,将CUDNN文件夹里面的bin、include、lib文件直接复制到CUDA的安装目录下,直接覆盖安装即可。
5. 安装tensorflow
在Anaconda的环境中安装 tensorflow-gpu 2.2.0
pip install tensorflow-gpu==2.2.0
如果下载速度慢的话,自行百度换源。
6. 安装Keras
pip install Keras==2.4.3
检验测试
打开Jupyter notebook
跑代码
from tensorflow.python.client import device_lib
print(device_lib.list_local_devices())
输出
incarnation: 4112472141665369881
physical_device_desc: "device: XLA_CPU device"
, name: "/device:GPU:0"
device_type: "GPU"
memory_limit: 1399891148
locality {
bus_id: 1
links {
}
}
incarnation: 1247557474537771722
physical_device_desc: "device: 0, name: GeForce MX350, pci bus id: 0000:02:00.0, compute capability: 6.1"
, name: "/device:XLA_GPU:0"
device_type: "XLA_GPU"
memory_limit: 17179869184
locality {
}
incarnation: 5997965106256956714
physical_device_desc: "device: XLA_GPU device"
]
可以看到GPU设备信息已经打印出来了。已经成功了。
再次跑一段代码
import tensorflow as tf
from tensorflow.keras import Model
from tensorflow.keras.layers import Dense, Flatten, Conv2D
class MyModel(Model):
def __init__(self):
super(MyModel, self).__init__()
self.conv1 = Conv2D(32, 3, activation='relu')
self.flatten = Flatten()
self.d1 = Dense(128, activation='relu')
self.d2 = Dense(10, activation='softmax')
def call(self, x):
x = self.conv1(x)
x = self.flatten(x)
x = self.d1(x)
return self.d2(x)
@tf.function
def train_step(images, labels):
with tf.GradientTape() as tape:
predictions = model(images)
loss = loss_object(labels, predictions)
gradients = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(zip(gradients, model.trainable_variables))
train_loss(loss)
train_accuracy(labels, predictions)
@tf.function
def test_step(images, labels):
predictions = model(images)
t_loss = loss_object(labels, predictions)
test_loss(t_loss)
test_accuracy(labels, predictions)
# 加载并准备 MNIST 数据集
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
# 添加通道维度
x_train = x_train[..., tf.newaxis]
x_test = x_test[..., tf.newaxis]
# 使用 tf.data 来将数据集切分为 batch 以及混淆数据集
train_ds = tf.data.Dataset.from_tensor_slices((x_train, y_train)).shuffle(10000).batch(32)
test_ds = tf.data.Dataset.from_tensor_slices((x_test, y_test)).batch(32)
# 构建模型
model = MyModel()
optimizer = tf.keras.optimizers.Adam() # 优化器
loss_object = tf.keras.losses.SparseCategoricalCrossentropy() # 损失函数
train_loss = tf.keras.metrics.Mean(name='train_loss')
train_accuracy = tf.keras.metrics.SparseCategoricalAccuracy(name='train_accuracy')
test_loss = tf.keras.metrics.Mean(name='test_loss')
test_accuracy = tf.keras.metrics.SparseCategoricalAccuracy(name='test_accuracy')
# 训练
EPOCHS = 5 # 迭代轮次
for epoch in range(EPOCHS):
# 在下一个epoch开始时,重置评估指标
train_loss.reset_states()
train_accuracy.reset_states()
test_loss.reset_states()
test_accuracy.reset_states()
for images, labels in train_ds:
train_step(images, labels)
for test_images, test_labels in test_ds:
test_step(test_images, test_labels)
template = 'Epoch {}, Loss: {}, Accuracy: {}, Test Loss: {}, Test Accuracy: {}'
print(template.format(epoch + 1,
train_loss.result(),
train_accuracy.result() * 100,
test_loss.result(),
test_accuracy.result() * 100))
输出
Executing op VarHandleOp in device /job:localhost/replica:0/task:0/device:GPU:0
Executing op __inference_train_step_46101 in device /job:localhost/replica:0/task:0/device:GPU:0
Executing op OptimizeDataset in device /job:localhost/replica:0/task:0/device:CPU:0
Executing op ModelDataset in device /job:localhost/replica:0/task:0/device:CPU:0
Executing op __inference_test_step_49926 in device /job:localhost/replica:0/task:0/device:GPU:0
Executing op __inference_test_step_50619 in device /job:localhost/replica:0/task:0/device:GPU:0
Epoch 1, Loss: 0.13640181720256805, Accuracy: 95.9316635131836, Test Loss: 0.06547310203313828, Test Accuracy: 97.8699951171875
可以看到跑这段代码,使用了GPU加速,大工告成,CPU跑这段代码是需要一两分钟的,GPU加速后两三秒就跑完了。
评论区