第九章 社交图谱与图神经网络
9.1 人是关系的总和
推荐系统传统的做法是将每个用户视为独立的个体,通过用户自身的特征和行为来建模。但在现实中,人不是孤立的——每个人都是社交网络中的一个节点,与周围的人有着千丝万缕的联系。
在婚恋场景中,社交关系的价值尤为突出:
- "朋友的朋友"更容易建立信任
- 共同的社交圈提供了社会验证
- 社交关系反映了一个人的社会资本和生活方式
图神经网络(Graph Neural Network, GNN)为建模这种复杂的关系网络提供了强大的工具。
9.2 婚恋场景的图结构
9.2.1 异构图建模
婚恋场景中的关系是多样化的,适合用异构图(Heterogeneous Graph)来建模:
import torch
from torch_geometric.data import HeteroData
def build_dating_graph(users, interactions, social_relations):
"""
构建婚恋场景的异构图
"""
graph = HeteroData()
# 节点类型
graph['user'].x = user_features # 用户节点特征
graph['photo'].x = photo_features # 照片节点特征
graph['hobby'].x = hobby_features # 爱好节点特征
graph['location'].x = location_features # 地点节点特征
# 边类型
# 用户-用户:浏览/喜欢/消息
graph['user', 'views', 'user'].edge_index = view_edges
graph['user', 'likes', 'user'].edge_index = like_edges
graph['user', 'messages', 'user'].edge_index = message_edges
# 用户-照片:上传
graph['user', 'uploads', 'photo'].edge_index = upload_edges
# 用户-爱好:拥有
graph['user', 'has_hobby', 'hobby'].edge_index = hobby_edges
# 用户-地点:常去
graph['user', 'frequents', 'location'].edge_index = location_edges
# 用户-用户:社交关系(朋友、共同好友)
graph['user', 'friends_with', 'user'].edge_index = friend_edges
graph['user', 'mutual_friends', 'user'].edge_index = mutual_friend_edges
return graph
9.2.2 边的权重设计
不同类型的边应该有不同的权重,反映关系的强度和重要性:
def compute_edge_weights(graph):
"""计算边的权重"""
# 浏览权重:基于浏览次数和时长
view_weights = []
for i in range(graph['user', 'views', 'user'].edge_index.size(1)):
src, dst = graph['user', 'views', 'user'].edge_index[:, i]
view_count = get_view_count(src.item(), dst.item())
avg_duration = get_avg_view_duration(src.item(), dst.item())
weight = np.log1p(view_count) * (1 + avg_duration / 60)
view_weights.append(weight)
graph['user', 'views', 'user'].edge_attr = torch.tensor(view_weights)
# 消息权重:基于消息数量和对话质量
message_weights = []
for i in range(graph['user', 'messages', 'user'].edge_index.size(1)):
src, dst = graph['user', 'messages', 'user'].edge_index[:, i]
msg_count = get_message_count(src.item(), dst.item())
quality = get_conversation_quality(src.item(), dst.item())
weight = np.log1p(msg_count) * quality
message_weights.append(weight)
graph['user', 'messages', 'user'].edge_attr = torch.tensor(message_weights)
return graph
9.3 图神经网络模型
9.3.1 基础GNN:消息传递机制
GNN的核心思想是消息传递:每个节点通过聚合邻居的信息来更新自己的表示。
import torch
import torch.nn as nn
from torch_geometric.nn import GATConv, HeteroConv
class DatingGNN(nn.Module):
"""婚恋场景的图神经网络"""
def __init__(self, hidden_dim=128, num_layers=3, num_heads=4):
super().__init__()
# 节点类型特定的输入投影
self.user_proj = nn.Linear(user_feat_dim, hidden_dim)
self.photo_proj = nn.Linear(photo_feat_dim, hidden_dim)
self.hobby_proj = nn.Linear(hobby_feat_dim, hidden_dim)
self.location_proj = nn.Linear(location_feat_dim, hidden_dim)
# 异构图卷积层
self.convs = nn.ModuleList()
for _ in range(num_layers):
conv = HeteroConv({
('user', 'views', 'user'): GATConv(hidden_dim, hidden_dim, heads=num_heads),
('user', 'likes', 'user'): GATConv(hidden_dim, hidden_dim, heads=num_heads),
('user', 'messages', 'user'): GATConv(hidden_dim, hidden_dim, heads=num_heads),
('user', 'friends_with', 'user'): GATConv(hidden_dim, hidden_dim, heads=num_heads),
('user', 'has_hobby', 'hobby'): GATConv(hidden_dim, hidden_dim, heads=num_heads),
('user', 'frequents', 'location'): GATConv(hidden_dim, hidden_dim, heads=num_heads),
})
self.convs.append(conv)
# 输出层
self.output = nn.Linear(hidden_dim, hidden_dim)
def forward(self, graph):
# 节点特征投影
x_dict = {
'user': self.user_proj(graph['user'].x),
'photo': self.photo_proj(graph['photo'].x),
'hobby': self.hobby_proj(graph['hobby'].x),
'location': self.location_proj(graph['location'].x),
}
# 多层消息传递
for conv in self.convs:
x_dict = conv(x_dict, graph.edge_index_dict)
x_dict = {key: torch.relu(x) for key, x in x_dict.items()}
# 输出用户表示
user_embeddings = self.output(x_dict['user'])
return user_embeddings
9.3.2 注意力机制的可解释性
GAT(Graph Attention Network)的注意力权重可以告诉我们,在聚合邻居信息时,哪些关系最重要:
def explain_user_embedding(user_id, gnn_model, graph):
"""解释用户嵌入的来源"""
# 获取最后一层的注意力权重
_, attention_weights = gnn_model.get_attention_weights(graph)
# 分析不同关系类型的重要性
explanations = {}
for edge_type, weights in attention_weights.items():
# 找到目标用户相关的边
relevant_edges = get_edges_for_user(user_id, edge_type, graph)
relevant_weights = weights[relevant_edges]
explanations[edge_type] = {
"avg_weight": relevant_weights.mean().item(),
"top_neighbors": get_top_neighbors(user_id, edge_type, relevant_weights, graph)
}
return explanations
9.4 社交关系在匹配中的应用
9.4.1 朋友的朋友
"朋友的朋友"是婚恋匹配中一个经典且有效的信号。研究表明,通过共同朋友认识的情侣,关系满意度和持久性都更高。
def friends_of_friends_recommendation(user_id, social_graph, max_hops=2):
"""基于朋友的朋友的推荐"""
# BFS查找2跳内的用户
candidates = set()
visited = {user_id}
queue = [(user_id, 0)]
while queue:
current, depth = queue.pop(0)
if depth >= max_hops:
continue
neighbors = get_neighbors(current, social_graph)
for neighbor in neighbors:
if neighbor not in visited:
visited.add(neighbor)
queue.append((neighbor, depth + 1))
if depth + 1 <= max_hops and is_potential_match(user_id, neighbor):
# 计算共同好友数量
mutual_count = count_mutual_friends(user_id, neighbor, social_graph)
candidates.add((neighbor, mutual_count, depth + 1))
# 按共同好友数和距离排序
candidates = sorted(candidates, key=lambda x: (-x[1], x[2]))
return candidates
9.4.2 社交验证
社交关系提供了社会验证——如果一个人的社交圈中有你认识且信任的人,你对这个人的信任度会更高。
def compute_social_trust(user_a, user_b, social_graph):
"""计算社交信任分数"""
trust_score = 0
# 1. 直接好友关系
if are_friends(user_a, user_b, social_graph):
trust_score += 0.5
# 2. 共同好友数量
mutual_friends = get_mutual_friends(user_a, user_b, social_graph)
trust_score += min(len(mutual_friends) * 0.1, 0.3)
# 3. 共同好友的质量(好友的好友的影响力)
for friend in mutual_friends:
friend_influence = get_user_influence(friend, social_graph)
trust_score += friend_influence * 0.05
# 4. 社交圈重叠度
circle_overlap = compute_circle_overlap(user_a, user_b, social_graph)
trust_score += circle_overlap * 0.2
return min(trust_score, 1.0)
9.4.3 社交圈层分析
通过图分析可以识别用户的社交圈层,这对于理解一个人的社会背景和生活方式很有价值:
def detect_social_circles(user_id, social_graph):
"""检测用户的社交圈层"""
# 使用社区发现算法
from community import community_louvain
# 获取用户的局部子图
ego_graph = get_ego_graph(user_id, social_graph, radius=2)
# Louvain社区发现
partition = community_louvain.best_partition(ego_graph)
# 分析每个社区的特征
circles = {}
for node, comm_id in partition.items():
if comm_id not in circles:
circles[comm_id] = []
circles[comm_id].append(node)
# 为每个圈层添加语义标签
circle_labels = {}
for comm_id, members in circles.items():
# 分析圈层成员的共同特征
common_features = analyze_circle_commonality(members, social_graph)
circle_labels[comm_id] = {
"size": len(members),
"features": common_features,
"label": generate_circle_label(common_features)
}
return circle_labels
9.5 图嵌入在推荐中的应用
9.5.1 Node2Vec:学习节点表示
Node2Vec是一种经典的图嵌入方法,通过随机游走学习节点的低维表示:
from node2vec import Node2Vec
def learn_user_embeddings(social_graph, dimensions=128):
"""使用Node2Vec学习用户嵌入"""
# 配置Node2Vec
node2vec = Node2Vec(
social_graph,
dimensions=dimensions,
walk_length=30,
num_walks=200,
p=1, # 返回参数
q=0.5, # 外出参数(<1偏向BFS,>1偏向DFS)
workers=4
)
# 训练模型
model = node2vec.fit(window=10, min_count=1)
# 获取用户嵌入
user_embeddings = {}
for user_id in social_graph.nodes():
user_embeddings[user_id] = model.wv[str(user_id)]
return user_embeddings
9.5.2 图嵌入与推荐的结合
将图嵌入与其他特征结合,可以提升推荐效果:
def hybrid_recommendation(user_id, gnn_embeddings, cf_scores, content_scores):
"""
混合推荐:结合图嵌入、协同过滤和内容匹配
"""
candidates = get_all_candidates(user_id)
final_scores = []
for candidate_id in candidates:
# 图嵌入相似度
gnn_sim = cosine_similarity(
gnn_embeddings[user_id],
gnn_embeddings[candidate_id]
)
# 协同过滤分数
cf_score = cf_scores.get((user_id, candidate_id), 0)
# 内容匹配分数
content_score = content_scores.get((user_id, candidate_id), 0)
# 加权融合
final_score = (
0.4 * gnn_sim +
0.3 * cf_score +
0.3 * content_score
)
final_scores.append((candidate_id, final_score))
return sorted(final_scores, key=lambda x: x[1], reverse=True)
9.6 图神经网络的挑战
9.6.1 冷启动问题
新用户没有社交关系,无法从图中获得有用的信息。解决方案包括:
- 利用注册信息初始化节点特征
- 通过兴趣相似性建立虚拟社交连接
- 使用归纳式GNN(Inductive GNN),支持对新节点的泛化
9.6.2 动态图更新
社交关系是动态变化的——新好友、解除好友、新的互动。图模型需要支持增量更新:
class DynamicGNN:
"""支持动态更新的GNN"""
def __init__(self, base_model):
self.model = base_model
self.graph = None
self.embeddings = None
def incremental_update(self, new_edges, removed_edges):
"""增量更新图结构"""
# 添加新边
for edge in new_edges:
self.graph.add_edge(*edge)
# 移除旧边
for edge in removed_edges:
self.graph.remove_edge(*edge)
# 只重新计算受影响的节点嵌入
affected_nodes = get_affected_nodes(new_edges + removed_edges)
self._partial_recompute(affected_nodes)
def _partial_recompute(self, nodes):
"""部分重新计算节点嵌入"""
# 使用之前计算的邻居嵌入作为初始化
# 进行少量迭代的局部消息传递
pass
9.6.3 隐私保护
社交图谱包含敏感的社交关系信息,需要特别注意隐私保护:
- 差分隐私:在图数据中添加噪声,防止个体识别
- 联邦图学习:在不共享原始图数据的情况下训练模型
- 图匿名化:移除可识别信息,同时保留图的结构特征
下一章预告:推荐不是一次性的事情,而是一个持续优化的过程。第10章将探讨强化学习如何让推荐系统越用越好。