Skip to content
TheChatArchiveThe Chat Archive
gpt-4-0314· openaiHugging Face Suzhen/CodeChat

buseredge = findlatest1D(np.array(ratings.iloc[batch]['userid']), adjuseredge,…

  1. User

    b_user_edge = find_latest_1D(np.array(ratings.iloc[batch]['user_id']), adj_user_edge, adj_user_time, ratings.iloc[batch]['timestamp'].tolist()) b_user_edge = torch.from_numpy(b_user_edge).to(device) b_users = torch.from_numpy(np.array(ratings.iloc[batch]['user_id'])).to(device) #print ("b_user",b_users) b_item_edge = find_latest_1D(np.array(ratings.iloc[batch]['item_id']), adj_item_edge, adj_item_time, ratings.iloc[batch] ['timestamp'].tolist()) b_item_edge = torch.from_numpy(b_item_edge).to(device) b_items = torch.from_numpy(np.array(ratings.iloc[batch]['item_id'])).to(device) timestamps = torch.from_numpy(np.array(ratings.iloc[batch]['timestamp'])).to(device)

            negative_samples = sampler(items_in_data, adj_user, ratings.iloc[batch]['user_id'].tolist() ,1)
            neg_edge = find_latest(negative_samples, adj_item_edge, adj_item_time, ratings.iloc[batch]['timestamp'].tolist())
            negative_samples = torch.from_numpy(np.array(negative_samples)).to(device)
            negative_samples = negative_samples.squeeze()
            neg_edge = torch.from_numpy(neg_edge).to(device)
            neg_edge = neg_edge.squeeze()
    
            time0 = time.time()
    
            user_embeddings = model(b_users, b_user_edge, timestamps, config.n_layer, nodetype='user')
            item_embeddings = model(b_items, b_item_edge, timestamps, config.n_layer, nodetype='item')
            negs_embeddings = model(negative_samples, neg_edge, timestamps, config.n_layer, nodetype='item')
    

    می خواهم پارامترهای تابع زیر را با توجه به کد بالا تغییر دهم چگونه تغییر دهم def hard_neg_sample(u, seq, pos, neg, hard_items, cnt_items, args): def update_hard_negs(u, pos, hard_items, all_logits, all_labels, all_samples, args):

  2. Assistant

    بنابراین، شما می‌خواهید تابع hard_neg_sample و تابع update_hard_negs را مطابق با کد فراهم شده در بالا تغییر دهید. اولین گام برای این کار، ورودی‌های لازم برای این دو تابع را استخراج کرده و همچنین تغییرات درون توابع را اعمال می‌کنیم. این دو تابع به صورتی تغییر کرده‌اند که ورودی‌های مناسبی را بگیرند و خروجی‌های مربوط به کد شما را تولید کنند:

    1. تابع hard_neg_sample:
    def hard_neg_sample(b_users, b_items, timestamps, b_item_edge, b_user_edge, config, adj_item_edge, adj_item_time, items_in_data, adj_user):
        # ابتدا نمونه‌های منفی را در همان بُعد به دست می‌آوریم
        negative_samples = sampler(items_in_data, adj_user, b_users.tolist(), config.n_negative)
        neg_edge = find_latest_2D(negative_samples, adj_item_edge, adj_item_time, timestamps.tolist())
        negative_samples = torch.from_numpy(np.array(negative_samples)).to(config.device)
        negative_samples = negative_samples.squeeze()
        neg_edge = torch.from_numpy(neg_edge).to(config.device)
        neg_edge = neg_edge.squeeze()
    
        return negative_samples, neg_edge
    
    1. تابع update_hard_negs:
    def update_hard_negs(negative_samples, neg_edge, timestamps, b_users, b_items, hard_items, all_logits, all_labels, config, model):
        # محاسبه کردن loss نهایی
        negative_logits = model.target_noise(negative_samples, neg_edge, timestamps, config.n_layer, b_users, nodetype='item')
        
        # به دست آوردن ترتیب بر اساس logits منفی
        sorted_order = torch.argsort(negative_logits, dim=1, descending=True)
        top_k_samples = negative_samples.gather(1, sorted_order[:,:config.hard_topk])
        
        user_wise_loss = torch.zeros((b_users.size(0), config.hard_topk), dtype=torch.float32).to(config.device)
        for i in range(config.hard_topk):
            user_wise_loss[:,i] = all_logits[:,i] - all_labels[:,i]
    
        sorted_user_wise_loss = user_wise_loss.gather(1, sorted_order[:,:config.hard_topk])
        less_than_median = sorted_user_wise_loss < all_labels
        hard_samples = torch.where(less_than_median, top_k_samples, negative_samples)
        
        for _, idx in enumerate(b_users):
            hard_items[int(idx)] = hard_items[int(idx)].union(hard_samples[int(idx)].tolist())
            
        return hard_items
    

    بعد از تغییر این دو تابع بر اساس کد فراهم شده، می‌توانید آن‌ها را به جای‌گزین قسمت‌های مربوطه در کد خود قرار داده و سپس داده‌های ورودی مورد نیاز را به دست آورده و از آن‌ها استفاده کنید.

    در نظر داشته باشید که با توجه به کدی که شما ارائه داده‌اید، من نمی‌توانم پارامترهای args از قبلی را تعیین کنم. به همین دلیل پیشنهاد می‌کنم که شما در صورت لزوم، این پارامترها را به توابع اضافه کنید و پس از رسیدن به پارامترهای مورد نیاز برای کد خود مقادیر آن‌ها را به تابع ارسال کنید.

  3. User

    b_user_edge = find_latest_1D(np.array(ratings.iloc[batch][‘user_id’]), adj_user_edge, adj_user_time, ratings.iloc[batch][‘timestamp’].tolist()) b_user_edge = torch.from_numpy(b_user_edge).to(device) b_users = torch.from_numpy(np.array(ratings.iloc[batch][‘user_id’])).to(device) #print (“b_user”,b_users) b_item_edge = find_latest_1D(np.array(ratings.iloc[batch][‘item_id’]), adj_item_edge, adj_item_time, ratings.iloc[batch] [‘timestamp’].tolist()) b_item_edge = torch.from_numpy(b_item_edge).to(device) b_items = torch.from_numpy(np.array(ratings.iloc[batch][‘item_id’])).to(device) timestamps = torch.from_numpy(np.array(ratings.iloc[batch][‘timestamp’])).to(device)

    negative_samples = sampler(items_in_data, adj_user, ratings.iloc[batch][‘user_id’].tolist() ,1) neg_edge = find_latest(negative_samples, adj_item_edge, adj_item_time, ratings.iloc[batch][‘timestamp’].tolist()) negative_samples = torch.from_numpy(np.array(negative_samples)).to(device) negative_samples = negative_samples.squeeze() neg_edge = torch.from_numpy(neg_edge).to(device) neg_edge = neg_edge.squeeze()

    time0 = time.time()

    user_embeddings = model(b_users, b_user_edge, timestamps, config.n_layer, nodetype=‘user’) item_embeddings = model(b_items, b_item_edge, timestamps, config.n_layer, nodetype=‘item’) negs_embeddings = model(negative_samples, neg_edge, timestamps, config.n_layer, nodetype=‘item’) می خواهم پارامترهای تابع زیر را با توجه به کد بالا تغییر دهم چگونه تغییر دهم def hard_neg_sample(u, seq, pos, neg, hard_items, cnt_items, args): reverse = [] # Record the location of neg_item needs to be reversed this step for uid, user in enumerate(np.nditer(u)): user = int(user) for pid in reversed(range(args.maxlen)): if (pos[uid][pid] == 0): break if (user,pid) not in hard_items: continue for neg_id in range(len(hard_items[(user,pid)])): hard = hard_items[(user,pid)][neg_id] neg[uid][pid][neg_id] = hard if (user,pid,hard) not in cnt_items: cnt_items[(user,pid,hard)] = 0 cnt_items[(user,pid,hard)] += 1

                if cnt_items[(user, pid, hard)] > args.reverse:
                    reverse.append((uid, pid, neg_id))
    return reverse
    

    def update_hard_negs(u, pos, hard_items, all_logits, all_labels, all_samples, args): all_logits = all_logits.detach().cpu().numpy() all_labels = all_labels.detach().cpu().numpy() for uid,user in enumerate(np.nditer(u)): user = int(user) for pid in reversed(range(args.maxlen)): if (pos[uid][pid] == 0): break hard_items[(user, pid)] = [] for neg_id in range(args.neg_nums): if (all_logits[uid][pid][neg_id + 1] > all_logits[uid][pid][0] and all_labels[uid][pid][neg_id + 1] != 1): hard_items[(user,pid)].append(copy.deepcopy(int(all_samples[uid][pid][neg_id + 1]))) return

  4. Assistant

    برای تغییر پارامترهای تابع hard_neg_sample و تابع update_hard_negs با توجه به کد شما، ابتدا ورودی‌های لازم برای این دو تابع را استخراج کرده و همچنین تغییرات درون تابع را اعمال می‌کنیم.

    1. تابع hard_neg_sample:
    def hard_neg_sample(u, pos, neg, hard_items, cnt_items, args):
        reverse = [] 
        for uid, user in enumerate(np.nditer(u)):
            user = int(user)
            for pid in reversed(range(args.maxlen)):
                if (pos[uid][pid] == 0): break
                if (user,pid) not in hard_items: continue
                for neg_id in range(len(hard_items[(user,pid)])):
                    hard = hard_items[(user,pid)][neg_id]
                    neg[uid][pid][neg_id] = hard
                    if (user,pid,hard) not in cnt_items: 
                        cnt_items[(user,pid,hard)] = 0
                    cnt_items[(user,pid,hard)] += 1
    
                    if cnt_items[(user, pid, hard)] > args.reverse:
                        reverse.append((uid, pid, neg_id))
        return reverse
    
    1. تابع update_hard_negs:
    def update_hard_negs(u, pos, hard_items, all_logits, all_labels, all_samples, args):
        all_logits = all_logits.detach().cpu().numpy()
        all_labels = all_labels.detach().cpu().numpy()
        for uid,user in enumerate(np.nditer(u)):
            user = int(user)
            for pid in reversed(range(args.maxlen)):
                if (pos[uid][pid] == 0): break
                hard_items[(user, pid)] = []
                for neg_id in range(args.neg_nums):
                    if (all_logits[uid][pid][neg_id + 1] > all_logits[uid][pid][0] and all_labels[uid][pid][neg_id + 1] != 1):
                        hard_items[(user,pid)].append(copy.deepcopy(int(all_samples[uid][pid][neg_id + 1])))
        return hard_items
    

    بعد از تغییر این دو تابع بر اساس کد شما، می‌توانید آن‌ها را در مکان‌های مربوطه در کد خود به کار برید و سپس ورودی‌های مورد نیاز را از کد:\

    b_user_edge = find_latest_1D(np.array(ratings.iloc[batch]['user_id']), adj_user_edge, adj_user_time, ratings.iloc[batch]['timestamp'].tolist())
    b_user_edge = torch.from_numpy(b_user_edge).to(device)
    b_users = torch.from_numpy(np.array(ratings.iloc[batch]['user_id'])).to(device)
    b_item_edge = find_latest_1D(np.array(ratings.iloc[batch]['item_id']), adj_item_edge, adj_item_time, ratings.iloc[batch]['timestamp'].tolist())
    b_item_edge = torch.from_numpy(b_item_edge).to(device)
    b_items = torch.from_numpy(np.array(ratings.iloc[batch]['item_id'])).to(device)
    timestamps = torch.from_numpy(np.array(ratings.iloc[batch]['timestamp'])).to(device)
    
    negative_samples = sampler(items_in_data, adj_user, ratings.iloc[batch]['user_id'].tolist() ,1)
    neg_edge = find_latest(negative_samples, adj_item_edge, adj_item_time, ratings.iloc[batch]['timestamp'].tolist())
    negative_samples = torch.from_numpy(np.array(negative_samples)).to(device)
    negative_samples = negative_samples.squeeze()
    neg_edge = torch.from_numpy(neg_edge).to(device)
    neg_edge = neg_edge.squeeze()
    
    time0 = time.time()
    
    user_embeddings = model(b_users, b_user_edge, timestamps, config.n_layer, nodetype='user')
    item_embeddings = model(b_items, b_item_edge, timestamps, config.n_layer, nodetype='item')
    negs_embeddings = model(negative_samples, neg_edge, timestamps, config.n_layer, nodetype='item')
    

    به صورت مناسب besed برای توابع استخراج کنید و آن‌ها را به عنوان ورودی ارسال کنید. دقت کنید که برخی از مقادیر ممکن است نیاز به تغییر داشته باشند یا به عنوان پارامتر به توابع اضافه شوند. لطفاً این نکات را بر اساس ساختار کد خود تنظیم کنید.

  5. Assistant

    بنابراین، شما می‌خواهید کد فراهم شده را در توابع hard_neg_sample() و update_hard_negs() درج کنید. در اینجا، این دو تابع را با قرار دادن کد فراهم شده به عنوان ورودی برای این دو تابع تغییر می‌دهم:

    1. تابع hard_neg_sample():
    def hard_neg_sample(b_users, b_items, timestamps, b_item_edge, b_user_edge, config, adj_item_edge, adj_item_time, items_in_data, adj_user, hard_items, cnt_items):
        # Finding the necessary inputs
        u = b_users.cpu().numpy()
        pos = b_items.cpu().numpy()
        neg = np.array(negative_samples).tolist()
        
        # ... Hard Negative Sampling logic ...
    
        return reverse
    
    1. تابع update_hard_negs():
    def update_hard_negs(b_users, b_items, negative_samples, neg_edge, timestamps, config, model, hard_items):
        # Finding the necessary inputs
        u = b_users.cpu().numpy()
        pos = b_items.cpu().numpy()
        all_samples = np.array(negative_samples).tolist()
    
        # Calculate logits
        logits = model.target_noise(b_items, b_item_edge, timestamps, config.n_layer, b_users, nodetype='item')
        all_logits = logits.detach().cpu().numpy()
       
        # Calculate labels
        labels = torch.zeros(1, config.item_count).scatter(1, b_items, 1)
        all_labels = labels.detach().cpu().numpy()
    
        # ... Update Hard Negative logic ...
    
        return hard_items
    

    همچنین، می‌توانید این توابع را به کار ببرید و ورودی‌های مورد نیاز را از کد به دست بیاورید:

    b_user_edge = find_latest_1D(np.array(ratings.iloc[batch]['user_id']), adj_user_edge, adj_user_time, ratings.iloc[batch]['timestamp'].tolist())
    b_user_edge = torch.from_numpy(b_user_edge).to(device)
    b_users = torch.from_numpy(np.array(ratings.iloc[batch]['user_id'])).to(device)
    b_item_edge = find_latest_1D(np.array(ratings.iloc[batch]['item_id']), adj_item_edge, adj_item_time, ratings.iloc[batch]['timestamp'].tolist())
    b_item_edge = torch.from_numpy(b_item_edge).to(device)
    b_items = torch.from_numpy(np.array(ratings.iloc[batch]['item_id'])).to(device)
    timestamps = torch.from_numpy(np.array(ratings.iloc[batch]['timestamp'])).to(device)
    
    negative_samples = sampler(items_in_data, adj_user, ratings.iloc[batch]['user_id'].tolist() ,1)
    neg_edge = find_latest(negative_samples, adj_item_edge, adj_item_time, ratings.iloc[batch]['timestamp'].tolist())
    negative_samples = torch.from_numpy(np.array(negative_samples)).to(device)
    negative_samples = negative_samples.squeeze()
    neg_edge = torch.from_numpy(neg_edge).to(device)
    neg_edge = neg_edge.squeeze()
    
    time0 = time.time()
    
    user_embeddings = model(b_users, b_user_edge, timestamps, config.n_layer, nodetype='user')
    item_embeddings = model(b_items, b_item_edge, timestamps, config.n_layer, nodetype='item')
    negs_embeddings = model(negative_samples, neg_edge, timestamps, config.n_layer, nodetype='item')
    
    reverse = hard_neg_sample(b_users, b_items, timestamps, b_item_edge, b_user_edge, config, adj_item_edge, adj_item_time, items_in_data, adj_user, hard_items, cnt_items)
    hard_items = update_hard_negs(b_users, b_items, negative_samples, neg_edge, timestamps, config, model, hard_items)
    

    مطمئن شوید که متغیرهای hard_items و cnt_items به درستی مقداردهی شده‌اند - قبل از فراخوانی توابع. دقت کنید که برخی از مقادیر ممکن است نیاز به اصلاح داشته باشند یا به عنوان پارامتر به توابع اضافه شود. لطفاً توجه داشته باشید که شما باید این مقادیر را بر اساس ساختار کد خود تنظیم کنید.

  6. User

    b_user_edge = find_latest_1D(np.array(ratings.iloc[batch]['user_id']), adj_user_edge, adj_user_time, ratings.iloc[batch]['timestamp'].tolist()) b_user_edge = torch.from_numpy(b_user_edge).to(device) b_users = torch.from_numpy(np.array(ratings.iloc[batch]['user_id'])).to(device) #print ("b_user",b_users) b_item_edge = find_latest_1D(np.array(ratings.iloc[batch]['item_id']), adj_item_edge, adj_item_time, ratings.iloc[batch] ['timestamp'].tolist()) b_item_edge = torch.from_numpy(b_item_edge).to(device) b_items = torch.from_numpy(np.array(ratings.iloc[batch]['item_id'])).to(device) timestamps = torch.from_numpy(np.array(ratings.iloc[batch]['timestamp'])).to(device) negative_samples = sampler(items_in_data, adj_user, ratings.iloc[batch]['user_id'].tolist() ,1) neg_edge = find_latest(negative_samples, adj_item_edge, adj_item_time, ratings.iloc[batch]['timestamp'].tolist()) negative_samples = torch.from_numpy(np.array(negative_samples)).to(device) negative_samples = negative_samples.squeeze() neg_edge = torch.from_numpy(neg_edge).to(device) neg_edge = neg_edge.squeeze()

        time0 = time.time()
    
        user_embeddings = model(b_users, b_user_edge, timestamps, config.n_layer, nodetype='user')
        item_embeddings = model(b_items, b_item_edge, timestamps, config.n_layer, nodetype='item')
        negs_embeddings = model(negative_samples, neg_edge, timestamps, config.n_layer, nodetype='item')
    

    می خواهم پارامترهای تابع زیر را با توجه به کد بالا تغییر دهم چگونه تغییر دهم def hard_neg_sample(u, seq, pos, neg, hard_items, cnt_items, args): reverse = [] # Record the location of neg_item needs to be reversed this step for uid, user in enumerate(np.nditer(u)): user = int(user) for pid in reversed(range(args.maxlen)): if (pos[uid][pid] == 0): break if (user,pid) not in hard_items: continue for neg_id in range(len(hard_items[(user,pid)])): hard = hard_items[(user,pid)][neg_id] neg[uid][pid][neg_id] = hard if (user,pid,hard) not in cnt_items: cnt_items[(user,pid,hard)] = 0 cnt_items[(user,pid,hard)] += 1 if cnt_items[(user, pid, hard)] > args.reverse: reverse.append((uid, pid, neg_id)) return reverse de

  7. Assistant

    برای تغییر پارامترهای توابع hard_neg_sample() با توجه به کدهای فراهم شده، می‌توانید تابع را به شکل زیر تغییر دهید:

    def hard_neg_sample(u, pos, neg, hard_items, cnt_items, args):
        reverse = [] 
        for uid, user in enumerate(np.nditer(u)):
            user = int(user)
            for pid in reversed(range(args.maxlen)):
                if (pos[uid][pid] == 0): break
                if (user,pid) not in hard_items: continue
                for neg_id in range(len(hard_items[(user,pid)])):
                    hard = hard_items[(user,pid)][neg_id]
                    neg[uid][pid][neg_id] = hard
                    if (user,pid,hard) not in cnt_items: 
                        cnt_items[(user,pid,hard)] = 0
                    cnt_items[(user,pid,hard)] += 1
    
                    if cnt_items[(user, pid, hard)] > args.reverse:
                        reverse.append((uid, pid, neg_id))
        return reverse
    

    حال می‌توانید این تابع را در جای مناسبی از کد خود قرار دهید و پارامترهای لازم را مطابق کدهای شما برای تابع فرستاده کنید.

    نمونه کد استفاده از تابع در زیر آورده شده است:

    # محاسبه‌ی مقادیر ورودی مربوط به تابع
    u = b_users.cpu().numpy()
    pos = b_items.cpu().numpy()
    neg = negative_samples.cpu().numpy().tolist()
    
    # استفاده از تابع hard_neg_sample
    reverse = hard_neg_sample(u, pos, neg, hard_items, cnt_items, args)
    

    مطمئن شوید که متغیرهای hard_items و cnt_items به درستی مقداردهی شده‌اند - قبل از فراخوانی توابع.

    توجه کنید که برخی از مقادیر ممکن است نیاز به تغییر داشته باشند یا به عنوان پارامتر به توابع اضافه شود. لطفاً توجه داشته باشید که شما باید این مقادیر را بر اساس ساختار کد خود تنظیم کنید.