【问题标题】:Python showing "too many values to unpack"Python 显示“太多值无法解包”
【发布时间】:2021-02-01 07:41:35
【问题描述】:

我正在尝试建立一个线性回归模型来计算婴儿死亡率是否会影响预期寿命。我正在使用 Google Collab 来执行它。这是我的代码:

x = data.loc[(data['Country'] == 'Bangladesh'), ['infant deaths']]
y = data.loc[(data['Country'] == 'Bangladesh'), ['Life expectancy ']]

slope, intercept, r, p, std_err = stats.linregress(x, y)

def myfunc(x):
 return slope * x + intercept

mymodel = list(map(myfunc, x))

plt.scatter(x, y)
plt.plot(x, slope * x + intercept)
plt.ylim(ymin=0, ymax=2000)
plt.xlim(xmin=0, xmax=200)
plt.xlabel("infact deaths")
plt.ylabel ("Life expectancy")
plt.show()

但是,我收到如下错误消息:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-10-32392bb3a878> in <module>()
      2 y = data.loc[(data['Country'] == 'Bangladesh'), ['Life expectancy ']]
      3 
----> 4 slope, intercept, r, p, std_err = stats.linregress(x, y)
      5 
      6 def myfunc(x):

/usr/local/lib/python3.6/dist-packages/scipy/stats/_stats_mstats_common.py in linregress(x, y)
    114 
    115     # average sum of squares:
--> 116     ssxm, ssxym, ssyxm, ssym = np.cov(x, y, bias=1).flat
    117     r_num = ssxym
    118     r_den = np.sqrt(ssxm * ssym)

ValueError: too many values to unpack (expected 4)

我确信我对列的命名是正确的。我还导入了所有库或模块。请帮我找到解决方案。

【问题讨论】:

  • 如果你使用 x = data.loc[data['Country'] == 'Bangladesh', 'infant deaths'] 这样的构造来返回一个系列而不是一个数据框(y 相同)怎么办? linregress 很可能会接受它。

标签: python linear-regression


【解决方案1】:

类似的问题是here。看起来您的 x 和 y 形状与lingress 要求的形状不符。例如,考虑使用.shape 期待他们。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-09
    • 2019-03-28
    • 2013-06-06
    • 2018-07-15
    • 2017-07-17
    • 1970-01-01
    • 2018-07-01
    • 2021-02-10
    相关资源
    最近更新 更多