神经网络基础-神经网络补充概念-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)
相关推荐
云卓SKYDROID20 分钟前
无人机避障与目标识别技术分析!
人工智能·无人机·科普·高科技·云卓科技·激光避障
chuangfumao27 分钟前
解读《人工智能指数报告 2025》:洞察 AI 发展新态势
人工智能·搜索引擎·百度
可爱の小公举39 分钟前
自然语言处理(NLP)领域大图
人工智能·自然语言处理
qq_436962181 小时前
AI数据分析的优势分析
人工智能·数据挖掘·数据分析
Vodka~1 小时前
深度学习——数据处理脚本(基于detectron2框架)
人工智能·windows·深度学习
爱的叹息1 小时前
关于 传感器 的详细解析,涵盖定义、分类、工作原理、常见类型、应用领域、技术挑战及未来趋势,结合实例帮助理解其核心概念
人工智能·机器人
恶霸不委屈1 小时前
突破精度极限!基于DeepSeek的无人机航拍图像智能校准系统技术解析
人工智能·python·无人机·deepseek
lixy5792 小时前
深度学习之自动微分
人工智能·python·深度学习
量子位2 小时前
飞猪 AI 意外出圈!邀请码被黄牛倒卖,分分钟搞定机酒预订,堪比专业定制团队
人工智能·llm·aigc