【问题标题】:How to run multiple regressions using a for loop?如何使用 for 循环运行多个回归?
【发布时间】:2021-02-18 06:59:07
【问题描述】:

我有一个包含多个城市、一个响应变量和一个预测变量的数据集。我正在尝试对每个城市进行回归。这不仅返回我一行数据,而且返回系数为 NaN。

train_output = pd.DataFrame(columns = ['intercept','coefficient','r2'])

for cit in train.city.unique():

    y = train[train['city']==cit]['response']

    y = np.array(y.values.tolist())

    x = train[data['city']==cit]['predictor']

    x = np.array(x).reshape((len(x), 1))

    model = LinearRegression().fit(x, y)

    model_output = {'intercept':model.intercept_,'coefficient':model.coef_[0], 'r2': model.score(x,y)}

    df = pd.DataFrame(model_output, columns = ['intercept','coefficient','r2'], index = [cit])

    train_output.append(df)

    print(train_output)

【问题讨论】:

    标签: python statistics regression sklearn-pandas


    【解决方案1】:

    如果没有看到数据,这有点难以判断。 但是,最常见的原因是输入中的 NaN 或 Inf(特征或标签)。 每次迭代都得到 NaN 吗?

    【讨论】:

    • 如果我单独运行每个城市的模型,我会得到系数。但是循环返回 NaN 并且只返回一行(每次不同的行)而不是我期望的 100 行,因为我有 100 个城市。
    • 所以当你进行拆分时可能会发生一些事情。这是引入错误的新步骤。拆分时是否检查了数据中的 NaN/Infs。尝试```打印(np.isnan(x).any())打印(np.isnan(y).any())```
    • 这两行都返回 False。
    猜你喜欢
    • 2014-12-30
    • 2015-02-10
    • 1970-01-01
    • 2016-09-18
    • 2016-07-18
    • 2019-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多