Python处理数据集-1

原数据集的数据格式:

每行为:(test_User, test_Item) negativeItem1 negativeItem2 negativeItem3 …… negativeItem99 

即每一行对应一个user 与100个item,其中1个item为正例,其余99个为负例。

将要处理成的目标数据的数据格式为:

将1个正例与99个负例拼在一起,也就是每行数据为100个item的list。(User的 ID默认从0 开始~)

【解决方案】

def load_negative100_file( filename):
    negativeList = []
    with open(filename, "r") as f:
        line = f.readline()
        while line != None and line != "":
            # arr = line.split("	")  # 针对 ml-1m 数据集
            arr = line.split(" ")  # 针对 Musical_Instruments 数据集
            negatives = []

            arr[0]=arr[0].lstrip("(")
            arr[0] = arr[0].rstrip(")")
            # print(arr[0])
            userList=arr[0].split(",")[0]
            itemList=arr[0].split(",")[1]
            negatives.append(int(itemList))
            # print(userList)
            # print(itemList)

            # for u,i in arr[0].split(","):
            #     print(i)
                # listui=list(setui)
                # negatives.append(setui[1])
            for x in arr[1:]:  # 第一个元素是(user,rating_item),故从第二个元素开始取,一共99个。
                negatives.append(int(x))
            negativeList.append(negatives)
            line = f.readline()
    return negativeList
    # testNegatives 数据格式:ratingList= ([item,neg_item,neg_item,neg_item,neg_item],)

   如下:

原文地址:https://www.cnblogs.com/shenxiaolin/p/11270605.html