手写数字识别

获取手写数字数据集

(train_images, train_labels), (test_images, test_labels) = mnist.load_data()

数据集预处理

训练集数据维度的调整:N H W C

train_images = np.reshape(train_images,
(train_images.shape[0],train_images.shape[1],train_images.shape[2],1))

测试集数据维度的调整:N H W C

test_images = np.reshape(test_images,
(test_images.shape[0],test_images.shape[1],test_images.shape[2],1))

获取训练集和测试集样本

def get_train(size):
    # 随机生成要抽样的样本的索引
    index = np.random.randint(0, np.shape(train_images)[0], size)
    # 将这些数据resize成224*224大小
    resized_images = tf.image.resize_with_pad(train_images[index],224,224)
    # 返回抽取的
    return resized_images.numpy(), train_labels[index]

# 获取测试集数据
def get_test(size):
    # 随机生成要抽样的样本的索引
    index = np.random.randint(0, np.shape(test_images)[0], size)
    # 将这些数据resize成224*224大小
    resized_images = tf.image.resize_with_pad(test_images[index],224,224)
    # 返回抽样的测试样本
    return resized_images.numpy(), test_labels[index]

# 获取训练样本和测试样本
train_images,train_labels = get_train(256)
test_images,test_labels = get_test(128)

模型训练和评估

# 指定优化器,损失函数和评价指标
optimizer = tf.keras.optimizers.SGD(learning_rate=0.01, momentum=0.0)
net.compile(optimizer=optimizer,loss='sparse_categorical_crossentropy',metrics=['accuracy'])

# 模型训练:指定训练数据,batchsize,epoch,验证集
net.fit(train_images,train_labels,batch_size=128,epochs=3,verbose=1,validation_split=0.1)

# 指定测试数据
net.evaluate(test_images,test_labels,verbose=1)

注意:

  • 以上代码需要你已经定义了一个名为net的神经网络模型。
  • tf.image.resize_with_pad() 函数用于调整图像尺寸,并将图像填充到指定的尺寸。
  • net.compile() 用于设置模型的优化器、损失函数和评价指标。
  • net.fit() 用于训练模型,net.evaluate() 用于评估模型。
手写数字识别:TensorFlow 2.0 中的 MNIST 数据集处理和训练

原文地址: https://www.cveoy.top/t/topic/pdzG 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录