← 返回题库
初级

存货估测:R²拟合优度计算与解读

未完成
初级参考 完整示例代码供参考,建议自己理解后重新输入
"""
金融风险管理 - q031
存货估测:R²拟合优度计算与解读
"""

metadata = {
    "id": "q031",
    "title": "存货估测:R²拟合优度计算与解读",
    "module": "存货估测与回归分析",
    "difficulty": "beginner",
    "data_files": ["case33_fry_cost.csv"],
    "skills": ["R²计算", "拟合优度", "模型评估"],
    "estimated_minutes": 10
}

"""
【题目】
读取case33_fry_cost.csv,计算线性回归模型的R²(拟合优度)。

步骤:
1. 建立Y(book_cost)对X(cumulative_3yr_stocking)的线性回归
2. 计算预测值 Y_hat
3. 计算R² = 1 - SS_res / SS_tot
   SS_res = sum((Y - Y_hat)²)
   SS_tot = sum((Y - Y_mean)²)

输出字符串(保留4位小数):
R²(拟合优度): {r2}
相关系数r: {r}
模型解释力: 强(R²>0.8)/ 中(0.5~0.8)/ 弱(<0.5)
"""

def solve():
    import pandas as pd
    import numpy as np
    from pyodide.http import open_url
    from io import StringIO

    BASE_URL = "https://data.zuihe.com/finance/"
    df = pd.read_csv(StringIO(open_url(BASE_URL + "case33_fry_cost.csv").read()))

    x = df['cumulative_3yr_stocking'].values
    y = df['book_cost'].values

    coeffs = np.polyfit(x, y, 1)
    y_hat = np.polyval(coeffs, x)

    ss_res = np.sum((y - y_hat) ** 2)
    ss_tot = np.sum((y - y.mean()) ** 2)
    r2 = round(1 - ss_res / ss_tot, 4)
    r = round(np.corrcoef(x, y)[0, 1], 4)

    if r2 > 0.8:
        strength = '强'
    elif r2 > 0.5:
        strength = '中'
    else:
        strength = '弱'

    lines = [
        f"R²(拟合优度): {r2}",
        f"相关系数r: {r}",
        f"模型解释力: {strength}(R²={r2})",
    ]
    return '
'.join(lines)

if __name__ == "__main__":
    print(solve())

示例

输入
solve()
期望输出
R²(拟合优度): 0.9087 | 相关系数r: -0.9533 | 模型解释力: 强(R²=0.9087)
Python 代码 🔒 登录后使用
🔒

登录后即可练习

注册免费账号,在浏览器中直接运行 Python 代码