简 介: ※通过测试网络上的这个极简的Paddle识别MNIST程序,也就是使用了一个非常简单的线性回归网络,初步熟悉了Paddle下的网络架构方式。对于如果从numpy到Paddle的tensor转换程序中也给出了示例。

关键词AI StudioPaddleMNIST

#mermaid-svg-EqD10fL0GOxYZmde .label{font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family);fill:#333;color:#333}#mermaid-svg-EqD10fL0GOxYZmde .label text{fill:#333}#mermaid-svg-EqD10fL0GOxYZmde .node rect,#mermaid-svg-EqD10fL0GOxYZmde .node circle,#mermaid-svg-EqD10fL0GOxYZmde .node ellipse,#mermaid-svg-EqD10fL0GOxYZmde .node polygon,#mermaid-svg-EqD10fL0GOxYZmde .node path{fill:#ECECFF;stroke:#9370db;stroke-width:1px}#mermaid-svg-EqD10fL0GOxYZmde .node .label{text-align:center;fill:#333}#mermaid-svg-EqD10fL0GOxYZmde .node.clickable{cursor:pointer}#mermaid-svg-EqD10fL0GOxYZmde .arrowheadPath{fill:#333}#mermaid-svg-EqD10fL0GOxYZmde .edgePath .path{stroke:#333;stroke-width:1.5px}#mermaid-svg-EqD10fL0GOxYZmde .flowchart-link{stroke:#333;fill:none}#mermaid-svg-EqD10fL0GOxYZmde .edgeLabel{background-color:#e8e8e8;text-align:center}#mermaid-svg-EqD10fL0GOxYZmde .edgeLabel rect{opacity:0.9}#mermaid-svg-EqD10fL0GOxYZmde .edgeLabel span{color:#333}#mermaid-svg-EqD10fL0GOxYZmde .cluster rect{fill:#ffffde;stroke:#aa3;stroke-width:1px}#mermaid-svg-EqD10fL0GOxYZmde .cluster text{fill:#333}#mermaid-svg-EqD10fL0GOxYZmde div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family);font-size:12px;background:#ffffde;border:1px solid #aa3;border-radius:2px;pointer-events:none;z-index:100}#mermaid-svg-EqD10fL0GOxYZmde .actor{stroke:#ccf;fill:#ECECFF}#mermaid-svg-EqD10fL0GOxYZmde text.actor>tspan{fill:#000;stroke:none}#mermaid-svg-EqD10fL0GOxYZmde .actor-line{stroke:grey}#mermaid-svg-EqD10fL0GOxYZmde .messageLine0{stroke-width:1.5;stroke-dasharray:none;stroke:#333}#mermaid-svg-EqD10fL0GOxYZmde .messageLine1{stroke-width:1.5;stroke-dasharray:2, 2;stroke:#333}#mermaid-svg-EqD10fL0GOxYZmde #arrowhead path{fill:#333;stroke:#333}#mermaid-svg-EqD10fL0GOxYZmde .sequenceNumber{fill:#fff}#mermaid-svg-EqD10fL0GOxYZmde #sequencenumber{fill:#333}#mermaid-svg-EqD10fL0GOxYZmde #crosshead path{fill:#333;stroke:#333}#mermaid-svg-EqD10fL0GOxYZmde .messageText{fill:#333;stroke:#333}#mermaid-svg-EqD10fL0GOxYZmde .labelBox{stroke:#ccf;fill:#ECECFF}#mermaid-svg-EqD10fL0GOxYZmde .labelText,#mermaid-svg-EqD10fL0GOxYZmde .labelText>tspan{fill:#000;stroke:none}#mermaid-svg-EqD10fL0GOxYZmde .loopText,#mermaid-svg-EqD10fL0GOxYZmde .loopText>tspan{fill:#000;stroke:none}#mermaid-svg-EqD10fL0GOxYZmde .loopLine{stroke-width:2px;stroke-dasharray:2, 2;stroke:#ccf;fill:#ccf}#mermaid-svg-EqD10fL0GOxYZmde .note{stroke:#aa3;fill:#fff5ad}#mermaid-svg-EqD10fL0GOxYZmde .noteText,#mermaid-svg-EqD10fL0GOxYZmde .noteText>tspan{fill:#000;stroke:none}#mermaid-svg-EqD10fL0GOxYZmde .activation0{fill:#f4f4f4;stroke:#666}#mermaid-svg-EqD10fL0GOxYZmde .activation1{fill:#f4f4f4;stroke:#666}#mermaid-svg-EqD10fL0GOxYZmde .activation2{fill:#f4f4f4;stroke:#666}#mermaid-svg-EqD10fL0GOxYZmde .mermaid-main-font{font-family:"trebuchet ms", verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-EqD10fL0GOxYZmde .section{stroke:none;opacity:0.2}#mermaid-svg-EqD10fL0GOxYZmde .section0{fill:rgba(102,102,255,0.49)}#mermaid-svg-EqD10fL0GOxYZmde .section2{fill:#fff400}#mermaid-svg-EqD10fL0GOxYZmde .section1,#mermaid-svg-EqD10fL0GOxYZmde .section3{fill:#fff;opacity:0.2}#mermaid-svg-EqD10fL0GOxYZmde .sectionTitle0{fill:#333}#mermaid-svg-EqD10fL0GOxYZmde .sectionTitle1{fill:#333}#mermaid-svg-EqD10fL0GOxYZmde .sectionTitle2{fill:#333}#mermaid-svg-EqD10fL0GOxYZmde .sectionTitle3{fill:#333}#mermaid-svg-EqD10fL0GOxYZmde .sectionTitle{text-anchor:start;font-size:11px;text-height:14px;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-EqD10fL0GOxYZmde .grid .tick{stroke:#d3d3d3;opacity:0.8;shape-rendering:crispEdges}#mermaid-svg-EqD10fL0GOxYZmde .grid .tick text{font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-EqD10fL0GOxYZmde .grid path{stroke-width:0}#mermaid-svg-EqD10fL0GOxYZmde .today{fill:none;stroke:red;stroke-width:2px}#mermaid-svg-EqD10fL0GOxYZmde .task{stroke-width:2}#mermaid-svg-EqD10fL0GOxYZmde .taskText{text-anchor:middle;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-EqD10fL0GOxYZmde .taskText:not([font-size]){font-size:11px}#mermaid-svg-EqD10fL0GOxYZmde .taskTextOutsideRight{fill:#000;text-anchor:start;font-size:11px;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-EqD10fL0GOxYZmde .taskTextOutsideLeft{fill:#000;text-anchor:end;font-size:11px}#mermaid-svg-EqD10fL0GOxYZmde .task.clickable{cursor:pointer}#mermaid-svg-EqD10fL0GOxYZmde .taskText.clickable{cursor:pointer;fill:#003163 !important;font-weight:bold}#mermaid-svg-EqD10fL0GOxYZmde .taskTextOutsideLeft.clickable{cursor:pointer;fill:#003163 !important;font-weight:bold}#mermaid-svg-EqD10fL0GOxYZmde .taskTextOutsideRight.clickable{cursor:pointer;fill:#003163 !important;font-weight:bold}#mermaid-svg-EqD10fL0GOxYZmde .taskText0,#mermaid-svg-EqD10fL0GOxYZmde .taskText1,#mermaid-svg-EqD10fL0GOxYZmde .taskText2,#mermaid-svg-EqD10fL0GOxYZmde .taskText3{fill:#fff}#mermaid-svg-EqD10fL0GOxYZmde .task0,#mermaid-svg-EqD10fL0GOxYZmde .task1,#mermaid-svg-EqD10fL0GOxYZmde .task2,#mermaid-svg-EqD10fL0GOxYZmde .task3{fill:#8a90dd;stroke:#534fbc}#mermaid-svg-EqD10fL0GOxYZmde .taskTextOutside0,#mermaid-svg-EqD10fL0GOxYZmde .taskTextOutside2{fill:#000}#mermaid-svg-EqD10fL0GOxYZmde .taskTextOutside1,#mermaid-svg-EqD10fL0GOxYZmde .taskTextOutside3{fill:#000}#mermaid-svg-EqD10fL0GOxYZmde .active0,#mermaid-svg-EqD10fL0GOxYZmde .active1,#mermaid-svg-EqD10fL0GOxYZmde .active2,#mermaid-svg-EqD10fL0GOxYZmde .active3{fill:#bfc7ff;stroke:#534fbc}#mermaid-svg-EqD10fL0GOxYZmde .activeText0,#mermaid-svg-EqD10fL0GOxYZmde .activeText1,#mermaid-svg-EqD10fL0GOxYZmde .activeText2,#mermaid-svg-EqD10fL0GOxYZmde .activeText3{fill:#000 !important}#mermaid-svg-EqD10fL0GOxYZmde .done0,#mermaid-svg-EqD10fL0GOxYZmde .done1,#mermaid-svg-EqD10fL0GOxYZmde .done2,#mermaid-svg-EqD10fL0GOxYZmde .done3{stroke:grey;fill:#d3d3d3;stroke-width:2}#mermaid-svg-EqD10fL0GOxYZmde .doneText0,#mermaid-svg-EqD10fL0GOxYZmde .doneText1,#mermaid-svg-EqD10fL0GOxYZmde .doneText2,#mermaid-svg-EqD10fL0GOxYZmde .doneText3{fill:#000 !important}#mermaid-svg-EqD10fL0GOxYZmde .crit0,#mermaid-svg-EqD10fL0GOxYZmde .crit1,#mermaid-svg-EqD10fL0GOxYZmde .crit2,#mermaid-svg-EqD10fL0GOxYZmde .crit3{stroke:#f88;fill:red;stroke-width:2}#mermaid-svg-EqD10fL0GOxYZmde .activeCrit0,#mermaid-svg-EqD10fL0GOxYZmde .activeCrit1,#mermaid-svg-EqD10fL0GOxYZmde .activeCrit2,#mermaid-svg-EqD10fL0GOxYZmde .activeCrit3{stroke:#f88;fill:#bfc7ff;stroke-width:2}#mermaid-svg-EqD10fL0GOxYZmde .doneCrit0,#mermaid-svg-EqD10fL0GOxYZmde .doneCrit1,#mermaid-svg-EqD10fL0GOxYZmde .doneCrit2,#mermaid-svg-EqD10fL0GOxYZmde .doneCrit3{stroke:#f88;fill:#d3d3d3;stroke-width:2;cursor:pointer;shape-rendering:crispEdges}#mermaid-svg-EqD10fL0GOxYZmde .milestone{transform:rotate(45deg) scale(0.8, 0.8)}#mermaid-svg-EqD10fL0GOxYZmde .milestoneText{font-style:italic}#mermaid-svg-EqD10fL0GOxYZmde .doneCritText0,#mermaid-svg-EqD10fL0GOxYZmde .doneCritText1,#mermaid-svg-EqD10fL0GOxYZmde .doneCritText2,#mermaid-svg-EqD10fL0GOxYZmde .doneCritText3{fill:#000 !important}#mermaid-svg-EqD10fL0GOxYZmde .activeCritText0,#mermaid-svg-EqD10fL0GOxYZmde .activeCritText1,#mermaid-svg-EqD10fL0GOxYZmde .activeCritText2,#mermaid-svg-EqD10fL0GOxYZmde .activeCritText3{fill:#000 !important}#mermaid-svg-EqD10fL0GOxYZmde .titleText{text-anchor:middle;font-size:18px;fill:#000;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-EqD10fL0GOxYZmde g.classGroup text{fill:#9370db;stroke:none;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family);font-size:10px}#mermaid-svg-EqD10fL0GOxYZmde g.classGroup text .title{font-weight:bolder}#mermaid-svg-EqD10fL0GOxYZmde g.clickable{cursor:pointer}#mermaid-svg-EqD10fL0GOxYZmde g.classGroup rect{fill:#ECECFF;stroke:#9370db}#mermaid-svg-EqD10fL0GOxYZmde g.classGroup line{stroke:#9370db;stroke-width:1}#mermaid-svg-EqD10fL0GOxYZmde .classLabel .box{stroke:none;stroke-width:0;fill:#ECECFF;opacity:0.5}#mermaid-svg-EqD10fL0GOxYZmde .classLabel .label{fill:#9370db;font-size:10px}#mermaid-svg-EqD10fL0GOxYZmde .relation{stroke:#9370db;stroke-width:1;fill:none}#mermaid-svg-EqD10fL0GOxYZmde .dashed-line{stroke-dasharray:3}#mermaid-svg-EqD10fL0GOxYZmde #compositionStart{fill:#9370db;stroke:#9370db;stroke-width:1}#mermaid-svg-EqD10fL0GOxYZmde #compositionEnd{fill:#9370db;stroke:#9370db;stroke-width:1}#mermaid-svg-EqD10fL0GOxYZmde #aggregationStart{fill:#ECECFF;stroke:#9370db;stroke-width:1}#mermaid-svg-EqD10fL0GOxYZmde #aggregationEnd{fill:#ECECFF;stroke:#9370db;stroke-width:1}#mermaid-svg-EqD10fL0GOxYZmde #dependencyStart{fill:#9370db;stroke:#9370db;stroke-width:1}#mermaid-svg-EqD10fL0GOxYZmde #dependencyEnd{fill:#9370db;stroke:#9370db;stroke-width:1}#mermaid-svg-EqD10fL0GOxYZmde #extensionStart{fill:#9370db;stroke:#9370db;stroke-width:1}#mermaid-svg-EqD10fL0GOxYZmde #extensionEnd{fill:#9370db;stroke:#9370db;stroke-width:1}#mermaid-svg-EqD10fL0GOxYZmde .commit-id,#mermaid-svg-EqD10fL0GOxYZmde .commit-msg,#mermaid-svg-EqD10fL0GOxYZmde .branch-label{fill:lightgrey;color:lightgrey;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-EqD10fL0GOxYZmde .pieTitleText{text-anchor:middle;font-size:25px;fill:#000;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-EqD10fL0GOxYZmde .slice{font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-EqD10fL0GOxYZmde g.stateGroup text{fill:#9370db;stroke:none;font-size:10px;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-EqD10fL0GOxYZmde g.stateGroup text{fill:#9370db;fill:#333;stroke:none;font-size:10px}#mermaid-svg-EqD10fL0GOxYZmde g.statediagram-cluster .cluster-label text{fill:#333}#mermaid-svg-EqD10fL0GOxYZmde g.stateGroup .state-title{font-weight:bolder;fill:#000}#mermaid-svg-EqD10fL0GOxYZmde g.stateGroup rect{fill:#ECECFF;stroke:#9370db}#mermaid-svg-EqD10fL0GOxYZmde g.stateGroup line{stroke:#9370db;stroke-width:1}#mermaid-svg-EqD10fL0GOxYZmde .transition{stroke:#9370db;stroke-width:1;fill:none}#mermaid-svg-EqD10fL0GOxYZmde .stateGroup .composit{fill:white;border-bottom:1px}#mermaid-svg-EqD10fL0GOxYZmde .stateGroup .alt-composit{fill:#e0e0e0;border-bottom:1px}#mermaid-svg-EqD10fL0GOxYZmde .state-note{stroke:#aa3;fill:#fff5ad}#mermaid-svg-EqD10fL0GOxYZmde .state-note text{fill:black;stroke:none;font-size:10px}#mermaid-svg-EqD10fL0GOxYZmde .stateLabel .box{stroke:none;stroke-width:0;fill:#ECECFF;opacity:0.7}#mermaid-svg-EqD10fL0GOxYZmde .edgeLabel text{fill:#333}#mermaid-svg-EqD10fL0GOxYZmde .stateLabel text{fill:#000;font-size:10px;font-weight:bold;font-family:'trebuchet ms', verdana, arial;font-family:var(--mermaid-font-family)}#mermaid-svg-EqD10fL0GOxYZmde .node circle.state-start{fill:black;stroke:black}#mermaid-svg-EqD10fL0GOxYZmde .node circle.state-end{fill:black;stroke:white;stroke-width:1.5}#mermaid-svg-EqD10fL0GOxYZmde #statediagram-barbEnd{fill:#9370db}#mermaid-svg-EqD10fL0GOxYZmde .statediagram-cluster rect{fill:#ECECFF;stroke:#9370db;stroke-width:1px}#mermaid-svg-EqD10fL0GOxYZmde .statediagram-cluster rect.outer{rx:5px;ry:5px}#mermaid-svg-EqD10fL0GOxYZmde .statediagram-state .divider{stroke:#9370db}#mermaid-svg-EqD10fL0GOxYZmde .statediagram-state .title-state{rx:5px;ry:5px}#mermaid-svg-EqD10fL0GOxYZmde .statediagram-cluster.statediagram-cluster .inner{fill:white}#mermaid-svg-EqD10fL0GOxYZmde .statediagram-cluster.statediagram-cluster-alt .inner{fill:#e0e0e0}#mermaid-svg-EqD10fL0GOxYZmde .statediagram-cluster .inner{rx:0;ry:0}#mermaid-svg-EqD10fL0GOxYZmde .statediagram-state rect.basic{rx:5px;ry:5px}#mermaid-svg-EqD10fL0GOxYZmde .statediagram-state rect.divider{stroke-dasharray:10,10;fill:#efefef}#mermaid-svg-EqD10fL0GOxYZmde .note-edge{stroke-dasharray:5}#mermaid-svg-EqD10fL0GOxYZmde .statediagram-note rect{fill:#fff5ad;stroke:#aa3;stroke-width:1px;rx:0;ry:0}:root{--mermaid-font-family: '"trebuchet ms", verdana, arial';--mermaid-font-family: "Comic Sans MS", "Comic Sans", cursive}#mermaid-svg-EqD10fL0GOxYZmde .error-icon{fill:#522}#mermaid-svg-EqD10fL0GOxYZmde .error-text{fill:#522;stroke:#522}#mermaid-svg-EqD10fL0GOxYZmde .edge-thickness-normal{stroke-width:2px}#mermaid-svg-EqD10fL0GOxYZmde .edge-thickness-thick{stroke-width:3.5px}#mermaid-svg-EqD10fL0GOxYZmde .edge-pattern-solid{stroke-dasharray:0}#mermaid-svg-EqD10fL0GOxYZmde .edge-pattern-dashed{stroke-dasharray:3}#mermaid-svg-EqD10fL0GOxYZmde .edge-pattern-dotted{stroke-dasharray:2}#mermaid-svg-EqD10fL0GOxYZmde .marker{fill:#333}#mermaid-svg-EqD10fL0GOxYZmde .marker.cross{stroke:#333}:root { --mermaid-font-family: "trebuchet ms", verdana, arial;}#mermaid-svg-EqD10fL0GOxYZmde {color: rgba(0, 0, 0, 0.75);font: ;}

建立工程
文章目录
调入数据库
极简工程
识别总结
数据转换

§01 建立工程


在AI Studio中建立基于NoteBook工程环境,选择其中的MNIST数据库。

在哪里能找到最后的版本的示例程序? AI Studio-MNIST 对于基于AI Studio中Paddle框架对于MNIST数据库进行实验。首先试验了其中的极简测试方法。但在其中过程中还是遇到了一些问题。

后来经过询问,可以知道现在书上的代码由于书籍出版比较慢,因此跟班上AI Studio代码的升级。建议还是通过观察 AI Studio 手写数字识别案例 ,根据其中的的代码进行测试。

▲ 图1.1 百度AI Studio 手写数字识别案例(上):讲师:淘淘

1.1 调入数据库

import matplotlib.pyplot as plt
from numpy import *
import math,timeimport paddle
from paddle.nn import Linear
import paddle.nn.functional as F
import ostrain_dataset = paddle.vision.datasets.MNIST(mode='train')
import paddle
from paddle.nn import Linear
import paddle.nn.functional as F
import ostrain_dataset = paddle.vision.datasets.MNIST(mode='train')train_data0 = array(train_dataset[0][0])
train_label0 = array(train_dataset[0][1])plt.figure('Image')
plt.figure(figsize=(5,5))
plt.imshow(train_data0, cmap=plt.cm.binary)
plt.axis('on')
plt.title('MNIST image')
plt.show()print('Image shape: {}'.format(train_data0.shape))
print('Image label shape: {} and data: {}'.format(train_label0.shape, train_label0))

▲ 图1.1.1 显示数据库图片

▲ 图1.1.2 显示MNIST中的数字

1.1.1 常见学术数据集合

在paddle.vision.datasets存在一些常见到的学术数据集合。

1.1.1.1 paddle.vision 中的数据集合

dir(paddle.vision.datasets)
['Cifar10','Cifar100','DatasetFolder','FashionMNIST','Flowers','ImageFolder','MNIST','VOC2012','__all__','__builtins__','__cached__','__doc__','__file__','__loader__','__name__','__package__','__path__','__spec__','cifar','flowers','folder','mnist','voc2012']

1.1.1.2 paddle.text 数据集合

dir(paddle.text.datasets)
['Conll05st','Imdb','Imikolov','Movielens','UCIHousing','WMT14','WMT16','__all__','__builtins__','__cached__','__doc__','__file__','__loader__','__name__','__package__','__path__','__spec__','conll05','imdb','imikolov','movielens','uci_housing','wmt14','wmt16']

1.2 极简工程

1.2.1 建立模型

class MNIST(paddle.nn.Layer):def __init__(self, ):super(MNIST, self).__init__()self.fc = paddle.nn.Linear(in_features=784, out_features=1)def forward(self, inputs):outputs = self.fc(inputs)return outputsdef norm_img(img):assert len(img.shape) == 3batch_size, img_h, img_w = img.shape[0], img.shape[1], img.shape[2]img = img/255img = paddle.reshape(img, [batch_size, img_h*img_w])return imgimport paddle
paddle.vision.set_image_backend('cv2')def train(model):model.train()train_loader = paddle.io.DataLoader(paddle.vision.datasets.MNIST(mode='train'),batch_size=16,shuffle=True)opt = paddle.optimizer.SGD(learning_rate=0.001, parameters=model.parameters())EPOCH_NUM = 10for epoch in range(EPOCH_NUM):for batch_id, data in enumerate(train_loader()):images = norm_img(data[0]).astype('float32')labels = data[1].astype('float32')predicts = model(images)loss = F.square_error_cost(predicts, labels)avg_loss = paddle.mean(loss)if batch_id%1000 == 0:print('epoch_id: {}, batch_id: {}, loss is: {}'.format(epoch, batch_id, avg_loss.numpy()))avg_loss.backward()opt.step()opt.clear_grad()

1.2.2 训练模型

model = MNIST()
train(model)
paddle.save(model.state_dict(), './mnist.pdparms')

1.2.3 训练结果

epoch_id: 0, batch_id: 0, loss is: [19.446383]
epoch_id: 0, batch_id: 1000, loss is: [4.280066]
epoch_id: 0, batch_id: 2000, loss is: [4.089441]
epoch_id: 0, batch_id: 3000, loss is: [2.5934415]
epoch_id: 1, batch_id: 0, loss is: [5.005641]
epoch_id: 1, batch_id: 1000, loss is: [2.2887247]
epoch_id: 1, batch_id: 2000, loss is: [2.5260096]
epoch_id: 1, batch_id: 3000, loss is: [4.377707]
epoch_id: 2, batch_id: 0, loss is: [3.2349763]
epoch_id: 2, batch_id: 1000, loss is: [2.8085265]
epoch_id: 2, batch_id: 2000, loss is: [2.2175798]
epoch_id: 2, batch_id: 3000, loss is: [5.4343185]
epoch_id: 3, batch_id: 0, loss is: [3.1255033]
epoch_id: 3, batch_id: 1000, loss is: [2.1449356]
epoch_id: 3, batch_id: 2000, loss is: [7.3950243]
epoch_id: 3, batch_id: 3000, loss is: [5.631453]
epoch_id: 4, batch_id: 0, loss is: [2.1221619]
epoch_id: 4, batch_id: 1000, loss is: [3.1189494]
epoch_id: 4, batch_id: 2000, loss is: [3.672319]
epoch_id: 4, batch_id: 3000, loss is: [4.128253]
epoch_id: 5, batch_id: 0, loss is: [7.7472067]
epoch_id: 5, batch_id: 1000, loss is: [2.6192496]
epoch_id: 5, batch_id: 2000, loss is: [3.7988458]
epoch_id: 5, batch_id: 3000, loss is: [2.1571586]
epoch_id: 6, batch_id: 0, loss is: [6.8091993]
epoch_id: 6, batch_id: 1000, loss is: [3.2879863]
epoch_id: 6, batch_id: 2000, loss is: [2.2202625]
epoch_id: 6, batch_id: 3000, loss is: [4.0542073]
epoch_id: 7, batch_id: 0, loss is: [2.4702597]
epoch_id: 7, batch_id: 1000, loss is: [3.267303]
epoch_id: 7, batch_id: 2000, loss is: [3.925469]
epoch_id: 7, batch_id: 3000, loss is: [4.502317]
epoch_id: 8, batch_id: 0, loss is: [1.6059736]
epoch_id: 8, batch_id: 1000, loss is: [5.4941883]
epoch_id: 8, batch_id: 2000, loss is: [1.0239292]
epoch_id: 8, batch_id: 3000, loss is: [2.333592]
epoch_id: 9, batch_id: 0, loss is: [2.7579784]
epoch_id: 9, batch_id: 1000, loss is: [1.5081773]
epoch_id: 9, batch_id: 2000, loss is: [4.925281]
epoch_id: 9, batch_id: 3000, loss is: [3.8142138]

▲ 图1.2.1 训练过程中误差下降曲线

1.2.4 测试模型

1.2.4.1 查看测试集合结果

for batch_id, data in enumerate(test_loader()):images = norm_img(data[0]).astype('float32')labels = data[1].astype('float32')predicts = model(images)loss = F.square_error_cost(predicts, labels)avg_loss = paddle.mean(loss)print(predicts)print(labels)print(loss)print(avg_loss)break

运行结果

Tensor(shape=[16, 1], dtype=float32, place=CPUPlace, stop_gradient=False,[[2.06245565],[1.97789598],[5.32851791],[2.76517129],[4.77754116],[1.96410847],[1.70493352],[2.46705198],[7.93237495],[5.77034092],[4.87852144],[0.48723245],[4.39118719],[1.38979697],[1.77543545],[1.47215056]])
Tensor(shape=[16, 1], dtype=float32, place=CPUPlace, stop_gradient=True,[[0.],[1.],[5.],[5.],[6.],[1.],[1.],[1.],[7.],[4.],[2.],[0.],[1.],[1.],[0.],[1.]])
Tensor(shape=[16, 1], dtype=float32, place=CPUPlace, stop_gradient=False,[[4.25372314],[0.95628053],[0.10792402],[4.99445915],[1.49440563],[0.92950511],[0.49693128],[2.15224147],[0.86932307],[3.13410687],[8.28588581],[0.23739545],[11.50015068],[0.15194169],[3.15217113],[0.22292615]])
Tensor(shape=[1], dtype=float32, place=CPUPlace, stop_gradient=False,[2.68371058])

1.2.4.2 测试预测结果

def showimg(img):imgdata = img.numpy()print(imgdata.shape)imgblock = [i.reshape([28,28]) for i in imgdata]imgb1 = concatenate(imgblock[:8], axis=1)imgb2 = concatenate(imgblock[8:], axis=1)imgb = concatenate((imgb1, imgb2))plt.figure(figsize=(10,10))plt.imshow(imgb)plt.axis('off')plt.show()

▲ 图1.2.2 测试集合MNIST图片

预测结果:

for batch_id, data in enumerate(test_loader()):showimg(images)predicts = model(images)print(labels.numpy().flatten().T)print([p for p in predicts.numpy().flatten().T])
3. 9. 4. 3. 0. 7. 0. 9. 9. 5. 6. 7. 1. 7. 0. 0.
3.3602648 8.111923 5.3560495 5.2887278 4.218868 5.3987856 2.5647051 8.387244 8.198596 3.977576 3.7429187 7.7407055 6.2851562 4.435977 2.9352028 3.7802896

1.2.5 网络上参考程序

import paddle
from paddle.nn import Linear
import paddle.nn.functional as F
import os
import numpy as np
import matplotlib.pyplot as plttrain_dataset = paddle.vision.datasets.MNIST(mode='train')train_data0 = np.array(train_dataset[0][0])
train_label_0 = np.array(train_dataset[0][1])import matplotlib.pyplot as plt
plt.figure("Image") # 图像窗口名称
plt.figure(figsize=(2,2))
plt.imshow(train_data0, cmap=plt.cm.binary)
plt.axis('on') # 关掉坐标轴为 off
plt.title('image') # 图像题目
plt.show()print("图像数据形状和对应数据为:", train_data0.shape)
print("图像标签形状和对应数据为:", train_label_0.shape, train_label_0)
print("\n打印第一个batch的第一个图像,对应标签数字为{}".format(train_label_0))class MNIST(paddle.nn.Layer):def __init__(self):super(MNIST, self).__init__()# 定义一层全连接层,输出维度是1self.fc = paddle.nn.Linear(in_features=784, out_features=1)# 定义网络结构的前向计算过程def forward(self, inputs):outputs = self.fc(inputs)return outputsmodel = MNIST()def train(model):# 启动训练模式model.train()# 加载训练集 batch_size 设为 16train_loader = paddle.io.DataLoader(paddle.vision.datasets.MNIST(mode='train'),batch_size=16,shuffle=True)# 定义优化器,使用随机梯度下降SGD优化器,学习率设置为0.001opt = paddle.optimizer.SGD(learning_rate=0.001, parameters=model.parameters())def norm_img(img):# 验证传入数据格式是否正确,img的shape为[batch_size, 28, 28]assert len(img.shape) == 3batch_size, img_h, img_w = img.shape[0], img.shape[1], img.shape[2]# 归一化图像数据img = img / 255# 将图像形式reshape为[batch_size, 784]img = paddle.reshape(img, [batch_size, img_h*img_w])return imgimport paddle
paddle.vision.set_image_backend('cv2')model = MNIST()def train(model):# 启动训练模式model.train()# 加载训练集 batch_size 设为 16train_loader = paddle.io.DataLoader(paddle.vision.datasets.MNIST(mode='train'),batch_size=16,shuffle=True)# 定义优化器,使用随机梯度下降SGD优化器,学习率设置为0.001opt = paddle.optimizer.SGD(learning_rate=0.001, parameters=model.parameters())EPOCH_NUM = 10for epoch in range(EPOCH_NUM):for batch_id, data in enumerate(train_loader()):images = norm_img(data[0]).astype('float32')labels = data[1].astype('float32')#前向计算的过程predicts = model(images)# 计算损失loss = F.square_error_cost(predicts, labels)avg_loss = paddle.mean(loss)#每训练了1000批次的数据,打印下当前Loss的情况if batch_id % 1000 == 0:print("epoch_id: {}, batch_id: {}, loss is: {}".format(epoch, batch_id, avg_loss.numpy()))#后向传播,更新参数的过程avg_loss.backward()opt.step()opt.clear_grad()train(model)
paddle.save(model.state_dict(), './mnist.pdparams')
import matplotlib.pyplot as plt
import numpy as np
from PIL import Imageimg_path = './work/下载.png'
im = Image.open('./work/下载.png')
plt.imshow(im)
plt.show()
im = im.convert('L')
print('原始图像shape: ', np.array(im).shape)
im = im.resize((28, 28), Image.ANTIALIAS)
plt.imshow(im)
plt.show()
print("采样后图片shape: ", np.array(im).shape)def load_image(img_path):# 从img_path中读取图像,并转为灰度图im = Image.open(img_path).convert('L')# print(np.array(im))im = im.resize((28, 28), Image.ANTIALIAS)im = np.array(im).reshape(1, -1).astype(np.float32)# 图像归一化,保持和数据集的数据范围一致im = 1 - im / 255return immodel = MNIST()
params_file_path = 'mnist.pdparams'
img_path = './work/下载.png'
param_dict = paddle.load(params_file_path)
model.load_dict(param_dict)
model.eval()
tensor_img = load_image(img_path)
result = model(paddle.to_tensor(tensor_img))
print('result',result)
print("本次预测的数字是", result.numpy().astype('int32'))

※ 识别总结 ※


通过测试网络上的这个极简的Paddle识别MNIST程序,也就是使用了一个非常简单的线性回归网络,初步熟悉了Paddle下的网络架构方式。对于如果从numpy到Paddle的tensor转换程序中也给出了示例。

2.1 数据转换

2.1.1 从numpy到tensor

paddle.to_tensor()

2.1.2 从tensor到numpy

data.numpy()


■ 相关文献链接:

  • 在哪里能找到最后的版本的示例程序? AI Studio-MNIST
  • AI Studio 手写数字识别案例

● 相关图表链接:

  • 图1.1 百度AI Studio 手写数字识别案例(上):讲师:淘淘
  • 图1.1.1 显示数据库图片
  • 图1.1.2 显示MNIST中的数字
  • 图1.2.1 训练过程中误差下降曲线
  • 图1.2.2 测试集合MNIST图片

AI Studio : 利用Paddle框架中的极简框架识别MNIST相关推荐

  1. android 日志框架封装,FLog: 一个基于函数组合的Android日志框架,拥有极简的结构和极高的灵活性、扩展性...

    FLog 一个基于函数组合的Android日志框架,拥有极简的结构和极高的灵活性.扩展性 下载 在根目录下的build.gradle中添加jitpack.io的maven地址 allprojects ...

  2. 极简主义_网页设计中功能极简主义的真实性要少得多

    极简主义 Written by Jessica Bennett 由杰西卡·贝内特 ( Jessica Bennett)撰写 介绍 (Introduction) "Less is more&q ...

  3. 怎么做极简ui设计?UI界面设计中的极简原则【萧蕊冰】

    怎么做极简ui设计?近几年,互联网的飞速发展引起了科技领域的巨大浪潮,UI设计行业需求大量专业优秀人才,吸引了很多想要学习UI设计的人.UI设计也就是用户界面的设计,作为引导用户快速正确使用产品的主要 ...

  4. 发明专利创造性答辩中的极简主义 ——试论答通风格对答通结果的影响

    原文载于:http://www.cypatent.com/cn/bow-67-1.htm 文章提供了一种答复创造性的文档模板,具有一定实用性,可供入门者参考,但实务中有更多变化,文内并未提及,以后再整 ...

  5. 网页设计中的极简主义

    极简主义起源于苏格兰,当时在各个领域都掀起了极简的风潮,设计.绘画.建筑.服装.工艺品等等,直到现在网页设计也开始盛夏极简设计. 极简设计作为一种设计哲学,它在保证了网站基础框架的基础上,剔除多余的装 ...

  6. 电商BANNER灵感背景欣赏|平面设计中的极简风格

    极简风格的特征是视觉语言的单纯一致,且有着简洁.清晰.准确的优点,可以更好地提高设计作品视觉传达的力量. 是单纯的.完整的.对比性强的视觉元素,首先被摄入眼帘容易被认知和记忆,这样也就提高了视觉传达的 ...

  7. koa2+html模板,lenneth -- 基于koa2 的web极简框架

    说明 封装 lenneth 旨在快速方便的搭建出一个 node web 应用,不过度封装也不随波逐流,koa 的 node 是简单的,lenneth 也是. 基于 ES6+typescript 的一些 ...

  8. 电商设计中的极简设计

    下面从3个方面来讲一下如何做极简的设计: 1.极致的版式(对齐 对比 留白) 2.精致的颜色 3.考究的字体 先看一下极简设计的案例: 这是锤子T1的页面设计,无论是手机的外型还是系统UI的设计都是各 ...

  9. 《致命框架2》——极简外衣下的华丽冒险

    <致命框架(FRAMED)>是一款独特的休闲解谜游戏.每个关卡是一段方格连环画,玩家可以通过调整方格的位置来使整段故事连贯并使主人公逃离危险.游戏画面简洁,具有别具一格的美感.FRAMED ...

最新文章

  1. JavaScript基础——Date对象
  2. 关于Timer的用法,先简单记下,稍后编辑
  3. python核心数据类型_Python核心数据类型—元组
  4. python中如将一个文件夹中的多张图片都进程序?
  5. JUST技术:管理海量空间数据的利器-空间填充曲线
  6. 哈夫曼树的构建、编码以及带权路径长计算
  7. vue混合开发笔记, this的指向
  8. gps频率范围_以GPS为例讲解射频接收阻抗匹配的过程
  9. springboot线程池使用
  10. webform窗体怎么实现session唯一标识_微信小程序用户登录和登录态维护的实现_javascript技巧...
  11. php网站入门鹿泉银山,银山门传说与银山门古石洞的考证
  12. torch.nn.NLLLoss()
  13. NLTK(自然语言工具包)
  14. android密码输入框6,Android 6位支付密码 密码输入框 极简单的代码实现 看这篇就够了...
  15. nodejs服务器部署unexpected token{
  16. 计算机音乐按键有声音,计算器上的声音键是哪个键
  17. 16k Star!一个开源的命令行视频播放器
  18. 春天来了,又到了--------------万物复苏的季节
  19. CTFshow新春欢乐赛--web6--反序列化字符串逃逸
  20. MarkdownPad

热门文章

  1. iOS 11.3立春后发布,电量用得快的人千万别升级!
  2. 文化创意企业纷纷跨界融合,软件资产管理奠定安全基础
  3. 液体冷却将在数据中心重现
  4. 安装Windows 2012域控(For SQLServer 2014 AlwaysOn)
  5. 并发编程(九)—— Java 并发队列 BlockingQueue 实现之 LinkedBlockingQueue 源码分析...
  6. spintboot学习笔记
  7. C 标准库 - assert.h
  8. 白盒测试实践作业任务分配
  9. 设置让TortoiseGit记住账号和密码
  10. 《Drupal实战》——1.9 小结