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

python第31天打卡

import numpy as np
from tensorflow import keras
from 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.0x_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}"] = historyprint(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.lqws.cn/news/92449.html

相关文章:

  • 多模态大语言模型arxiv论文略读(105)
  • Java-redis实现限时在线秒杀功能
  • Servlet 快速入门
  • 1130 - Host ‘xxx.x.xx.xxx‘is not allowed to connect to this MySQL server
  • 70道Hive高频题整理(附答案背诵版)
  • 如何合理设计缓存 Key的命名规范,以避免在共享 Redis 或跨服务场景下的冲突?
  • Java并发编程:读写锁与普通互斥锁的深度对比
  • 【ROS2】各种相关概念汇总解释
  • 动态规划-1143.最长公共子序列-力扣(LeetCode)
  • 机器学习——随机森林算法
  • 【如何在IntelliJ IDEA中新建Spring Boot项目(基于JDK 21 + Maven)】
  • Linux Maven Install
  • 【论文笔记】High-Resolution Representations for Labeling Pixels and Regions
  • 3.2 HarmonyOS NEXT跨设备任务调度与协同实战:算力分配、音视频协同与智能家居联动
  • 机器学习——SVM
  • Foundation Models for Generalist Geospatial Artificial Intelligence论文阅读
  • 微软Build 2025:Copilot Studio升级,解锁多智能体协作未来
  • 论文阅读:CLIP:Learning Transferable Visual Models From Natural Language Supervision
  • 谷歌地图手机版(Google maps)v11.152.0100安卓版 - 前端工具导航
  • 力扣刷题 -- 225. 用队列实现栈
  • Spring 中创建 Bean 有几种方式?
  • 深入理解Android进程间通信机制
  • 秋招Day12 - 计算机网络 - IP
  • 蓝桥杯 k倍区间
  • docker创建postgreSql带多个init的sql
  • openharmony5.0.0中kernel子系统编译构建流程概览(rk3568)
  • Dockerfile 使用多阶段构建(build 阶段 → release 阶段)前端配置
  • 5.Nginx+Tomcat负载均衡群集
  • PyTorch——非线性激活(5)
  • Docker 插件生态:从网络插件到存储插件的扩展能力解析