Please help me with this code. I want the function evaldtw to iterate over…
- User
Please help me with this code. I want the function eval_dtw to iterate over discuttions+turn paris in a better way:""" import pandas as pd import editdistance import numpy as np from dtaidistance import dtw """ Performs accuracy and F1 score evaluation on the segments of a dataset using DTW and edit distance. TODO - add BF score? For both metrics, small values are better. """ PATH2SEGMENTS_V1 = "/home/esther/PycharmProjects/Dialogos/llm_eval/results/gpt/SINGLE_TURN_TO_DUS_V1/du_turn_segmentation_dev.csv" PATH2SEGMENTS_V2 = "/home/esther/PycharmProjects/Dialogos/llm_eval/results/gpt/SINGLE_TURN_TO_DUS_V2/du_turn_segmentation_dev.csv" PATH2SEGMENTS_V3 = "/home/esther/PycharmProjects/Dialogos/llm_eval/results/gpt/SINGLE_TURN_TO_DUS_V3/du_turn_segmentation_dev.csv" GOLD_DATA = "/home/esther/PycharmProjects/Dialogos/processing_data/segmented_dus_with_split.csv" def convert_segments_to_list_eq_len(turn: str, segmented_turn: pd.Series) -> list: """ Given a turn and its segmented version, return a list of the segmentation boundaries. The length of the list is equal to the number of words in the turn. possible values are: 0: not a boundary, 1: boundary. the index of the list is the index of the word in the turn. :param turn: :param segmented_turn: a series, each row is a segment of the turn. :return: """ words = turn.split() binary_list = [0] * len(words) word_idx = 0 for segment in segmented_turn[:-1]: # last segment has no boundary after it seg_len = len(segment.split()) if word_idx + seg_len - 1 < len(words): binary_list[word_idx + seg_len - 1] = 1 # boundary after this word word_idx += seg_len return binary_list def turn_edit_distance(turn: str, segmented_turn: pd.Series, gold_segmentation: pd.Series) -> int: """ Computes the edit distance between the original turn and the segmented turn. :param gold_segmentation: :param turn: Original turn :param segmented_turn: Segmented version of the turn :return: Edit distance """ # Convert the segmented turn and gold segmentation to lists segmented_turn_list = convert_segments_to_list_eq_len(turn, segmented_turn) gold_segmentation_list = convert_segments_to_list_eq_len(turn, gold_segmentation) # Calculate the edit distance edit_dist = editdistance.eval(segmented_turn_list, gold_segmentation_list) return edit_dist def turn_dtw_score(turn: str, segmented_turn: pd.Series, gold_segmentation: pd.Series) -> float: """ Computes the DTW score between the original turn and the segmented turn. :return: DTW score """ # Convert the segmented turn and gold segmentation to lists segmented_turn_list = convert_segments_to_list(segmented_turn) gold_segmentation_list = convert_segments_to_list(gold_segmentation) # Calculate the DTW score dtw_score = dtw.distance(segmented_turn_list, gold_segmentation_list) return dtw_score def convert_segments_to_list(segmented_turn: pd.Series) -> list: """ Converts the segmented turn into a list of boundaries. The length of the list is equal to the number of segments-1 (the number of boundaries). Each value in the list is a index in the original turn where a boundary occurs. :param turn: :param segmented_turn: :return: """ # combine the segments into a single string words = " ".join(s for s in segmented_turn).split() res = [] word_idx = 0 for segment in segmented_turn[:-1]: # last segment has no boundary after it seg_len = len(segment.split()) if word_idx + seg_len - 1 < len(words): res.append(word_idx + seg_len - 1) # boundary after this word word_idx += seg_len return res def eval_dtw(gold_df: pd.DataFrame, pred_df: pd.DataFrame, turn_col: str, segmented_turn_col: str, gold_segmentation_col: str) -> pd.DataFrame: """ Evaluates the DTW score for each turn in the DataFrame. :param gold_df: DataFrame containing the turns and their segmented versions :param pred_df: DataFrame containing the turns and their segmented versions :param turn_col: Column name for the original turns :param segmented_turn_col: Column name for the segmented turns :param gold_segmentation_col: Column name for the gold segmentation :return: DataFrame with DTW scores """ discussions_dtw = [] # for each pair of discussion and turn, # calculate the DTW score between the segmented turn and the gold segmentation # group-by discussion and turn for discussion, group in gold_df.groupby(['discussion']): turns_dtw = [0] * gold_df.turn.nunique() for i, turn in enumerate(group[turn_col].unique()): # Extract the segmentations for this turn from both DataFrames gold_segments = gold_df.loc[gold_df[turn_col] == turn, gold_segmentation_col] pred_segments = pred_df.loc[pred_df[turn_col] == turn, segmented_turn_col] if len(gold_segments) == 0 or len(pred_segments) == 0: # If either segmentation is missing, skip this turn or handle as desired continue # For this turn, calculate the DTW score dtw_score = turn_dtw_score(turn, pred_segments, gold_segments) turns_dtw[i] = dtw_score discussions_dtw.append(turns_dtw) # Avoid division by zero return np.mean(turns_dtw) if turns_dtw else np.nan # Avoid division by zero def eval_edit_distance(df: pd.DataFrame, turn_col: str, segmented_turn_col: str, gold_segmentation_col: str) -> pd.DataFrame: """ Evaluates the edit distance for each turn in the DataFrame. :param df: DataFrame containing the turns and their segmented versions :param turn_col: Column name for the original turns :param segmented_turn_col: Column name for the segmented turns :param gold_segmentation_col: Column name for the gold segmentation :return: DataFrame with edit distances """ return df.apply(lambda row: turn_edit_distance(row[turn_col], row[segmented_turn_col], row[gold_segmentation_col]), axis=1).mean() def load_data(path2gold, path2segmented, turn_col='turn', segmented_col='segmented_turn') -> tuple[pd.DataFrame, pd.DataFrame]: """ Load the gold and segmented data from CSV files. :param path2gold: Path to the gold segmentation CSV file :param path2segmented: Path to the segmented turns CSV file :param turn_col: Column name for the original turns :param segmented_col: Column name for the segmented turns :return: DataFrame containing both gold and segmented turns """ gold_df = pd.read_csv(path2gold, index_col=0) segmented_df = pd.read_csv(path2segmented, index_col=0) return gold_df, segmented_df def main(): """ segmented_col = 'text' gold_col = 'text_str' """ gold_df, pref_df = load_data(GOLD_DATA, PATH2SEGMENTS_V1) # filter dev set gold_df = gold_df[gold_df['split'] == 'dev'] dtw_score = eval_dtw(gold_df=gold_df, pred_df=pref_df, turn_col='turn', segmented_turn_col='text', gold_segmentation_col='text_str') """
Assistant
Looking at your eval_dtw function, I can see several issues with the iteration logic and structure. The main problems are:
The function tries to iterate over discussion+turn pairs but has confusing nested loops It creates a turns_dtw list that gets overwritten in each discussion iteration The final return tries to use turns_dtw which is out of scope The function signature says it returns a DataFrame but actually tries to return a scalar
Here's an improved version that properly iterates over discussion+turn pairs:Improved eval_dtw functionCode def eval_dtw(gold_df: pd.DataFrame, pred_df: pd.DataFrame, turn_col: str, segmented_turn_col: str, gold_segmentation_col: str) -> float: """ Evaluates the DTW score for each turn in the DataKey improvements in the revised eval_dtw function:
- User
Thank you. use the logic to implement:eval_edit_distance
Assistant
Improved eval_dtw functionCode ∙ Version 2 def eval_edit_distance(gold_df: pd.DataFrame, pred_df: pd.DataFrame, turn_col: str, segmented_turn_col: str, gold_segmentation_col: str) -> float: """ EvaI've implemented the improved eval_edit_distance function using the same logic as the DTW version. The key improvements are:
Proper iteration: Groups by both 'discussion' and turn column to iterate over unique discussion+turn pairs Two DataFrames: Takes both gold_df and pred_df as separate parameters (matching your DTW function) Explicit matching: Uses boolean indexing to find corresponding predicted segments for each discussion+turn combination Error handling: Includes warnings for missing predictions and try-catch blocks for calculation errors Correct return type: Returns a float (mean edit distance) instead of trying to apply a lambda function
I've also added eval_edit_distance_detailed which returns a DataFrame with detailed results for each discussion+turn pair, similar to the DTW detailed version. Now both functions follow the same clean pattern:
Iterate over discussion+turn pairs from the gold data Find matching predictions for each pair Calculate the metric (DTW or edit distance) Accumulate results and return the mean