神经网络基础-神经网络补充概念-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)
相关推荐
留意_yl几秒前
量化感知训练(QAT)流程
人工智能
山烛18 分钟前
KNN 算法中的各种距离:从原理到应用
人工智能·python·算法·机器学习·knn·k近邻算法·距离公式
盲盒Q28 分钟前
《频率之光:归途之光》
人工智能·硬件架构·量子计算
墨染点香36 分钟前
第七章 Pytorch构建模型详解【构建CIFAR10模型结构】
人工智能·pytorch·python
go546315846536 分钟前
基于分组规则的Excel数据分组优化系统设计与实现
人工智能·学习·生成对抗网络·数学建模·语音识别
茫茫人海一粒沙43 分钟前
vLLM 的“投机取巧”:Speculative Decoding 如何加速大语言模型推理
人工智能·语言模型·自然语言处理
诗酒当趁年华1 小时前
【NLP实践】二、自训练数据实现中文文本分类并提供RestfulAPI服务
人工智能·自然语言处理·分类
静心问道1 小时前
Idefics3:构建和更好地理解视觉-语言模型:洞察与未来方向
人工智能·多模态·ai技术应用
sheep88881 小时前
AI与区块链Web3技术融合:重塑数字经济的未来格局
人工智能·区块链
奋进的孤狼1 小时前
【Spring AI】阿里云DashScope灵积模型
人工智能·spring·阿里云·ai·云计算