运行 基于标签的三个回归模型

Run three regression models based on a label

我正在尝试 运行 根据提供给我的数据进行三种不同的回归。这个想法是为了了解甜味与苦味是如何联系在一起的,但是对于我们拥有的三种不同的苹果酒:{干、半干、甜}。

我的想法是首先用所有的 x 值制作一个散点图,不管我们有哪种苹果酒,然后根据三个不同的 'sliced' 熊猫制作三个不同的回归模型df, x_dry, x_semidry 和 x_sweet.

我收到第 20 行错误,说我实际上是将 int 与 numpy 数组相乘。因此,为了开始解决我的问题,我尝试列出(myarray)。但是错误仍然存​​在。有人可以在这里为我指明正确的方向吗?

我得到的错误:

TypeError                                 Traceback (most recent call last)
<ipython-input-138-fa4209c61f04> in <module>
     20     return slope*i + intercept
     21 
---> 22 mymodeldry = list(map(myfunc, x_dry))
     23 mymodelsemidry = list(map(myfunc, x_semidry))
     24 mymodelsweet = list(map(myfunc, x_sweet))

<ipython-input-138-fa4209c61f04> in myfunc(i)
     18 
     19 def myfunc(i):
---> 20     return slope*i + intercept
     21 
     22 mymodeldry = list(map(myfunc, x_dry))

TypeError: can't multiply sequence by non-int of type 'numpy.float64'

我的代码

# d) Represent the sweet flavor according to the bitter flavor and add the regression line, for each type of cider.
x = list(ciderdf["Sweetness"])

x_dry = ciderdf[ciderdf["Type"]=="Dry"]
x_dry = list(x_dry[["Sweetness"]])

x_semidry = ciderdf[ciderdf["Type"]=="Semi-dry"]
x_semidry = list(x_semidry[["Sweetness"]])

x_sweet = ciderdf[ciderdf["Type"]=="Sweet"]
x_sweet = list(x_sweet[["Sweetness"]])

y = list(ciderdf["Bitterness"])

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

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

mymodeldry = list(map(myfunc, x_dry))
mymodelsemidry = list(map(myfunc, x_semidry))
mymodelsweet = list(map(myfunc, x_sweet))

plt.scatter(x,y)
plt.plot(x, mymodeldry, mymodelsemidry, mymodelsweet)
plt.show()

您实际上是将一个列表乘以一个浮点数,这是不可能的。 这实际上只有 int 才有可能,因为将列表乘以数字 n 会重复列表 n 次。

我认为您想将列表的每个元素乘以一个浮点值,您可以通过将列表 x_dry = list(x_dry[["Sweetness"]]) 转换为 numpy 数组 x_dry = np.array(list(x_dry[["Sweetness"]]))

来实现

错误在 x_dry = list(x_dry[["Sweetness"]])。当你这样做时,你 return x_dry = ['Sweetness'].

因此,在 map 函数中,您实际上是将浮点数 slope 与字符串相乘,从而引发 TypeError: can't multiply sequence by non-int of type 'numpy.float64'.

改为:x_dry = x_dry["Sweetness"].tolist().

df = pd.DataFrame({'a':[1,2,3], 'b':[4,5,6]})
x_dry = df["a"].tolist()
print(x_dry)

def myfunc(i):
    return 3.14*i + 2.56

mymodeldry = list(map(myfunc, x_dry))
print(mymodeldry)

输出:

[1, 2, 3]
[5.7, 8.84, 11.98]