如何修改此函数以接受多个数据框?

我编写了这个函数,我想让它能够接受多个数据框,以便最终的图表能够展示多个预测线,同时coef_DF也能够完成其他系数的填充。

该函数从一个更大的数据集中提取所需的特征和目标,使用线性回归函数进行预测,然后构建模型,在数据集上绘制线条,并返回一个包含所有系数的数据框。

(这只是一个练习。)

def prep_model_and_predict(feature, target, dataset, degree):    # part 1: make a df with relevant format and features         # degree >=1    poly_df=pd.DataFrame()    poly_df[str(target)] = dataset[str(target)]    poly_df['power_1']   = dataset[str(feature)]    #cehck if degree >1    if degree > 1:        for power in range(2, degree+1): #loop over reaming deg            name = 'power_'+str(power)            poly_df[name]=poly_df['power_1'].apply(lambda x: x**power)    #part 2: make model and predictions    features=list(poly_df.columns[1:])    X=poly_df[features]    y=poly_df[str(target)]    model=LinearRegression().fit(X,y)    predictions=model.predict(X)    #part 3: put weghts in a nice df    coef_df=pd.DataFrame()    coef_df=coef_df.append({"Name":'Intercept', 'Value':model.intercept_},     ignore_index=True)    coef_df=coef_df.append({'Name':'Power_1',   'Value':model.coef_[0]},   ignore_index=True)    if degree > 1:        for degree in range(2, degree+1):            name = 'Power_' + str(degree)            coef_df = coef_df.append({"Name":name,                                       'Value':'{:.3e}'.format(model.coef_[degree-1])}, ignore_index=True)    #prt 4: plot it    fig, ax = plt.subplots()    ax.plot(poly_df['power_1'], poly_df[str(target)], '.',            poly_df['power_1'], predictions, '-')    ax.set_xlabel('Square footage, living area')    ax.set_ylabel('Price per Sqft')    ax.ticklabel_format(axis='y', style='sci', scilimits=(-2,2))    return coef_df, ax

这是结果:

         Name        Value0   Intercept       5067381     Power_1  2.71336e-772     Power_2    7.335e-393     Power_3   -1.850e-444     Power_4    8.437e-505     Power_5    0.000e+006     Power_6    0.000e+007     Power_7    3.645e-558     Power_8    1.504e-519     Power_9    5.760e-4810   Power_10    1.958e-4411   Power_11    5.394e-4112   Power_12    9.404e-3813   Power_13   -3.635e-4114   Power_14    4.655e-4515   Power_15   -1.972e-49

enter image description here

非常感谢!


回答:

我不确定您到底在问什么。但我建议您下次尝试提出一个让Stack Overflow上的其他人容易重现和运行的问题。

我已经尝试回答您的问题。如果我误解了您的问题,请纠正我。

  • 将任意数量的数据框传递给您的函数并绘制它们:

我创建了三个随机数据框用于演示:

df1 = pd.DataFrame(np.random.randint(0,10,size=(10, 2)), columns=list('AB'))df2 = pd.DataFrame(np.random.randint(0,10,size=(10, 2)), columns=list('AB'))df3 = pd.DataFrame(np.random.randint(0,10,size=(10, 2)), columns=list('AB'))

用于绘制的函数如下:

def plot_me(*kwargs):    plt.figure(figsize=(13,9))    lab_ind = 0    for i in kwargs:        plt.plot(i['A'], i['B'], label = lab_ind)        lab_ind += 1    plt.legend()    plt.show()

您得到的结果图表:

enter image description here


  • 将模型结果放入DataFrame

关于您的第二个问题,我不会过多关注您的具体细节 – 例如您的数据框列名等。

在这个特定示例中,我生成了两个随机数组:

X = np.random.randint(0,50 ,size=(50, 2))y = np.random.randint(0,2 ,size=(50, 1))

然后在此数据上拟合一个线性回归模型

model=LinearRegression().fit(X,y)predictions=model.predict(X)

然后将其添加到一个DataFrame中:

res_df = pd.DataFrame(predictions,columns = ['Value'])

如果您打印res_df

    Value0   0.4203951   0.4593892   0.3696483   0.4160584   0.6440885   0.3620726   0.3631577   0.468943.      ..      .

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注