【chatgpt】train_split_test的random_state

在使用train_test_split函数划分数据集时,random_state参数用于控制随机数生成器的种子,以确保划分结果的可重复性。这样,无论你运行多少次代码,只要使用相同的random_state值,得到的训练集和测试集划分就会是一样的。

使用 train_test_split 示例

以下是一个示例,展示如何使用train_test_split函数进行数据集划分,并设置random_state参数:
程序输出结果
Training set shape: (80, 10), (80,)
Test set shape: (20, 10), (20,)

import numpy as np
from sklearn.model_selection import train_test_split

# 假设我们有一些数据
X = np.random.rand(100, 10)  # 100个样本,每个样本10个特征
y = np.random.randint(0, 2, 100)  # 100个样本的标签(0或1)

# 使用train_test_split进行数据集划分
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 打印划分后的数据集形状
print(f'Training set shape: {X_train.shape}, {y_train.shape}')
print(f'Test set shape: {X_test.shape}, {y_test.shape}')

在这个示例中:

  • X 是特征矩阵,包含100个样本,每个样本有10个特征。
  • y 是标签数组,包含100个样本的标签。
  • test_size=0.2 表示将数据集的20%用作测试集,剩下的80%用作训练集。
  • random_state=42 用于确保划分的可重复性。

为什么使用 random_state

使用 random_state 可以确保在多次运行代码时,得到的训练集和测试集划分是一致的,这在以下情况下特别有用:

  1. 调试和开发: 在开发和调试模型时,使用相同的 random_state 可以确保数据划分的一致性,从而使得调试更加容易。
  2. 实验的可重复性: 在进行实验时,使用相同的 random_state 可以确保实验结果的可重复性,使得其他人可以验证你的结果。
  3. 比较模型性能: 在比较不同模型的性能时,使用相同的 random_state 可以确保每个模型都使用相同的训练集和测试集,从而使比较更加公平。
    在这里插入图片描述

示例:比较大数据集和小数据集的模型性能

假设我们有一个大数据集和一个小数据集,我们想要比较它们在同一模型上的性能。我们可以使用 train_test_split 进行数据集划分,并设置 random_state 以确保划分的可重复性。

import torch
import torch.nn as nn
import torch.optim as optim
from sklearn.model_selection import train_test_split
from torch.utils.data import DataLoader, TensorDataset
import matplotlib.pyplot as plt
import numpy as np
# 创建大数据集和小数据集
X_large = np.random.rand(1000, 10)
y_large = np.random.rand(1000, 1)

X_small = np.random.rand(100, 10)
y_small = np.random.rand(100, 1)

# 使用train_test_split进行数据集划分
X_train_large, X_test_large, y_train_large, y_test_large = train_test_split(X_large, y_large, test_size=0.2, random_state=42)
X_train_small, X_test_small, y_train_small, y_test_small = train_test_split(X_small, y_small, test_size=0.2, random_state=42)

# 转换为张量
X_train_large = torch.tensor(X_train_large, dtype=torch.float32)
y_train_large = torch.tensor(y_train_large, dtype=torch.float32)
X_test_large = torch.tensor(X_test_large, dtype=torch.float32)
y_test_large = torch.tensor(y_test_large, dtype=torch.float32)

X_train_small = torch.tensor(X_train_small, dtype=torch.float32)
y_train_small = torch.tensor(y_train_small, dtype=torch.float32)
X_test_small = torch.tensor(X_test_small, dtype=torch.float32)
y_test_small = torch.tensor(y_test_small, dtype=torch.float32)

# 创建数据加载器
train_loader_large = DataLoader(TensorDataset(X_train_large, y_train_large), batch_size=32, shuffle=True)
test_loader_large = DataLoader(TensorDataset(X_test_large, y_test_large), batch_size=32, shuffle=False)

train_loader_small = DataLoader(TensorDataset(X_train_small, y_train_small), batch_size=32, shuffle=True)
test_loader_small = DataLoader(TensorDataset(X_test_small, y_test_small), batch_size=32, shuffle=False)

# 定义简单的线性模型
class SimpleModel(nn.Module):
    def __init__(self):
        super(SimpleModel, self).__init__()
        self.linear = nn.Linear(10, 1)
    
    def forward(self, x):
        return self.linear(x)

# 训练模型的通用函数
def train_model(train_loader, num_epochs=50, learning_rate=0.01):
    model = SimpleModel()
    criterion = nn.MSELoss()
    optimizer = optim.SGD(model.parameters(), lr=learning_rate)

    train_losses = []

    for epoch in range(num_epochs):
        model.train()
        epoch_train_loss = 0.0
        for batch_x, batch_y in train_loader:
            outputs = model(batch_x)
            loss = criterion(outputs, batch_y)
            optimizer.zero_grad()
            loss.backward()
            optimizer.step()
            epoch_train_loss += loss.item()
        epoch_train_loss /= len(train_loader)
        train_losses.append(epoch_train_loss)

        print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {epoch_train_loss:.4f}')

    return model, train_losses

# 训练大数据集的模型
print("Training on large dataset")
model_large, train_losses_large = train_model(train_loader_large)

# 训练小数据集的模型
print("\nTraining on small dataset")
model_small, train_losses_small = train_model(train_loader_small)

# 绘制训练损失曲线
plt.figure(figsize=(12, 6))
plt.plot(range(1, len(train_losses_large) + 1), train_losses_large, label='Large Dataset Train Loss')
plt.plot(range(1, len(train_losses_small) + 1), train_losses_small, label='Small Dataset Train Loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
plt.title('Training Loss Comparison')
plt.savefig("test")

# 在测试集上计算最终的评估指标(例如均方误差)
def evaluate_model(model, test_loader):
    model.eval()
    test_loss = 0.0
    criterion = nn.MSELoss()
    with torch.no_grad():
        for batch_x, batch_y in test_loader:
            outputs = model(batch_x)
            loss = criterion(outputs, batch_y)
            test_loss += loss.item()
    test_loss /= len(test_loader)
    return test_loss

# 评估大数据集的模型
final_test_loss_large = evaluate_model(model_large, test_loader_large)

# 评估小数据集的模型
final_test_loss_small = evaluate_model(model_small, test_loader_small)

print(f'Final Test Loss on Large Dataset: {final_test_loss_large:.4f}')
print(f'Final Test Loss on Small Dataset: {final_test_loss_small:.4f}')

结果分析

通过上述代码,可以得到大数据集和小数据集在训练过程中的损失曲线以及最终的测试损失。根据这些信息,可以比较它们的收敛情况和性能。

  • 损失曲线: 通过观察损失曲线,判断模型在两个数据集上的收敛速度和稳定性。如果两者曲线形状相似,并且在同一水平上趋于平稳,可以认为它们收敛到了相似的程度。

  • 最终测试损失: 最终测试损失值可以用于直接比较两个模型的性能。如果两者最终测试损失值接近,则可以认为它们的模型性能相当。

通过使用相同的 random_state 值,确保数据集划分的一致性,从而使得比较结果更加公平和具有可重复性。

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

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

Linux_软硬链接

目录 1、软链接 2、软链接的使用方式 3、软链接的删除 4、硬链接 5、硬链接的使用方式 6、软硬链接的使用场景 7、软硬链接的区别 结语 前言: 在Linux操作系统中,有软链接和硬链接,他们是一种特殊的文件引用,主要用于与…

破碎的像素地牢探险:游戏分享

软件介绍 《破碎的像素地牢》是开源一款地牢冒险探索类的游戏,融合了日系RPG经典风格,玩家将控制主角进行未知场景的探索。除了经典地牢玩法外,游戏还添加了更多创意内容,如黑屏状态前的挑战性等,使得游戏更加富有挑战…

git 初基本使用-----------笔记

Git命令 下载git 打开Git官网(git-scm.com),根据自己电脑的操作系统选择相应的Git版本,点击“Download”。 基本的git命令使用 可以在项目文件下右击“Git Bash Here” ,也可以命令终端下cd到指定目录执行初始化命令…

【React】登录-封装Token的存取删方法--共享复用

在token.js中 // 封装存取方法const TOKENKEY token_keyfunction setToken (token) {return localStorage.setItem(TOKENKEY, token) }function getToken () {return localStorage.getItem(TOKENKEY) }function clearToken () {return localStorage.removeItem(TOKENKEY) }ex…

springboot3多模块实践

先帖下目录结构&#xff0c;直接在idea里面新建就行&#xff0c;删掉多余的文件 子模块的新建 根目录pom文件&#xff0c;注意modules、packaging&#xff0c;dependencyManagement统一管理依赖&#xff0c;子模块添加依赖的时候就不用加版本号 <?xml version"1.0…

富文本编辑器CKEditor

介绍 富文本编辑器不同于文本编辑器,它提供类似于 Microsoft Word 的编辑功能 在Django中,有可以现成的富文本三方模块django-ckeditor,具体安排方式: pip install django-ckeditor==6.5.1官网:Django CKEditor — Django CKEditor 6.7.0 documentation 使用方式 创建项…

I2C总线8位IO扩展器PCF8574

PCF8574用于I2C总线的远程8位I/O扩展器 PCF8574国产有多个厂家有替代产品&#xff0c;图示为其中一款HT8574 1 产品特点 低待机电流消耗&#xff1a;10 uA&#xff08;最大值&#xff09; I2C 转并行端口扩展器 漏极开路中断输出 与大多数微控制器兼容 具有大电流驱动能力的闭…

在linux系统中使用docker、mysql实例

systemctl 是一个命令行工具&#xff0c;用于控制和管理基于 systemd 的 Linux 发行版中的系统和服务。 启动服务 &#xff1a;使用 systemctl start [service-name] 开始一个服务。 如启动docker&#xff1a;systemctl start docker 停止服务 &#xff1a;使用 systemctl st…

JAVA期末复习题1

目录 Java 填空题整理及解析 1. 说出Java的特点&#xff1a; 2. Java的运行机制是先编译再解释运行。 3. 请按照以下分类补全对应的数据类型&#xff1a; 4. 在有限次数循环时&#xff0c;一般选择for循环结构&#xff1b;未知循环次数时&#xff0c;可以选择while循环结构…

预备资金有5000-6000买什么电脑比较好?大学生电脑选购指南

小新pro14 2024 处理器&#xff1a;采用了英特尔酷睿Ultra5 125H或Ultra9 185H两种处理器可选&#xff0c;这是英特尔最新的高性能低功耗处理器&#xff0c;具有18个线程&#xff0c;最高可达4.5GHz的加速频率&#xff0c;支持PCIe 4.0接口&#xff0c;内置了强大的ARC核芯显卡…

如何使用ig507金融数据库的股票接口,股票API来获取MACD指标

一、MACD指标简介 MACD&#xff08;Moving Average Convergence Divergence&#xff0c;移动平均收敛/发散&#xff09;是一种趋势跟踪动量指标&#xff0c;用于分析股票或其他金融产品的价格趋势。MACD由两部分组成&#xff1a;差离值&#xff08;DIF&#xff09;和信号线&am…

【FreeRTOS】任务管理与调度

文章目录 调度&#xff1a;总结 调度&#xff1a; 相同优先级的任务轮流运行最高优先级的任务先运行 可以得出结论如下&#xff1a; a 高优先级的任务在运行&#xff0c;未执行完&#xff0c;更低优先级的任务无法运行b 一旦高优先级任务就绪&#xff0c;它会马上运行&#xf…

笔记本更换固态,保留数据,无需重装系统和软件

一、问题描述&#xff1a; 原有一块128GB的固态硬盘作为c盘使用&#xff0c;由于工作学习需要&#xff0c;经常跑虚拟机&#xff0c;现在需要升级容量。 二、解决思路&#xff1a; 硬件 购买一款大容量的固态硬盘 不同的容量有不同的价格&#xff0c;这个根据预算和实际需要来…

Android,RPC原理,C语言实现Binder跨进程通信Demo

RPC原理图 Binder C语言层的Demo演示 新建目录 把两个文件拷贝到我们的Demo下面 1.binder_server.c #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <linux/types.h> #include <stdbool.h> #include <string.h> #…

odoo的采购询价单,默认情况下显示‘draft‘,‘sent‘,‘purchase‘,请问什么情况下才会显示‘to approve‘?

odoo的采购询价单&#xff0c;默认情况下显示’draft’,‘sent’,‘purchase’&#xff0c;请问什么情况下才会显示’to approve’? 见下图&#xff1a; 这与操作人员的角色是相关的&#xff1a; 当操作人员是群组 “采购 / 用户”时&#xff0c;点击“confirm order/确认订…

越复杂的CoT越有效吗?Complexity-Based Prompting for Multi-step Reasoning

Complexity-Based Prompting for Multi-step Reasoning 论文&#xff1a;https://openreview.net/pdf?idyf1icZHC-l9 Github&#xff1a;https://github.com/FranxYao/chain-of-thought-hub 发表位置&#xff1a;ICLR 2023 Complexity-Based Prompting for Multi-step Reason…

【C语言】算法:二分查找

当我们想在一个有序的序列里面查找一个数字的时候&#xff0c;通常会想到使用循环遍历&#xff0c;也就是下面这种方法&#xff1a; 比如我们想在下面的数组里面找到7&#xff1a; int main() {int num 7;int arr[10] { 1,2,3,4,5,6,7,8,9,10 };for (int i 0; i < size…

5.树莓派4b+ubuntu18.04(ros版本melodic)+arduino mega自制两轮差速小车,实现建图导航功能

这一节介绍雷达的使用&#xff0c;我们使用的雷达型号是ydlidar x3 1.进入工作空间 cd catkin_ws/src2.下载官方提供的SDK文件 git clone https://github.com/YDLIDAR/YDLidar-SDK.git3.安装cmake sudo apt install cmake pkg-config4.编译和安装 进入YDLidar-SDK文件夹后如…

Linux动态网站架构(部署开发php代码)

动态网站架构&#xff08;部署开发php代码&#xff09; 测试能否直接部署nginx需要什么服务&#xff0c;及原理准备并进行开发测试部署代码 概述 静态网站&#xff1a;图片仅仅包含&#xff1a;html&#xff0c;css样式js脚本&#xff0c;图片及视频&#xff1b;nginx直接处…

DHCP原理1-单个局域网出现多个DHCP服务器会发生什么

1. 背景 DHCP全称是Dynamic Host Configuration Protocol。其协议标准是RFC1541&#xff08;已被RFC2131取代&#xff09;&#xff0c;主要实现服务器向客户端动态分配IP地址&#xff08;如IP地址、子网掩码、网关、DNS&#xff09;和配置信息。其系统架构是标准的C/S架构。RFC…