4619——Warm up 2

本文介绍了一个基于并查集算法的实现案例,通过该算法解决特定问题。代码使用 C++ 编写,展示了如何初始化并查集、查找根节点及合并节点等功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 并查集

 

#include<iostream>
#include<cstring>
#include<cstdio>
using namespace  std;
int map[110][110];
int father[2100];
int vis[2100];
int getfather(int x)
{
	while(father[x]!=-1)
	{
		x=father[x];
	}
	return x;
}
void Union(int x,int y)
{
	int fx=getfather(x);
	int fy=getfather(y);
	if(fx!=fy)
		father[fx]=fy;
}
int main()
{
    int n,m;
    int x,y;
    while (~scanf("%d%d",&n,&m)&&n+m)
    {
        memset(map,0,sizeof(map));
        memset(father,-1,sizeof(father));
        memset(vis,0,sizeof(vis));
        for (int i = 1; i <= n; i++)
        {
            scanf("%d%d",&x,&y);
            map[x][y]=i;
        }
        for (int i = n+1; i <= n+m; i++)
        {
            scanf("%d%d",&x,&y);
            if (map[x][y])
				Union(map[x][y],i);
            if (x>0&&map[x-1][y])
            	Union(map[x-1][y],i);
            y++;
            if (map[x][y])
    			Union(map[x][y],i);
            if (x>0&&map[x-1][y])
    			Union(map[x-1][y],i);
        }
        for(int i=1;i<=n+m;i++)
        	vis[getfather(i)]++;
       	int ans=0;
       	for(int i=1;i<=n+m;i++)
			ans+=vis[i]/2;
		ans=n+m-ans;
		printf("%d\n",ans);
    }
    return 0;
}


 

### Warmup 学习率调度的作用 Warmup 学习率调度是一种在训练初期使学习率从小值逐渐增加至设定较大值的方法。这种方法能够确保模型在训练早期阶段保持稳定,防止因过高的初始学习率而导致梯度爆炸或其他不稳定的状况发生[^1]。 对于图像分类任务而言,采用此策略可提升最终的准确性,在某些特定网络架构下同样验证了其有效性。当与 Cosine 衰减等其他形式的学习率调整机制联合应用时,能进一步优化整个训练过程中的参数更新效率和效果[^2]。 ### 实现方法 为了更好地理解如何实现 warmup 学习率调度器,这里给出一段 Python 代码作为示例: ```python import math from torch.optim.lr_scheduler import _LRScheduler class WarmUpLR(_LRScheduler): """Warm up learning rate scheduler""" def __init__(self, optimizer, total_iters, last_epoch=-1): self.total_iters = total_iters super().__init__(optimizer, last_epoch) def get_lr(self): return [ base_lr * (float(self.last_epoch + 1) / self.total_iters) for base_lr in self.base_lrs ] def adjust_learning_rate(optimizer, epoch, epochs, lr_init, warm_up_epochs=5): """ Adjusts the learning rate during training. Args: optimizer: Optimizer object used by PyTorch model. epoch: Current epoch number. epochs: Total number of epochs planned for training. lr_init: Initial learning rate after warming up phase ends. warm_up_epochs: Number of epochs dedicated to warming up process. Returns: Updated learning rate value based on current epoch and schedule rules. """ if epoch < warm_up_epochs: alpha = float(epoch) / warm_up_epochs warm-up_factor = min(1., (alpha + 1.) / 2.) new_lr = lr_init * warm_up_factor elif isinstance(lr_decay_milestones, list): # MultiStep LR decay policy gamma = 0.1 ** sum([epoch >= m for m in lr_decay_milestones]) new_lr = max(min_lr, lr_init * gamma) else: # Cosine Annealing LR decay policy cos_inner = (math.pi * (epoch - warm_up_epochs)) / \ (epochs - warm_up_epochs) new_lr = lr_init * ((1 + math.cos(cos_inner)) / 2.) for param_group in optimizer.param_groups: param_group['lr'] = new_lr return new_lr ``` 上述 `adjust_learning_rate` 函数展示了两种常见的学习率衰减政策——多步长(MultiStep)和余弦退火(Cosine Annealing),并结合了一个简单的线性 warmup 过程来初始化学习率。通过这种方式可以在不同的训练阶段灵活控制学习率变化规律,从而达到更好的性能表现。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值