神经网络基础-神经网络补充概念-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)
相关推荐
lijianhua_97123 小时前
国内某顶级大学内部用的ai自动生成论文的提示词
人工智能
EDPJ3 小时前
当图像与文本 “各说各话” —— CLIP 中的模态鸿沟与对象偏向
深度学习·计算机视觉
蔡俊锋3 小时前
用AI实现乐高式大型可插拔系统的技术方案
人工智能·ai工程·ai原子能力·ai乐高工程
自然语3 小时前
人工智能之数字生命 认知架构白皮书 第7章
人工智能·架构
大熊背3 小时前
利用ISP离线模式进行分块LSC校正的方法
人工智能·算法·机器学习
eastyuxiao4 小时前
如何在不同的机器上运行多个OpenClaw实例?
人工智能·git·架构·github·php
诸葛务农4 小时前
AGI 主要技术路径及核心技术:归一融合及未来之路5
大数据·人工智能
光影少年4 小时前
AI Agent智能体开发
人工智能·aigc·ai编程
ai生成式引擎优化技术4 小时前
TSPR-WEB-LLM-HIC (TWLH四元结构)AI生成式引擎(GEO)技术白皮书
人工智能
帐篷Li4 小时前
9Router:开源AI路由网关的架构设计与技术实现深度解析
人工智能