Scipy 优化最小化使用数据帧 [英] Scipy optimize minimize using dataframe

查看:47
本文介绍了Scipy 优化最小化使用数据帧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含 3 列的数据框:Y、X1、X2.我想通过最小化平方和来找到参数估计 b1 和 b2:

I have a dataframe with 3 columns: Y, X1, X2. I want to find the parameter estimates b1 and b2 by minimizing the sum of squares according to:

Objective function: minimize the sum of squares (Y - (b1*X1 + b2*X2))^2
Constraints: 0 < b1 < 2, 0 < b2 < 1
Initial guesses: b1=b2=0.5
Technique: Newton-Raphson

我知道我可以使用

scipy.optimize.minimize(fun, x0, args=(), method=None, jac=None, hess=None, hessp=None, bounds=None, constraints=(), tol=None, callback=None, options=None)

但我看不到如何传递数据框中的列,因为我从搜索中找到的所有示例都不使用数据框中的列.

but I can't see how to pass the columns from the dataframe in as all the examples I found from searching don't use columns from a dataframe.

我将非常感谢您的帮助.

I would be very grateful for any help.

推荐答案

这可能是您的一些起点.只要你的目标函数的返回是标量,应该没问题.通过元组中的 args-keywords 传递数据帧.请参阅最小化函数的文档以检查您要使用的方法.

This could be some start-point for you. As long as the return of your objective function is scalar, it should be no problem. Pass the dataframe via the args-keywords in a tuple. See the Documentation of the minimize function to check which method you want to use.

我根据您评论中的描述更改了代码.

I changed the code based on the description in your comment.

import numpy as np
import scipy.optimize as opt
import pandas as pd

def main(df):
    x0 = [0.5,0.5]
    res = opt.minimize(fun=obj, x0=np.array(x0), args=(df), method="BFGS", bounds=[(0,2),(0,1)])
    return res

def obj(x, df):
    #maybe use a global variable to get the dataframe or via args
    sumSquares = np.mean((df["Y"] - (x[0]*df["X1"] + x[1]*df["X2"]))**2)
    return sumSquares

df = pd.DataFrame({"Y":np.random.rand(100),
                   "X1":np.random.rand(100),
                   "X2":np.random.rand(100)})
print(main(df))

这篇关于Scipy 优化最小化使用数据帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆