tensorflow之简单卷积神经网络(CNN)搭建

优快云博客转载示例
本文为优快云博客的一篇转载文章示例,具体内容未给出,通常会涉及信息技术领域的某个具体话题,例如编程语言、开发工具等。
基于TensorFlow搭建用于服装分类的卷积神经网络CNN)可按以下步骤进行: ### 1. 导入必要的库 ```python import tensorflow as tf from tensorflow.keras import layers, models import numpy as np import matplotlib.pyplot as plt ``` ### 2. 加载和预处理数据 可以使用Fashion MNIST数据集,它包含了不同类型的服装图像。 ```python # 加载数据集 fashion_mnist = tf.keras.datasets.fashion_mnist (train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data() # 数据预处理 train_images = train_images.reshape((60000, 28, 28, 1)) train_images = train_images / 255.0 test_images = test_images.reshape((10000, 28, 28, 1)) test_images = test_images / 255.0 ``` ### 3. 构建卷积神经网络模型 构建一个类似VGG的结构,即卷积层与池化层反复堆叠,然后经过全连接层,最后用softmax映射为每个类别的概率。 ```python model = models.Sequential() # 卷积层 model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1))) # 池化层 model.add(layers.MaxPooling2D((2, 2))) model.add(layers.Conv2D(64, (3, 3), activation='relu')) model.add(layers.MaxPooling2D((2, 2))) model.add(layers.Conv2D(64, (3, 3), activation='relu')) # 展平层 model.add(layers.Flatten()) # 全连接层 model.add(layers.Dense(64, activation='relu')) # 输出层,使用softmax model.add(layers.Dense(10, activation='softmax')) ``` ### 4. 编译模型 ```python model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) ``` ### 5. 训练模型 ```python history = model.fit(train_images, train_labels, epochs=10, validation_data=(test_images, test_labels)) ``` ### 6. 评估模型 ```python test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2) print(f'Test accuracy: {test_acc}') ``` ### 7. 预测 ```python predictions = model.predict(test_images) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值