用Python实现数字识别的简单AI应用
今天分享一个用Python写了一个能识别图片里文字的AI!不用任何现成的大模型,就靠最基础的代码。
这个简单的AI能做什么?
简单的说就是你画了一个简单的数字“8”,这个AI就能认出它是8!虽然它现在只能认0-9这10个数字,但这就是真正AI识别的原理。
第一步:准备“训练教材”
import numpy as np
import matplotlib.pyplot as plt
# 我们自己来造一些“手写数字”
def create_number_data():
# 数字0的模板
zero = np.array([
[0, 1, 1, 0],
[1, 0, 0, 1],
[1, 0, 0, 1],
[0, 1, 1, 0]
])
# 数字1的模板
one = np.array([
[0, 0, 1, 0],
[0, 1, 1, 0],
[0, 0, 1, 0],
[0, 0, 1, 0]
])
# 数字2的模板
two = np.array([
[0, 1, 1, 0],
[0, 0, 0, 1],
[0, 1, 1, 0],
[1, 1, 1, 1]
])
data = []
labels = []
templates = [zero, one, two]
# 给每个数字造50个稍微不一样的版本
for number, template in enumerate(templates):
for i in range(50):
# 加入一点点随机变化,就像不同人写的字
noisy_template = template + np.random.normal(0, 0.2, (4, 4))
data.append(noisy_template.flatten()) # 把4x4变成16个数字的一行
labels.append(number)
return np.array(data), np.array(labels)
print("正在制作训练数据...")
X_train, y_train = create_number_data()
print(f"制作了 {len(X_train)} 个手写数字样本")
第二步:建造AI的“大脑”
class MyFirstOCR:
def __init__(self):
# 随机初始化权重 - 就像给AI一个空白的脑子
self.weights = np.random.randn(16, 3) * 0.1 # 16个输入,3个输出(0,1,2)
self.bias = np.zeros(3)
def softmax(self, x):
# 把输出变成概率,比如[0.1, 0.8, 0.1]表示80%可能是数字1
exp_x = np.exp(x - np.max(x)) # 防止数值过大
return exp_x / np.sum(exp_x)
def forward(self, x):
# AI的思考过程:输入 → 计算 → 输出概率
z = np.dot(x, self.weights) + self.bias
return self.softmax(z)
def train(self, X, y, learning_rate=0.1, epochs=1000):
print("开始教AI认数字...")
for epoch in range(epochs):
total_loss = 0
for i in range(len(X)):
# 取一个训练样本
x_i = X[i]
y_i = y[i]
# 前向传播:AI猜答案
prediction = self.forward(x_i)
# 计算误差:AI知道自己错多少
true_label = np.zeros(3)
true_label[y_i] = 1 # 变成[1,0,0]这样的形式
loss = -np.log(prediction[y_i] + 1e-8) # 交叉熵损失
total_loss += loss
# 反向传播:AI从错误中学习
error = prediction - true_label
dw = np.outer(x_i, error)
db = error
# 更新权重:调整AI的“知识”
self.weights -= learning_rate * dw
self.bias -= learning_rate * db
if epoch % 200 == 0:
print(f"训练轮次 {epoch}, 平均误差: {total_loss/len(X):.4f}")
def predict(self, x):
# 用训练好的AI预测数字
probabilities = self.forward(x)
return np.argmax(probabilities) # 返回概率最大的那个数字
# 创建我们的AI
print("创建AI大脑中...")
my_ocr_ai = MyFirstOCR()
第三步:训练AI
# 开始训练!
my_ocr_ai.train(X_train, y_train)
print("训练完成!AI已经学会认数字了!")
第四步:测试我们的AI
# 让我们画个数字测试一下
def test_ai():
# 画一个数字2
test_digit = np.array([
[0.1, 0.9, 0.8, 0.2],
[0.0, 0.1, 0.0, 0.9],
[0.2, 0.8, 0.9, 0.1],
[0.9, 0.9, 0.8, 0.9]
]).flatten()
# 让AI识别
prediction = my_ocr_ai.predict(test_digit)
confidence = np.max(my_ocr_ai.forward(test_digit))
print(f"AI识别结果:数字 {prediction}")
print(f"置信度:{confidence*100:.2f}%")
# 显示我们画的数字
plt.imshow(test_digit.reshape(4, 4), cmap='gray')
plt.title(f"AI识别为: 数字 {prediction}")
plt.show()
# 测试!
test_ai()
它是怎么“思考”的?
- 看图片:把4x4的图片变成16个数字
- 计算特征:用权重计算每个数字的可能性
- 做决定:选择可能性最大的那个数字
从这个案例中我们学到了
- AI不神秘:就是权重 + 计算 + 学习
- 训练是关键:就像教小孩,要反复练习
- 从简单开始:先学会认0-9,后面就能认更多
这个AI虽然简单,但原理和那些复杂的图像识别系统是一样的!
你运行这段代码,然后自己尝试一下,就拥有自己的第一个图片识别AI了!

浙公网安备 33010602011771号