赞
踩
其他实现手写数字识别的方法:
1.聚类(K-means)实现手写数字识别
2.全连接神经网络实现手写数字识别
3.KNN实现手写数字识别
4.聚类(K-means)实现手写数字识别-2
from keras.utils import to_categorical from keras import models, layers from keras.optimizers import RMSprop import numpy as np from os import listdir # 因为你的数据是自己的数据,所以才会有前三个方法:img2vector(), getLabel(), # getData()用来获取数据,数据标签和处理数据。如果你用的是mnist数据集 # 或者是sklearn中自带的数据集,则直接加载即可 """ 函数说明:将32x32的二进制图像转换为1x1024向量 """ def img2vector(filename): # 创建1x1024零向量 returnVect = np.zeros((1, 1024)) # 打开文件 fr = open(filename) # 按行读取 for i in range(32): # 读一行数据 lineStr = fr.readline() # 每一行的前32个元素依次添加到returnVect中 for j in range(32): returnVect[0, 32 * i + j] = float(lineStr[j]) # 返回转换后的1x1024向量 return returnVect ''' 函数说明:获取标签 ''' def getLabel(Datapath): # 训练集的Labels hwLabels = [] # 返回Datapath目录下的文件名 trainingFileList = listdir(Datapath) # 返回文件夹下文件的个数 m = len(trainingFileList) # 从文件名中解析出训练集的类别 for i in range(m): # 获得文件的名字 fileNameStr = trainingFileList[i] # 获得分类的数字 classNumber = int(fileNameStr.split('_')[0]) # 将获得的类别添加到hwLabels中 hwLabels.append(classNumber) return hwLabels ''' 函数说明:获取数据 ''' def getData(Datapath): # 返回train目录下的文件名 trainingFileList = listdir(Datapath) # 返回文件夹下文件的个数 m = len(trainingFileList) # 初始化训练的Mat矩阵,训练集 trainingMat = np.zeros((m, 1024)) for i in range(m): # 获得文件的名字 fileNameStr = trainingFileList[i] # 将每一个文件的1x1024数据存储到trainingMat矩阵中 trainingMat[i, :] = img2vector(Datapath+'/%s' % (fileNameStr)) return trainingMat # 加载数据 train_images = getData('你的训练数据') test_images = getData('你的测试数据') train_labels = getLabel('你的训练数据') test_labels = getLabel('你的测试数据') # 搭建LeNet网络 def LeNet(): network = models.Sequential() network.add(layers.Conv2D(filters=6, kernel_size=(3, 3), activation='relu', input_shape=(32, 32, 1))) network.add(layers.AveragePooling2D((2, 2))) network.add(layers.Conv2D(filters=16, kernel_size=(3, 3), activation='relu')) network.add(layers.AveragePooling2D((2, 2))) network.add(layers.Conv2D(filters=120, kernel_size=(3, 3), activation='relu')) network.add(layers.Flatten()) network.add(layers.Dense(84, activation='relu')) network.add(layers.Dense(10, activation='softmax')) return network network = LeNet() network.compile(optimizer=RMSprop(lr=0.001), loss='categorical_crossentropy', metrics=['accuracy']) train_images = train_images.reshape((1200, 32, 32, 1)).astype('float') / 255 test_images = test_images.reshape((200, 32, 32, 1)).astype('float') / 255 train_labels = to_categorical(train_labels) test_labels = to_categorical(test_labels) # 训练网络,用fit函数, epochs表示训练多少个回合, batch_size表示每次训练给多大的数据 network.fit(train_images, train_labels, epochs=100, batch_size=100, verbose=2) test_loss, test_accuracy = network.evaluate(test_images, test_labels) print("test_loss:", test_loss, "test_accuracy:", test_accuracy)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。