算法案例手写数字识别
MNIST数据集是机器学习领域中非常经典的一个数据集,由60000个
训练样本和10000个测试样本组成,每个样本都是一张28 * 28像素的灰度
手写数字图片。
选择算法,并保存模型
import pickle
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
from sklearn.ensemble import RandomForestClassifier
import joblib
with open('mnist.pkl','rb') as f:
train, val ,test = pickle.load(f,encoding='iso-8859-1')
train_x = train[0]
train_y = train[1]
test_x = test[0]
test_y = test[1]
# lr = LogisticRegression()
# lr.fit(train_x,train_y)
rdt = RandomForestClassifier()
rdt.fit(train_x,train_y)
acc = accuracy_score(rdt.predict(train_x),train_y)
print("训练集上的准确率为:",acc)
acc = accuracy_score(rdt.predict(test_x),test_y)
print("测试集上的准确率为:",acc)
joblib.dump(rdt,'rdt.pkl')
加载模型
给出识别图片
import cv2
img = cv2.imread('1.png')
b = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
w = 255 - b
cv2.imwrite('9.png',w)
import joblib
import cv2
from sklearn.preprocessing import StandardScaler
rdt = joblib.load('rdt.pkl')
#读取图片
img = cv2.imread('9.png',0)
img = cv2.resize(img,(28,28))
test = img.reshape(1,28*28)
std = StandardScaler()
test = std.fit_transform(test)
pre = rdt.predict(test)
print(pre)
cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/147422.html