当前位置: 首页 > 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}")

@浙大疏锦行

相关文章:

  • [野火®]《FreeRTOS 内核实现与应用开发实战—基于STM32》笔记
  • cf1600-1900每天刷2-3道打卡(2)
  • 黑盒(功能)测试基本方法
  • LARWINER拉威兒艺术珠宝携手郭培GUOPEI高定服装 共谱「宝光凝粹,锦绣华裳」
  • OpenCV CUDA模块图像处理------图像融合函数blendLinear()
  • ChatGPT实战嵌入式开发应用指南与代码演示
  • 2025中国主流大模型全景解析:技术路线、场景实践与生态博弈
  • docker中启动 Python 程序并调用某个模块内的函数的方法
  • centos安装locate(快速查找linux文件)
  • SMART原则讲解
  • docker-compose 方式搭建 Jpom
  • 关于线缆行业设备数据采集异构问题的解决
  • 深度思考:摆脱无效忙碌的核心策略
  • 【Typst】2.Typst标记语法和基础样式
  • 7.5- Loading a pretrained LLM
  • Linux 测试本机与192.168.1.130 主机161/udp端口连通性
  • 数组的常用方法有哪些?
  • vSOME/IP与ETAS DSOME/IP通信的问题解决方案
  • 各个主要目录的功能 / Linux 常见指令
  • python实现基于声音识别的腕带式打鼾干预装置设计与实现
  • 合肥能做网站的公司/seo精灵
  • 国内做网站公司排名/网站查询seo
  • 长沙找人做网站/青岛网站权重提升
  • 风水网站开发/中国站长站
  • 做原型的素材网站/百度词条优化工作
  • 嘉兴外贸网站制作/郑州网络营销公司哪家好