【RippleNet】(一)preprocessor.py【未完】
生活随笔
收集整理的這篇文章主要介紹了
【RippleNet】(一)preprocessor.py【未完】
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
首先讀入的文件有movie和book和news三種,肯定會選擇一種進行解析!
下面我們以movies作為樣例分析:
本論文中使用的數據集是movie-1m
-
ratings.dat:
分別是用戶::電影::評分::電影編號
-
item_index2entity_id_rehashed.txt文件:
內容:
import argparse import numpy as npRATING_FILE_NAME = dict({'movie': 'ratings.dat', 'book': 'BX-Book-Ratings.csv', 'news': 'ratings.txt'}) #定義字典 字典保存中保存的都是原始文件 SEP = dict({'movie': '::', 'book': ';', 'news': '\t'}) #定義的分隔符! THRESHOLD = dict({'movie': 4, 'book': 0, 'news': 0}) #定義電影喜好的閾值吧def read_item_index_to_entity_id_file(): #看名字:讀item的索引轉化為實體的idfile = '../data/' + DATASET + '/item_index2entity_id_rehashed.txt'#../data/movie/item_index2entity_id_rehashed.txtprint('reading item index to entity id file: ' + file + ' ...')i = 0for line in open(file, encoding='utf-8').readlines():item_index = line.strip().split('\t')[0] satori_id = line.strip().split('\t')[1] #返回字符列表,并獲取第一個和第二個元素, 第一個元素是原item的索引,第二個元素是satori中實體的索引。 satori是微軟的大型知識圖譜。 具體看后面解析item_index_old2new[item_index] = i # item 的舊的index轉換為新的indexentity_id2index[satori_id] = i # 實體id轉換為index i += 1 def convert_rating():file = '../data/' + DATASET + '/' + RATING_FILE_NAME[DATASET]# '../data/movie/ratings.datprint('reading rating file ...')item_set = set(item_index_old2new.values()) # 將item新的index轉化為集合user_pos_ratings = dict() # 用戶正樣本的評分user_neg_ratings = dict() # 用戶負樣本的評分for line in open(file, encoding='utf-8').readlines()[1:]:array = line.strip().split(SEP[DATASET]) #看上面,我們經過分割后得到四個元素# remove prefix and suffix quotation marks for BX datasetif DATASET == 'book':array = list(map(lambda x: x[1:-1], array))item_index_old = array[1] # 取的是第二個元素,item的舊index if item_index_old not in item_index_old2new: # the item is not in the final item set # 比較的是keys,不是values,item_index_old也是字符,查看評價的items是不是在我們記錄的item_index中,如果不在直接終止continueitem_index = item_index_old2new[item_index_old] #如果在,那么我們就賦值新的item_indexuser_index_old = int(array[0]) # 獲得user舊的id的indexrating = float(array[2]) #獲得用戶的電影評分if rating >= THRESHOLD[DATASET]: #我們選取列表中所有大于閾值的評分if user_index_old not in user_pos_ratings: #注意這里比較的是keys值user_pos_ratings[user_index_old] = set() # 積極評分的設置為set集合user_pos_ratings[user_index_old].add(item_index) #list列表中添加用戶舊的index#并且添加了item新的indexelse:if user_index_old not in user_neg_ratings: #同樣的道理,這里存儲列表中小于閾值的評分user_neg_ratings[user_index_old] = set()user_neg_ratings[user_index_old].add(item_index)print('converting rating file ...') #將用戶的index轉為新的writer = open('../data/' + DATASET + '/ratings_final.txt', 'w', encoding='utf-8')user_cnt = 0user_index_old2new = dict()for user_index_old, pos_item_set in user_pos_ratings.items():if user_index_old not in user_index_old2new:user_index_old2new[user_index_old] = user_cnt #記錄user的總數user_cnt += 1user_index = user_index_old2new[user_index_old] #for item in pos_item_set:writer.write('%d\t%d\t1\n' % (user_index, item))unwatched_set = item_set - pos_item_setif user_index_old in user_neg_ratings:unwatched_set -= user_neg_ratings[user_index_old]for item in np.random.choice(list(unwatched_set), size=len(pos_item_set), replace=False):writer.write('%d\t%d\t0\n' % (user_index, item))writer.close()print('number of users: %d' % user_cnt)print('number of items: %d' % len(item_set))def convert_kg(): #基本都是轉變id的事 print('converting kg file ...')entity_cnt = len(entity_id2index)relation_cnt = 0writer = open('../data/' + DATASET + '/kg_final.txt', 'w', encoding='utf-8')files = []if DATASET == 'movie':files.append(open('../data/' + DATASET + '/kg_part1_rehashed.txt', encoding='utf-8'))files.append(open('../data/' + DATASET + '/kg_part2_rehashed.txt', encoding='utf-8'))else:files.append(open('../data/' + DATASET + '/kg_rehashed.txt', encoding='utf-8'))for file in files:for line in file:array = line.strip().split('\t')head_old = array[0]relation_old = array[1]tail_old = array[2]if head_old not in entity_id2index:entity_id2index[head_old] = entity_cntentity_cnt += 1head = entity_id2index[head_old]if tail_old not in entity_id2index:entity_id2index[tail_old] = entity_cntentity_cnt += 1tail = entity_id2index[tail_old]if relation_old not in relation_id2index:relation_id2index[relation_old] = relation_cntrelation_cnt += 1relation = relation_id2index[relation_old]writer.write('%d\t%d\t%d\n' % (head, relation, tail))writer.close()print('number of entities (containing items): %d' % entity_cnt)print('number of relations: %d' % relation_cnt)if __name__ == '__main__':np.random.seed(555)parser = argparse.ArgumentParser()parser.add_argument('-d', '--dataset', type=str, default='movie', help='which dataset to preprocess')args = parser.parse_args()DATASET = args.datasetentity_id2index = dict()relation_id2index = dict()item_index_old2new = dict()read_item_index_to_entity_id_file()convert_rating()convert_kg()print('done')補充:
1. line.strip.split(’\t’)
- 描述
Python strip() 方法用于移除字符串頭尾指定的字符(默認為空格)或字符序列。
注意:該方法只能刪除開頭或是結尾的字符,不能刪除中間部分的字符。 - 語法
strip()方法語法:
-
參數
chars – 移除字符串頭尾指定的字符序列。 -
返回值
返回移除字符串頭尾指定的字符序列生成的新字符串
2. split(’\t’)
已經在上個代碼分析中討論過了,這里只是簡單說一下,它會返回字符列表!
- 源代碼分析:
可以看出其一,如果只是輸出一行的數據,長度為4,該字符串是"1 \t 0 空格" 多個空格為一個!
所以我們在獲取一行數據的時候,要特別注意這些空格符(在首尾)、分隔符(在中間)!
最后split返回的是字符列表!
3. Set()集合
集合是為了啥? 關系運算啊! 并交差集
定義:
set() 函數創建一個無序不重復元素集,可進行關系測試,刪除重復數據,還可以計算交集、差集、并集等。
注意是沒有順序,而是是不重復的集合!
返回值:
返回新的集合對象
實例:
>>>x = set('runoob') >>> y = set('google') >>> x, y (set(['b', 'r', 'u', 'o', 'n']), set(['e', 'o', 'g', 'l'])) # 重復的被刪除 >>> x & y # 交集 set(['o']) >>> x | y # 并集 set(['b', 'e', 'g', 'l', 'o', 'n', 'r', 'u']) >>> x - y # 差集 set(['r', 'b', 'u', 'n']) >>>4. “XXX” not in dict
比較的是keys,不是values; 如果字典中沒有,那么就返回False,否則返回True。
配合的操作就是如果沒有,那么就添加該key值!
源碼舉例:
if item_index_old not in item_index_old2new: # the item is not in the final item set # 比較的是keys,不是values,item_index_old也是字符,查看評價的items是不是在我們記錄的item_index中,如果不在直接終止continueitem_index = item_index_old2new[item_index_old] #如果在,那么我們就賦值新的item_index總結
以上是生活随笔為你收集整理的【RippleNet】(一)preprocessor.py【未完】的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: matlab 转换为正整数_【MATLA
- 下一篇: 行业分析-实战价值方法