【Python练习】069. 编写一个函数,实现简单的神经网络模型

069. 编写一个函数,实现简单的神经网络模型

在 Python 中,可以使用 TensorFlowPyTorch 这样的深度学习框架来实现简单的神经网络模型。以下我们将分别使用这两个框架来实现一个简单的神经网络模型,用于分类任务。

安装依赖库

在开始之前,请确保你已经安装了 TensorFlowPyTorch。如果没有安装,可以通过以下命令安装:

pip install tensorflow torch torchvision

示例代码:使用 TensorFlow 实现简单的神经网络

以下代码使用 TensorFlow 和 Keras(TensorFlow 的高级 API)实现一个简单的神经网络模型,用于分类任务。

import tensorflow as tf
from tensorflow.keras import layers, models
from tensorflow.keras.datasets import mnist
from tensorflow.keras.utils import to_categorical

def simple_neural_network_tensorflow():
    # 加载 MNIST 数据集
    (train_images, train_labels), (test_images, test_labels) = mnist.load_data()

    # 数据预处理
    train_images = train_images.reshape((60000, 28 * 28)).astype('float32') / 255
    test_images = test_images.reshape((10000, 28 * 28)).astype('float32') / 255

    train_labels = to_categorical(train_labels)
    test_labels = to_categorical(test_labels)

    # 构建简单的神经网络模型
    model = models.Sequential()
    model.add(layers.Dense(512, activation='relu', input_shape=(28 * 28,)))
    model.add(layers.Dense(10, activation='softmax'))

    # 编译模型
    model.compile(optimizer='rmsprop',
                  loss='categorical_crossentropy',
                  metrics=['accuracy'])

    # 训练模型
    model.fit(train_images, train_labels, epochs=5, batch_size=128)

    # 评估模型
    test_loss, test_acc = model.evaluate(test_images, test_labels)
    print(f"测试集准确率: {
     
     test_acc:.4f}")

# 示例用法
if __name__ == "__main__":
    simple_neural_network_tensorflow()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值