BP-手写字识别,自建数据集

代码 中的手写字数据是自建的。当然也可以用官方的数据。
自建数据集

BP-手写字识别
#BP手写字识别
import tensorflow as tf
tf.random.set_seed(123)
import  matplotlib.pyplot as plt
import os
import PIL
import numpy as np
np.random.seed(123)
from tensorflow import keras
from tensorflow.keras import layers,models
import pathlib

data_dir = r"D:\Python\python_code\tensorflow\data_one"
data_dir = pathlib.Path(data_dir)
image_count = len(list(data_dir.glob('*/*.png')))
print("图片总数",image_count)

batch_size = 32
img_height = 28
img_width = 28

train_datsets = tf.keras.preprocessing.image_dataset_from_directory(
    data_dir,
    color_mode='grayscale',
    validation_split=0.2,
    subset='training',
    seed=123,
    image_size=(img_height,img_width),
    batch_size=batch_size)

val_datasets = tf.keras.preprocessing.image_dataset_from_directory(
    data_dir,
    color_mode='grayscale',
    validation_split=0.2,
    subset='validation',
    seed=123,
    image_size=(img_height,img_width),
    batch_size=batch_size)

class_names = train_datsets.class_names
print(class_names)
print(len(class_names))

AUTOTUNE = tf.data.experimental.AUTOTUNE
train_datsets = train_datsets.cache().shuffle(500).prefetch(buffer_size=AUTOTUNE)
val_datasets =val_datasets.cache().prefetch(buffer_size=AUTOTUNE)

model1 = models.Sequential([
    layers.experimental.preprocessing.Rescaling(1./255,input_shape=(img_height,img_width,1)),
    layers.Flatten(),
    
    layers.Dense(64,activation='relu'),
    layers.Dense(64,activation='relu'),
    layers.Dense(10)
])
model1.summary()
model1.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=0.0001),
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
             metrics=['accuracy'])
history = model1.fit(train_datsets,validation_data=val_datasets,epochs=100)
import matplotlib.pyplot as plt
plt.figure(figsize=(20,20))
plt.subplot(1,2,1)
plt.plot(history.history['accuracy'],label='training accuracy')
plt.plot(history.history['val_accuracy'],label='val accuracy')
plt.legend(loc='upper right')
plt.title('Training and Validation Accuracy')
plt.subplot(1,2,2)
plt.plot(history.history['loss'],label=' training loss')
plt.plot(history.history['val_loss'],label='val loss')
plt.legend(loc='upper right')
plt.title('Training and Validation Loss')
plt.show()

 model1.get_weights()  #导入各层权重以及偏置值    很重要!!!
 #保存模型
 model1.save(model/model1.h5)
 #加载模型
 model = tf.keras.models.load_model('model/model1.h5')
 
#预测
自己写吧,很简单滴

结果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_50918736/article/details/120599764
今日推荐