鏈路預測算法MATLAB實現

鏈路預測算法MATLAB實現

鏈路預測是復雜網絡分析中的重要任務,旨在預測網絡中尚未連接的兩個節點之間未來產生連接的可能性。

程序概述

MATLAB程序實現了以下鏈路預測算法:

  1. 基于局部信息的相似性指標(Common Neighbors, Jaccard, Adamic-Adar等)
  2. 基于路徑的相似性指標(Katz指數)
  3. 基于隨機游走的相似性指標(Rooted PageRank, SimRank)
  4. 矩陣分解方法

代碼

classdef LinkPrediction%LINKPREDICTION 鏈路預測算法實現%   包含多種鏈路預測算法propertiesA;          % 鄰接矩陣train_mask; % 訓練掩碼矩陣test_mask;  % 測試掩碼矩陣methods;    % 可用的預測方法endmethodsfunction obj = LinkPrediction(adj_matrix, train_ratio)%LINKPREDICTION 構造函數%   adj_matrix - 網絡鄰接矩陣%   train_ratio - 訓練集比例(0-1)obj.A = adj_matrix;obj.methods = {'CommonNeighbors', 'Jaccard', 'AdamicAdar', ...'PreferentialAttachment', 'Katz', 'RootedPageRank', ...'SimRank', 'MatrixFactorization'};% 劃分訓練集和測試集if nargin > 1obj = obj.split_dataset(train_ratio);elseobj.train_mask = ones(size(obj.A));obj.test_mask = zeros(size(obj.A));endendfunction obj = split_dataset(obj, train_ratio)%SPLIT_DATASET 劃分訓練集和測試集%   隨機隱藏一部分邊作為測試集[n, ~] = size(obj.A);obj.train_mask = ones(n);obj.test_mask = zeros(n);% 獲取所有邊的索引[rows, cols] = find(triu(obj.A, 1)); % 只取上三角避免重復num_edges = length(rows);num_train = round(num_edges * train_ratio);% 隨機選擇訓練邊idx = randperm(num_edges);train_idx = idx(1:num_train);test_idx = idx(num_train+1:end);% 創建掩碼矩陣for i = 1:length(test_idx)r = rows(test_idx(i));c = cols(test_idx(i));obj.train_mask(r, c) = 0;obj.train_mask(c, r) = 0;obj.test_mask(r, c) = 1;obj.test_mask(c, r) = 1;end% 確保對角線為0obj.train_mask(1:n+1:end) = 0;obj.test_mask(1:n+1:end) = 0;endfunction scores = common_neighbors(obj)%COMMON_NEIGHBORS 共同鄰居算法scores = (obj.A * obj.A) .* obj.train_mask;endfunction scores = jaccard(obj)%JACCARD Jaccard相似系數[n, ~] = size(obj.A);scores = zeros(n);for i = 1:nfor j = i+1:nif obj.train_mask(i, j) == 0continue;endneighbors_i = find(obj.A(i, :));neighbors_j = find(obj.A(j, :));intersection = length(intersect(neighbors_i, neighbors_j));union = length(union(neighbors_i, neighbors_j));if union > 0scores(i, j) = intersection / union;elsescores(i, j) = 0;endscores(j, i) = scores(i, j);endendendfunction scores = adamic_adar(obj)%ADAMIC_ADAR Adamic-Adar指數[n, ~] = size(obj.A);scores = zeros(n);% 計算每個節點的度degrees = sum(obj.A, 2);for i = 1:nfor j = i+1:nif obj.train_mask(i, j) == 0continue;endcommon_neighbors = find(obj.A(i, :) & obj.A(j, :));score = 0;for k = common_neighborsif degrees(k) > 1 % 避免除以0score = score + 1 / log(degrees(k));endendscores(i, j) = score;scores(j, i) = score;endendendfunction scores = preferential_attachment(obj)%PREFERENTIAL_ATTACHMENT 優先連接算法degrees = sum(obj.A, 2);scores = (degrees * degrees') .* obj.train_mask;endfunction scores = katz(obj, beta)%KATZ Katz指數%   beta - 衰減因子,默認0.01if nargin < 2beta = 0.01;end[n, ~] = size(obj.A);I = eye(n);scores = beta * obj.A; % 長度為1的路徑% 計算Katz指數:S = βA + β2A2 + β3A3 + ...% 使用矩陣求逆近似:S = (I - βA)^-1 - Iscores = inv(I - beta * obj.A) - I;scores = scores .* obj.train_mask;endfunction scores = rooted_pagerank(obj, alpha, max_iter, tol)%ROOTED_PAGERANK Rooted PageRank算法%   alpha - 隨機游走概率,默認0.85%   max_iter - 最大迭代次數,默認100%   tol - 收斂容差,默認1e-6if nargin < 2alpha = 0.85;endif nargin < 3max_iter = 100;endif nargin < 4tol = 1e-6;end[n, ~] = size(obj.A);scores = zeros(n);% 創建列隨機矩陣(轉移概率矩陣)P = obj.A ./ sum(obj.A, 1);P(isnan(P)) = 0; % 處理度為0的節點% 對每個節點計算Rooted PageRankfor i = 1:nr = zeros(n, 1);r(i) = 1;for iter = 1:max_iterr_new = alpha * P * r + (1 - alpha) * r;if norm(r_new - r, 1) < tolbreak;endr = r_new;endscores(:, i) = r;endscores = scores .* obj.train_mask;endfunction scores = simrank(obj, C, max_iter, tol)%SIMRANK SimRank算法%   C - 衰減因子,默認0.8%   max_iter - 最大迭代次數,默認10%   tol - 收斂容差,默認1e-4if nargin < 2C = 0.8;endif nargin < 3max_iter = 10;endif nargin < 4tol = 1e-4;end[n, ~] = size(obj.A);S = eye(n); % 初始化SimRank矩陣% 計算入鄰居in_neighbors = cell(n, 1);for i = 1:nin_neighbors{i} = find(obj.A(:, i));end% 迭代計算SimRankfor iter = 1:max_iterS_old = S;for i = 1:nfor j = 1:nif i == jS(i, j) = 1;continue;endin_i = in_neighbors{i};in_j = in_neighbors{j};if isempty(in_i) || isempty(in_j)S(i, j) = 0;continue;endsum_sim = 0;for a = 1:length(in_i)for b = 1:length(in_j)sum_sim = sum_sim + S_old(in_i(a), in_j(b));endendS(i, j) = C * sum_sim / (length(in_i) * length(in_j));endendif norm(S - S_old, 'fro') < tolbreak;endendscores = S .* obj.train_mask;endfunction scores = matrix_factorization(obj, dim, lambda, max_iter, learning_rate)%MATRIX_FACTORIZATION 矩陣分解方法%   dim - 潛在特征維度,默認10%   lambda - 正則化參數,默認0.01%   max_iter - 最大迭代次數,默認100%   learning_rate - 學習率,默認0.01if nargin < 2dim = 10;endif nargin < 3lambda = 0.01;endif nargin < 4max_iter = 100;endif nargin < 5learning_rate = 0.01;end[n, ~] = size(obj.A);% 初始化用戶和物品特征矩陣U = randn(n, dim) * 0.01;V = randn(n, dim) * 0.01;% 獲取訓練集中的非零元素(即存在的邊)[rows, cols] = find(obj.train_mask);values = ones(length(rows), 1);% 隨機梯度下降for iter = 1:max_itertotal_error = 0;for idx = 1:length(rows)i = rows(idx);j = cols(idx);% 計算預測值和誤差prediction = U(i, :) * V(j, :)';error = values(idx) - prediction;total_error = total_error + error^2;% 更新特征向量U_i_old = U(i, :);U(i, :) = U(i, :) + learning_rate * (error * V(j, :) - lambda * U(i, :));V(j, :) = V(j, :) + learning_rate * (error * U_i_old - lambda * V(j, :));end% 添加正則化項total_error = total_error + lambda * (norm(U, 'fro')^2 + norm(V, 'fro')^2);if mod(iter, 10) == 0fprintf('迭代 %d, 誤差: %.4f\n', iter, total_error);endend% 計算得分矩陣scores = U * V';scores = scores .* obj.train_mask;endfunction [precision, recall, auc] = evaluate(obj, scores, top_k)%EVALUATE 評估預測結果%   scores - 預測得分矩陣%   top_k - 計算precision@k和recall@k的k值if nargin < 3top_k = 100;end% 獲取測試集中的正樣本[test_rows, test_cols] = find(obj.test_mask);positive_pairs = [test_rows, test_cols];num_positives = size(positive_pairs, 1);% 獲取所有未連接的節點對(負樣本+測試正樣本)negative_mask = (obj.train_mask == 0) & (obj.A == 0) & (eye(size(obj.A)) == 0);[negative_rows, negative_cols] = find(negative_mask);negative_pairs = [negative_rows, negative_cols];% 隨機選擇與正樣本數量相同的負樣本idx = randperm(size(negative_pairs, 1), num_positives);negative_pairs = negative_pairs(idx, :);% 合并正負樣本all_pairs = [positive_pairs; negative_pairs];labels = [ones(num_positives, 1); zeros(num_positives, 1)];% 獲取預測得分pred_scores = zeros(size(all_pairs, 1), 1);for i = 1:size(all_pairs, 1)pred_scores(i) = scores(all_pairs(i, 1), all_pairs(i, 2));end% 計算AUC[~, ~, ~, auc] = perfcurve(labels, pred_scores, 1);% 計算Precision@K和Recall@K% 獲取得分最高的top_k個節點對[~, sorted_idx] = sort(pred_scores(1:num_positives), 'descend');top_predictions = sorted_idx(1:min(top_k, length(sorted_idx)));true_positives = sum(ismember(top_predictions, 1:num_positives));precision = true_positives / top_k;recall = true_positives / num_positives;endfunction results = compare_methods(obj, methods, top_k)%COMPARE_METHODS 比較不同算法的性能%   methods - 要比較的方法列表%   top_k - 計算precision@k和recall@k的k值if nargin < 2methods = obj.methods;endif nargin < 3top_k = 100;endresults = struct();for i = 1:length(methods)method = methods{i};fprintf('正在計算 %s...\n', method);try% 調用相應的方法tic;scores = obj.(lower(method))();time = toc;% 評估性能[precision, recall, auc] = obj.evaluate(scores, top_k);% 保存結果results.(method).scores = scores;results.(method).precision = precision;results.(method).recall = recall;results.(method).auc = auc;results.(method).time = time;fprintf('%s: Precision@%d=%.4f, Recall@%d=%.4f, AUC=%.4f, 時間=%.2fs\n', ...method, top_k, precision, top_k, recall, auc, time);catch MEfprintf('計算 %s 時出錯: %s\n', method, ME.message);results.(method).error = ME.message;endendendfunction plot_results(obj, results)%PLOT_RESULTS 可視化比較結果methods = fieldnames(results);num_methods = length(methods);precisions = zeros(num_methods, 1);recalls = zeros(num_methods, 1);aucs = zeros(num_methods, 1);times = zeros(num_methods, 1);for i = 1:num_methodsif isfield(results.(methods{i}), 'error')continue;endprecisions(i) = results.(methods{i}).precision;recalls(i) = results.(methods{i}).recall;aucs(i) = results.(methods{i}).auc;times(i) = results.(methods{i}).time;end% 創建圖形figure('Position', [100, 100, 1200, 800]);% 繪制精確度subplot(2, 2, 1);bar(precisions);set(gca, 'XTickLabel', methods, 'XTickLabelRotation', 45);title('Precision@K');ylabel('Precision');grid on;% 繪制召回率subplot(2, 2, 2);bar(recalls);set(gca, 'XTickLabel', methods, 'XTickLabelRotation', 45);title('Recall@K');ylabel('Recall');grid on;% 繪制AUCsubplot(2, 2, 3);bar(aucs);set(gca, 'XTickLabel', methods, 'XTickLabelRotation', 45);title('AUC');ylabel('AUC');grid on;% 繪制運行時間subplot(2, 2, 4);bar(times);set(gca, 'XTickLabel', methods, 'XTickLabelRotation', 45);title('運行時間');ylabel('時間 (秒)');grid on;% 調整布局set(gcf, 'Color', 'w');endend
end% 示例使用代碼
function example_usage()% 生成示例網絡(無標度網絡)n = 100; % 節點數量A = create_scale_free_network(n);% 創建鏈路預測對象,使用80%的邊作為訓練集lp = LinkPrediction(A, 0.8);% 比較所有方法的性能results = lp.compare_methods();% 可視化結果lp.plot_results(results);% 單獨使用某個方法scores = lp.common_neighbors();[precision, recall, auc] = lp.evaluate(scores);fprintf('\nCommon Neighbors: Precision=%.4f, Recall=%.4f, AUC=%.4f\n', precision, recall, auc);
endfunction A = create_scale_free_network(n)%CREATE_SCALE_FREE_NETWORK 生成無標度網絡(Barabási-Albert模型)%   n - 網絡節點數% 初始完全圖m0 = 5; % 初始節點數A = zeros(n);A(1:m0, 1:m0) = ones(m0) - eye(m0);% 添加新節點for i = m0+1:n% 計算現有節點的度degrees = sum(A(1:i-1, 1:i-1), 2);total_degree = sum(degrees);% 根據度分布選擇連接節點if total_degree > 0prob = degrees / total_degree;targets = randsample(1:i-1, m0, true, prob);elsetargets = randperm(i-1, min(m0, i-1));end% 添加連接for j = targetsA(i, j) = 1;A(j, i) = 1;endend
end% 運行示例
example_usage();

說明

這個MATLAB鏈路預測程序提供了以下功能:

1. 核心類 LinkPrediction

包含多種鏈路預測算法的實現,以及評估和比較功能。

2. 實現的算法

  1. Common Neighbors (共同鄰居):基于兩個節點共同鄰居的數量
  2. Jaccard Coefficient:共同鄰居數除以總鄰居數
  3. Adamic-Adar:考慮共同鄰居的度,度越小權重越大
  4. Preferential Attachment:基于兩個節點的度乘積
  5. Katz Index:考慮所有路徑,路徑越短權重越大
  6. Rooted PageRank:基于隨機游走的相似性度量
  7. SimRank:基于結構上下文的相似性度量
  8. Matrix Factorization:基于矩陣分解的潛在特征方法

3. 評估指標

  • Precision@K:前K個預測中正確預測的比例
  • Recall@K:正確預測的正樣本占所有正樣本的比例
  • AUC:ROC曲線下面積,衡量分類器整體性能

4. 可視化功能

提供四種評估指標的可視化比較,便于分析不同算法的性能。

推薦代碼 鏈路預測程序,主程序,包含31個鏈路預測的函數代碼 www.youwenfan.com/contentcsg/52463.html

使用

程序最后提供了一個示例使用代碼:

  1. 生成一個無標度網絡(Barabási-Albert模型)
  2. 創建鏈路預測對象,劃分訓練集和測試集
  3. 比較所有算法的性能
  4. 可視化比較結果
  5. 單獨使用Common Neighbors算法并進行評估

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/922086.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/922086.shtml
英文地址,請注明出處:http://en.pswp.cn/news/922086.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

淘寶商品詳情 API 的安全強化與生態協同創新路徑

一、安全強化&#xff1a;從 “被動防御” 到 “主動免疫” 的體系升級動態身份認證與權限顆粒化構建 “生物特征 設備指紋 行為基線” 的三重認證機制&#xff1a;結合用戶操作習慣&#xff08;如點擊間隔、滑動軌跡&#xff09;生成動態令牌&#xff0c;對高權限接口&#…

快消26屆聯合利華校招AI測評及第二輪線上認知能力測評SHL筆試真題及評分要求

在求職的道路上&#xff0c;聯合利華作為一家全球知名企業&#xff0c;其招聘流程一直備受關注。尤其是其AI面試環節&#xff0c;更是讓許多求職者既期待又緊張。本文將詳細總結聯合利華AI面試的規律與應對策略&#xff0c;希望能為正在準備面試的你提供一些幫助。一、聯合利華…

使用Langchain生成本地rag知識庫并搭載大模型

準備設備&#xff1a; 手機aidlux2.0個人版 一、下載依賴pip install langchain langchain-community faiss-cpu pypdf二、安裝ollama并下載模型 curl -fsSL https://ollama.com/install.sh | sh #需要科學上網 ollama serve & #讓ollama服務在后臺運行安裝完畢可以查看oll…

L2-【英音】地道語音語調--語調

文章目錄語調英式語調四步法語調含義降調升調降升調升降語調如何正確表情達意1. 用降調的句型語調 英語里沒有任何一句話具有固定節奏模式 英式語調四步法 意群劃分重音核心語調&#xff08;重中之重&#xff09;語調的選擇 A French burglar broke-into-a flat while the o…

計算機視覺進階教學之圖像投影(透視)變換

目錄 簡介 一、了解圖像投影(透視)變換 一、定義與原理 二、應用場景 三、實現方法 二、案例分析 1. 輔助函數定義 1.1.cv_show 函數 1.2.order_points 函數 1.3.four_point_transform 函數 1.4.resize 函數 2. 主程序執行流程 2.1.圖像縮放處理 2.2.輪廓檢測 2.…

Java面試問題記錄(二)

三、系統設計與問題排查1、假設你要設計一個 “秒殺系統”&#xff0c;需要考慮高并發、高可用、防超賣等問題&#xff0c;你的整體技術方案是什么&#xff1f;從前端、接口層、服務層、存儲層分別說說核心設計點。秒殺系統設計設計核心&#xff1a;瞬時高并發&#xff0c;庫存…

k8s部署kafka三節點集群

本來認為部署kafka很簡單&#xff0c;沒想到也折騰了2-3天&#xff0c;這水平沒治了&#xff5e; kafka從3.4.0版本之后&#xff0c;可以不依賴zookeeper直接使用KRaft模式部署&#xff0c;也就是說部署kafka可以不安裝zookeeper直接部署。 在官網上沒有找到如何使用yaml文件…

在公用同一公網IP和端口的K8S環境中,不同域名實現不同訪問需求的解決方案

目錄 1. 訪問需求 2. 解決方案 3. 具體配置 3.1 允許互聯網訪問的域名&#xff08;a.lmzf.com&#xff09; 3.2 需IP白名單訪問的域名&#xff08;b.lmzf.com&#xff09; 3.3 關鍵參數說明 3.4 測試驗證 1. 訪問需求 在騰訊云TKE環境中&#xff0c;多個域名解析到同一…

FlinkCDC 達夢數據庫實時同步

一、Flink部署 1.1、JAVA環境 vi /etc/profile export JAVA_HOME/data/flinkcdc/jdk1.8.0_181 export CLASSPATH$JAVA_HOME/lib/tools.jar:$JAVA_HOME/lib/dt.jar export PATH$JAVA_HOME/bin:$PATHsource /etc/profilevi ~/.bash_profileexport FLINK_HOME/data/flinkcdc/fli…

Eip開源主站EIPScanner在Linux上的調試記錄(二 多生產者連接)

目錄 一、背景 二、可行性驗證 三、開發調試 一、背景 在一般場景下&#xff0c;只需一路IO連接&#xff0c;但稍微復雜的場景&#xff0c;就需要不同通訊周期的連接&#xff0c;這就需要有多組IO連接。 而大于一組的連接調試方法是一樣的&#xff0c;因此主要解決2組連接的…

Oracle APEX 利用卡片實現翻轉(方法二)

目錄 0. 以 Oracle 的標準示例表 EMP 為例&#xff0c;實現卡片翻轉 1. 創建卡片區域 (Cards Region) 2. 定義卡片的 HTML 結構 3. 添加 CSS 實現樣式和翻轉動畫 4. 創建動態操作觸發翻轉 5. 運行效果 0. 以 Oracle 的標準示例表 EMP 為例&#xff0c;實現卡片翻轉 目標如…

低代碼拖拽實現與bpmn-js詳解

低代碼平臺中的可視化拖拽功能是其核心魅力所在&#xff0c;它讓構建應用變得像搭積木一樣直觀。下面我將為你梳理其實現原理&#xff0c;并詳細介紹 vue-draggable 這個常用工具。 &#x1f9f1; 一、核心架構&#xff1a;三大區域與數據驅動 低代碼編輯器界面通常分為三個核心…

【科研繪圖系列】R語言繪制模型預測與數據可視化

禁止商業或二改轉載,僅供自學使用,侵權必究,如需截取部分內容請后臺聯系作者! 文章目錄 介紹 加載R包 數據下載 函數 導入數據 數據預處理 畫圖 總結 系統信息 介紹 本文介紹了一種利用R語言進行海洋微生物群落動態分析的方法,該方法通過構建多個統計模型來預測不同環境…

TODO的面試(dw三面、sqb二面、ks二面)

得物的前端三面&#xff08;通常是技術終面&#xff09;會深入考察你的技術深度、項目經驗、解決問題的思路以及職業素養。下面我結合搜索結果&#xff0c;為你梳理一份得物前端三面的常問問題及詳解&#xff0c;希望能助你一臂之力。 &#x1f9e0; 得物前端三面常問問題及詳解…

開發 PHP 擴展新途徑 通過 FrankenPHP 用 Go 語言編寫 PHP 擴展

通過 FrankenPHP 用 Go 語言編寫 PHP 擴展 在 PHPVerse 2025 大會上&#xff08;JetBrains 為紀念 PHP 語言 30 周年而組織的會議&#xff09;&#xff0c;FrankenPHP 開發者 Kvin Dunglas 做了一個開創性的宣布&#xff1a;通過 FrankenPHP&#xff0c;可以使用 Go 語言創建 …

完美解決:應用版本更新,增加字段導致 Redis 舊數據反序列化報錯

完美解決&#xff1a;應用版本更新&#xff0c;增加字段導致 Redis 舊數據反序列化報錯 前言 在敏捷開發和快速迭代的今天&#xff0c;我們經常需要為現有的業務模型增加新的字段。但一個看似簡單的操作&#xff0c;卻可能給正在穩定運行的系統埋下“地雷”。 一個典型的場景是…

66-python中的文件操作

1. 文件的編碼 UTF-8 GBK GB2312 Big5 GB18030 2. 文件讀取 文件操作步驟: 打開文件 讀\寫文件 關閉文件 open(name,mode,encoding) name:文件名字符串 “D:/haha.txt” mode: 只讀、寫入、追加 r:以只讀方式打開 w: 只用于寫 a :用于追加 encoding:編碼方式 # -*- coding: utf…

FPGA實例源代碼集錦:27個實戰項目

本文還有配套的精品資源&#xff0c;點擊獲取 簡介&#xff1a;FPGA是一種可編程邏輯器件&#xff0c;允許用戶根據需求配置硬件功能。本壓縮包提供27個不同的FPGA應用實例源代碼&#xff0c;旨在幫助初學者深入學習FPGA設計&#xff0c;并為專業工程師提供靈感。內容涵蓋了…

基于 Vue+Mapbox 的智慧礦山可視化功能的技術拆解

01、項目背景 在全球礦業加速向 “高端化、智能化、綠色化” 轉型的浪潮下&#xff0c;傳統礦業面臨的深地開采難題、效率瓶頸與安全隱患日益凸顯。 在礦業轉型的迫切需求與政策、技術支撐的背景下依托 GIS 技術&#xff0c;開展了 “中國智礦” GIS 開發項目&#xff0c;旨在…

進程狀態(Linux)

進程狀態Linux進程狀態Linux進程狀態進程描述R運行狀態S睡眠狀態D磁盤休眠狀態T停止狀態t被追蹤狀態(調試狀態)X死亡狀態Z僵死狀態其實大致也就可以分為三種運行&#xff0c;阻塞&#xff0c;掛起。運行狀態每個cpu里都有一個運行隊列&#xff0c;進程在運行隊列里&#xff0c;…