paddlepaddle学习笔记(4)mnist手写数字识别

一、代码

import paddle
from paddle import fluid


images = fluid.layers.data(name='pixel',shape=[1,28,28],dtype='float32')
label = fluid.layers.data(name='label',shape=[1],dtype='int64')

conv_pool_1 = fluid.nets.simple_img_conv_pool(input=images,filter_size=5
                        ,num_filters=20,pool_size=2,pool_stride=2,act="relu")
conv_pool_2 = fluid.nets.simple_img_conv_pool(input=conv_pool_1,filter_size=5,
                        num_filters=50,pool_size=2,pool_stride=2,act="relu")

SIZE = 10
input_shape  = conv_pool_2.shape
param_shape = [reduce(lambda a,b:a*b,input_shape[1:],1)]+[SIZE]
scale = (2.0/(param_shape[0]**2 * SIZE))**0.5

predict = fluid.layers.fc(input=conv_pool_2,size=SIZE,act="softmax",
                         param_attr=fluid.param_attr.ParamAttr(
                             initializer=fluid.initializer.NormalInitializer(loc=0.0,scale=scale)))

cost = fluid.layers.cross_entropy(input=predict,label=label)
avg_cost=fluid.layers.mean(x=cost)
opt = fluid.optimizer.AdamOptimizer(learning_rate=0.001,beta1=0.9,
                                    beta2=0.999)
opt.minimize(avg_cost)

reader = paddle.dataset.mnist.train()
batched_reader = paddle.batch(reader,batch_size=32)

place = fluid.CPUPlace()#or fluid.CUDAPlace(0) if gpu availble
exe = fluid.Executor(place)
feeder=fluid.DataFeeder(feed_list=[images,label],place=place)
exe.run(fluid.default_startup_program())

for i,data in zip(range(10),batched_reader()):
    loss=exe.run(feed=feeder.feed(data),fetch_list=[avg_cost])
    print(loss)

二、运行结果

猜你喜欢

转载自blog.csdn.net/Johnisjohn/article/details/89714896