无法执行缩减弹性类型

问题描述 投票:1回答:1

执行线性回归以找到估计系数并为其绘制回归线,这给我带来了错误...无法对柔韧性类型执行归约。代码中有什么问题.... var应该在哪里定义!

import numpy as np
import matplotlib.pyplot as plt
x="GarageArea"
y="SalePrice"
def estimate_coef(x, y):

    n = np.size(x)
    m_x, m_y = np.mean(x), np.mean(y)

    SS_xy = np.sum(y*x) - n*m_y*m_x
    SS_xx = np.sum(x*x) - n*m_x*m_x

    b_1 = SS_xy / SS_xx
    b_0 = m_y - b_1*m_x
    return(GarageArea)
def plot_regression_line(x, y, b):

    plt.scatter(x, y, color = "m", marker = "o", s = 30)


    y_pred = b[0] + b[1]*x


    plt.plot(x, y_pred, color = "g")
    plt.xlabel('x')
    plt.ylabel('y')

    plt.show()

# Visualize your results

b=estimate_coef(x,y)
plot_regression_line(GarageArea,GarageArea,b)
python-3.x regression linear-regression
1个回答
0
投票

您尚未在代码中定义xy,但尝试将它们传递给plot_regression_line。不知道您是否假设当您将GarageAreaSalePrice传递给estimate_coef函数时,该函数将它们本地映射到xy,您以为您仍可以引用它们。但是,x函数中的yestimate_coef在该函数中是局部作用域,因此在其外部不存在,因此无法对其进行引用。

假设您打算将GarageAreaSalePricexy传递给plot_regression_line函数。

import numpy as np
import matplotlib.pyplot as plt

def estimate_coef(x, y):
    n = np.size(x)
    m_x, m_y = np.mean(x), np.mean(y)

    SS_xy = np.sum(y*x) - n*m_y*m_x
    SS_xx = np.sum(x*x) - n*m_x*m_x

    b_1 = SS_xy / SS_xx
    b_0 = m_y - b_1*m_x

    return(b_0, b_1)

def plot_regression_line(x, y, b):

    plt.scatter(x, y, color = "m", marker = "o", s = 30)


    y_pred = b[0] + b[1]*x


    plt.plot(x, y_pred, color = "g")


    plt.xlabel('x')
    plt.ylabel('y')

    plt.show()

# Visualize your results
b=estimate_coef(GarageArea,SalePrice)
plot_regression_line(GarageArea,GarageArea,b)

这是假设您在代码中定义了xy,但我可能是错的,因为您还使用了您发布的代码中未定义的GarageAreaSalePrice。如果这不能回答您的问题,那么您应该编辑问题并发布所得到的错误的堆栈跟踪。

© www.soinside.com 2019 - 2024. All rights reserved.