基于transformer预测双色球(代码+数据+一键可运行)

news2024/10/7 8:30:56

 对AI炒股感兴趣的小伙伴可加WX群:

1、引言

在这期内容中,我们将暂时将股票搁置一旁,转而探索人工智能技术如何应用于另一个有趣的领域:预测未来双色球号码

2、AI与双色球预测的关系

在彩票预测中,AI充当着数据分析和模式识别的角色。虽然无法确保百分之百准确的结果,但它为增加预测的洞察力和理解提供了全新的途径。

3、数据收集与处理

首先,下载2005年至今的所有开奖号码。

预处理之后形成以下数据集,前面6个数是红球而第7个数是蓝球

4、预测模型

我们采用神经网络算法中最先进的Transformer作为模型,但是在输入模型之前,我们需要进行一些预处理,具体如下:

1、数字表示转化为独热编码:我们需要将数字表示转换为独热编码,以便让AI能够更好地学习。我们采用以下方式进行独热编码:

图片

这样,原本每期7个数字的数据将被转换成每期49个独热编码。

2、数据和制作标签:我们的模型应该被设计成:输入过去29天的历史数据,形成的独热编码,来预测未来下一次的独热编码。为实现这个理念,我们对数据进行了滑窗提取,每次滑窗提取过去29天的历史数据,并对应需要预测的未来一天的真实值。具体代码如下:

df = pd.read_csv('./basedata.csv').dropna()
train_df = np.array(df)
samples = []
label = []
for j in range(len(train_df)):
    if j > 27:
        feat = train_df[j - 28:j + 1][:, 2:]
        l = train_df[j - 27:j + 2][-1:, 2:]
        samples.append(feat)
        label.append(l)
DATA = np.array(samples).astype(int)
LABEL = np.array(label).astype(int)
LABEL = np.squeeze(LABEL, axis=(1,))

独热编码处理:

num_classes_first_six = 33
num_classes_last_one = 16
encoded_data = np.zeros((DATA.shape[0], DATA.shape[1], num_classes_first_six + num_classes_last_one), dtype=int)
for i in range(DATA.shape[0]):
    for j in range(DATA.shape[1]):
        for k in range(DATA.shape[2]):
            num = int(DATA[i, j, k])
            if k < 6:
                encoded_data[i, j, num - 1] = 1
            else:
                encoded_data[i, j, num_classes_first_six + num - 1] = 1
train_D = torch.tensor(encoded_data, dtype=torch.float32)
num_classes_first_six = 33
num_classes_last_one = 16
encoded_data = np.zeros((LABEL.shape[0], num_classes_first_six + num_classes_last_one), dtype=int)
for i in range(LABEL.shape[0]):
    for j in range(LABEL.shape[1]):
        num = int(LABEL[i, j])
        if j < 6:
            encoded_data[i, num - 1] = 1
        else:
            encoded_data[i, num_classes_first_six + num - 1] = 1
train_L = torch.tensor(encoded_data, dtype=torch.float32)

3、基于PyTorch框架,由于我们的输入维度是49,我们选择了以下参数:

图片

进入Transformer解码之后,我们会对高阶特征进行降维,将特征区间映射到标签区间。我们的标签区间同样是一个49的独热编码。

具体步骤如下:

图片

5、AI学习情况

我们采用前3000期彩票数据进行训练,而将后续的彩票期数用于测试。

测试结果如下所示:

图片

总结:在经过大约100个epoch的训练后,模型达到了约0.15的相关性水平。随后的训练导致了过拟合现象的出现,因此我们建议考虑提前停止训练,以避免过拟合的问题。

6、应用

由于预测值是一个49的独热矩阵,我们要将其转化成数字表示,我爬取最近29天的数据特征,预测2023-08-22的号码为:

图片

大胆试试!!!!期待今天开奖!hahahahahahaha

希望强大的transformer高阶表示能学到双色球的生成规律。

数据在这里下载:百度网盘 请输入提取码

提取码:1234

完整训练代码:


import numpy as np
import pandas as pd
import torch
from sklearn import metrics
import matplotlib.pyplot as plt
import torchvision.transforms as transforms
from torch.utils.data import DataLoader, Dataset
from torchvision.transforms import Normalize
from sklearn.model_selection import KFold
import torch
import torch.nn as nn
from torch.utils.data import DataLoader, TensorDataset, Dataset
from torch.optim import lr_scheduler
from tqdm import tqdm
from sklearn.metrics import precision_recall_curve, auc
from torch.utils.data import TensorDataset, DataLoader, WeightedRandomSampler
import time
from tqdm import tqdm

device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")

df = pd.read_csv('./basedata.csv').dropna()
train_df = np.array(df.iloc[:-300])
samples = []
label = []
for j in range(len(train_df)):
    if j > 27:
        feat = train_df[j - 28:j + 1][:, 2:]
        l = train_df[j - 27:j + 2][-1:, 2:]
        samples.append(feat)
        label.append(l)
DATA = np.array(samples).astype(int)
LABEL = np.array(label).astype(int)
LABEL = np.squeeze(LABEL, axis=(1,))

num_classes_first_six = 33
num_classes_last_one = 16
encoded_data = np.zeros((DATA.shape[0], DATA.shape[1], num_classes_first_six + num_classes_last_one), dtype=int)
for i in range(DATA.shape[0]):
    for j in range(DATA.shape[1]):
        for k in range(DATA.shape[2]):
            num = int(DATA[i, j, k])
            if k < 6:
                encoded_data[i, j, num - 1] = 1
            else:
                encoded_data[i, j, num_classes_first_six + num - 1] = 1
train_D = torch.tensor(encoded_data, dtype=torch.float32)
num_classes_first_six = 33
num_classes_last_one = 16
encoded_data = np.zeros((LABEL.shape[0], num_classes_first_six + num_classes_last_one), dtype=int)
for i in range(LABEL.shape[0]):
    for j in range(LABEL.shape[1]):
        num = int(LABEL[i, j])
        if j < 6:
            encoded_data[i, num - 1] = 1
        else:
            encoded_data[i, num_classes_first_six + num - 1] = 1
train_L = torch.tensor(encoded_data, dtype=torch.float32)

test_df = np.array(df.iloc[-300:])
samples = []
label = []
for j in range(len(test_df)):
    if j > 27:
        feat = test_df[j - 28:j + 1][:, 2:]
        samples.append(feat)
        label.append(test_df[j - 27:j + 2][-1:, 2:])
DATA = np.array(samples).astype(int)
LABEL = np.array(label).astype(int)
LABEL = np.squeeze(LABEL, axis=(1,))

num_classes_first_six = 33
num_classes_last_one = 16
encoded_data = np.zeros((DATA.shape[0], DATA.shape[1], num_classes_first_six + num_classes_last_one), dtype=int)
for i in range(DATA.shape[0]):
    for j in range(DATA.shape[1]):
        for k in range(DATA.shape[2]):
            num = int(DATA[i, j, k])
            if k < 6:
                encoded_data[i, j, num - 1] = 1
            else:
                encoded_data[i, j, num_classes_first_six + num - 1] = 1

test_D = torch.tensor(encoded_data, dtype=torch.float32)
num_classes_first_six = 33
num_classes_last_one = 16
encoded_data = np.zeros((LABEL.shape[0], num_classes_first_six + num_classes_last_one), dtype=int)
for i in range(LABEL.shape[0]):
    for j in range(LABEL.shape[1]):
        num = int(LABEL[i, j])
        if j < 6:
            encoded_data[i, num - 1] = 1
        else:
            encoded_data[i, num_classes_first_six + num - 1] = 1
test_L = torch.tensor(encoded_data, dtype=torch.float32)



batch_size = 100
learning_rate = 0.001
num_epochs = 200
MODEL = '1.0'

dataset_train = TensorDataset(train_D, train_L)
dataset_val = TensorDataset(test_D, test_L)
# dataset_val = TensorDataset(train_D, train_L)
train_loader = DataLoader(dataset_train, shuffle=True, batch_size=batch_size)
val_loader = DataLoader(dataset_val, shuffle=True, batch_size=batch_size)


class model(nn.Module):

    def __init__(self,
                 fc1_size=400,
                 fc2_size=200,
                 fc3_size=100,
                 fc1_dropout=0.2,
                 fc2_dropout=0.2,
                 fc3_dropout=0.2,
                 num_of_classes=50):
        super(model, self).__init__()

        self.f_model = nn.Sequential(
            nn.Linear(1421, fc1_size),  # 887
            nn.BatchNorm1d(fc1_size),
            nn.ReLU(),
            nn.Dropout(fc1_dropout),
            nn.Linear(fc1_size, fc2_size),
            nn.BatchNorm1d(fc2_size),
            nn.ReLU(),
            nn.Dropout(fc2_dropout),
            nn.Linear(fc2_size, fc3_size),
            nn.BatchNorm1d(fc3_size),
            nn.ReLU(),
            nn.Dropout(fc3_dropout),
            nn.Linear(fc3_size, 49),
        )


        d_model = 49  # 模型的维度
        nhead = 7  # 多头注意力的头数
        num_encoder_layers = 6  # 编码器层数
        num_decoder_layers = 6  # 解码器层数

        # 创建Transformer模型
        self.transformer = nn.Transformer(d_model=d_model, nhead=nhead,
                                          num_encoder_layers=num_encoder_layers,
                                          num_decoder_layers=num_decoder_layers)

        for name, module in self.named_modules():
            if isinstance(module, nn.Linear):
                nn.init.kaiming_normal_(module.weight, mode='fan_in', nonlinearity='relu')
            if isinstance(module, nn.Conv2d):
                nn.init.kaiming_normal_(module.weight, mode='fan_in', nonlinearity='relu')
            if isinstance(module, nn.Conv1d):
                nn.init.kaiming_normal_(module.weight, mode='fan_in', nonlinearity='relu')


    def forward(self, x):

        input_tensor = x.permute(1, 0, 2)  # 转换为(seq_len, batch_size, features)
        target_tensor = input_tensor.clone()
        output = self.transformer(input_tensor, target_tensor)
        output = output.permute(1, 0, 2)
        output= torch.reshape(output, (output.shape[0], output.shape[1] * output.shape[2]))


        out = self.f_model(output)
        return out


model = model()
model.to(device)
criterion = nn.MSELoss()
# optimizer = torch.optim.AdamW(model.parameters(), lr=learning_rate)
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate, betas=(0.9, 0.98), weight_decay=1e-5)
scheduler = lr_scheduler.CosineAnnealingLR(optimizer, T_max=10)


L_train = []
L_val = []
AUC = []
PRAUC = []
min_validation_loss = 9999
for epoch in range(num_epochs):
    torch.nn.utils.clip_grad_norm_(model.parameters(), 0.5)
    train_running_loss = 0.0
    counter = 0
    model.train()
    for seq, y in tqdm(train_loader):
        counter += 1
        output = model(seq.to(device))
        loss = criterion(output, y.to(device))
        train_running_loss += loss.item()
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
    scheduler.step()
    TL = train_running_loss / counter
    L_train.append(TL)
    model.eval()
    PREDICT = []
    TRUE = []
    counter = 0
    with torch.no_grad():
        current_test_loss = 0.0
        for SEQ, Z in tqdm(val_loader):
            counter += 1
            output = model(SEQ.to(device))
            loss = criterion(output, Z.to(device))
            current_test_loss += loss.item()
            PREDICT.extend(output.cpu().numpy())
            TRUE.extend(Z.cpu().numpy())
        T_loss = current_test_loss / counter
        L_val.append(T_loss)
        PP = np.array(PREDICT)
        TT = np.array(TRUE)
        flattened_array1 = PP.flatten()
        flattened_array2 = TT.flatten()
        correlation_matrix = np.corrcoef(flattened_array1, flattened_array2)
        pr_auc = correlation_matrix[0, 1]
        print("Train loss: ", TL, "Val loss: ", T_loss, 'correlation_value', pr_auc)
        AUC.append(pr_auc)
        if min_validation_loss > T_loss:
            min_validation_loss = T_loss
            best_epoch = epoch
            print('Max pr_auc ' + str(min_validation_loss) + ' in epoch ' + str(best_epoch))
            torch.save(model.state_dict(), fr"./model_{MODEL}.pt")

fig1, ax1 = plt.subplots()
ax1.plot(L_train)
ax1.set_xlabel('Epoch')
ax1.set_ylabel('Training Loss')

fig2, ax2 = plt.subplots()
ax2.plot(L_val)
ax2.set_xlabel('Epoch')
ax2.set_ylabel('Validation Loss')

fig3, ax3 = plt.subplots()
ax3.plot(AUC)
ax3.set_xlabel('Epoch')
ax3.set_ylabel('Validation Loss')

fig1.savefig(f"./{MODEL}_1.png")
fig2.savefig(f"./{MODEL}_2.png")
fig3.savefig(f"./{MODEL}_3.png")


本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/912919.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

QRadioButton

QRadioButton API使用方式 QRadioButton是Qt提供的单选按钮, 一般都是以组的方式来使用(多个按钮中同时只能选中其中一个) 如果单选按钮被选中, 再次点击这个按钮选中状态是不能被取消的 API // 构造函数 /* 参数:- text: 按钮上显示的标题- parent: 按钮的父对象 */ QRadio…

SpringBoot3.x原生镜像-Native Image实践

前提 之前曾经写过一篇《SpringBoot3.x 原生镜像-Native Image 尝鲜》&#xff0c;当时SpringBoot处于3.0.0-M5版本&#xff0c;功能尚未稳定。这次会基于SpringBoot当前最新的稳定版本3.1.2详细分析Native Image的实践过程。系统或者软件版本清单如下&#xff1a; 组件版本备注…

【已解决】Linux中启动docker 出现 ‘ Failed to start docker.service: Unit not found. ’ 错误

启动docker 出现 ‘ Failed to start docker.service: Unit not found. ’ 错误 这是因为缺少 rhel-push-plugin.socket 单元&#xff0c;该单元是rhel-push-plugin软件包的一部分。所以我们执行以下指令就可以成功解决&#xff1a; curl -sSL https://get.docker.com/ | sh 执…

学习平台助力职场发展与提升

近年来&#xff0c;随着互联网技术的发展&#xff0c;学习平台逐渐成为了职场发展和提升的必备工具。学习平台通过提供丰富的课程内容、灵活的学习时间和个性化的学习路径&#xff0c;帮助职场人士更好地提升自己的技能和知识储备&#xff0c;为职场发展打下坚实的基础。 学习…

mysql 8.0 窗口函数 之 分布函数 与 sql server (2017以后支持) 分布函数 一样

mysql 分布函数 percent_rank&#xff08;&#xff09; &#xff1a;等级值 百分比cume_dist() &#xff1a;累积分布值 percent_rank&#xff08;&#xff09; 计算方式 (rank-1)/(rows-1)&#xff0c; 其中 rank 的值为使用RANK()函数产生的序号&#xff0c;rows 的值为当前…

并查集及其简单应用

文章目录 一.并查集二.并查集的实现三.并查集的基本应用 一.并查集 并查集的逻辑结构:由多颗不相连通的多叉树构成的森林(一个这样的多叉树就是森林的一个连通分量) 并查集的元素(树节点)用0~9的整数表示,并查集可以表示如下: 并查集的物理存储结构:并查集一般采用顺序结构实…

Springboot 项目配置Swagger2

1. 加入swagger 依赖 springboot 项目的 pom.xml 中添加下列依赖&#xff1a; <dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger2</artifactId><version>2.9.2</version> </dependency> <depe…

Postgresql部署及简单操作

目录 1、介绍 2、什么是PostgreSQL 3、PostgreSQL 的特点 4、数据库定为 5、环境准备 6、编译安装 6.1 安装依赖包 6.2 下载安装包 6.3 创建用户 6.4 创建 postgresql数据目录并授权 6.5 上传压缩包并解压 6.6 编译postgresql源码 6.7 配置环境变量 6.8 初始化数…

使用 wxPython 和 pymupdf进行 PDF 加密

PDF 文件是一种常见的文档格式&#xff0c;但有时候我们希望对敏感信息进行保护&#xff0c;以防止未经授权的访问。在本文中&#xff0c;我们将使用 Python 和 wxPython 库创建一个简单的图形用户界面&#xff08;GUI&#xff09;应用程序&#xff0c;用于对 PDF 文件进行加密…

2023年你会选择哪种编程语言?

2023年你会选择哪种编程语言&#xff1f; 关于编程语言的个人见解。 KOTLIN&#xff1a;由于其先进的多平台能力&#xff0c;未来5年内它很可能成为开发任何类型的客户端应用&#xff08;移动端、桌面端或Web端&#xff09;的首选编程语言。他们正在为iOS和WebAssembly开发的…

power designer 反向工程过程已中断,原因是某些字符无法通过ANSI-->UTF-16转换进行映射

起因&#xff1a;sqlserver导入sql时报错&#xff0c;一查询是power designer 反向工程过程已中断&#xff0c;原因是。某些字符无法通过ANSI-->UTF-16转换进行映射&#xff08;会导致数据丢失&#xff09; 解决办法&#xff1a; 导入成功

【Vue】全家桶之vue-Router

文章目录 概述后端路由前端路由Vue Router安装 vue-router 的常见用法路由懒加载路由重定向嵌套路由动态路由匹配 声明式导航 & 编程式导航声明式导航编程式导航 导航守卫全局前置守卫守卫方法的 3 个形参next 函数的 3 种调用方式控制后台主页的访问权限 路由的两种工作模…

骨传导耳机音质好吗?骨传导耳机音质和普通耳机对比哪个好?

相信不少朋友还是比较排斥骨传导耳机的&#xff0c;并不是说骨传导技术不成熟&#xff0c;而是骨传导对技术的要求实在太高了&#xff0c;尤其是对音质以及防漏音的考验。作为一款新兴产品&#xff0c;骨传导耳机打破了传统的传音模式&#xff0c;由空气传导&#xff0c;转变为…

element上传图片,调取接口传值,参数FormData为空

需求 输入完reason&#xff0c;选完文件后&#xff0c;点击提交按钮后 调取接口。 遇到的问题 上传文件orderFile 字段一直为空 打印了发现&#xff0c;上传文件也是有值得。但是传到接口中就为空 原因 json里边不能放file&#xff0c;但是formData里可以放 file 也可以放…

每个世界500强公司,都遇到过增长瓶颈

在《财富》100强公司的增长历程分析中&#xff0c;最容易得出的结论是大部分大型企业都曾经历过一段停滞期。这些公司的规模大小各不相同&#xff0c;尽管绝大部分停滞都发生在收入10亿—100亿美元之间的公司内&#xff0c;但任何规模的企业都有可能出现增长停滞。这是因为&…

C++学习第十五天----循环和文本输入

昨天说到使用cin进行键盘输入的一些弊端&#xff0c;那么怎么解决呢&#xff1f; 1.使用cin.get&#xff08;char&#xff09;进行补救 使用下面这句代码替换掉cin >> ch;,这样就会回显空格&#xff1b; cin.get(ch);//读取输入中的下一个字符&#xff08;即使它是空格&…

LeetCode——二叉树片(七)

刷题顺序及思路来源于代码随想录&#xff0c;网站地址&#xff1a;https://programmercarl.com 目录 617. 合并二叉树 700. 二叉搜索树中的搜索 98. 验证二叉搜索树 530. 二叉搜索树的最小绝对差 501. 二叉搜索树中的众数 617. 合并二叉树 给你两棵二叉树&#xff1a; …

leetcode 309. 买卖股票的最佳时机含冷冻期

2023.8.22 本题是买卖股票系列 冷冻期。 由于引入了冷冻期&#xff0c;并且这个冷冻期是在卖出股票才会出现&#xff0c;因此我dp数组设置了四种状态&#xff1a; 状态一&#xff1a;持有股票。状态二&#xff1a;不持有股票&#xff1a; 之前就卖了&#xff0c;所以今天不处…

小区新冠疫情管理系统的设计与实现/基于springboot的小区疫情管理系统

摘要 采用更加便于维护和使用的Java语言&#xff0c;其可拓展性高且更富于表现力&#xff0c;基于mysql数据库、Springboot框架开发的小区新冠疫情管理系统&#xff0c;方便用户查看物资信息、疫苗信息。通过Eclipse来进行网页编程&#xff0c;其方便易用、移植适用性广、更加安…

【JVM】对String::intern()方法深入详解(JDK7及以上)一文搞懂

文章目录 1、什么是intern&#xff1f;2、经典例题解释例1例2例3 1、什么是intern&#xff1f; String::intern()是一个本地方法&#xff0c;它的作用是如果字符串常量池中已经包含一个等于此String对象的字符串&#xff0c;则返回代表池中这个字符串的String对象的引用&#…