【Keras入门】1.1 使用Keras训练简单的神经网络(手写数字为例)

这篇博客展示了如何利用Keras框架训练神经网络处理MNIST数据集。首先,介绍了数据预处理步骤,包括数据加载、向量化和One-hot编码。接着,构建了一个简单的全连接神经网络,测试集精度达到88.5%。随后,通过添加两个隐藏层的全连接神经网络,精度进一步提升至97.7%。博客讨论了模型训练过程和性能评估,并可视化了训练过程中的准确性变化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

将以最简单的MNIST数据集展示如何使用Keras框架训练神经网络。

  • 最简单的神经网络,在测试集上的精度达到了88.5%
  • 使用全连接的神经网络,精度达到97.2%。
    在这里插入图片描述

最简单的神经网络(输入784维,输出10维)

1.加载和处理MNIST数据集

1.1 加载数据集

from keras.datasets import mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()

print('shape of x_train:' + str(x_train.shape))
print('shape of x_test:' + str(x_test.shape))
print('shape of y_train:' + str(y_train.shape))
print('shape of y_test:' + str(y_test.shape))

输出mnist训练集、测试集的数据和标签的shape:

shape of x_train:(60000, 28, 28)
shape of x_test:(10000, 28, 28)
shape of y_train:(60000,)
shape of y_test:(10000,)

1.2 将28×28的images转换成784维的向量

x_train_vec = x_train.reshape(60000,784)
x_test_vec = x_test.reshape(10000,784)
print('shape of x_train_vec is' + str(x_train_vec.shape))

输出训练集数据的向量shape:

shape of x_train_vec is(60000, 784)

1.3 使用One-hot编码,将0-9的整数数字用10维的向量表示

import numpy as np
def to_one_hot(labels,dimension = 10):
  results = np.zeros((len(labels),dimension))
  for i, label in enumerate(labels):
    results[i, label] =1.
  return results

y_train_vec = to_one_hot(y_train)
y_test_vec = to_one_hot
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值