paddle练习(六)手写字图像识别

import numpy as np
import paddle as paddle

import paddle.dataset.mnist as mnist
import paddle.fluid as fluid
from PIL import Image
import matplotlib.pyplot as plt
paddle.enable_static()
# 定义多层感知器
def multilayer_perceptron(input):
    # 第一个全连接层,激活函数为ReLU
    hidden1 = fluid.layers.fc(input=input, size=100, act='relu')
    # 第二个全连接层,激活函数为ReLU
    hidden2 = fluid.layers.fc(input=hidden1, size=100, act='relu')
    # 以softmax为激活函数的全连接输出层,大小为label大小
    fc = fluid.layers.fc(input=hidden2, size=10, act='softmax')
    return fc
# 卷积神经网络
def convolutional_neural_network(input):
    # 第一个卷积层,卷积核大小为3*3,一共有32个卷积核
    conv1 = fluid.layers.conv2d(input=input,
                                num_filters=32,
                                filter_size=3,
                                stride=1)

    # 第一个池化层,池化大小为2*2,步长为1,最大池化
    pool1 = fluid.layers.pool2d(input=conv1,
                                pool_size=2,
                                pool_stride=1,
                                pool_type='max')

    # 第二个卷积层,卷积核大小为3*3,一共有64个卷积核
    conv2 = fluid.layers.conv2d(input=pool1,
                                num_filters=64,
                                filter_size=3,
                                stride=1)

    # 第二个池化层,池化大小为2*2,步长为1,最大池化
    pool2 = fluid.layers.pool2d(input=conv2,
                                pool_size=2,
                                pool_stride=1,
                                pool_type='max')

    # 以softmax为激活函数的全连接输出层,大小为label大小
    fc = fluid.layers.fc(input=pool2, size=10, act='softmax')
    return fc

# 定义输入层
image = fluid.layers.data(name='image', shape=[1, 28, 28], dtype='float32')
label = fluid.layers.data(name='label', shape=[1], dtype='int64')

# 获取分类器
# model = multilayer_perceptron(image)
model = convolutional_neural_network(image)

# 获取损失函数和准确率函数
cost = fluid.layers.cross_entropy(input=model, label=label)
avg_cost = fluid.layers.mean(cost)
acc = fluid.layers.accuracy(input=model, label=label)

# 获取测试程序
test_program = fluid.default_main_program().clone(for_test=True)

# 定义优化方法
optimizer = fluid.optimizer.AdamOptimizer(learning_rate=0.001)
opts = optimizer.minimize(avg_cost)

# 获取MNIST数据
train_reader = paddle.batch(mnist.train(), batch_size=128)
test_reader = paddle.batch(mnist.test(), batch_size=128)

# 定义一个使用CPU的解析器
place = fluid.CPUPlace()
exe = fluid.Executor(place)
# 进行参数初始化
exe.run(fluid.default_startup_program())
[]

# 定义输入数据维度
feeder = fluid.DataFeeder(place=place, feed_list=[image, label])

# 开始训练和测试
for pass_id in range(5):
    # 进行训练
    for batch_id, data in enumerate(train_reader()):
        train_cost, train_acc = exe.run(program=fluid.default_main_program(),
                                        feed=feeder.feed(data),
                                        fetch_list=[avg_cost, acc])
        # 每100个batch打印一次信息
        if batch_id % 100 == 0:
            print('Pass:%d, Batch:%d, Cost:%0.5f, Accuracy:%0.5f' %
                  (pass_id, batch_id, train_cost[0], train_acc[0]))

    # 进行测试
    test_accs = []
    test_costs = []
    for batch_id, data in enumerate(test_reader()):
        test_cost, test_acc = exe.run(program=test_program,
                                      feed=feeder.feed(data),
                                      fetch_list=[avg_cost, acc])
        test_accs.append(test_acc[0])
        test_costs.append(test_cost[0])
    # 求测试结果的平均值
    test_cost = (sum(test_costs) / len(test_costs))
    test_acc = (sum(test_accs) / len(test_accs))
    print('Test:%d, Cost:%0.5f, Accuracy:%0.5f' % (pass_id, test_cost, test_acc))




# 加载数据并开始预测
def load_image(file):
    im = Image.open(file).convert('L')
    im = im.resize((28, 28), Image.ANTIALIAS)
    im = np.array(im).reshape(1, 1, 28, 28).astype(np.float32)
    im = im / 255.0 * 2.0 - 1.0
    return im

img = load_image('3.png')
results = exe.run(program=test_program,
                  feed={'image': img, "label": np.array([[1]]).astype("int64")},
                  fetch_list=[model])

# 获取概率最大的label
lab = np.argsort(results)
print("该图片的预测结果的label为: %d" % lab[0][0][-1])

关于import 依赖库的安装 及其快速安装方法。

参考:

paddle练习(一)使用线性回归预测波士顿房价_Vertira的博客-CSDN博客import paddleimport numpy as npimport osimport matplotlibimport matplotlib.pyplot as pltimport pandas as pdimport seaborn as snsimport warningswarnings.filterwarnings("ignore")print(paddle.__version__)# 从文件导入数据datafile = 'housing.data'housin.https://blog.csdn.net/Vertira/article/details/122171950

程序运行结果:

训练结果

Pass:0, Batch:0, Cost:5.62981, Accuracy:0.07031
Pass:0, Batch:100, Cost:0.22028, Accuracy:0.92188
Pass:0, Batch:200, Cost:0.16295, Accuracy:0.96094
Pass:0, Batch:300, Cost:0.16200, Accuracy:0.95312
Pass:0, Batch:400, Cost:0.24813, Accuracy:0.92969
Test:0, Cost:0.09430, Accuracy:0.97271
Pass:1, Batch:0, Cost:0.09913, Accuracy:0.98438
Pass:1, Batch:100, Cost:0.08717, Accuracy:0.96875
Pass:1, Batch:200, Cost:0.05952, Accuracy:0.99219
Pass:1, Batch:300, Cost:0.11509, Accuracy:0.97656
Pass:1, Batch:400, Cost:0.15095, Accuracy:0.95312
Test:1, Cost:0.11022, Accuracy:0.97093
Pass:2, Batch:0, Cost:0.10068, Accuracy:0.97656
Pass:2, Batch:100, Cost:0.06170, Accuracy:0.96875
Pass:2, Batch:200, Cost:0.04817, Accuracy:0.98438
Pass:2, Batch:300, Cost:0.12149, Accuracy:0.97656
Pass:2, Batch:400, Cost:0.08126, Accuracy:0.96875
Test:2, Cost:0.10471, Accuracy:0.97597
Pass:3, Batch:0, Cost:0.02993, Accuracy:0.99219
Pass:3, Batch:100, Cost:0.03880, Accuracy:0.98438
Pass:3, Batch:200, Cost:0.01673, Accuracy:0.98438
Pass:3, Batch:300, Cost:0.06603, Accuracy:0.98438
Pass:3, Batch:400, Cost:0.04971, Accuracy:0.97656
Test:3, Cost:0.18114, Accuracy:0.96697
Pass:4, Batch:0, Cost:0.10860, Accuracy:0.96094
Pass:4, Batch:100, Cost:0.07501, Accuracy:0.96875
Pass:4, Batch:200, Cost:0.03184, Accuracy:0.99219
Pass:4, Batch:300, Cost:0.14522, Accuracy:0.98438
Pass:4, Batch:400, Cost:0.16144, Accuracy:0.96094
Test:4, Cost:0.13065, Accuracy:0.97498

Process finished with exit code 0

预测图像结果

该图片的预测结果的label为: 3

欢迎点赞,收藏,关注。

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
GoogleNet是一种深度卷积神经网络架构,常用于图像识别任务。而PaddlePaddle是一种深度学习开源平台,提供了丰富的神经网络模型和训练工具。GoogleNet和PaddlePaddle可以结合应用于写数字识别写数字识别是一种常见的图像分类任务,其目标是将写数字的图像分类为0到9的数字。利用GoogleNet模型的卷积和池化层可以有效地提取图像的特征,而全连接层可以进一步将这些特征映射到0到9的类别上。这样,通过GoogleNet模型可以对写数字进行准确的识别。 在PaddlePaddle中,我们可以使用提供的图像分类工具箱,利用GoogleNet模型进行写数字识别的训练和推断。首先,我们可以利用PaddlePaddle的数据处理模块对写数字的图像进行预处理,例如,将图像调整为统一的大小、进行灰度化处理等。然后,我们可以使用PaddlePaddle的模型定义模块构建GoogleNet模型,并设置合适的超参数和损失函数。接下来,我们可以使用PaddlePaddle的训练模块对GoogleNet模型进行训练,通过反向传播算法不断优化模型的参数。训练完成后,我们可以使用PaddlePaddle的预测模块对新的写数字图像进行推断,即预测其所属的数字类别。 总结来说,GoogleNet在写数字识别上的应用存在于PaddlePaddle这个深度学习开源平台中。利用PaddlePaddle提供的工具和模块,我们可以方便地构建和训练GoogleNet模型,从而实现准确和高效的写数字识别

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值