machine learning-mnist
ml8-3全连接神经网络实现mnist手写识别
import numpy as np from keras.models import _clone_sequential_model from keras.models import Sequential from keras.layers.core import Dense,Dropout,Activation from keras.layers import Conv2D,MaxPooling2D,Flatten from keras.optimizers import SGD,Adam from keras.datasets import mnist from keras.utils import np_utils import keras import matplotlib.pyplot as plt import tensorflow as tf import os def load_data(): (x_train,y_train),(x_test,y_test)=mnist.load_data() number=10000 x_train=x_train[0:number] y_train=y_train[0:number] x_train=x_train.reshape(number,28*28) x_test=x_test.reshape(x_test.shape[0],28*28) #转化为float类型 x_train=x_train.astype('float32') x_test=x_test.astype('float32') y_train=np_utils.to_categorical(y_train,10) y_test = np_utils.to_categorical(y_test, 10) x_train=x_train x_test=x_test #nomal归一化 x_train=x_train/255 x_test=x_test/255 # x_test=np.random.normal(x_test)#加入噪声 return(x_train,y_train),(x_test,y_test) (x_train,y_train),(x_test,y_test)=load_data() #定义模型 model=Sequential() model.add(Dense(input_dim=28*28,units=689,activation='relu')) #model.add(Dropout(0.7)) model.add(Dense(units=689,activation='relu')) #model.add(Dropout(0.7)) model.add(Dense(units=689,activation='relu')) #model.add(Dropout(0.7)) # for i in range(10): # model.add(Dense(units=689,activation='relu')) model.add(Dense(units=10,activation='softmax')) model.compile(loss='categorical_crossentropy',optimizer=SGD(lr=0.1),metrics=['accuracy']) #model.compile(loss='categorical_crossentropy',optimizer=Adam(lr=0.1),metrics=['accuracy']) #训练 model.fit(x_train,y_train,batch_size=100,epochs=20) model.save('mymodel1') #评估 result=model.evaluate(x_train,y_train,batch_size=10000) print('train acc',result[1]) result=model.evaluate(x_test,y_test,batch_size=10000) print('test acc',result[1]) #保存测试 new_model = keras.models.load_model('mymodel1') #new_model.compile(optimizer=tf.train.AdamOptimizer(), # loss='categorical_crossentropy', # metrics=['accuracy']) new_model.summary() #mypath = 'F:\\PyPractice\\ML\\testdir'
手写识别预测
import random import numpy as np import matplotlib.pyplot as plt from keras.datasets import mnist from keras.models import load_model from PIL import Image # # 数据集 # (_, _), (X_test, y_test) = mnist.load_data() # 划分MNIST训练集、测试集 # # # 随机数 # index = random.randint(0, X_test.shape[0]) # x = X_test[index] # y = y_test[index] x=Image.open('3.PNG') y=3 # 显示该数字 plt.imshow(x, cmap='gray_r') plt.title("original {}".format(y)) plt.show() # 加载 mymodel = load_model('mymodel1') # 预测 x.reshape = (1,784)#变成[[]] x = x.astype('float32') x = x/255 # x = x.flatten()[None] # 也可以用这个 predict = mymodel.predict(x) predict = np.argmax(predict)#取最大值的位置 #print('index:', index) print('original:', y) print('predicted:', predict)
posted on 2019-05-23 16:25 yaqiong1112 阅读(131) 评论(0) 编辑 收藏 举报