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

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.lryc.cn/news/2399416.html

相关文章:

  • 4.1 HarmonyOS NEXT原生AI能力集成:盘古大模型端侧部署与多模态交互实战
  • 学习STC51单片机27(芯片为STC89C52RCRC)
  • PAT-甲级JAVA题解(更新中...)
  • Deep Chat:重塑人机对话边界的开源智能对话框架—— 让下一代AI交互无缝融入你的应用
  • DA14531_beacon_大小信标设备开发
  • 【算法训练营Day06】哈希表part2
  • Word双栏英文论文排版攻略
  • 乡村三维建模 | 江苏农田无人机建模案例
  • 2025 5 月 学习笔记
  • SpringBoot(七) --- Redis基础
  • Oracle 故障实例 - 通过备份恢复到某时间点 故障恢复
  • 滑动智能降级:Glide优化加载性能的黑科技
  • 【前端并发请求控制:必要性与实现策略】
  • LeetCode 139. 单词拆分(Word Break) - 动态规划深度解析
  • @Prometheus动态配置管理-ConsulConfd
  • CentOS7 + JDK8 虚拟机安装与 Hadoop + Spark 集群搭建实践
  • 从OSI到TCP/IP:网络协议的演变与作用
  • Stream流性能分析及优雅使用
  • iOS 电子书听书功能的实现
  • 【和春笋一起学C++】(十七)C++函数新特性——内联函数和引用变量
  • GitHub 趋势日报 (2025年06月02日)
  • 卫星的“太空陀螺”:反作用轮如何精准控制姿态?
  • proteus新建工程
  • 缓存击穿 缓存穿透 缓存雪崩
  • RTC实时时钟DS1338Z-33/PT7C433833WEX国产替代FRTC1338S
  • Redis命令使用
  • 【免费数据】1980-2022年中国2384个站点的水质数据
  • Java基础 Day28 完结篇
  • 小红薯商品搜索详情分析与实现
  • Git 极简使用指南