TensorFlow练习03-多层神经网络构造

本文介绍如何使用TensorFlow和NumPy从零开始构建一个简单的神经网络模型,通过定义神经层函数并应用ReLU激活函数来解决非线性回归问题。

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

import tensorflow as tf
import numpy as np
###定义添加神经层函数add_layer
def add_layer(inputs, in_size, out_size, activation_function = None):#输入值,输入量,输出量,激活函数默认:无
    Weights = tf.Variable(tf.random_normal([in_size, out_size]))   #随机初始化权重
    biases = tf.add(tf.Variable(tf.zeros([1,out_size])), 0.1)
    Wx_plus_b = tf.matmul(inputs, Weights) + biases
    if activation_function is None:  #默认无激活函数
        outputs = Wx_plus_b
    else:
        outputs = activation_function(Wx_plus_b)  #调用激活函数,引入非线性因素
    return  outputs

###构造样本
x_data = np.linspace(-1, 1, 300)[:,np.newaxis]   #输入值x: 1维
noise = np.random.normal(0,0.05,x_data.shape)    #噪声,正态分布均值0,标准差0.05
y_data = np.square(x_data) - 0.5 + noise       #输出值

xs = tf.placeholder(tf.float32, [None, 1])    #None: [None, 1]:输入维数为1
ys = tf.placeholder(tf.float32, [None, 1])

inputLayer = add_layer(xs, 1, 10, activation_function = tf.nn.relu)     #输入层:输入量1,输出量10(隐含层),激活函数:relu
outputLayer = add_layer(inputLayer, 10, 1, activation_function = None)    #输出层:输入量:10(隐含层),输出量1

loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys-outputLayer),1)) #reduce_sum:对所有元素求和,reduction_indices[1]按行求和,最后输出行向量
                                                                            # reduction_indices[0]按列求和,输出行向量
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)                   #设定学习效率 <1
init = tf.initialize_all_variables()

with tf.Session() as sess:
    sess.run(init)
    for i in range(1000):
        sess.run(train_step, feed_dict={xs:x_data, ys:y_data})    #placeholder传参
        if (i % 50 == 0):
            print(sess.run(loss, feed_dict={xs:x_data, ys:y_data})) #每次调用run操作都需要placeholder传参

### TensorFlow 实现多层感知机(MLP)入门教程 多层感知机(Multilayer Perceptron, MLP)是一种经典的前馈神经网络模型,能够通过多层的神经元和激活函数学习并逼近复杂的非线性函数[^2]。在深度学习领域,MLP 是理解神经网络基本原理的重要工具之一。以下是一个使用 TensorFlow 框架实现 MLP 的完整教程。 --- #### 1. 环境准备与数据加载 首先需要安装 TensorFlow,并加载 MNIST 数据集作为训练和测试数据。MNIST 数据集包含手写数字的灰度图像,每张图片为 28x28 像素,标签为 0-9 的数字类别。 ```python import tensorflow as tf from tensorflow.keras import layers, models import numpy as np # 加载 MNIST 数据集 (x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data() # 数据预处理:将像素值归一化到 [0, 1] 范围,并调整形状 x_train = x_train.astype('float32') / 255.0 x_test = x_test.astype('float32') / 255.0 x_train = np.expand_dims(x_train, -1) # 添加通道维度,形状变为 (batch_size, 28, 28, 1) x_test = np.expand_dims(x_test, -1) # 将标签转换为 one-hot 编码 y_train = tf.keras.utils.to_categorical(y_train, 10) y_test = tf.keras.utils.to_categorical(y_test, 10) ``` --- #### 2. 搭建模型 定义一个 MLP 模型,包含输入层、隐藏层和输出层。隐藏层通常使用 ReLU 激活函数,而输出层使用 Softmax 激活函数进行分类。 ```python class MLP(models.Model): def __init__(self): super(MLP, self).__init__() self.flatten = layers.Flatten() # 将输入展平为一维向量 self.dense1 = layers.Dense(128, activation='relu') # 第一层全连接层,128 个神经元 self.dense2 = layers.Dense(64, activation='relu') # 第二层全连接层,64 个神经元 self.output_layer = layers.Dense(10, activation='softmax') # 输出层,10 个神经元对应 10 类 def call(self, inputs): x = self.flatten(inputs) x = self.dense1(x) x = self.dense2(x) return self.output_layer(x) model = MLP() ``` --- #### 3. 配置模型 配置模型的优化器、损失函数和评估指标。对于分类任务,常用的损失函数是交叉熵损失。 ```python # 使用 Adam 优化器,学习率设为 0.001 optimizer = tf.keras.optimizers.Adam(learning_rate=0.001) # 定义损失函数为分类交叉熵 loss_function = tf.keras.losses.CategoricalCrossentropy() # 配置模型 model.compile(optimizer=optimizer, loss=loss_function, metrics=['accuracy']) ``` --- #### 4. 训练模型 使用 `fit` 方法对模型进行训练,指定训练轮数(epochs)和批量大小(batch size)。 ```python # 训练模型 history = model.fit(x_train, y_train, epochs=10, batch_size=32, validation_split=0.2) ``` --- #### 5. 验证模型 在测试集上评估模型性能,并绘制训练过程中的损失和准确率变化曲线。 ```python # 在测试集上评估模型 test_loss, test_accuracy = model.evaluate(x_test, y_test) print(f"Test Loss: {test_loss}, Test Accuracy: {test_accuracy}") # 绘制训练曲线 import matplotlib.pyplot as plt plt.plot(history.history['loss'], label='Train Loss') plt.plot(history.history['val_loss'], label='Validation Loss') plt.legend() plt.show() plt.plot(history.history['accuracy'], label='Train Accuracy') plt.plot(history.history['val_accuracy'], label='Validation Accuracy') plt.legend() plt.show() ``` --- #### 6. 总结 通过上述步骤,可以成功构建并训练一个基于 TensorFlow多层感知机模型。该模型可以用于 MNIST 手写数字识别任务,同时也可以扩展到其他分类问题中[^1]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值