本文将详细解析如何使用生成对抗网络(GAN)来生成彩票号码。我们将介绍代码的每个部分,并给出详细注释,帮助读者理解整个过程。效果如下:
 
导入依赖
首先,我们需要导入所需的库。
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader, TensorDataset
from collections import deque
这些库包括:
- numpy和- pandas:用于数据处理和分析。
- torch:用于构建和训练神经网络。
- collections.deque:用于实现滑动窗口记录。
加载和预处理数据
我们从 Excel 文件中加载彩票数据,并对数据进行预处理。
# 加载数据
file_path = './dlts.xlsx'
data = pd.read_excel(file_path)
# 数据预处理:拆分前区和后区号码并合并为一个数据集,然后进行归一化处理
front_area_numbers = data['前区'].str.split(' ', expand=True).astype(int)
back_area_numbers = data['后区'].str.split(' ', expand=True).astype(int)
# 归一化处理
front_area_numbers = (front_area_numbers - 1) / 34.0  # 前区号码范围1-35,归一化到0-1
back_area_numbers = (back_area_numbers - 1) / 11.0   # 后区号码范围1-12,归一化到0-1
# 合并前区和后区的号码
all_numbers = pd.concat([front_area_numbers, back_area_numbers], axis=1).values
all_numbers = torch.tensor(all_numbers, dtype=torch.float32)
代码解析
-  加载数据: - 使用 pandas库从 Excel 文件中加载数据。
 
- 使用 
-  数据预处理: - 拆分前区和后区号码,并将其转换为整数。
- 对号码进行归一化处理,使其值在 0 到 1 之间。
 
-  合并数据: - 合并前区和后区号码,形成一个完整的数据集。
- 将数据转换为 PyTorch 张量,以便于后续处理。
 
构建生成器模型
生成器模型的作用是生成彩票号码。我们使用了一个简单的全连接神经网络,其中包含多个层和激活函数。
# 构建生成器模型
class Generator(nn.Module):
    def __init__(self, input_dim, output_dim):
        super(Generator, self).__init__()
        self.model = nn.Sequential(
            nn.Linear(input_dim, 256),
            nn.LeakyReLU(0.2),
            nn.BatchNorm1d(256),
            nn.Linear(256, 512),
            nn.LeakyReLU(0.2),
            nn.BatchNorm1d(512),
            nn.Linear(512, 1024),
            nn.LeakyReLU(0.2),
            nn.BatchNorm1d(1024),
            nn.Linear(1024, output_dim),
            nn.Sigmoid()  # 使用sigmoid激活函数,将输出限制在0到1之间
        )
    
    def forward(self, x):
        return self.model(x)
代码解析
-  类定义和初始化: - Generator类继承自- nn.Module。
- 初始化方法定义了网络结构,包括输入层、隐藏层和输出层。
 
-  网络结构: - nn.Sequential用于顺序地定义网络层。
- 每一层包含一个全连接层 (nn.Linear),一个 LeakyReLU 激活函数 (nn.LeakyReLU),和一个批量归一化层 (nn.BatchNorm1d)。
- 输出层使用 Sigmoid 激活函数,将输出限制在 0 到 1 之间。
 
构建判别器模型
判别器模型的作用是判断生成的号码是否真实。它也是一个全连接神经网络。
# 构建判别器模型
class Discriminator(nn.Module):
    def __init__(self

















