zzh980711 2023-05-31 08:07 采纳率: 0%
浏览 13

python 涉及循环的问题

Python问题,想实现这样一段代码,大家帮忙看看错误。

  1. 导入所需的库。
  2. 设置要处理的文件夹路径(dir_path)。
  3. 遍历文件夹中的所有Excel文件。
  4. 对每个Excel文件中的工作表执行以下操作:
    a. 按照表的顺序读取Excel文件
    b. 对数据进行预处理(排序、切分训练和测试集)(除最后一张表外的表前3/4为训练集,后1/4为测试集,最后一张表除最后一行外前3/4为训练集,后1/4为测试集)
    c. 对第一个工作表(第一个文件)进行超参数调整,以选择最佳的XGBoost模型。
    d. 依次对其他工作表应用已选定的XGBoost模型,读取到最后一个工作表时进行预测。
    e. 评估模型性能(均方根误差、平均绝对误差和R²得分)。
    f. 将结果输出到控制台。
  5. 画出特征重要性图。
  6. 当所有工作表处理完成后,打印"程序结束"。

代码如图所示

import os
import pandas as pd
import xgboost as xgb
from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score
from sklearn.model_selection import GridSearchCV
from xgboost import plot_importance
import matplotlib.pyplot as plt
import numpy as np
dir_path = 'F:/Test/Test/Test/Test/Test'
excel_files = [os.path.join(dp, f) for dp, dn, filenames in os.walk(dir_path) for f in filenames if f.endswith('.xlsx')]
for file in excel_files:
    xls = pd.ExcelFile(file)
    df_old = pd.DataFrame()
    for sheet_name in xls.sheet_names:
        df = pd.read_excel(xls, sheet_name=sheet_name)
        df = df.sort_values(by='日期')
        testing_cutoff = int(0.75 * len(df))
        train_df, test_df = df[:testing_cutoff], df[testing_cutoff:]

        if sheet_name == xls.sheet_names[0] and file == excel_files[0]:
            x_train, y_train = train_df.iloc[:, 6:21], train_df.iloc[:, 21]
            x_test, y_test = test_df.iloc[:, 6:21], test_df.iloc[:, 21]
            #超参数调整
            params = {
                'learning_rate': [0.01, 0.05, 0.1, 0.2, 0.3],
                'max_depth': [3, 4, 5, 6, 7],
                'n_estimators': [50, 100, 150, 200, 250],
                'gamma': [0, 0.01, 0.05, 0.1, 0.2],
            }
            # 创建XGB回归器实例
            xgb_model = xgb.XGBRegressor(objective='reg:squarederror')
            # 创建网格搜索实例
            grid_search = GridSearchCV(xgb_model, params, scoring='neg_mean_squared_error', cv=5)
            #使网格搜索适合训练数据
            grid_search.fit(x_train, y_train)
            # 从网格搜索中检索最佳模型
            xgb_model = grid_search.best_estimator_
        else:
            if sheet_name == xls.sheet_names[-1]:  # 检查这是否是当前Excel文件中的最后一张工作表
                x_train, y_train = df.iloc[:, 6:21], df.iloc[:, 21]  # 训练集
                x_p = df.iloc[-1, 6:21]  # 最后需要练习的数据为测试集
                x_test, y_test = df.iloc[:-1, 6:21], df.iloc[:-1, 21]  # 使用除最后一行以外的所有行作为测试集
            else:
                x_train, y_train = train_df.iloc[:, 6:21], train_df.iloc[:, 21]
                x_test, y_test = test_df.iloc[:, 6:21], test_df.iloc[:, 21]

            df = pd.concat([df_old, df], ignore_index=True)
            df = df.sort_values(by='日期')
            testing_cutoff = int(0.75 * len(df))
            train_df, test_df = df[:testing_cutoff], df[testing_cutoff:]
            x_train, y_train = train_df.iloc[:, 6:21], train_df.iloc[:, 21]
            x_test, y_test = test_df.iloc[:, 6:21], test_df.iloc[:, 21]
            xgb_model.fit(x_train, y_train)

        y_pred = xgb_model.predict(x_test)
        y_p = xgb_model.predict(np.array([x_p]))[0]
        mse = mean_squared_error(y_test, y_pred)
        mae = mean_absolute_error(y_test, y_pred)
        r2 = r2_score(y_test, y_pred)
        df_old = df.copy()
        if sheet_name == xls.sheet_names[-1]:  # 检查这是否是当前Excel文件中的最后一张工作表
            print(f"Final metrics for {sheet_name} in file {file}:")
            print(f"Final metrics: RMSE: {np.sqrt(mse):.5f}, MAE: {mae:.5f}, R^2: {r2:.5f}")
            print(f"预测收益率为: rp: {y_p:.5f}")
        else:
            pass
    plot_importance(xgb_model)
    plt.show()
print("程序结束")

报错的原因是x_p未命名,应该和循环赋值有关,我改了半天很能实现我想要的效果,希望大家能帮帮我

  • 写回答

2条回答 默认 最新

  • 阳光宅男xxb 2023-05-31 08:38
    关注

    你的x_p这个变量是在内层第二个循环里面申明使用的,但是你再循环外面又想使用x_p,导致报错x_p未命名,如果你想使用x_p,那就需要在第二循环外面先申明x_p = []

    评论

报告相同问题?

问题事件

  • 创建了问题 5月31日

悬赏问题

  • ¥15 CPU卡指令整合指令数据都在图片上
  • ¥15 火车票关联12306问题
  • ¥15 odoo17处理受托加工产品
  • ¥15 如何用MATLAB编码图三的积分
  • ¥15 圆孔衍射光强随孔径变化
  • ¥15 MacBook pro m3max上用vscode运行c语言没有反应
  • ¥15 ESP-PROG配置错误,ALL ONES
  • ¥15 结构功能耦合指标计算
  • ¥50 AI大模型精调(百度千帆、飞浆)
  • ¥15 非科班怎么跑代码?如何导数据和调参