import pandas as pd # recall@k function def recall(actual, predicted, k): """ Calculate recall for set results :param actual: actual results on question from annotated datatest :param predicted: predicted results on question from searched engine :param k: max results in set :return: recall value """ # corrects results act_set = actual # search results (count edit k) pred_set = predicted[:k] # count and find same numbers common_elements = 0 for item in act_set: if item in pred_set: common_elements += 1 result = round(common_elements / float(len(act_set)), 2) return result def count_recall(actual_list, predicted_list, count_results): """ Calculate recall for search engine :param actual_list: actual results from annotated datatest :param predicted_list: predicted results from searched engine :return: average recall value """ # set values for parameter k k_start = 3 k_end = count_results + 1 # Initialization empty DataFrame df_recall = pd.DataFrame(index=range(3, count_results + 1)) # For cycle go to every predicted questions for i, predicted_val in enumerate(predicted_list, 1): recalls = [] # Count recall for question for k in range(k_start, k_end): recall_val = recall(actual_list[i - 1], predicted_val, k) recalls.append(recall_val) df_temp = pd.DataFrame({f"Question {i}": recalls}, index=range(3, count_results + 1)) df_recall = pd.concat([df_recall, df_temp], axis=1) df_recall[f"Question {i}"] = recalls # Calculate the average recall value for each number of questions average_recall = df_recall.mean(axis=1) # Print list the recall values for each question separately # print("Recall values for every question:") # print(df_recall) # set results two dots numbers pd.set_option('display.float_format', '{:.2f}'.format) # Print all mean recall # print(f"\nAll Mean Recall for {count_results} results :{round(average_recall.mean(), 2)}") print(f"Recall Metric for {count_results} is: {round(average_recall.iloc[-1], 2)}") return average_recall