You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

tqdm进度条重复显示求助:如何实现单条进度条更新

问题:tqdm进度条每次迭代重复显示,如何让进度更新到第一条进度条?

我尝试了多种方法,但tqdm进度条在每次迭代时都会重新显示。如何让所有进度都更新至代码下方的第一条进度条?是不是pbar.update(1)的位置不对?

import numpy as np
import pandas as pd
import tensorflow as tf
from tensorflow import keras
from sklearn.model_selection import train_test_split
from tqdm import tqdm
from sklearn.metrics import mean_squared_error

# Initialize RSI-related variables
rsi_values = []

# Define the parameters
num_epochs = 40
batch_size = 64
initial_balance_usd = 110000  # Initial balance in USD
minimum_buy_fee = 52  # Minimum buy fee
buy_fee_percentage = 0.03  # Buy fee percentage
minimum_sell_fee = 63  # Minimum sell fee
sell_fee_percentage = 0.027  # Sell fee percentage
rsi_period = 14  # RSI calculation period (e.g., 14 days)

# Define a list of sequence lengths to experiment with
input_sequence_lengths = [16]

# Define URLs for historical data of different time series
urls = [
    ["C:/Users/max2/Desktop/12.xlsx", 2],
]

total_iterations = 50

# Define a list of weight_rsi values to experiment with
weight_rsi_values = [0.1, 0.2, 0.3, 0.4, 0.5]

# Initialize a dictionary to store results for each weight_rsi value
results = {}

# Initialize the progress bar at the very top
with tqdm(total=total_iterations, desc="Processing") as pbar:
    for weight_rsi in weight_rsi_values:
        pbar.update(1)
        print(f"Training with weight_rsi={weight_rsi:.10f}")
        # Loop through each URL and process the data separately
        for url_info in urls:
            print(f"Processing data from URL: {url_info}")
            url = url_info[0]
            action = url_info[1]

            if action == 0:
                print(f"Executing command A for URL: {url}")
                df = pd.read_csv(url, header=None, skiprows=1)
            elif action == 2:
                df = pd.read_excel(url, skiprows=1) 
            else:
                print(f"Executing command B for URL: {url}")
                df = pd.read_excel(url, header=None, skiprows=1)

            # Rest of your data processing and modeling code goes here

            # Access the second column (all rows) and convert it to a list
            if action == 2:
                column_b_values = df.iloc[:, 1].tolist()
            else:    
                column_b_values = df.iloc[:, 1].tolist()

            # Initialize RSI-related variables
            price_changes = np.diff(column_b_values)
            gains = price_changes.clip(min=0)
            losses = -price_changes.clip(max=0)

            avg_gain = np.mean(gains[:rsi_period])
            avg_loss = np.mean(losses[:rsi_period])

            # Train and evaluate the models for each sequence length
            for sequence_length in input_sequence_lengths:
                print(f"Training and evaluating model for sequence length: {sequence_length}")

解决方法

核心问题分析

  1. print语句破坏进度条渲染:普通print会强制换行,导致tqdm进度条被挤到新行,看起来像是重复显示。
  2. 总迭代数与实际循环不匹配:你设置total_iterations = 50,但实际总循环次数是len(weight_rsi_values)*len(urls)*len(input_sequence_lengths)=511=5,进度条逻辑完全混乱。
  3. update位置错误:你只在最外层循环更新进度,但实际每个sequence_length循环才是一个完整的迭代单元。

具体修复步骤

1. 替换print为tqdm.write()

tqdm提供的pbar.write()方法可以在不干扰进度条的情况下输出日志,不会导致进度条换行。

2. 修正总迭代数

动态计算实际总迭代次数,避免硬编码错误:

total_iterations = len(weight_rsi_values) * len(urls) * len(input_sequence_lengths)

3. 调整update位置

把pbar.update(1)移到最内层循环末尾,确保每个完整任务完成后才更新进度。

修改后的完整代码

import numpy as np
import pandas as pd
import tensorflow as tf
from tensorflow import keras
from sklearn.model_selection import train_test_split
from tqdm import tqdm
from sklearn.metrics import mean_squared_error

# Initialize RSI-related variables
rsi_values = []

# Define the parameters
num_epochs = 40
batch_size = 64
initial_balance_usd = 110000  # Initial balance in USD
minimum_buy_fee = 52  # Minimum buy fee
buy_fee_percentage = 0.03  # Buy fee percentage
minimum_sell_fee = 63  # Minimum sell fee
sell_fee_percentage = 0.027  # Sell fee percentage
rsi_period = 14  # RSI calculation period (e.g., 14 days)

# Define a list of sequence lengths to experiment with
input_sequence_lengths = [16]

# Define URLs for historical data of different time series
urls = [
    ["C:/Users/max2/Desktop/12.xlsx", 2],
]

# Define a list of weight_rsi values to experiment with
weight_rsi_values = [0.1, 0.2, 0.3, 0.4, 0.5]

# 动态计算实际总迭代数
total_iterations = len(weight_rsi_values) * len(urls) * len(input_sequence_lengths)

# Initialize a dictionary to store results for each weight_rsi value
results = {}

# Initialize the progress bar at the very top
with tqdm(total=total_iterations, desc="Processing") as pbar:
    for weight_rsi in weight_rsi_values:
        pbar.write(f"Training with weight_rsi={weight_rsi:.10f}")
        # Loop through each URL and process the data separately
        for url_info in urls:
            pbar.write(f"Processing data from URL: {url_info}")
            url = url_info[0]
            action = url_info[1]

            if action == 0:
                pbar.write(f"Executing command A for URL: {url}")
                df = pd.read_csv(url, header=None, skiprows=1)
            elif action == 2:
                df = pd.read_excel(url, skiprows=1) 
            else:
                pbar.write(f"Executing command B for URL: {url}")
                df = pd.read_excel(url, header=None, skiprows=1)

            # Rest of your data processing and modeling code goes here

            # Access the second column (all rows) and convert it to a list
            if action == 2:
                column_b_values = df.iloc[:, 1].tolist()
            else:    
                column_b_values = df.iloc[:, 1].tolist()

            # Initialize RSI-related variables
            price_changes = np.diff(column_b_values)
            gains = price_changes.clip(min=0)
            losses = -price_changes.clip(max=0)

            avg_gain = np.mean(gains[:rsi_period])
            avg_loss = np.mean(losses[:rsi_period])

            # Train and evaluate the models for each sequence length
            for sequence_length in input_sequence_lengths:
                pbar.write(f"Training and evaluating model for sequence length: {sequence_length}")
                # 每个完整迭代单元完成后更新进度条
                pbar.update(1)

额外注意事项

  • 后续新增的日志输出都要用pbar.write(),禁止使用普通print。
  • 如果后续代码有更多内层逻辑,确保update放在每个需要计数的独立任务结束后。

内容的提问来源于stack exchange,提问作者user865044

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 10:23:16