Open DrPepper8888 opened 8 months ago
def manual_label_encoder(labels): # 初始化一个空字典用于存储标签到整数的映射 label_to_int = {} # 初始化一个空字典用于存储整数到标签的映射 int_to_label = {} # 初始化类别计数器 class_count = 0 # 遍历所有标签 for label in labels: # 如果标签不在字典中,则添加它 if label not in label_to_int: label_to_int[label] = class_count int_to_label[class_count] = label class_count += 1 # 如果标签已经在字典中,就不需要做任何事情 # 使用映射将标签转换为整数 encoded_labels = [label_to_int[label] for label in labels] return encoded_labels, int_to_label # 示例使用 labels = ['cat', 'dog', 'dog', 'cat', 'mouse'] encoded_labels, reverse_mapping = manual_label_encoder(labels) print("Encoded labels:", encoded_labels) print("Reverse mapping:", reverse_mapping)