rate = (step + 1) / len(train_loader) a = "*" * int(rate * 50) b = "." * int((1 - rate) * 50) print("\rtrain loss: {:^3.0f}%[{}->{}]{:.4f}".format(int(rate * 100), a, b, loss), end="") print()
时间: 2024-03-31 12:38:51 浏览: 39
这段代码用于在训练过程中动态地展示当前训练进度和损失函数值。
首先,我们计算当前mini-batch在所有mini-batch中所占的比例rate,即(rate+1)/len(train_loader)。然后,我们使用"*"和"."来表示当前训练进度,其中"*"表示已经训练的部分,"."表示还未训练的部分。
接着,我们使用print函数输出当前训练进度和损失函数值。其中,格式化字符串"{:^3.0f}%[{}->{}]{:.4f}"表示输出的字符串包含四个变量,分别是当前训练进度、"*"和"."的组合、"."和"*"的组合、当前mini-batch的损失函数值。其中,"{:^3.0f}%"表示将当前训练进度格式化为一个居中对齐的整数百分比,"{:.4f}"表示将损失函数值格式化为一个保留4位小数的浮点数。
最后,我们使用end=""来避免print函数输出换行符,从而达到动态展示训练进度和损失函数值的效果。
相关问题
下面代码转化为paddle2.2.2代码 :from __future__ import division import os, time, scipy.io import torch import torch.nn as nn import torch.optim as optim import numpy as np import glob import cv2 import argparse from PIL import Image from skimage.measure import compare_psnr,compare_ssim from tensorboardX import SummaryWriter from models import RViDeNet from utils import * parser = argparse.ArgumentParser(description='Pretrain denoising model') parser.add_argument('--gpu_id', dest='gpu_id', type=int, default=0, help='gpu id') parser.add_argument('--num_epochs', dest='num_epochs', type=int, default=33, help='num_epochs') parser.add_argument('--patch_size', dest='patch_size', type=int, default=128, help='patch_size') parser.add_argument('--batch_size', dest='batch_size', type=int, default=1, help='batch_size') args = parser.parse_args() os.environ["CUDA_VISIBLE_DEVICES"] = str(args.gpu_id) save_dir = './pretrain_model' if not os.path.isdir(save_dir): os.makedirs(save_dir) gt_paths1 = glob.glob('./data/SRVD_data/raw_clean/MOT17-02_raw/*.tiff') gt_paths2 = glob.glob('./data/SRVD_data/raw_clean/MOT17-09_raw/*.tiff') gt_paths3 = glob.glob('./data/SRVD_data/raw_clean/MOT17-10_raw/*.tiff') gt_paths4 = glob.glob('./data/SRVD_data/raw_clean/MOT17-11_raw/*.tiff') gt_paths = gt_paths1 + gt_paths2 + gt_paths3 + gt_paths4 ps = args.patch_size # patch size for training batch_size = args.batch_size # batch size for training
把原始代码转换为PaddlePaddle 2.2.2 的代码如下:
```python
import os
import time
import argparse
import glob
import cv2
import numpy as np
from PIL import Image
from skimage.measure import compare_psnr, compare_ssim
from tensorboardX import SummaryWriter
from models import RViDeNet
from utils import *
import paddle
from paddle import nn
from paddle.optimizer import optim
paddle.set_device('gpu')
parser = argparse.ArgumentParser(description='Pretrain denoising model')
parser.add_argument('--gpu_id', dest='gpu_id', type=int, default=0, help='gpu id')
parser.add_argument('--num_epochs', dest='num_epochs', type=int, default=33, help='num_epochs')
parser.add_argument('--patch_size', dest='patch_size', type=int, default=128, help='patch_size')
parser.add_argument('--batch_size', dest='batch_size', type=int, default=1, help='batch_size')
args = parser.parse_args()
save_dir = './pretrain_model'
if not os.path.isdir(save_dir):
os.makedirs(save_dir)
gt_paths1 = glob.glob('./data/SRVD_data/raw_clean/MOT17-02_raw/*.tiff')
gt_paths2 = glob.glob('./data/SRVD_data/raw_clean/MOT17-09_raw/*.tiff')
gt_paths3 = glob.glob('./data/SRVD_data/raw_clean/MOT17-10_raw/*.tiff')
gt_paths4 = glob.glob('./data/SRVD_data/raw_clean/MOT17-11_raw/*.tiff')
gt_paths = gt_paths1 + gt_paths2 + gt_paths3 + gt_paths4
ps = args.patch_size # patch size for training
batch_size = args.batch_size # batch size for training
num_epochs = args.num_epochs
train_dataset = DatasetDenoising(gt_paths, ps=ps)
train_loader = paddle.io.DataLoader(train_dataset, batch_size=batch_size, shuffle=True, num_workers=4)
model = RViDeNet()
model.train()
optimizer = optim.Adam(learning_rate=1e-4, parameters=model.parameters())
writer = SummaryWriter()
for epoch in range(num_epochs):
epoch_start_time = time.time()
epoch_loss = 0
for i, (noisy_patches, gt_patches) in enumerate(train_loader()):
noisy_patches = paddle.to_tensor(noisy_patches)
gt_patches = paddle.to_tensor(gt_patches)
output = model(noisy_patches)
loss = nn.functional.mse_loss(output, gt_patches)
optimizer.clear_grad()
loss.backward()
optimizer.step()
epoch_loss += loss
epoch_time = time.time() - epoch_start_time
epoch_loss = epoch_loss / len(train_loader)
print("Epoch [{}/{}] Loss: {:.5f} [{:.2f}s]".format(epoch + 1, num_epochs, epoch_loss, epoch_time))
writer.add_scalar("Loss/train", epoch_loss, epoch + 1)
if (epoch + 1) % 10 == 0:
model_path = os.path.join(save_dir, 'RViDeNet_epoch{}.pdparams'.format(epoch + 1))
paddle.save(model.state_dict(), model_path)
print("Saving model to: {}".format(model_path))
writer.close()
```
dataset = CocoDetection(root=r'D:\file\study\data\COCO2017\train2017', annFile=r'D:\file\study\data\COCO2017\annotations\instances_train2017.json', transforms=transforms.Compose([transforms.ToTensor()])) # 定义训练集和测试集的比例 train_ratio = 0.8 test_ratio = 0.2 # 计算训练集和测试集的数据数量 num_data = len(dataset) num_train_data = int(num_data * train_ratio) num_test_data = num_data - num_train_data # 使用random_split函数将数据集划分为训练集和测试集 train_dataset, test_dataset = random_split(dataset, [num_train_data, num_test_data]) # 打印训练集和测试集的数据数量 print(f"Number of training data: {len(train_dataset)}") print(f"Number of test data: {len(test_dataset)}") train_loader = DataLoader(train_dataset, batch_size=8, shuffle=True, num_workers=0) test_loader = DataLoader(test_dataset, batch_size=8, shuffle=True, num_workers=0) # define the optimizer and the learning rate scheduler params = [p for p in model.parameters() if p.requires_grad] optimizer = torch.optim.SGD(params, lr=0.005, momentum=0.9, weight_decay=0.0005) lr_scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=3, gamma=0.1) # train the model for 10 epochs num_epochs = 10 for epoch in range(num_epochs): # 将模型设置为训练模式 model.train() # 初始化训练损失的累计值 train_loss = 0.0 # 构建一个迭代器,用于遍历数据集 for i, images, targets in train_loader: print(images) print(targets) # 将数据转移到设备上 images = list(image.to(device) for image in images) targets = [{k: v.to(device) for k, v in t.items()} for t in targets]上述代码报错:TypeError: call() takes 2 positional arguments but 3 were given
这个错误是因为在你的数据读取过程中,`train_loader`返回了三个值,包括索引、图像和目标,但是你在迭代器中只使用了后两个值。为了解决这个问题,你可以修改迭代器的定义,将索引也加入到迭代器中,如下所示:
```python
for i, (images, targets) in enumerate(train_loader):
# do something with images and targets
```
这样,你就可以使用`enumerate`函数获取每个批次数据的索引,同时获取图像和目标。同时,如果你希望在训练过程中输出批次数据的索引,你也可以在代码中加入打印语句,如下所示:
```python
for i, (images, targets) in enumerate(train_loader):
print(f"Batch {i}:")
# do something with images and targets
```
希望这可以帮助你解决问题。
阅读全文