目录:
1.激活环境
2.版本选择
突发情况:ModuleNotFoundError: No module named 'paddle'
检验是否安装成功
1.激活环境
Anaconda:
conda remove -n paddle --all
conda activate paddle
2.版本选择
打开链接:https://www.paddlepaddle.org.cn/install/quick?docurl=/documentation/docs/zh/install/conda/windows-conda.html
以conda11.7为例:
conda install paddlepaddle-gpu==2.4.1 cudatoolkit=11.7 -c https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/Paddle/ -c conda-forge
静候等待安装完成
突发情况:ModuleNotFoundError: No module named 'paddle'
解决方法:anaconda内:python -m pip install paddlepaddle -i https://mirror.baidu.com/pypi/simple
检验是否安装成功
进入python解释器:
import paddle.fluid as fluid ,
fluid.install_check.run_check()
出现Your Paddle Fluid is installed succesfully!,说明您已成功安装。
测试:手写数字识别
import paddle
import numpy as np
from paddle.vision.transforms import Normalize
transform = Normalize(mean=[127.5], std=[127.5], data_format='CHW')
# 下载数据集并初始化 DataSet
train_dataset = paddle.vision.datasets.MNIST(mode='train', transform=transform)
test_dataset = paddle.vision.datasets.MNIST(mode='test', transform=transform)
# 模型组网并初始化网络
lenet = paddle.vision.models.LeNet(num_classes=10)
model = paddle.Model(lenet)
# 模型训练的配置准备,准备损失函数,优化器和评价指标
model.prepare(paddle.optimizer.Adam(parameters=model.parameters()),
paddle.nn.CrossEntropyLoss(),
paddle.metric.Accuracy())
# 模型训练
model.fit(train_dataset, epochs=5, batch_size=64, verbose=1)
# 模型评估
model.evaluate(test_dataset, batch_size=64, verbose=1)
# 保存模型
model.save('./output/mnist')
# 加载模型
model.load('output/mnist')
# 从测试集中取出一张图片
img, label = test_dataset[0]
# 将图片shape从1*28*28变为1*1*28*28,增加一个batch维度,以匹配模型输入格式要求
img_batch = np.expand_dims(img.astype('float32'), axis=0)
# 执行推理并打印结果,此处predict_batch返回的是一个list,取出其中数据获得预测结果
out = model.predict_batch(img_batch)[0]
pred_label = out.argmax()
print('true label: {}, pred label: {}'.format(label[0], pred_label))
# 可视化图片
from matplotlib import pyplot as plt
plt.imshow(img[0])
item 2/2 [===========================>..] - ETA: 0s - 500us/itemThe loss value printed in the log is the current step, and the metric is the average value of previous steps.
Epoch 1/5
step 938/938 [==============================] - loss: 0.0808 - acc: 0.9364 - 15ms/step
Epoch 2/5
step 938/938 [==============================] - loss: 0.0375 - acc: 0.9772 - 14ms/step
Epoch 3/5
step 938/938 [==============================] - loss: 0.0103 - acc: 0.9816 - 14ms/step
Epoch 4/5
step 938/938 [==============================] - loss: 0.0147 - acc: 0.9838 - 15ms/step
Epoch 5/5
step 938/938 [==============================] - loss: 0.0159 - acc: 0.9853 - 14ms/step
Eval begin...
step 157/157 [==============================] - loss: 5.4424e-04 - acc: 0.9821 - 5ms/step
Eval samples: 10000
true label: 7, pred label: 7
进程已结束,退出代码0