应用支持向量机(SVM)实现图像分类——Python

文章目录

  • 1.代码运行
  • 2.注意事项
  • 3.代码分析
  • 4.源代码

1.代码运行

  1. 输入 1 测试一张图片并预测结果

  2. 输入 2 对测试集整体进行测试,得出准确率(2分钟左右)

  3. 输入其他数字自动退出程序

2.注意事项

  1. 本程序包含python库较多,请自行配置(pip),如有需求,请评论或私信

  2. 回复其他数字会自动退出程序

  3. 输入图片要求是28*28像素

  4. 模型训练大概需要5分钟,请耐心等候!

  5. 本代码使用本地MNIST数据库,请将代码放至合适位置(同目录下有raw文件夹,文件夹内有以下四个文件

3.代码分析

  1. 加载MNIST数据库
def load_mnist_train(path, kind='train'):labels_path = os.path.join(path, '%s-labels.idx1-ubyte' % kind)images_path = os.path.join(path, '%s-images.idx3-ubyte' % kind)with open(labels_path, 'rb') as lbpath:magic, n = struct.unpack('>II', lbpath.read(8))# >II表示以大端模式读取2个int,大端模式是指二进制中最高位在左边。labels = np.fromfile(lbpath, dtype=np.uint8)with open(images_path, 'rb') as imgpath:magic, num, rows, cols = struct.unpack('>IIII', imgpath.read(16))images = np.fromfile(imgpath, dtype=np.uint8).reshape(len(labels), 784)return images, labelsdef load_mnist_test(path, kind='t10k'):labels_path = os.path.join(path, '%s-labels.idx1-ubyte' % kind)images_path = os.path.join(path, '%s-images.idx3-ubyte' % kind)with open(labels_path, 'rb') as lbpath:magic, n = struct.unpack('>II', lbpath.read(8))labels = np.fromfile(lbpath, dtype=np.uint8)with open(images_path, 'rb') as imgpath:magic, num, rows, cols = struct.unpack('>IIII', imgpath.read(16))images = np.fromfile(imgpath, dtype=np.uint8).reshape(len(labels), 784)return images, labels

2.训练模型


def creat_model():if not os.path.exists('HW.model'):# 标准化X = preprocessing.StandardScaler().fit_transform(train_images)X_train = X[0:60000]y_train = train_labels[0:60000]# 模型训练print(time.strftime('%Y-%m-%d %H:%M:%S'))print('开始训练模型,大概需要5分钟,请耐心等候!!!')model_svc = svm.SVC()model_svc.fit(X_train, y_train)print(time.strftime('%Y-%m-%d %H:%M:%S'))joblib.dump(model_svc, 'HW.model')else:print(time.strftime('%Y-%m-%d %H:%M:%S'))print('已经存在model文件')

3.测试单张和多张


def Test_one(imgPath,modelPath):model_svc=modelPathimage = preprocessing.StandardScaler().fit_transform(np.array(Image.open(imgPath).convert('L'), dtype=np.uint8))print('预测结果是:', model_svc.predict([image.reshape(-1), image.reshape(-1)])[0], '\n')def Test_all():model_svc = joblib.load('HW.model')# 评分并预测x = preprocessing.StandardScaler().fit_transform(test_images)x_test = x[0:10000]y_pred = test_labels[0:10000]print(model_svc.score(x_test, y_pred))y = model_svc.predict(x_test)

4.主程序

if __name__ == '__main__':print('本程序会默认加载测试集、训练集与模型,只需将四个文件置于raw文件夹即可,模型文件会生成在本文件同目录下')train_images, train_labels = load_mnist_train(path)test_images, test_labels = load_mnist_test(path)creat_model()print('数字格式为28*28像素,路径没有要求!!!')print('回复数字1为测试一张图片,回复数字2为测试测试集准确率,回复其他数字自动退出程序!!!\n')while 1:ans = eval(input('测试一张(1)还是测试集准确率(2):'))if ans == 1:modelPath = joblib.load('HW.model') # 模型文件会生成在本文件同目录下不需要选择,这里Path默认直接加载模型root = tk.Tk()root.withdraw()print('请选择测试图片')imgPath = filedialog.askopenfilename()Test_one(imgPath,modelPath)elif ans == 2:Test_all()else:exit()

4.源代码

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName  :HW5.py
# @Time      :2023/4/8 22:56
# @Author    :YKW
import struct
import os
import time
import joblib
import numpy as np
import tkinter as tk
from tkinter import filedialog
from PIL import Image
from sklearn import svm
from sklearn import preprocessingpath = './raw/'  # MNIST源文件目录def load_mnist_train(path, kind='train'):labels_path = os.path.join(path, '%s-labels.idx1-ubyte' % kind)images_path = os.path.join(path, '%s-images.idx3-ubyte' % kind)with open(labels_path, 'rb') as lbpath:magic, n = struct.unpack('>II', lbpath.read(8))# >II表示以大端模式读取2个int,大端模式是指二进制中最高位在左边。labels = np.fromfile(lbpath, dtype=np.uint8)with open(images_path, 'rb') as imgpath:magic, num, rows, cols = struct.unpack('>IIII', imgpath.read(16))images = np.fromfile(imgpath, dtype=np.uint8).reshape(len(labels), 784)return images, labelsdef load_mnist_test(path, kind='t10k'):labels_path = os.path.join(path, '%s-labels.idx1-ubyte' % kind)images_path = os.path.join(path, '%s-images.idx3-ubyte' % kind)with open(labels_path, 'rb') as lbpath:magic, n = struct.unpack('>II', lbpath.read(8))labels = np.fromfile(lbpath, dtype=np.uint8)with open(images_path, 'rb') as imgpath:magic, num, rows, cols = struct.unpack('>IIII', imgpath.read(16))images = np.fromfile(imgpath, dtype=np.uint8).reshape(len(labels), 784)return images, labelsdef creat_model():if not os.path.exists('HW.model'):# 标准化X = preprocessing.StandardScaler().fit_transform(train_images)X_train = X[0:60000]y_train = train_labels[0:60000]# 模型训练print(time.strftime('%Y-%m-%d %H:%M:%S'))print('开始训练模型,大概需要5分钟,请耐心等候!!!')model_svc = svm.SVC()model_svc.fit(X_train, y_train)print(time.strftime('%Y-%m-%d %H:%M:%S'))joblib.dump(model_svc, 'HW.model')else:print(time.strftime('%Y-%m-%d %H:%M:%S'))print('已经存在model文件')def Test_one(imgPath,modelPath):model_svc=modelPathimage = preprocessing.StandardScaler().fit_transform(np.array(Image.open(imgPath).convert('L'), dtype=np.uint8))print('预测结果是:', model_svc.predict([image.reshape(-1), image.reshape(-1)])[0], '\n')def Test_all():model_svc = joblib.load('HW.model')# 评分并预测x = preprocessing.StandardScaler().fit_transform(test_images)x_test = x[0:10000]y_pred = test_labels[0:10000]print(model_svc.score(x_test, y_pred))y = model_svc.predict(x_test)if __name__ == '__main__':print('本程序会默认加载测试集、训练集与模型,只需将四个文件置于raw文件夹即可,模型文件会生成在本文件同目录下')train_images, train_labels = load_mnist_train(path)test_images, test_labels = load_mnist_test(path)creat_model()print('数字格式为28*28像素,路径没有要求!!!')print('回复数字1为测试一张图片,回复数字2为测试测试集准确率,回复其他数字自动退出程序!!!\n')while 1:ans = eval(input('测试一张(1)还是测试集准确率(2):'))if ans == 1:modelPath = joblib.load('HW.model') # 模型文件会生成在本文件同目录下不需要选择,这里Path默认直接加载模型root = tk.Tk()root.withdraw()print('请选择测试图片')imgPath = filedialog.askopenfilename()Test_one(imgPath,modelPath)elif ans == 2:Test_all()else:exit()

应用支持向量机(SVM)实现图像分类——Python相关推荐

  1. python图像分类_关于使用SVM进行图像分类:使用SVM进行图像分类-Python

    我有一组图像分为高质量图像和劣质图像. 我必须训练一个分类模型,以便可以将任何新图像分类为好/坏. SVM似乎是执行此操作的最佳方法. 我已经在MATLAB中完成了图像处理,但没有在python中完成 ...

  2. 深度学习-机器学习(5.2支持向量机SVM上的Python应用)

    1.简单的应用,(用前两节的例子) 直接上代码: from sklearn import svm x = [[2,0],[1,1],[2,3]]#定义三个点 y = [0,0,1] #(class l ...

  3. Python,OpenCV基于支持向量机SVM的手写数字OCR

    Python,OpenCV基于支持向量机SVM的手写数字OCR 1. 效果图 2. SVM及原理 2. 源码 2.1 SVM的手写数字OCR 2.2 非线性SVM 参考 上一节介绍了基于KNN的手写数 ...

  4. python向量机使用方法_Python中支持向量机SVM的使用方法详解

    除了在Matlab中使用PRTools工具箱中的svm算法,Python中一样可以使用支持向量机做分类.因为Python中的sklearn库也集成了SVM算法,本文的运行环境是Pycharm. 一.导 ...

  5. Python中的支持向量机SVM的使用(有实例项目给的地址)

    除了在Matlab中使用PRTools工具箱中的svm算法,Python中一样可以使用支持向量机做分类.因为Python中的sklearn库也集成了SVM算法,本文的运行环境是Pycharm. 一.导 ...

  6. Python中的支持向量机SVM的使用(有实例有源码)

    转自:http://www.cnblogs.com/luyaoblog/p/6775342.html 除了在Matlab中使用PRTools工具箱中的svm算法,Python中一样可以使用支持向量机做 ...

  7. 机器学习之支持向量机SVM之python实现ROC曲线绘制(二分类和多分类)

    目录 一.ROC曲线 二.TP.FP.TN.FN 三. python绘制ROC曲线(二分类) 1.思路 2.关键代码 3.完整代码 四. python绘制ROC曲线(多分类) 五.参考文献 一.ROC ...

  8. python支持向量机回归_Python中支持向量机SVM的使用方法详解

    除了在Matlab中使用PRTools工具箱中的svm算法,Python中一样可以使用支持向量机做分类.因为Python中的sklearn库也集成了SVM算法,本文的运行环境是Pycharm. 一.导 ...

  9. 支持向量机python代码_Python中的支持向量机SVM的使用(有实例)

    除了在Matlab中使用PRTools工具箱中的svm算法,Python中一样可以使用支持向量机做分类.因为Python中的sklearn库也集成了SVM算法,本文的运行环境是Pycharm. 一.导 ...

最新文章

  1. 系列四、SpringMVC响应数据和结果视图
  2. Java远程发送表单信息,java – 从html表单读取POST数据发送到serversocket
  3. 第二章:方法区和运行时常量池溢出
  4. 本科、硕士、博士,究竟有何区别?
  5. MYSQL中的空格及大小写问题
  6. IAR环境中实现数据或函数的定位
  7. IBM打造云访问量子计算机 规模仅相当于D-Wave系统的四百分之一
  8. 移动硬盘无法休眠了?
  9. win11网络无法连接怎么办 Windows11连不上网的解决方法
  10. HDU2206 IP的计算【文本处理】
  11. LeetCode Interleaving String
  12. linux中安装mysql_Linux下安装MySQL
  13. 软件测试面试的自我介绍
  14. 新型传感器将改变大脑控制的机器人技术
  15. Coursera吴恩达《构建机器学习项目》课程笔记(2)-- 机器学习策略(下)
  16. Reinforcement learning book 学习笔记 第一章
  17. IdentityServer3 v1文档
  18. 理性看待“视觉中国版权问题”,强化知识产权保护意识
  19. 【转帖】视频聊天网站的研究、发展以及趋势
  20. 【Pytorch学习笔记三】Pytorch神经网络包nn和优化器optm(一个简单的卷积神经网络模型的搭建)

热门文章

  1. 一篇文章讲透单片机的RAM和FLASH
  2. Android 机顶盒(Box)替换修改鼠标指针样式(需要Root)
  3. python笔记14介绍几个魔法方法
  4. 计算两组标签/关键词 相似度算法
  5. 考研高数之无穷级数题型三:将函数展开成幂级数和傅里叶级数(题目讲解)
  6. ML之KG:基于MovieLens电影评分数据集利用基于知识图谱的推荐算法(networkx+基于路径相似度的方法)实现对用户进行Top电影推荐案例
  7. java 接入水晶报表实现代码自定义数据源(新手接触水晶报表)
  8. pytorch训练第一个项目VOC2007分割
  9. 做外贸人手一份的WhastApp私域运营地图,你值得拥有
  10. CSS-3D酷炫日期选择器