Bruce a nomal man 2023-03-15 17:57 采纳率: 50%
浏览 21
已结题

深度学习入门实践的典型例题-手写数字识别

深度学习入门实践-手写数字识别
代码如下,是在aistudio上运行的,但是不知道怎么回事运行不了
部分错误如下:
模型训练部分出现的错误
AttributeError: module 'paddle.fluid.dygraph' has no attribute 'to_varlable'

模型验证部分出现的错误
NameError: name 'best_test_acc' is not defined

预测的问题
ValueError: Model saved directory './work/24' is not exists.

#导入需要的包
import numpy as np
import paddle as paddle
from PIL import Image
import matplotlib.pyplot as plt
import os
from paddle.fluid.dygraph import Linear
#训练数据集准备
BUF_SIZE=512
BATCH_SIZE=128
train_reader = paddle.batch(
    paddle.reader.shuffle(paddle.dataset.mnist.train(),buf_size=BUF_SIZE),batch_size=BATCH_SIZE 
)

#测试数据集准备
#用于训练的数据提供器,每次从缓存中随机读取批次大小的数据
test_reader = paddle.batch(
    paddle.reader.shuffle(paddle.dataset.mnist.test(),buf_size=BUF_SIZE),batch_size=BATCH_SIZE 
)
#定义多层感知器
#动态图定义多层感知器
import paddle.fluid as fluid #防止出现name fluid is not defined
class multilayer_perceptron(fluid.dygraph.Layer):
    def __init__(self):
        super(multilayer_perceptron,self).__init__()
        self.fc1 = Linear(input_dim=28*28,output_dim=100,act='relu')
        self.fc2 = Linear(input_dim=100,output_dim=100,act='relu')
        self.fc3 = Linear(input_dim=100,output_dim=10,act='softmax')
    def forward(self,input_):
        x = fluid.layers.reshape(input_,[input_.shape[0],-1])
        x = self.fc1(x)
        x = self.fc2(x)
        y = self.fc3(x)
        return y
#模型训练
with fluid.dygraph.guard():
    model=multilayer_perceptron() #模型实例化
    model.train() #训练模式
    opt=fluid.optimizer.Adam(learning_rate=fluid.dygraph.ExponentialDecay(
        learning_rate=0.01,
        decay_steps=4000,
        decay_rate=0.1,
        staircase=True
    ),parameter_list=model.parameters())

    epochs_num=30 #选代次数
    
    for pass_num in range(epochs_num):
        lr = opt.current_step_lr() 
        print("learning-rate:",lr)

        for batch_id,date in enumerate(train_reader()):
            images=np.array([x[0].reshape(1,28,28) for x in data],np.float32) 

            labels = np.array([x[1] for x in data]).astype('int64')
            labels = labels[:,np.newaxis]
            
            image=fluid.dygraph.to_variable(images) 
            label=fluid.dygraph.to_varlable(labels) 
            predict=model(image) #预测
            #print(predict)
            loss=fluid.layers.cross_entropy(predict,label) 
            avg_loss=fluid.layers.mean(loss)#获取loss
            acc=fluid.layers.eccuracy(predict,label)#计算精度 
            avg_loss.backvard()
            opt.minimize(avg_loss) 
            model.clear_gredients()

            all_train_iter=all_train_iter+256 
            all_train_iters.append(all_train_iter) 
            all_train_costs.append(loss.numpy()[0]) 
            a1l_train_accs.append(acc,numpy()[0]) 
            
            
            if batch_idlse and batch_id%50==0:
                prinf("train_pass:{},batch_id:{},train_loss:{},train_acc:{}",format(pass_num,batch_id,avg_loss.numpy(),acc.numpy())) 

#模型验证
with fluid.dygraph.guard():
    accs = []
    model.eval()#评估模式
    for batch_id,data in enumerate(test_reader()):#测试集
        images=np.array([x[0].reshape(1,28,28) for x in data],np.float32)
        labels = np.array([x[1] for x in data]).astype('int64')
        labels = labels[:,np.newaxis]

        image=fluid.dygraph.to_variable(images)
        label=fluid.dygraph.to_variable(labels)

        predict=model(image)#预测
        acc=fluid.layers.accuracy(predict,label)
        accs.append(acc.numpy()[0])
        avg_acc = np.mean(accs)

    
    if avg_acc >= best_test_acc:
        best_test_acc = avg_acc
        if pass_num > 10:
            fluid.save_dygraph(model.state_dict(),'./work/{}'.format(pass_num))#保存模型

    print('Test:%d,Accuracy:%0.5f, Best: %0.5f'% (pass_num,avg_acc,best_test_acc))

#图片预处理
def load_image(flie):
    im = Image.open(flie).convert('L')
    im = im.resize((28,28),Image.ANTIALIAS)
    im = np.array(im).reshape(1,1,28,28).astype(np.float32)
    #print(im)
    im = im/255.0 * 2.0 - 1.0
    return im

#开始预测
#构建预测动态图过程
model_path = './work/24'
with fluid.dygraph.guard():
    model=multilayer_perceptron()#模型实例化
    model_dict,_=fluid.load_dygraph(model_path)
    model.load_dict(model_dict)
    model.eval()
    infer_img = load_image(infer_path)
    infer_img=np.array(infer_img).astype('float32')
    infer_img=infer_img[np.newaxis,:,:,:]
    infer_img = fluid.dygraph.to_variable(infer_img)
    result=model(infer_img)

    print("infer results: %s"% label_list[np.argmax(result.numpy())])

  • 写回答

2条回答 默认 最新

  • 「已注销」 2023-03-15 18:30
    关注

    参考GPT和自己的思路:

    针对你提出的问题,我来逐一回答:

    1. AttributeError: module 'paddle.fluid.dygraph' has no attribute 'to_varlable'
      这个错误是因为拼写错误,正确的应该是 to_variable,将代码中 to_varlable 修改为 to_variable 即可。

    2. NameError: name 'best_test_acc' is not defined
      这个错误是因为没有定义 best_test_acc 变量,需要在模型训练前先定义这个变量。可以在代码前面加上一行 best_test_acc = 0。

    3. ValueError: Model saved directory './work/24' is not exists.
      这个错误是因为模型保存路径不正确,你需要检查一下模型保存路径是否正确(即模型训练部分的代码中是否有保存模型的代码,以及你的模型保存目录是否存在)。

    希望以上回答能够帮到你解决问题,祝你成功实现手写数字识别!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 3月23日
  • 已采纳回答 3月15日
  • 创建了问题 3月15日

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效