【发布时间】:2019-07-31 21:25:30
【问题描述】:
编辑:31/7/19
我有一个数据集,其中包含 4 个地点的 PGR(牧场生长率)和 Foo(牧场数量)读数,一年中大约 6 周。 PGR和Foo之间的关系是反指数的。
我想做的是将周分成 3 个批次。 PGR 和 Foo 之间具有相似关系的周将在一起。
组大小不必相同。
但是周必须是连续的,即
第一组 - 第 1 周、第 2 周、第 3 周。
第二组 - 第 4 周。
第三组 - 第 5 周、第 6 周。
我想做的是创建 3 个回归来优化以减少平方和,同时优化周选择。
上面的例子表明第 1 - 3 周相似,第 4 周与第 3 周不同,第 5 周和第 6 周彼此相似但与第 4 周不同。(我希望此分组根据回归自动发生)
下面的代码是我的尝试,但它不起作用(我将其包含在内以帮助更好地解释我正在尝试做的事情)。
data = {'Week':[1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,6,6,6,6],
'PGR':[10,29,34.93,32,10,29,34.93,35,31,36,34.93,37,40,46,50,52,40,60,65,68,42,62,65,68],
'Foo': [20,45,102.28,66.79,25,50,90,75,50,75,90,130,50,75,90,130,30,60,105,150,35,60,110,140]}
df = pd.DataFrame(data)
def group(x):
a, b, c, e, f, g, h, i, j, w, z, y = x
#below defines the groups, I want z, y & w to be optimised when this function is solverd
#This determines which weeks are in which groups
group1 = df.loc[(df['Week'] == range(1,z))]
group2 = df.loc[(df['Week'] == range(z,y))]
group3 = df.loc[(df['Week'] == range(y,w))]
#Once the groups are defined this will extract Foo and PGR values for regressions
xm1 = group1['Foo'].to_numpy()
ym1 = group1['PGR'].to_numpy()
xm2 = group2['Foo'].to_numpy()
ym2 = group2['PGR'].to_numpy()
xm3 = group3['Foo'].to_numpy()
ym3 = group3['PGR'].to_numpy()
#These are the 3 regressions
y1 = a + b / xm1 + c * np.log(xm1)
SSE1 = (y1 - ym1)**2
y2 = e + f / xm2 + g * np.log(xm2)
SSE2 = (y2 - ym2) ** 2
y3 = h + i / xm3 + j * np.log(xm3)
SSE3 = (y3 - ym3) ** 2
return SSE1, SSE2, SSE3
#I now have the sum of squares for all the regressions, which I want to minimise
#Minimising can happen by selecting groups that are more similar or by changing the regression coefficients
def objective(x):
return np.sum(group(x))
x0 = np.zeros(12)
# bounds for a, b, c, e, f, g, h, i, j, w, z, y
bndspositive = (0,52)
bnds100 = (-100.0, 100.0)
no_bnds = (-1.0e10, 1.0e10)
bnds = (no_bnds, no_bnds, bnds100, no_bnds, no_bnds, bnds100, no_bnds, no_bnds, bnds100, bndspositive, bndspositive, bndspositive)
# optimise groups and regressions for best fit
solution = minimize(objective, x0, method=None, bounds=bnds)
# solution
x = solution.x
希望这是有道理的,谢谢
【问题讨论】:
标签: python dataframe optimization regression