19、TensorFlow教程--- 感知器的隐藏层

这篇教程聚焦于使用TensorFlow构建具有单隐藏层的网络,以从给定点集学习。通过代码解释,阐述了如何实现这一简单网络,并用图表展示了训练数据和验证数据在函数层近似中的表现。

在本章中,我们将专注于从已知点集(称为 x 和 f(x))中学习的网络。一个单隐藏层将构建这个简单的网络。

解释感知器隐藏层的代码如下所示 −

#Importing the necessary modules 
import tensorflow as tf 
import numpy as np 
import math, random 
import matplotlib.pyplot as plt 

np.random.seed(1000) 
function_to_learn = lambda x: np.cos(x) + 0.1*np.random.randn(*x.shape) 
layer_1_neurons = 10 
NUM_points = 1000 

#Training the parameters 
batch_size = 100 
NUM_EPOCHS = 1500 

all_x = np.float32(np.random.uniform(-2*math.pi, 2*math.pi, (1, NUM_points))).T 
   np.random.shuffle(all_x) 

train_size = int(900) 
#Training the first 700 points in the given set x_training = all_x[:train_size] 
y_training = function_to_learn(x_training)

#Training the last 300 points in the given set x_validation = all_x[train_size:] 
y
### 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
发出的红包

打赏作者

Knowledgebase

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值