吴裕雄 PYTHON 神经网络——TENSORFLOW 双隐藏层自编码器设计处理MNIST手写数字数据集并使用TENSORBORD描绘神经网络数据...

本文介绍了一个基于TensorFlow的自编码器模型,该模型在MNIST手写数字数据集上进行训练,旨在通过减少和随后重建数据来学习高效的数据编码。自编码器由两个部分组成:编码器和解码器。编码器将输入数据转换为较低维度的表示,而解码器则尝试从这个压缩表示中重建原始输入。

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

import os
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data

 
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
 
batch_size = 128  # batch容量
display_step = 1  # 展示间隔
learning_rate = 0.01  # 学习率
training_epochs = 20  # 训练轮数,1轮等于n_samples/batch_size
example_to_show = 10  # 展示图像数目
 
n_hidden1_units = 256  # 第一隐藏层
n_hidden2_units = 128  # 第二隐藏层
n_input_units = 784
n_output_units = n_input_units
 
def WeightsVariable(n_in, n_out, name_str):
    return tf.Variable(tf.random_normal([n_in, n_out]), dtype=tf.float32, name=name_str)
 
def biasesVariable(n_out, name_str):
    return tf.Variable(tf.random_normal([n_out]), dtype=tf.float32, name=name_str)
 
def encoder(x_origin, activate_func=tf.nn.sigmoid):
    with tf.name_scope('Layer1'):
        Weights = WeightsVariable(n_input_units, n_hidden1_units, 'Weights')
        biases = biasesVariable(n_hidden1_units, 'biases')
        x_code1 = activate_func(tf.add(tf.matmul(x_origin, Weights), biases))
    with tf.name_scope('Layer2'):
        Weights = WeightsVariable(n_hidden1_units, n_hidden2_units, 'Weights')
        biases = biasesVariable(n_hidden2_units, 'biases')
        x_code2 = activate_func(tf.add(tf.matmul(x_code1, Weights), biases))
    return x_code2
 
def decode(x_code, activate_func=tf.nn.sigmoid):
    with tf.name_scope('Layer1'):
        Weights = WeightsVariable(n_hidden2_units, n_hidden1_units, 'Weights')
        biases = biasesVariable(n_hidden1_units, 'biases')
        x_decode1 = activate_func(tf.add(tf.matmul(x_code, Weights), biases))
    with tf.name_scope('Layer2'):
        Weights = WeightsVariable(n_hidden1_units, n_output_units, 'Weights')
        biases = biasesVariable(n_output_units, 'biases')
        x_decode2 = activate_func(tf.add(tf.matmul(x_decode1, Weights), biases))
    return x_decode2
 
with tf.Graph().as_default():
    with tf.name_scope('Input'):
        X_input = tf.placeholder(tf.float32, [None, n_input_units])
    with tf.name_scope('Encode'):
        X_code = encoder(X_input)
    with tf.name_scope('decode'):
        X_decode = decode(X_code)
    with tf.name_scope('loss'):
        loss = tf.reduce_mean(tf.pow(X_input - X_decode, 2))
    with tf.name_scope('train'):
        Optimizer = tf.train.RMSPropOptimizer(learning_rate)
        train = Optimizer.minimize(loss)
 
    init = tf.global_variables_initializer()
 
    # 因为使用了tf.Graph.as_default()上下文环境
    # 所以下面的记录必须放在上下文里面,否则记录下来的图是空的(get不到上面的default)
    writer = tf.summary.FileWriter(logdir='logsss', graph=tf.get_default_graph())
    writer.flush()
 
    mnist = input_data.read_data_sets('E:\\MNIST_data\\', one_hot=True)
 
    with tf.Session() as sess:
        sess.run(init)
        total_batch = int(mnist.train.num_examples / batch_size)
        for epoch in range(training_epochs):
            for i in range(total_batch):
                batch_xs, batch_ys = mnist.train.next_batch(batch_size)
                _, Loss = sess.run([train, loss], feed_dict={X_input: batch_xs})
                Loss = sess.run(loss, feed_dict={X_input: batch_xs})
            if epoch % display_step == 0:
                print('Epoch: %04d' % (epoch + 1), 'loss= ', '{:.9f}'.format(Loss))
        writer.close()
        print('训练完毕!')
 
        '''比较输入和输出的图像'''
        # 输出图像获取
        reconstructions = sess.run(X_decode, feed_dict={X_input: mnist.test.images[:example_to_show]})
        # 画布建立
        f, a = plt.subplots(2, 10, figsize=(10, 2))
        for i in range(example_to_show):
            a[0][i].imshow(np.reshape(mnist.test.images[i], (28, 28)))
            a[1][i].imshow(np.reshape(reconstructions[i], (28, 28)))
        f.show()  # 渲染图像
        plt.draw()  # 刷新图像
        # plt.waitforbuttonpress()

 

 

转载于:https://www.cnblogs.com/tszr/p/10864284.html

### 构建两层神经网络MNIST手写数字进行分类 #### 1. 导入必要的库 为了构建训练一个简单的两层神经网络来对手写数字进行分类,首先需要导入所需的Python库。这包括用于加载和预处理数据的模块以及定义模型架构的核心组件。 ```python import tensorflow as tf from tensorflow.keras import layers, models from tensorflow.keras.datasets import mnist from tensorflow.keras.utils import to_categorical ``` 这些命令引入了`tensorflow`及其子包`keras`中的功能,后者提供了高层API以便快速创建复杂的机器学习模型[^2]。 #### 2. 加载与准备数据集 接下来是从Keras内置的数据集中获取MNIST图像,对其进行标准化处理以适应后续操作的需求: ```python (train_images, train_labels), (test_images, test_labels) = mnist.load_data() train_images = train_images.reshape((60000, 28 * 28)) train_images = train_images.astype('float32') / 255 test_images = test_images.reshape((10000, 28 * 28)) test_images = test_images.astype('float32') / 255 train_labels = to_categorical(train_labels) test_labels = to_categorical(test_labels) ``` 上述代码片段完成了几个重要任务:下载MNIST数据库;调整输入图片大小使之成为一维向量形式;将像素强度值缩放到区间\[0,1\];最后把标签转换成独热编码(one-hot encoding)[^3]. #### 3. 定义模型结构 现在可以建立具有两个隐藏层的人工神经元网络(ANN)。这里采用的是密集连接型(Densely Connected),即每一层上的节点都与其他各层相连: ```python model = models.Sequential() model.add(layers.Dense(512, activation='relu', input_shape=(28 * 28,))) model.add(layers.Dense(10, activation='softmax')) ``` 这段脚本初始化了一个顺序堆叠式的多层感知器(Multilayer Perceptron, MLP),其中包含了第一个拥有512个单元且激活函数为ReLU(Rectified Linear Unit) 的隐含层,紧接着是一个输出维度等于类别数目的Softmax层用来预测概率分布. #### 4. 编译配置优化算法及损失度量方式 完成模型设计之后,则需指定求解过程所使用的梯度下降法变体以及其他辅助参数如性能指标等: ```python model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy']) ``` 此部分指定了RMSProp作为更新权重的方法之一,它能够自适应调节步长从而加快收敛速度; 同时选择了交叉熵(cross entropy)衡量误差水平,关注最终准确率的变化趋势. #### 5. 训练模型 有了完整的设置后就可以调用fit()方法启动迭代计算循环直至达到预定轮次或满足特定条件为止: ```python history = model.fit(train_images, train_labels, epochs=5, batch_size=128, validation_split=0.2) ``` 此处设置了总共执行五遍完整扫描整个训练样本集合的过程(batch size设为128意味着每次仅取固定数量实例参与反向传播); 此外还保留了一定量比例的数据供验证用途,帮助监控泛化能力的表现情况. #### 6. 绘制精度和损失曲线 训练完成后可以通过绘制图表直观了解模型在整个过程中表现出来的特性变化规律: ```python import matplotlib.pyplot as plt plt.figure(figsize=(12, 4)) plt.subplot(1, 2, 1) plt.plot(history.history['accuracy'], label='Training Accuracy') plt.plot(history.history['val_accuracy'], label='Validation Accuracy') plt.xlabel('Epochs') plt.ylabel('Accuracy') plt.legend(loc='lower right') plt.subplot(1, 2, 2) plt.plot(history.history['loss'], label='Training Loss') plt.plot(history.history['val_loss'], label='Validation Loss') plt.xlabel('Epochs') plt.ylabel('Loss') plt.legend(loc='upper right') plt.tight_layout() plt.show() ``` 该段绘图指令利用Matplotlib工具箱呈现出了随时间推移而演变的学习动态——左侧展示了不同阶段下的平均正确率对比关系;右侧则反映了累积错误程度的发展轨迹[^4].
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值