神经网络基础-神经网络补充概念-30-搭建神经网络块

概念

搭建神经网络块是一种常见的做法,它可以帮助你更好地组织和复用网络结构。神经网络块可以是一些相对独立的模块,例如卷积块、全连接块等,用于构建更复杂的网络架构。

代码实现

python 复制代码
import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers

# 定义一个卷积块
def convolutional_block(x, num_filters, kernel_size, pool_size):
    x = layers.Conv2D(num_filters, kernel_size, activation='relu', padding='same')(x)
    x = layers.MaxPooling2D(pool_size)(x)
    return x

# 构建神经网络模型
def build_model():
    inputs = layers.Input(shape=(28, 28, 1))  # 输入数据为28x28的灰度图像
    x = convolutional_block(inputs, num_filters=32, kernel_size=(3, 3), pool_size=(2, 2))
    x = convolutional_block(x, num_filters=64, kernel_size=(3, 3), pool_size=(2, 2))
    x = layers.Flatten()(x)
    x = layers.Dense(128, activation='relu')(x)
    outputs = layers.Dense(10, activation='softmax')(x)  # 输出层,10个类别
    model = keras.Model(inputs, outputs)
    return model

# 加载数据
(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
x_train = np.expand_dims(x_train, axis=-1).astype('float32') / 255.0
x_test = np.expand_dims(x_test, axis=-1).astype('float32') / 255.0
y_train = keras.utils.to_categorical(y_train, num_classes=10)
y_test = keras.utils.to_categorical(y_test, num_classes=10)

# 构建模型
model = build_model()

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

# 训练模型
model.fit(x_train, y_train, batch_size=64, epochs=10, validation_split=0.1)

# 评估模型
test_loss, test_accuracy = model.evaluate(x_test, y_test)
print("Test Loss:", test_loss)
print("Test Accuracy:", test_accuracy)
相关推荐
CV-King16 分钟前
opencv实战项目(三十):使用傅里叶变换进行图像边缘检测
人工智能·opencv·算法·计算机视觉
禁默19 分钟前
2024年计算机视觉与艺术研讨会(CVA 2024)
人工智能·计算机视觉
slomay1 小时前
关于对比学习(简单整理
经验分享·深度学习·学习·机器学习
whaosoft-1431 小时前
大模型~合集3
人工智能
Dream-Y.ocean1 小时前
文心智能体平台AgenBuilder | 搭建智能体:情感顾问叶晴
人工智能·智能体
丶21361 小时前
【CUDA】【PyTorch】安装 PyTorch 与 CUDA 11.7 的详细步骤
人工智能·pytorch·python
春末的南方城市2 小时前
FLUX的ID保持项目也来了! 字节开源PuLID-FLUX-v0.9.0,开启一致性风格写真新纪元!
人工智能·计算机视觉·stable diffusion·aigc·图像生成
zmjia1112 小时前
AI大语言模型进阶应用及模型优化、本地化部署、从0-1搭建、智能体构建技术
人工智能·语言模型·自然语言处理
jndingxin2 小时前
OpenCV视频I/O(14)创建和写入视频文件的类:VideoWriter介绍
人工智能·opencv·音视频
AI完全体3 小时前
【AI知识点】偏差-方差权衡(Bias-Variance Tradeoff)
人工智能·深度学习·神经网络·机器学习·过拟合·模型复杂度·偏差-方差