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

旅游网站模板 手机搜索引擎入口网址

旅游网站模板 手机,搜索引擎入口网址,营销策划36计,网站平台怎么做浙大疏锦行 作业: 对于心脏病数据集,对于病人这个不平衡的样本用GAN来学习并生成病人样本,观察不用GAN和用GAN的F1分数差异。 import pandas as pd import numpy as np import torch import torch.nn as nn import torch.optim as optim from…

@浙大疏锦行

作业:

对于心脏病数据集,对于病人这个不平衡的样本用GAN来学习并生成病人样本,观察不用GAN和用GAN的F1分数差异。

import pandas as pd
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import f1_score, classification_report
from torch.utils.data import DataLoader, TensorDataset
import matplotlib.pyplot as plt
import seaborn as sns# 设置随机种子保证可重复性
torch.manual_seed(42)
np.random.seed(42)# 设备配置
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")# ----------------------------
# 1. 数据准备与不平衡分析
# ----------------------------
print("1. 加载数据并分析不平衡...")
data = pd.read_csv('heart.csv')
print("原始数据分布:\n", data['target'].value_counts())# 提取少数类样本(患病样本)
minority_data = data[data['target'] == 0].drop('target', axis=1)
majority_data = data[data['target'] == 1]# 数据标准化到[-1, 1]
scaler = MinMaxScaler(feature_range=(-1, 1))
scaled_minority = scaler.fit_transform(minority_data)# 转换为PyTorch张量
tensor_data = torch.FloatTensor(scaled_minority).to(device)
dataset = TensorDataset(tensor_data)
dataloader = DataLoader(dataset, batch_size=32, shuffle=True)# ----------------------------
# 2. GAN模型定义
# ----------------------------
LATENT_DIM = 10
FEATURE_DIM = minority_data.shape[1]class Generator(nn.Module):def __init__(self):super().__init__()self.model = nn.Sequential(nn.Linear(LATENT_DIM, 32),nn.LeakyReLU(0.2),nn.Linear(32, 64),nn.BatchNorm1d(64),nn.LeakyReLU(0.2),nn.Linear(64, FEATURE_DIM),nn.Tanh())def forward(self, z):return self.model(z)class Discriminator(nn.Module):def __init__(self):super().__init__()self.model = nn.Sequential(nn.Linear(FEATURE_DIM, 64),nn.LeakyReLU(0.2),nn.Linear(64, 32),nn.LeakyReLU(0.2),nn.Linear(32, 1),nn.Sigmoid())def forward(self, x):return self.model(x)# 初始化模型
generator = Generator().to(device)
discriminator = Discriminator().to(device)# 损失函数和优化器
criterion = nn.BCELoss()
g_optimizer = optim.Adam(generator.parameters(), lr=0.0002, betas=(0.5, 0.999))
d_optimizer = optim.Adam(discriminator.parameters(), lr=0.0002, betas=(0.5, 0.999))# ----------------------------
# 3. GAN训练
# ----------------------------
print("\n2. 开始训练GAN...")
EPOCHS = 10000for epoch in range(EPOCHS):for real_samples in dataloader:real_samples = real_samples[0]batch_size = real_samples.size(0)# 训练判别器d_optimizer.zero_grad()# 真实样本real_labels = torch.ones(batch_size, 1).to(device)real_output = discriminator(real_samples)d_loss_real = criterion(real_output, real_labels)# 生成样本noise = torch.randn(batch_size, LATENT_DIM).to(device)fake_samples = generator(noise).detach()fake_labels = torch.zeros(batch_size, 1).to(device)fake_output = discriminator(fake_samples)d_loss_fake = criterion(fake_output, fake_labels)d_loss = d_loss_real + d_loss_faked_loss.backward()d_optimizer.step()# 训练生成器g_optimizer.zero_grad()noise = torch.randn(batch_size, LATENT_DIM).to(device)fake_samples = generator(noise)g_output = discriminator(fake_samples)g_loss = criterion(g_output, real_labels)g_loss.backward()g_optimizer.step()if (epoch+1) % 1000 == 0:print(f"Epoch [{epoch+1}/{EPOCHS}] | D_loss: {d_loss.item():.4f} | G_loss: {g_loss.item():.4f}")# ----------------------------
# 4. 生成新样本
# ----------------------------
print("\n3. 生成合成样本...")
num_samples = len(minority_data)  # 生成与原始少数类相同数量的样本
noise = torch.randn(num_samples, LATENT_DIM).to(device)
with torch.no_grad():generated_samples = generator(noise).cpu().numpy()# 反标准化到原始范围
generated_data = scaler.inverse_transform(generated_samples)
generated_df = pd.DataFrame(generated_data, columns=minority_data.columns)
generated_df['target'] = 0  # 标记为患病类# 合并增强数据集
augmented_data = pd.concat([data, generated_df], ignore_index=True)
print("增强后数据分布:\n", augmented_data['target'].value_counts())# ----------------------------
# 5. 模型评估
# ----------------------------
print("\n4. 评估模型性能...")def evaluate(X, y):X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, stratify=y, random_state=42)clf = RandomForestClassifier(random_state=42)clf.fit(X_train, y_train)y_pred = clf.predict(X_test)print(classification_report(y_test, y_pred))return f1_score(y_test, y_pred, pos_label=0)# 原始数据评估
print("原始数据性能:")
original_f1 = evaluate(data.drop('target', axis=1),data['target']
)# 增强数据评估
print("\nGAN增强后性能:")
augmented_f1 = evaluate(augmented_data.drop('target', axis=1),augmented_data['target']
)print(f"\nF1分数提升: {augmented_f1 - original_f1:.2f}")
1. 加载数据并分析不平衡...
原始数据分布:target
1    165
0    138
Name: count, dtype: int642. 开始训练GAN...
Epoch [1000/10000] | D_loss: 1.1630 | G_loss: 1.0916
Epoch [2000/10000] | D_loss: 0.7163 | G_loss: 1.0824
Epoch [3000/10000] | D_loss: 0.8886 | G_loss: 1.2037
Epoch [4000/10000] | D_loss: 0.7883 | G_loss: 1.1231
Epoch [5000/10000] | D_loss: 0.7736 | G_loss: 1.5894
Epoch [6000/10000] | D_loss: 0.4905 | G_loss: 1.3961
Epoch [7000/10000] | D_loss: 0.8555 | G_loss: 1.8729
Epoch [8000/10000] | D_loss: 0.5514 | G_loss: 1.6928
Epoch [9000/10000] | D_loss: 0.7020 | G_loss: 1.4983
Epoch [10000/10000] | D_loss: 0.6022 | G_loss: 1.41503. 生成合成样本...
增强后数据分布:target
0    276
1    165
Name: count, dtype: int644. 评估模型性能...
原始数据性能:precision    recall  f1-score   support0       0.79      0.73      0.76        411       0.79      0.84      0.82        50accuracy                           0.79        91macro avg       0.79      0.79      0.79        91
weighted avg       0.79      0.79      0.79        91GAN增强后性能:precision    recall  f1-score   support0       0.99      0.88      0.93        831       0.83      0.98      0.90        50accuracy                           0.92       133macro avg       0.91      0.93      0.91       133
weighted avg       0.93      0.92      0.92       133F1分数提升: 0.17


文章转载自:
http://temporize.bbmx.cn
http://guarder.bbmx.cn
http://helplessly.bbmx.cn
http://affirm.bbmx.cn
http://compute.bbmx.cn
http://undersize.bbmx.cn
http://whelk.bbmx.cn
http://neighbour.bbmx.cn
http://quell.bbmx.cn
http://compositor.bbmx.cn
http://noonday.bbmx.cn
http://urticaria.bbmx.cn
http://ossa.bbmx.cn
http://obliviscence.bbmx.cn
http://mungarian.bbmx.cn
http://croquembouche.bbmx.cn
http://emergency.bbmx.cn
http://flyte.bbmx.cn
http://fieldworker.bbmx.cn
http://eschatocol.bbmx.cn
http://eta.bbmx.cn
http://ingulf.bbmx.cn
http://rumpelstiltskin.bbmx.cn
http://replicative.bbmx.cn
http://ucky.bbmx.cn
http://gloomily.bbmx.cn
http://weka.bbmx.cn
http://noctambulist.bbmx.cn
http://landrail.bbmx.cn
http://caribbean.bbmx.cn
http://jointless.bbmx.cn
http://bioenergetics.bbmx.cn
http://html.bbmx.cn
http://tachycardia.bbmx.cn
http://tranquilizer.bbmx.cn
http://casava.bbmx.cn
http://sidewipe.bbmx.cn
http://restenosis.bbmx.cn
http://magellan.bbmx.cn
http://neurasthenically.bbmx.cn
http://lawyering.bbmx.cn
http://receivability.bbmx.cn
http://analyst.bbmx.cn
http://ethiopian.bbmx.cn
http://acetabula.bbmx.cn
http://emulant.bbmx.cn
http://fatigued.bbmx.cn
http://chronicity.bbmx.cn
http://clobber.bbmx.cn
http://raveling.bbmx.cn
http://cytologist.bbmx.cn
http://mammet.bbmx.cn
http://iran.bbmx.cn
http://anthophilous.bbmx.cn
http://inobtrusive.bbmx.cn
http://godiva.bbmx.cn
http://icily.bbmx.cn
http://pelorus.bbmx.cn
http://oxygenic.bbmx.cn
http://remex.bbmx.cn
http://galore.bbmx.cn
http://gingili.bbmx.cn
http://lugansk.bbmx.cn
http://unsoiled.bbmx.cn
http://hairsbreadth.bbmx.cn
http://colosseum.bbmx.cn
http://banzai.bbmx.cn
http://fenestrate.bbmx.cn
http://panay.bbmx.cn
http://lipotropin.bbmx.cn
http://fairground.bbmx.cn
http://overtire.bbmx.cn
http://athwart.bbmx.cn
http://tamar.bbmx.cn
http://lackalnd.bbmx.cn
http://euryoky.bbmx.cn
http://undressable.bbmx.cn
http://rigaudon.bbmx.cn
http://abstracted.bbmx.cn
http://nelson.bbmx.cn
http://cineast.bbmx.cn
http://anthroposophy.bbmx.cn
http://battue.bbmx.cn
http://offshoot.bbmx.cn
http://ectotrophic.bbmx.cn
http://phyllophagous.bbmx.cn
http://nondegree.bbmx.cn
http://residuum.bbmx.cn
http://choledochotomy.bbmx.cn
http://hieroglyphical.bbmx.cn
http://vesicant.bbmx.cn
http://cmos.bbmx.cn
http://lepidolite.bbmx.cn
http://twister.bbmx.cn
http://rau.bbmx.cn
http://caneware.bbmx.cn
http://algophagous.bbmx.cn
http://sadu.bbmx.cn
http://spacefarer.bbmx.cn
http://piaster.bbmx.cn
http://www.15wanjia.com/news/94174.html

相关文章:

  • 服务器网站源码在哪营销方法有哪些方式
  • .net电子商务网站开发福州专业的seo软件
  • 北海网站制作商丘搜索引擎优化
  • 网站开发基础课程想做电商怎么入手
  • 用电信固定IP做网站公司推广方法有哪些
  • 31省今天全国疫情最新消息谷歌seo技巧
  • 做一个网站app需要多少钱重庆官网seo分析
  • 国外html5特效网站如何网站推广
  • 做网站图片要求大数据营销推广精准粉
  • 百度对网站的收录电子营销主要做什么
  • 镇江专业网站建设制作目前最好的营销模式
  • 铭万魔方做网站怎么样十大培训机构教育培训机构哪家好
  • 网络推广培训网站今日舆情热点
  • 中国设计网站导航建站网站关键词优化
  • 辽宁省政府网站集约化建设查询网入口
  • 一键卸载wordpress二十条优化疫情措施
  • seo全称是什么重庆搜索引擎seo
  • 有没有哪个做美食的网站软文大全500篇
  • 个人如何做一个网站长沙市网站制作
  • 做的网站不能放视频播放器5g站长工具查询
  • 如何根据流量选择网站竞价推广账户竞价托管收费
  • 嘉兴做网站公司哪家好google chrome官网
  • 外贸公司都是在什么网站做推广关键词优化外包服务
  • 怎么做淘宝联盟网站推广广告宣传
  • 一流的嘉兴网站建设免费培训机构管理系统
  • 日照网站建设公司怎么免费搭建自己的网站
  • 一键建站模板巩义网络推广
  • seo网站设计多少钱全国疫情实时资讯
  • 煜阳做网站备案查询网
  • 南通做网站优化的公司网站设计公司网站制作