基于mnist数据集,建立mlp模型,实现0-9数字的十分类

mnist数据集是机器学习领域中非常经典的一个数据集,由60000个训练样本和10000个测试样本组成,每个样本都是一张28*28像素的灰度手写数字图片。一共四个文件,训练集、训练集标签、测试集、测试集标签

  • 实现mnist数据载入,可视化图形数字
  • 实现数据预处理,图像数据维度转换与归一化,输出结果格式转换
  • 计算模型在预测数据集的准确率
  • 模型结构:两层隐藏层,每层有392个神经元

实现mnist数据载入,可视化图形数字

  • 加载mnist数据集

    from matplotlib import pyplot as plt
    
    (X_train, y_train), (X_test, y_test) = mnist.load_data()
    print(type(X_train), X_train.shape)
    

    结果是<class 'numpy.ndarray'> (60000, 28, 28)

  • 可视化第一个图形数字

from matplotlib import pyplot as plt
# 可视化部分数据
img1 = X_train[0]
fig1 = plt.figure(figsize=(5, 5))
plt.imshow(img1)
plt.title(y_train[0])
plt.show()

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

从图形中可以看出来大概是数字5输出维度print(img1.shape),结果的确是(28, 28)每个样本都是一张28*28像素的灰度手写数字图片

实现数据预处理,图像数据维度转换与归一化,输出结果格式转换

  • 图像数据维度转换

    要把28*28=784的像素灰度转换成784列

    feature_size = img1.shape[0] * img1.shape[1]
    X_train_format = X_train.reshape(X_train.shape[0], feature_size)
    print(X_train_format.shape)
    结果是(60000, 784)
    
  • 归一化

    为了更快的进行mlp的迭代和求解

    X_train_normal = X_train_format / 255
    X_test_normal = X_test_format / 255
    
  • 输出结果格式转换

    from keras.utils import to_categorical
    y_train_format = to_categorical(y_train)
    y_test_format = to_categorical(y_test)
    print(y_train[0]) 
    print(y_train_format[0])
    输出结果是5[0. 0. 0. 0. 0. 1. 0. 0. 0. 0.]
    

    模型结构搭建

  • 建立模型结构

    from keras.models import Sequential
    from keras.layers import Dense, Activation
    mlp = Sequential()
    mlp.add(Dense(units=392, activation='sigmoid', input_dim=feature_size))
    mlp.add(Dense(units=392, activation='sigmoid'))
    mlp.add(Dense(units=10, activation='softmax'))
    mlp.summary()
    

    输出结果是

  • 模型配置

    # 模型配置
    mlp.compile(loss='categorical_crossentropy', optimizer='adam')
    
  • 模型训练

    # 模型训练
    mlp.fit(X_train_normal, y_train_format, epochs=10)
    
  • 模型评估

    # 模型评估
    # 训练集训练准确率
    y_train_predict = mlp.predict_classes(X_train_normal)
    print(y_train_predict)
    accuracy_train = accuracy_score(y_train, y_train_predict)
    print(accuracy_train)
    # 测试集训练准确率
    y_test_predict = mlp.predict_classes(X_test_normal)
    print(y_test_predict)
    accuracy_test = accuracy_score(y_test, y_test_predict)
    print(accuracy_test)
    

    输出结果
    在这里插入图片描述

可以看到这个模型训练的很好,训练集的准确率是0.99,测试集的准确率是0.98

  • 直观查看模型的预测结果

    # 测试集图形的可视化展示
    img2 = X_test[100]
    fig2 = plt.figure(figsize=(3, 3))
    plt.imshow(img2)
    plt.title(y_test_predict[100])
    plt.show()
    

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

可以看到,预测的结果和照片中是一样的。

全部代码为

# 加载mnist数据集

from keras.datasets import mnist
from keras.utils import to_categorical
from keras.models import Sequential
from keras.layers import Dense, Activation
from sklearn.metrics import accuracy_score
from matplotlib import pyplot as plt

(X_train, y_train), (X_test, y_test) = mnist.load_data()
print(type(X_train), X_train.shape)

# 可视化部分数据
img1 = X_train[0]
fig1 = plt.figure(figsize=(3, 3))
plt.imshow(img1)
plt.title(y_train[0])
plt.show()

feature_size = img1.shape[0] * img1.shape[1]
X_train_format = X_train.reshape(X_train.shape[0], feature_size)
X_test_format = X_test.reshape(X_test.shape[0], feature_size)
print(X_test_format.shape)

X_train_normal = X_train_format / 255
X_test_normal = X_test_format / 255

y_train_format = to_categorical(y_train)
y_test_format = to_categorical(y_test)
print(y_train[0])
print(y_train_format[0])

# 建立模型结构
mlp = Sequential()
mlp.add(Dense(units=392, activation='sigmoid', input_dim=feature_size))
mlp.add(Dense(units=392, activation='sigmoid'))
mlp.add(Dense(units=10, activation='softmax'))
mlp.summary()

# 模型配置
mlp.compile(loss='categorical_crossentropy', optimizer='adam')
# 模型训练
mlp.fit(X_train_normal, y_train_format, epochs=10)
# 模型评估
# 训练集训练准确率
y_train_predict = mlp.predict_classes(X_train_normal)
print(y_train_predict)
accuracy_train = accuracy_score(y_train, y_train_predict)
print(accuracy_train)
# 测试集训练准确率
y_test_predict = mlp.predict_classes(X_test_normal)
print(y_test_predict)
accuracy_test = accuracy_score(y_test, y_test_predict)
print(accuracy_test)

# 测试集图形的可视化展示
img2 = X_test[100]
fig2 = plt.figure(figsize=(3, 3))
plt.imshow(img2)
plt.title(y_test_predict[100])
plt.show()
 = accuracy_score(y_test, y_test_predict)
print(accuracy_test)

# 测试集图形的可视化展示
img2 = X_test[100]
fig2 = plt.figure(figsize=(3, 3))
plt.imshow(img2)
plt.title(y_test_predict[100])
plt.show()
  • 1
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是基于MNIST数据集构建MLP的Python代码,并绘制训练次数和准确率的图像: ```python import numpy as np import tensorflow as tf import matplotlib.pyplot as plt from tensorflow.examples.tutorials.mnist import input_data # 加载MNIST数据mnist = input_data.read_data_sets('MNIST_data', one_hot=True) # 定义超参数 learning_rate = 0.1 num_epochs = 100 batch_size = 100 display_step = 1 # 定义输入和输出变量 x = tf.placeholder(tf.float32, [None, 784]) y = tf.placeholder(tf.float32, [None, 10]) # 定义权重和偏置变量 W1 = tf.Variable(tf.random_normal([784, 256])) b1 = tf.Variable(tf.random_normal([256])) W2 = tf.Variable(tf.random_normal([256, 10])) b2 = tf.Variable(tf.random_normal([10])) # 定义MLP模型 hidden_layer = tf.nn.relu(tf.add(tf.matmul(x, W1), b1)) output_layer = tf.add(tf.matmul(hidden_layer, W2), b2) # 定义损失函数和优化器 cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=output_layer, labels=y)) optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost) # 定义准确率计算方式 correct_pred = tf.equal(tf.argmax(output_layer, 1), tf.argmax(y, 1)) accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32)) # 初始化变量 init = tf.global_variables_initializer() # 开始训练MLP模型 with tf.Session() as sess: sess.run(init) num_batches = int(mnist.train.num_examples / batch_size) training_costs = [] training_accs = [] for epoch in range(num_epochs): for i in range(num_batches): batch_x, batch_y = mnist.train.next_batch(batch_size) _, c, acc = sess.run([optimizer, cost, accuracy], feed_dict={x: batch_x, y: batch_y}) if epoch % display_step == 0: training_costs.append(c) training_accs.append(acc) print("Epoch:", '%04d' % (epoch + 1), "cost=", "{:.9f}".format(c), "accuracy=", "{:.9f}".format(acc)) print("Optimization Finished!") # 测试MLP模型 test_acc = sess.run(accuracy, feed_dict={x: mnist.test.images, y: mnist.test.labels}) print("Test Accuracy:", test_acc) # 绘制训练次数和准确率的图像 plt.plot(range(num_epochs), training_accs) plt.xlabel('Training Epochs') plt.ylabel('Training Accuracy') plt.show() ``` 运行代码后,将输出每个epoch的损失和准确率,并在训练结束时输出测试准确率。此外,还将绘制训练次数和准确率的图像,以便更好地了解模型的训练情况。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值