当前位置: 首页 > news >正文

详细介绍:python第31天打卡

import numpy as npfrom tensorflow import kerasfrom tensorflow.keras import layers, optimizers, utils, datasets # 数据加载和预处理函数def load_and_preprocess_data():    (x_train, y_train), (x_test, y_test) = datasets.mnist.load_data()    # 重塑并归一化图像数据    x_train = x_train.reshape(-1, 28, 28, 1).astype("float32") / 255.0    x_test = x_test.reshape(-1, 28, 28, 1).astype("float32") / 255.0    # 转换标签为one-hot编码    y_train = utils.to_categorical(y_train, 10)    y_test = utils.to_categorical(y_test, 10)    return (x_train, y_train), (x_test, y_test) # 模型定义def create_simple_cnn():    return keras.Sequential([        layers.Conv2D(16, (3, 3), activation='relu', input_shape=(28, 28, 1)),        layers.MaxPooling2D((2, 2)),        layers.Flatten(),        layers.Dense(128, activation='relu'),        layers.Dense(10, activation='softmax')    ]) def create_complex_cnn():    return keras.Sequential([        layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)),        layers.MaxPooling2D((2, 2)),        layers.Conv2D(64, (3, 3), activation='relu'),        layers.MaxPooling2D((2, 2)),        layers.Flatten(),        layers.Dense(256, activation='relu'),        layers.Dense(128, activation='relu'),        layers.Dense(10, activation='softmax')    ]) # 训练和评估函数def train_and_evaluate(model, optimizer, x_train, y_train, x_test, y_test):    model.compile(        optimizer=optimizer,        loss='categorical_crossentropy',        metrics=['accuracy']    )    history = model.fit(        x_train, y_train,        epochs=5,        batch_size=64,        validation_data=(x_test, y_test)    )    return history.history # 主程序if __name__ == "__main__":    # 加载数据    (x_train, y_train), (x_test, y_test) = load_and_preprocess_data()        # 模型和优化器配置    model_configs = [        ('Simple CNN', create_simple_cnn),        ('Complex CNN', create_complex_cnn)    ]    optimizers_config = {        'SGD': optimizers.SGD(learning_rate=0.01),        'Adam': optimizers.Adam(learning_rate=0.001)    }        # 训练和评估所有组合    results = {}    for model_name, model_fn in model_configs:        for opt_name, optimizer in optimizers_config.items():            print(f"\n{'='*50}")            print(f"Training {model_name} with {opt_name} optimizer:")                        model = model_fn()            history = train_and_evaluate(                model, optimizer,                x_train, y_train,                x_test, y_test            )                        # 记录结果            results[f"{model_name}_{opt_name}"] = history            print(f"\nTraining results for {model_name}/{opt_name}:")            print(f"Final Training Accuracy: {history['accuracy'][-1]:.4f}")            print(f"Final Validation Accuracy: {history['val_accuracy'][-1]:.4f}")            print(f"Final Training Loss: {history['loss'][-1]:.4f}")            print(f"Final Validation Loss: {history['val_loss'][-1]:.4f}")

@浙大疏锦行

http://www.zskr.cn/news/16431.html

相关文章:

  • 如何采用插件和子主题添加WordPress自定义CSS(附:常见错误)
  • 02020502 EF Core高级02-IQuerable会延迟执行、分部和动态构建IQuerable、IQuerable的复用
  • 在 PyCharm 中,环境:bert_env , 执行 import wandb 报错。但是,在CMD窗口,环境:bert_env , 执行 import wandb 正常。
  • Linux_T(Sticky Bit)粘滞位详解 - 详解
  • Valley靶机渗透实战:从凭证复用到Python库劫持
  • 深入解析:IP Search Performance Tests dat/db/xdb/mmdb 结构性能差异对比
  • 10.05模拟赛反思
  • 如何快速搭建spring-boot工程 - murphy
  • 做题记录 #1
  • 深度学习优化器算法巧思速览
  • 在Windows下使用lucky实现TLS/SSL证书自动化
  • CF700E
  • 价值弥漫:“AI元人文”的场域革命与共生之路
  • k8s之pod概念
  • 鸿蒙版Taro 搭建开发环境 - 教程
  • CF 1055 Div.1+Div.2
  • 2026 NOI 做题记录(五)
  • “齐俊杰投资智能体”更新完了9月份的资料
  • docker 离线安装
  • minio 离线安装
  • 银行同业存单产品的筛选方法
  • deepseek 私有部署文档
  • MySQL运维及开发规范
  • 异步读写mysql依赖pymysql (asyncio/ aiomysql)
  • Linux发行版切换技术全解析
  • 完整教程:高效Excel数据净化工具:一键清除不可见字符与格式残留
  • 手把手教你用 Docker 部署 Redis
  • 长租公寓的生存越来越难了 - 智慧园区
  • Spring Boot中保存前端上传的图片 - 教程
  • Linux--进程概念 - 详解