Python打卡第36天

@浙大疏錦行

作業:

對之前的信貸項目,利用神經網絡訓練下,嘗試用到目前的知識點讓代碼更加規范和美觀。

import torch
import torch.nn as nn
import torch.optim as optim
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
import time
import matplotlib.pyplot as plt
from tqdm import tqdm
import pandas as pd
import warningswarnings.filterwarnings("ignore")# 設置GPU設備
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
print(f"使用設備: {device}")# 數據預處理函數
def preprocess_data(data_path):data = pd.read_csv(data_path)# 標簽編碼home_ownership_mapping = {'Own Home': 1, 'Rent': 2, 'Have Mortgage': 3, 'Home Mortgage': 4}data['Home Ownership'] = data['Home Ownership'].map(home_ownership_mapping)years_in_job_mapping = {'< 1 year': 1, '1 year': 2, '2 years': 3, '3 years': 4,'4 years': 5, '5 years': 6, '6 years': 7, '7 years': 8,'8 years': 9, '9 years': 10, '10+ years': 11}data['Years in current job'] = data['Years in current job'].map(years_in_job_mapping)# 獨熱編碼data = pd.get_dummies(data, columns=['Purpose'])# 轉換bool為intfor col in data.select_dtypes(include=['bool']).columns:data[col] = data[col].astype(int)# Term映射term_mapping = {'Short Term': 0, 'Long Term': 1}data['Term'] = data['Term'].map(term_mapping)data.rename(columns={'Term': 'Long Term'}, inplace=True)# 填充缺失值for feature in data.select_dtypes(include=['int64', 'float64']).columns:mode_value = data[feature].mode()[0]data[feature].fillna(mode_value, inplace=True)return data# 加載并預處理數據
data = preprocess_data('data.csv')
X = data.drop('Credit Default', axis=1)
y = data['Credit Default']# 劃分數據集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y
)# 歸一化
scaler = MinMaxScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)# 轉換為Tensor
X_train = torch.FloatTensor(X_train).to(device)
y_train = torch.LongTensor(y_train.values).to(device)
X_test = torch.FloatTensor(X_test).to(device)
y_test = torch.LongTensor(y_test.values).to(device)# 定義模型
class MLP(nn.Module):def __init__(self, input_dim, hidden_dim=10, output_dim=2):super().__init__()self.layers = nn.Sequential(nn.Linear(input_dim, hidden_dim),nn.ReLU(),nn.Linear(hidden_dim, output_dim))def forward(self, x):return self.layers(x)# 初始化模型
input_dim = X_train.shape[1]
model = MLP(input_dim=input_dim, output_dim=2).to(device)  # 二分類問題輸出維度應為2# 損失函數和優化器
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)  # 使用Adam優化器# 訓練參數
num_epochs = 1000
batch_size = 64
n_batches = len(X_train) // batch_size# 訓練循環
losses = []
start_time = time.time()with tqdm(range(num_epochs), desc="訓練進度") as pbar:for epoch in pbar:epoch_loss = 0# 小批量訓練for i in range(n_batches):start = i * batch_sizeend = start + batch_sizebatch_X = X_train[start:end]batch_y = y_train[start:end]# 前向傳播outputs = model(batch_X)loss = criterion(outputs, batch_y)# 反向傳播optimizer.zero_grad()loss.backward()optimizer.step()epoch_loss += loss.item()avg_loss = epoch_loss / n_batcheslosses.append(avg_loss)# 更新進度條pbar.set_postfix({'Loss': f'{avg_loss:.4f}'})print(f'訓練時間: {time.time()-start_time:.2f}秒')# 繪制損失曲線
plt.figure(figsize=(10, 6))
plt.plot(losses)
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.title('Training Loss')
plt.grid(True)
plt.show()# 評估模型
model.eval()
with torch.no_grad():outputs = model(X_test)_, predicted = torch.max(outputs, 1)accuracy = (predicted == y_test).float().mean()print(f'測試集準確率: {accuracy.item()*100:.2f}%')
使用設備: cuda:0
訓練進度: 100%|██████████| 1000/1000 [03:01<00:00,  5.50it/s, Loss=0.4466]
訓練時間: 181.73秒

測試集準確率: 77.20%

代碼耗時過長,進行優化

import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import TensorDataset, DataLoader
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import accuracy_score
import pandas as pd
import numpy as np
import time
from tqdm import tqdm
import matplotlib.pyplot as plt
import warnings# 禁用警告
warnings.filterwarnings("ignore")# 設備配置
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
print(f"使用設備: {device}")# ==================== 數據預處理函數 ====================
def preprocess_data(data_path):"""優化點1:封裝預處理邏輯為函數"""data = pd.read_csv(data_path)# 標簽編碼(優化點2:使用字典映射替代if-else)mapping_dicts = {'Home Ownership': {'Own Home': 1, 'Rent': 2, 'Have Mortgage': 3, 'Home Mortgage': 4},'Years in current job': {'< 1 year': 1, '1 year': 2, '2 years': 3, '3 years': 4,'4 years': 5, '5 years': 6, '6 years': 7, '7 years': 8,'8 years': 9, '9 years': 10, '10+ years': 11},'Term': {'Short Term': 0, 'Long Term': 1}}for col, mapping in mapping_dicts.items():data[col] = data[col].map(mapping)# 獨熱編碼(優化點3:自動處理新特征)data = pd.get_dummies(data, columns=['Purpose'], drop_first=True)# 優化點4:自動類型轉換for col in data.select_dtypes(include=['bool', 'uint8']).columns:data[col] = data[col].astype(int)# 優化點5:統一缺失值處理num_cols = data.select_dtypes(include=['int64', 'float64']).columnsdata[num_cols] = data[num_cols].fillna(data[num_cols].mode().iloc[0])return data# ==================== 數據加載與分割 ====================
data = preprocess_data('data.csv')
X = data.drop('Credit Default', axis=1)
y = data['Credit Default']# 優化點6:分層抽樣保證類別平衡
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y
)# 歸一化(優化點7:避免數據泄露)
scaler = MinMaxScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)# ==================== 模型定義 ====================
class MLP(nn.Module):"""優化點8:參數化模型結構"""def __init__(self, input_dim, hidden_dims=[64, 32], output_dim=2):super().__init__()layers = []prev_dim = input_dim# 動態構建隱藏層for hidden_dim in hidden_dims:layers.extend([nn.Linear(prev_dim, hidden_dim),nn.ReLU(),nn.Dropout(0.3)  # 優化點9:添加Dropout防止過擬合])prev_dim = hidden_dimlayers.append(nn.Linear(prev_dim, output_dim))self.net = nn.Sequential(*layers)def forward(self, x):return self.net(x)# ==================== 訓練配置 ====================
# 轉換為Tensor
X_train_t = torch.FloatTensor(X_train).to(device)
y_train_t = torch.LongTensor(y_train.values).to(device)
X_test_t = torch.FloatTensor(X_test).to(device)
y_test_t = torch.LongTensor(y_test.values).to(device)# 創建DataLoader(優化點10:批處理)
train_dataset = TensorDataset(X_train_t, y_train_t)
train_loader = DataLoader(train_dataset, batch_size=128, shuffle=True)# 初始化模型
model = MLP(input_dim=X_train.shape[1]).to(device)# 損失函數與優化器(優化點11:AdamW + 權重衰減)
criterion = nn.CrossEntropyLoss()
optimizer = optim.AdamW(model.parameters(), lr=0.001, weight_decay=1e-4)# 學習率調度器(優化點12:余弦退火)
scheduler = optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=50)# ==================== 訓練循環 ====================
def train_model(model, train_loader, criterion, optimizer, num_epochs=100):"""優化點13:封裝訓練過程"""train_losses = []best_loss = float('inf')patience, counter = 5, 0pbar = tqdm(range(num_epochs), desc="訓練進度")for epoch in pbar:model.train()epoch_loss = 0for batch_X, batch_y in train_loader:optimizer.zero_grad()outputs = model(batch_X)loss = criterion(outputs, batch_y)loss.backward()optimizer.step()epoch_loss += loss.item()# 計算平均損失avg_loss = epoch_loss / len(train_loader)train_losses.append(avg_loss)# 早停機制(優化點14)if avg_loss < best_loss:best_loss = avg_losscounter = 0torch.save(model.state_dict(), 'best_model.pth')else:counter += 1if counter >= patience:print(f"\n早停觸發,最佳損失: {best_loss:.4f}")break# 更新進度條pbar.set_postfix({'Loss': f'{avg_loss:.4f}','LR': f"{optimizer.param_groups[0]['lr']:.2e}"})scheduler.step()return train_losses# 執行訓練
start_time = time.time()
loss_history = train_model(model, train_loader, criterion, optimizer, num_epochs=100)
print(f"訓練耗時: {time.time()-start_time:.2f}秒")# ==================== 結果可視化 ====================
plt.figure(figsize=(10, 5))
plt.plot(loss_history, label='訓練損失')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.title('訓練損失曲線')
plt.legend()
plt.grid(True)
plt.show()# ==================== 模型評估 ====================
model.load_state_dict(torch.load('best_model.pth'))
model.eval()
with torch.no_grad():y_pred = model(X_test_t)_, predicted = torch.max(y_pred, 1)acc = accuracy_score(y_test, predicted.cpu())print(f"\n測試集準確率: {acc*100:.2f}%")# 優化點15:輸出分類報告
from sklearn.metrics import classification_report
print("\n分類報告:")
print(classification_report(y_test, predicted.cpu()))
使用設備: cuda:0
訓練進度:  33%|███▎      | 33/100 [00:06<00:13,  5.12it/s, Loss=0.4611, LR=2.87e-04]早停觸發,最佳損失: 0.4596
訓練耗時: 6.45秒

測試集準確率: 77.80%分類報告:precision    recall  f1-score   support0       0.77      0.98      0.86      10771       0.83      0.27      0.40       423accuracy                           0.78      1500macro avg       0.80      0.62      0.63      1500
weighted avg       0.79      0.78      0.73      1500

探索性作業(隨意完成)

嘗試進入nn.Module中,查看他的方法

方法一:使用?dir()?查看所有方法和屬性

import torch.nn as nn# 列出 nn.Module 的所有方法和屬性
print(dir(nn.Module))

這會輸出?nn.Module?的所有成員,包括方法、屬性和特殊方法(以?__?開頭和結尾的)。

方法二:使用?help()?查看詳細文檔

help(nn.Module)

這會顯示?nn.Module?的完整文檔,包括方法的詳細說明、參數和返回值。

方法三:查看特定方法的源代碼

如果你想深入了解某個方法的實現,可以使用?inspect?模塊查看源代碼:

import inspect
from torch.nn import Module# 查看 forward 方法的源代碼
print(inspect.getsource(Module.forward))

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/diannao/84462.shtml
繁體地址,請注明出處:http://hk.pswp.cn/diannao/84462.shtml
英文地址,請注明出處:http://en.pswp.cn/diannao/84462.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

全面理解類和對象(下)

文章目錄 再談構造函數初始化列表 static概念&#xff1a; 友元友元函數友元類 內部類再次理解類和對象 再談構造函數 class Date { public:Date(int year, int month, int day){_year year;_month month;_day day;} private:int _year;int _month;int _day; };上述代碼有了…

TomatoSCI分析日記——層次聚類

TomatoSCI分析日記——層次聚類 今天介紹的是一種常見的聚類方法——層次聚類。層次聚類會將數據集劃分成嵌套的簇&#xff0c;形成一個層次結構&#xff08;樹狀圖&#xff09;&#xff0c;經常用于探究樣本的相似性。用大白話來說&#xff0c;就是&#xff1a;我有一大堆樣品…

mysql都有哪些鎖?

MySQL中的鎖機制是確保數據庫并發操作正確性和一致性的重要組成部分&#xff0c;根據鎖的粒度、用途和特性&#xff0c;可以分為多種類型。以下是MySQL中常見的鎖及其詳細說明&#xff1a; 一、按鎖的粒度劃分 行級鎖&#xff08;Row-level Locks&#xff09; 描述&#xff1a;…

flutter 項目調試、flutter run --debug調試模式 devtools界面說明

Flutter DevTools 網頁界面說明 1. 頂部導航欄 Inspector&#xff1a;查看和調試 Widget 樹&#xff0c;實時定位 UI 問題。Performance-- 性能分析面板&#xff0c;查看幀率、CPU 和 GPU 使用情況&#xff0c;識別卡頓和性能瓶頸。Memory-- 內存使用和對象分配分析&#xff…

使用Kotlin創建Spring Boot用戶應用項目

項目初始化與配置 通過Spring Initializr創建Kotlin項目 若需使用Kotlin語言開發Spring Boot應用(假設已安裝Kotlin環境),可通過start.spring.io進行項目初始化。在項目創建頁面需進行以下關鍵配置: 語言選擇:切換至Kotlin選項項目元數據:需填寫Group(如com.apress.us…

【Linux網絡篇】:Socket網絡套接字以及簡單的UDP網絡程序編寫

?感謝您閱讀本篇文章&#xff0c;文章內容是個人學習筆記的整理&#xff0c;如果哪里有誤的話還請您指正噢? ? 個人主頁&#xff1a;余輝zmh–CSDN博客 ? 文章所屬專欄&#xff1a;Linux篇–CSDN博客 文章目錄 網絡編程套接字一.預備知識1.理解源IP地址和目的IP地址2.認識端…

Python爬蟲實戰:研究Newspaper框架相關技術

1. 引言 1.1 研究背景與意義 互聯網的快速發展使得新聞信息呈現爆炸式增長&#xff0c;如何高效地獲取和分析這些新聞數據成為研究熱點。新聞爬蟲作為一種自動獲取網頁內容的技術工具&#xff0c;能夠幫助用戶從海量的互聯網信息中提取有價值的新聞內容。本文基于 Python 的 …

【node.js】實戰項目

個人主頁&#xff1a;Guiat 歸屬專欄&#xff1a;node.js 文章目錄 1. 項目概覽與架構設計1.1 實戰項目&#xff1a;企業級電商管理系統1.2 技術棧選擇 2. 項目初始化與基礎架構2.1 項目結構設計2.2 基礎配置管理 3. 用戶服務實現3.1 用戶服務架構3.2 用戶模型設計3.3 用戶服務…

Mybatis框架的構建(IDEA)

選擇maven項目 修改設置 在設置中添加自定義代碼模板 開始寫代碼 動態SQL語句的示例&#xff1a; pom文件&#xff1a; <?xml version"1.0" encoding"UTF-8"?> <project xmlns"http://maven.apache.org/POM/4.0.0"xmlns:xsi"…

經濟法-6-公司法律制度知識點

一、出資期限 1.有限責任公司&#xff1a;全體股東需在公司成立之日起5年內繳足認繳的注冊資本 2.股份有限公司&#xff1a;以發起方式設立的&#xff0c;發起人需在公司登記前實繳全部股款 3.認繳期加速到期 公司不能清償到期債務的&#xff0c;公司或者已到期債權的債權人…

jquery.table2excel方法導出

jquery提供了一個table2excel方法可以用來導出頁面到xls等 $("#grid_595607").table2excel({exclude: ".noExport", // 排除類名為 noExport 的元素filename: "導出數據.xls",exclude_img: true, // 不導出圖片exclude_links: true, // 不導…

echarts設置標線和最大值最小值

echarts設置標線和最大值最小值 基本ECharts圖表初始化配置 設置動態的y軸范圍&#xff08;min/max值&#xff09; 通過markPoint標記最大值和最小值點 使用markLine添加水平參考線 配置雙y軸圖表 自定義標記點和線的樣式&#xff08;顏色、符號等&#xff09; 響應式調整圖表大…

Java文件操作:從“Hello World”到“Hello File”

&#x1f50d; 開發者資源導航 &#x1f50d;&#x1f3f7;? 博客主頁&#xff1a; 個人主頁&#x1f4da; 專欄訂閱&#xff1a; JavaEE全棧專欄 文件 什么是文件&#xff1f; 廣義&#xff1a;操作系統進行資源管理的一種機制&#xff0c;很多的軟件/硬件資源&#xff0c;…

2025第三屆黃河流域網絡安全技能挑戰賽--Crypto--WriteUp

2025第三屆黃河流域網絡安全技能挑戰賽–Crypto–WriteUp Crypto sandwitch task from Crypto.Util.number import * import gmpy2 flag bflag{fake_flag} assert len(flag) 39 p getPrime(512) q getPrime(512) n p * q e 0x3 pad1 beasy_problem pad2 bHow_to_so…

三重天理論

第一重天&#xff1a;公理層&#xff08;形而上地基&#xff09; 這里構建的是人類理性的"操作系統"&#xff0c;公理作為不證自明的邏輯起點&#xff08;如矛盾律/同一律&#xff09;&#xff0c;恰似海德格爾所說的"存在之鏡"。黑格爾辯證法在此顯現為動…

2025年第八屆廣西大學生程序設計大賽(正式賽)題解(更新中)

知乎評價&#xff1a;如何評價2025年第八屆GXCPC廣西大學生程序設計大賽暨中國-東盟國際大學生程序設計大賽&#xff1f; 榜單&#xff1a;牛客比賽排名 題目鏈接&#xff1a;第八屆廣西大學生程序設計大賽暨2025邀請賽 TIP&#xff1a;提交處可查看別人過題代碼 難度簽到題普通…

WHAT - 兆比特每秒 vs 兆字節每秒

文章目錄 Mbps 解釋Mbps 和 MB/s&#xff08;兆字節每秒&#xff09;換算總結網絡場景1. 在路由器設置中的 Mbps2. 在游戲下載時的 Mbps / MB/s總結 Mbps 解釋 首先&#xff0c;Mbps 是一個常見的網絡帶寬單位&#xff0c;意思是&#xff1a; Megabits per second&#xff08;…

[C語言實戰]C語言內存管理實戰:實現自定義malloc與free(四)

[C語言實戰]C語言內存管理實戰&#xff1a;實現自定義malloc與free&#xff08;四&#xff09; 摘要&#xff1a;通過實現簡化版的內存管理器&#xff0c;深入理解動態內存分配的核心原理。本文包含內存塊設計、分配算法、空閑合并策略的完整實現&#xff0c;并附可運行的代碼…

YOLOv8源碼修改(5)- YOLO知識蒸餾(下)設置蒸餾超參數:以yolov8-pose為例

目錄 前言 1. 不同蒸餾算法資源占用 2. 不動態調整蒸餾損失 2.1 訓練定量化結果 2.1 訓練結果可視化結果 3. 動態調整蒸餾損失權重及實驗分析 3.1 余弦衰減和指數衰減 3.2 CWD蒸餾損失 3.3 MGD蒸餾損失 3.4 AT蒸餾損失 3.5 SKD和PKD蒸餾損失 4. 調權重心得總結 5…

歷年華東師范大學保研上機真題

2025華東師范大學保研上機真題 2024華東師范大學保研上機真題 2023華東師范大學保研上機真題 在線測評鏈接&#xff1a;https://pgcode.cn/school?classification1 簡單一位數代數式計算 題目描述 給一個小學生都會算的1位數與1位數運算的代數式&#xff0c;請你求出這個表…