构建手写数字识别模型
import numpy as np
import random
import math
w1 = np.random.random()
w2 = np.random.random()
x1 = np.array([0,0,1,1])
x2 = np.array([0,1,0,1])
t = np.array([0,0,0,1])
# y = sum(w1*x1+w2*x2)
# sigmod = 1/(1+np.exp(y))
# delta= 2*sigmod(1-sigmod)*(x1 or x2)
g = 0.01
delta1 = 10
delta2 = 10
for i in range(10):
while delta1 <= np.exp(-5) and delta2 <= np.exp(-5):
i = 0
y = (w1 * x1[i] + w2 * x2[i])
sigmod = 1 / (1 + np.exp(-y))
delta1 = 2 * sigmod(1 - sigmod) * x1[i]
delta2 = 2 * sigmod(1 - sigmod) * x2[i]
i += 1
w1 = w1 + g*delta1
w2 = w2 + g*delta2
print(w1,w2)
模型设计
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
img_path = './work/example_0.jpg'
# 读取原始图像并显示
im = Image.open('./work/example_0.jpg')
plt.imshow(im)
plt.show()
# 将原始图像转为灰度图
im = im.convert('L')
print('原始图像shape: ', np.array(im).shape)
# 使用Image.ANTIALIAS方式采样原始图片
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 / 255
return im
# 定义预测过程
model = MNIST()
params_file_path = 'mnist.pdparams'
img_path = './work/example_0.jpg'
# 加载模型参数
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'))