1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
| /**
* 社交網絡中的社群檢測服務
* 使用圖論算法檢測用戶社群
*/
@Service
public class SocialNetworkAnalysisService {
/**
* 社交關係實體
*/
@Entity
@Table(name = "social_relationships")
public static class SocialRelationship {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "user_id_1")
private Long userId1;
@Column(name = "user_id_2")
private Long userId2;
@Enumerated(EnumType.STRING)
private RelationshipType type;
@Column(name = "strength")
private Double strength; // 關係強度 0.0 - 1.0
@Column(name = "created_at")
private LocalDateTime createdAt;
public enum RelationshipType {
FRIEND, FOLLOWER, COLLEAGUE, FAMILY, ACQUAINTANCE
}
// 構造函數、getter、setter 省略
}
/**
* 社群檢測結果
*/
public static class CommunityDetectionResult {
private final List<List<Long>> communities;
private final Map<Long, Integer> userToCommunity;
private final double modularity;
private final int communityCount;
public CommunityDetectionResult(List<List<Long>> communities,
Map<Long, Integer> userToCommunity,
double modularity) {
this.communities = communities;
this.userToCommunity = userToCommunity;
this.modularity = modularity;
this.communityCount = communities.size();
}
// getter 方法省略
}
/**
* 檢測社交網絡中的社群
*/
public CommunityDetectionResult detectCommunities(
List<SocialRelationship> relationships,
double strengthThreshold) {
// 構建加權圖
Map<Long, Set<Long>> graph = buildWeightedGraph(relationships, strengthThreshold);
// 使用並查集檢測連通分量作為初始社群
GenericUnionFind<Long> uf = new GenericUnionFind<>();
// 初始化所有用戶
Set<Long> allUsers = getAllUsers(relationships);
for (Long userId : allUsers) {
uf.makeSet(userId);
}
// 根據關係強度進行合併
for (SocialRelationship relationship : relationships) {
if (relationship.getStrength() >= strengthThreshold) {
uf.union(relationship.getUserId1(), relationship.getUserId2());
}
}
// 獲取社群
Map<Long, List<Long>> rawCommunities = uf.getConnectedComponents();
List<List<Long>> communities = new ArrayList<>(rawCommunities.values());
// 建立用戶到社群的映射
Map<Long, Integer> userToCommunity = new HashMap<>();
for (int i = 0; i < communities.size(); i++) {
for (Long userId : communities.get(i)) {
userToCommunity.put(userId, i);
}
}
// 計算模塊度(衡量社群檢測質量的指標)
double modularity = calculateModularity(relationships, userToCommunity);
return new CommunityDetectionResult(communities, userToCommunity, modularity);
}
/**
* 構建加權圖
*/
private Map<Long, Set<Long>> buildWeightedGraph(
List<SocialRelationship> relationships,
double strengthThreshold) {
Map<Long, Set<Long>> graph = new HashMap<>();
for (SocialRelationship relationship : relationships) {
if (relationship.getStrength() >= strengthThreshold) {
Long user1 = relationship.getUserId1();
Long user2 = relationship.getUserId2();
graph.computeIfAbsent(user1, k -> new HashSet<>()).add(user2);
graph.computeIfAbsent(user2, k -> new HashSet<>()).add(user1);
}
}
return graph;
}
/**
* 獲取所有用戶ID
*/
private Set<Long> getAllUsers(List<SocialRelationship> relationships) {
Set<Long> users = new HashSet<>();
for (SocialRelationship relationship : relationships) {
users.add(relationship.getUserId1());
users.add(relationship.getUserId2());
}
return users;
}
/**
* 計算網絡模塊度
* 模塊度是衡量社群檢測質量的重要指標
*/
private double calculateModularity(List<SocialRelationship> relationships,
Map<Long, Integer> userToCommunity) {
int totalEdges = relationships.size();
if (totalEdges == 0) return 0.0;
// 計算每個社群內部的邊數
Map<Integer, Integer> internalEdges = new HashMap<>();
Map<Long, Integer> userDegree = new HashMap<>();
// 統計每個用戶的度數
for (SocialRelationship relationship : relationships) {
Long user1 = relationship.getUserId1();
Long user2 = relationship.getUserId2();
userDegree.put(user1, userDegree.getOrDefault(user1, 0) + 1);
userDegree.put(user2, userDegree.getOrDefault(user2, 0) + 1);
// 如果兩個用戶在同一社群,增加內部邊數
Integer community1 = userToCommunity.get(user1);
Integer community2 = userToCommunity.get(user2);
if (community1 != null && community1.equals(community2)) {
internalEdges.put(community1,
internalEdges.getOrDefault(community1, 0) + 1);
}
}
// 計算模塊度
double modularity = 0.0;
Map<Integer, Integer> communityDegreeSum = new HashMap<>();
// 計算每個社群的度數總和
for (Map.Entry<Long, Integer> entry : userToCommunity.entrySet()) {
Long userId = entry.getKey();
Integer communityId = entry.getValue();
int degree = userDegree.getOrDefault(userId, 0);
communityDegreeSum.put(communityId,
communityDegreeSum.getOrDefault(communityId, 0) + degree);
}
// 計算模塊度公式:Q = (1/2m) * Σ[Aij - (ki*kj/2m)] * δ(ci, cj)
for (Map.Entry<Integer, Integer> entry : internalEdges.entrySet()) {
Integer communityId = entry.getKey();
Integer internal = entry.getValue();
Integer degreeSum = communityDegreeSum.get(communityId);
double expectedInternal = (double) (degreeSum * degreeSum) / (4.0 * totalEdges);
modularity += (internal - expectedInternal) / totalEdges;
}
return modularity;
}
/**
* 分析社群特徵
*/
public Map<String, Object> analyzeCommunityCharacteristics(
CommunityDetectionResult result,
List<SocialRelationship> relationships) {
Map<String, Object> analysis = new HashMap<>();
// 基本統計
analysis.put("totalCommunities", result.getCommunityCount());
analysis.put("modularity", result.getModularity());
// 社群大小分析
List<Integer> communitySizes = result.getCommunities().stream()
.map(List::size)
.sorted(Collections.reverseOrder())
.collect(Collectors.toList());
analysis.put("communitySizes", communitySizes);
analysis.put("largestCommunitySize", communitySizes.get(0));
analysis.put("averageCommunitySize",
communitySizes.stream().mapToInt(Integer::intValue).average().orElse(0.0));
// 社群密度分析
Map<Integer, Double> communityDensities = calculateCommunityDensities(
result, relationships);
analysis.put("communityDensities", communityDensities);
return analysis;
}
private Map<Integer, Double> calculateCommunityDensities(
CommunityDetectionResult result,
List<SocialRelationship> relationships) {
Map<Integer, Double> densities = new HashMap<>();
for (int i = 0; i < result.getCommunities().size(); i++) {
List<Long> community = result.getCommunities().get(i);
int communitySize = community.size();
if (communitySize < 2) {
densities.put(i, 0.0);
continue;
}
// 計算社群內部的邊數
int internalEdges = 0;
Set<Long> communitySet = new HashSet<>(community);
for (SocialRelationship relationship : relationships) {
if (communitySet.contains(relationship.getUserId1()) &&
communitySet.contains(relationship.getUserId2())) {
internalEdges++;
}
}
// 密度 = 實際邊數 / 可能的最大邊數
int maxPossibleEdges = communitySize * (communitySize - 1) / 2;
double density = (double) internalEdges / maxPossibleEdges;
densities.put(i, density);
}
return densities;
}
}
|
留言討論