1. # 这里用np.random创建一个随机数组作为输入数据
    2. x = np.random.randn(*[3,1,28,28])
    3. x = x.astype('float32')
    4. with fluid.dygraph.guard():
    5. # 创建LeNet类的实例,指定模型名称和分类的类别数目
    6. m = LeNet('LeNet', num_classes=10)
    7. # 通过调用LeNet从基类继承的sublayers()函数,
    8. # 查看LeNet中所包含的子层
    9. print(m.sublayers())
    10. x = fluid.dygraph.to_variable(x)
    11. for item in m.sublayers():
    12. # item是LeNet类中的一个子层
    13. # 查看经过子层之后的输出数据形状
    14. try:
    15. x = item(x)
    16. except:
    17. x = fluid.layers.reshape(x, [x.shape[0], -1])
    18. x = item(x)
    19. if len(item.parameters())==2:
    20. # 查看卷积和全连接层的数据和参数的形状,
    21. # 其中item.parameters()[0]是权重参数w,item.parameters()[1]是偏置参数b
    22. print(item.full_name(), x.shape, item.parameters()[0].shape, item.parameters()[1].shape)
    23. else:
    24. # 池化层没有参数
    25. print(item.full_name(), x.shape)
    1. # -*- coding: utf-8 -*-
    2. # LeNet 识别手写数字
    3. import os
    4. import random
    5. import paddle.fluid as fluid
    6. import numpy as np
    7. # 定义训练过程
    8. print('start training ... ')
    9. model.train()
    10. epoch_num = 5
    11. opt = fluid.optimizer.Momentum(learning_rate=0.001, momentum=0.9, parameter_list=model.parameters())
    12. # 使用Paddle自带的数据读取器
    13. train_loader = paddle.batch(paddle.dataset.mnist.train(), batch_size=10)
    14. valid_loader = paddle.batch(paddle.dataset.mnist.test(), batch_size=10)
    15. for epoch in range(epoch_num):
    16. for batch_id, data in enumerate(train_loader()):
    17. # 调整输入数据形状和类型
    18. x_data = np.array([item[0] for item in data], dtype='float32').reshape(-1, 1, 28, 28)
    19. y_data = np.array([item[1] for item in data], dtype='int64').reshape(-1, 1)
    20. # 将numpy.ndarray转化成Tensor
    21. img = fluid.dygraph.to_variable(x_data)
    22. label = fluid.dygraph.to_variable(y_data)
    23. # 计算模型输出
    24. logits = model(img)
    25. # 计算损失函数
    26. loss = fluid.layers.softmax_with_cross_entropy(logits, label)
    27. avg_loss = fluid.layers.mean(loss)
    28. if batch_id % 1000 == 0:
    29. print("epoch: {}, batch_id: {}, loss is: {}".format(epoch, batch_id, avg_loss.numpy()))
    30. avg_loss.backward()
    31. opt.minimize(avg_loss)
    32. model.clear_gradients()
    33. accuracies = []
    34. losses = []
    35. for batch_id, data in enumerate(valid_loader()):
    36. # 调整输入数据形状和类型
    37. x_data = np.array([item[0] for item in data], dtype='float32').reshape(-1, 1, 28, 28)
    38. y_data = np.array([item[1] for item in data], dtype='int64').reshape(-1, 1)
    39. # 将numpy.ndarray转化成Tensor
    40. img = fluid.dygraph.to_variable(x_data)
    41. label = fluid.dygraph.to_variable(y_data)
    42. # 计算模型输出
    43. pred = fluid.layers.softmax(logits)
    44. # 计算损失函数
    45. loss = fluid.layers.softmax_with_cross_entropy(logits, label)
    46. acc = fluid.layers.accuracy(pred, label)
    47. accuracies.append(acc.numpy())
    48. losses.append(loss.numpy())
    49. print("[validation] accuracy/loss: {}/{}".format(np.mean(accuracies), np.mean(losses)))
    50. model.train()
    51. # 保存模型参数
    52. fluid.save_dygraph(model.state_dict(), 'mnist')
    53. if __name__ == '__main__':
    54. # 创建模型
    55. with fluid.dygraph.guard():
    56. model = LeNet("LeNet", num_classes=10)
    57. #启动训练过程
    58. train(model)
    1. Cache file /home/aistudio/.cache/paddle/dataset/mnist/train-images-idx3-ubyte.gz not found, downloading https://dataset.bj.bcebos.com/mnist/train-images-idx3-ubyte.gz
    2. Begin to download
    3.  
    4. Download finished
    5. Cache file /home/aistudio/.cache/paddle/dataset/mnist/train-labels-idx1-ubyte.gz not found, downloading https://dataset.bj.bcebos.com/mnist/train-labels-idx1-ubyte.gz
    6. Begin to download
    7. ........
    8. Download finished
    9. Cache file /home/aistudio/.cache/paddle/dataset/mnist/t10k-images-idx3-ubyte.gz not found, downloading https://dataset.bj.bcebos.com/mnist/t10k-images-idx3-ubyte.gz
    10. Begin to download
    11.  
    12. Download finished
    13. Cache file /home/aistudio/.cache/paddle/dataset/mnist/t10k-labels-idx1-ubyte.gz not found, downloading https://dataset.bj.bcebos.com/mnist/t10k-labels-idx1-ubyte.gz
    14. Begin to download
    15. ..
    16. Download finished