让我们假设我得到以下熊猫数据框进行回归分析。
import pandas
import math
import numpy
df = pandas.DataFrame(numpy.random.randint(0,100,size=(100, 2)), columns=['labels','predictions'])
我现在想将RMSE计算为
math.sqrt(numpy.mean((df["predictions"] - df["lables"]) ** 2))
对于间隔为7的标签值
这里有一个非常丑陋的代码可以完成工作...如果您能帮助我对其进行python化,那就太好了...
# define step
step = 7
# initialize counter
idx = 0
# initialize empty dataframe
rmse = pandas.DataFrame(columns=['bout' , 'rmse'],index=range(0,len(range(int(df['labels'].min())+step,int(df['labels'].max()),step))))
# start loop to calculate rmse every 7 units
for i in range(int(df['labels'].min())+step,int(df['labels'].max()),step):
# select values in interval
df_bout = df[(df['labels']>=i-step) & (df['labels']<i)]
# calculate rmse in interval
rmse.loc[idx] = [str(i-step)+'-'+str(i),math.sqrt(numpy.mean((df_bout.predictions - df_bout.labels) ** 2))]
# increment counter
idx = idx + 1
答案 0 :(得分:0)
对于一开始的误解,我深表歉意。以下代码段给出了您想要的结果
from sklearn.metrics import mean_squared_error
import pandas
import math
import numpy
df = pandas.DataFrame(numpy.random.randint(0, 100, size = (100, 2)), columns = ['labels','predictions']).sort_values(by = 'labels', ascending = True)
def rmse(df):
return numpy.sqrt(mean_squared_error(df['labels'], df['predictions']))
output = df.groupby(numpy.floor(numpy.array(df['labels'] / 7))).apply(rmse)
rmse_df = pandas.DataFrame({'bout': [str(int(output.index[i] * 7)) + ' - ' + str(int(output.index[i + 1] * 7)) for i in range(output.shape[0] - 1)], 'rmse': output.values[:-1]})
如果要动态更改步长,可以在代码中为变量step
更改7s