In addition to the recommended tasks , In the binary task , It can also be calculated , The code is as follows :
# ndcg def get_dcg(y_pred, y_true, k):
# be careful y_pred And y_true It has to be one-to-one , also y_pred The bigger, the closer label=1( In terms of relevance , And label=1 The more relevant ) df = pd.
DataFrame({"y_pred":y_pred, "y_true":y_true}) df = df.sort_values(by="y_pred",
ascending=False) # Yes y_pred Sort in descending order , More and more at the front , The closer we get label=1 df = df.iloc[0:k, :] # Before removal K individual
dcg= (2 ** df["y_true"] - 1) / np.log2(np.arange(1, df["y_true"].count()+1) + 1)
# Position from 1 Start counting dcg = np.sum(dcg) def get_ndcg(df, k): # df contain y_pred and y_true dcg =
get_dcg(df["y_pred"], df["y_true"], k) idcg = get_dcg(df["y_true"], df["y_true"]
, k) ndcg = dcg / idcg return ndcg
Technology