python计算R2、RMSE、NSE、PBIAS

  • Post author:
  • Post category:python


计算公式:

# -*- coding: utf-8 -*-
"""
YMJ 20230515 21:49
"""
import os
import numpy as np
import pandas as pd
import math
from random import random, uniform
from pylab import mpl

# 首先定义公式
def R2(y_obs, y_sim):
    # 观测值的平均值, 对应(LE, E)
    y_obs_mean = y_obs.mean()
    y_sim_mean = y_sim.mean()
    sum1 = 0
    sum2 = 0
    sum3 = 0
    for i in range(len(y_obs)):
        sum1 = sum1 + (y_sim.iloc[i] - y_sim_mean) * (y_obs.iloc[i] - y_obs_mean)
        sum2 = sum2 + ((y_sim.iloc[i] - y_sim_mean) ** 2)
        sum3 = sum3 + ((y_obs.iloc[i] - y_obs_mean) ** 2)
    R2 = (sum1 / ((sum2 ** 0.5) * (sum3 ** 0.5))) ** 2
    return R2

def RMSE(y_obs, y_sim):
    sum1 = 0
    for i in range(len(y_obs)):
        sum1 = sum1 + (y_sim.iloc[i] - y_obs.iloc[i]) ** 2
    RMSE = (sum1 / len(y_obs)) ** 0.5
    return RMSE

def PBIAS(y_obs, y_sim):
    sum1 = 0
    sum2 = 0
    for i in range(len(y_obs)):
        sum1 = sum1 + (y_sim.iloc[i] - y_obs.iloc[i])
        sum2 = sum2 + y_obs.iloc[i]
    PBIAS = 100 * (sum1 / sum2)
    return PBIAS

def NSE(y_obs, y_sim):
    y_obs_mean = y_obs.mean()
    sum1 = 0
    sum2 = 0
    for i in range(len(y_obs)):
        sum1 = sum1 + ((y_obs.iloc[i] - y_sim.iloc[i]) ** 2)
        sum2 = sum2 + ((y_obs.iloc[i] - y_obs_mean) ** 2)
    NSE = 1 - (sum1/sum2)
    return NSE


file = "D:\\YMJ_file\\通量数据相关\\All模型评价\\3SGCF\\All\\hhhh.xlsx"

df_sum = pd.DataFrame()
name_list = []
# 放和LE-E
R2_1 = []
RMSE_1 = []
PBIAS_1 = []
NSE_1 = []

df = pd.read_excel(file)

y_obs1 = df["LE"]
y_sim_1 = df["E"]
R2_1.append(R2(y_obs1, y_sim_1))
RMSE_1.append(RMSE(y_obs1, y_sim_1))
PBIAS_1.append(PBIAS(y_obs1, y_sim_1))
NSE_1.append(NSE(y_obs1, y_sim_1))

df_sum["name_list"] = pd.DataFrame(name_list)
df_sum["R2_1"] = pd.DataFrame(R2_1)
df_sum["RMSE_1"] = pd.DataFrame(RMSE_1)
df_sum["PBIAS_1"] = pd.DataFrame(PBIAS_1)
df_sum["NSE_1"] = pd.DataFrame(NSE_1)

out_path = os.path.join(dir, "model_evaluation_index" + ".csv")
df_sum.to_csv(out_path, index=False)



版权声明:本文为weixin_46080995原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。