Create a weights adjacency matrix in python with networkX - networkx

I want to implement the Dijkstra algorithm in python but with weighted adjacency matrix but NetworkX give us just the adjacency without the weights ( distance for my algorithm ) so I tried to search a way to create a weighted adjacency matrix but I didn't found. The only code I find from NetworkX is :
A = nx.adjacency_matrix(G, weight='weight')
This is my code for the rest :
G = ox.graph_from_bbox(nord, sud, est, ouest, network_type='drive')
noeud_origine = ox.get_nearest_node(G, point_origine) noeud_destination = ox.get_nearest_node(G, point_destination)

Related

How to calculate cosine similarity between two frequency vectors in MATLAB?

I need to find the cosine similarity between two frequency vectors in MATLAB.
Example vectors:
a = [2,3,4,4,6,1]
b = [1,3,2,4,6,3]
How do I measure the cosine similarity between these vectors in MATLAB?
Take a quick look at the mathematical definition of Cosine similarity.
From the definition, you just need the dot product of the vectors divided by the product of the Euclidean norms of those vectors.
% MATLAB 2018b
a = [2,3,4,4,6,1];
b = [1,3,2,4,6,3];
cosSim = sum(a.*b)/sqrt(sum(a.^2)*sum(b.^2)); % 0.9436
Alternatively, you could use
cosSim = (a(:).'*b(:))/sqrt(sum(a.^2)*sum(b.^2)); % 0.9436
which gives the same result.
After reading this correct answer, to avoid sending you to another castle I've added another approach using MATLAB's built-in linear algebra functions, dot() and norm().
cosSim = dot(a,b)/(norm(a)*norm(b)); % 0.9436
See also the tag-wiki for cosine-similarity.
Performance by Approach:
sum(a.*b)/sqrt(sum(a.^2)*sum(b.^2))
(a(:).'*b(:))/sqrt(sum(a.^2)*sum(b.^2))
dot(a,b)/(norm(a)*norm(b))
Each point represents the geometric mean of the computation times for 10 randomly generated vectors.
If you have the Statistics toolbox, you can use the pdist2 function with the 'cosine' input flag, which gives 1 minus the cosine similarity:
a = [2,3,4,4,6,1];
b = [1,3,2,4,6,3];
result = 1-pdist2(a, b, 'cosine');

What data of images are given to kmeans clustering in matlab?

Iam having 100 images in my database.Iam using those 100 images as both training set and also test images.I have to make 5 clusters.Iam using eigen faces(PCA) for feature extraction.What data should be given for kmeans command in matlab?
Syntax for kmeans command:
[IDX,C] = kmeans(X,k)
1.What is the X value?
2.Whether we have to give euclidian distance as input?
3.Whether we have to give weight vector of input images?
Please explain me in detail.
Source code i tried
X = []
srcFiles = dir('C:\Users\rahul\Desktop\tomorow\*.jpg'); % the folder in which ur images exists
for i = 1 : length(srcFiles)
filename = strcat('C:\Users\rahul\Desktop\tomorow\',srcFiles(b).name);
Imgdata = imread(filename);
X(:, i) = princomp(Imgdata);
end
[idx, c] = kmeans(X, 5)
Error iam getting:
Index exceeds matrix dimensions.
Error in pca (line 4)
filename =strcat('C:\Users\rahul\Desktop\tomorow\',srcFiles(b).name);
The PCA function you are using (I don't know what it is exactly), produces a vector of n numbers. This vectors describes the picture, and is what needs to be given to the k-means algorithm.
First of all, run the PCA for all 100 images, producing a nX100 matrix.
X = []
for i = 1 : 100
X(:, i) = PCA(picture...)
end
If pca return a line instead of column, you need
X(:, i) = PCA(picture)'
The k-means functions takes this parameter, as well as the number k of clusters. So
[idx, c] = kmeans(X, 5);
The distance used for clustering is euclidean by default. If you want some different distance metric, you can supply it as a parameter. See the table here for the available distance metrics.
Finally, the standard k-means algorithm is not weighted, so you can't supply weights to the vectors.

Calculating the degree matrix having the sparse representation of the adjacency matrix

I am trying to calculate the laplacian matrix of a graph. I ve calculated the sparse representation of the adjacency matrix which is stored in a text file with dimension Nx3. N the size of nodes (ith-node jth node weight). I open in Matlab this file with adj = spconvert(adj);. The next step is to calculate the degree matrix of this sparse matrix in order to perform the operation L = D - adj. How is it possible to calculate the degree matrix having as an input the sparse adjacency matrix of the graph? In order to calculate the degree matrix I calculate the degree for every node:
for i=1:n % size of the node
degree(i) = length(find(adj(:,1) == i & adj(:,3) == 1));
end
However, how can I perform the subtraction of D and A?
Use the spdiags function to convert the degree vector to a sparse diagonal matrix. Then subtract the adjacency matrix from diagonal matrix to get the Laplacian. Example using your code:
adj = spconvert(adj);
for i=1:size(adj, 1)
degree(i) = CalcDegree(adj, i)
end
D = spdiags(degree, 0, size(adj, 1), size(adj, 2));
L = D - adj;
By the way, your code for calculating the node degree may be incorrect.

Generating random weighted adjacency matrix in MATLAB

I would like to create a random adjacency matrix in MATLAB such that the total sum of weight is equal to the number of edges. Finally find the Laplacian matrix using
L = diag(sum(A)) - A
and then graph it. Is there any way to do so?
Thanks in advance.
An adjacency matrix for an undirected graph is simply a square symmetric matrix.
If you have no constraints on the degree of the nodes only on the weights than I would suggest something like
n ; % number of nodes in the graph
density = 1e-3; % a rough estimate of the amount of edges
A = sprand( n, n, density ); % generate adjacency matrix at random
% normalize weights to sum to num of edges
A = tril( A, -1 );
A = spfun( #(x) x./nnz(A), A );
% make it symmetric (for undirected graph)
A = A + A.';
I have used in this code:
sprand to generate random sparse matrix.
spfun to help normalize the edge weights.
tril to extract only half the matrix.

Ploting degree distribution for a directed network

I have a dataset for the edges and nodes I've crawled from a social networking site. How can I plot the degree distribution using the data I have in a spreadsheet? The edges are directed. I am a MATLAB beginner. Please help.
I have created the adjacency matrix adj as follows:
clear all;
disp('Processing Edge-List File');
A = xlsread('edges.csv');
dim = max(max(A));
[E_Size, junk] = size(A);
sprintf('The dataset has %d nodes and %d edges',dim, E_Size);
disp('Filling Adjanceny Matrix');
adj = sparse(A(:,1), A(:,2), ones(E_Size,1), dim, dim, E_Size);
if(adj==adj') disp('Symmetric Adjacency Matrix - Undirected Graph') ;
else disp('Assymmetric Adjacency Matrix - Directed Graph');
Then i tried surf(adj) . its giving me an empty graph . Is there a problem in the way I am creating the adjacency matrix?
I'm assuming that you want to plot something like this:
Once you have determined the in and out degree of each node, you need to store it in a matrix A such that A(i,j) represents the number of nodes with in-degree i and out-degree j.
Then you can display this information with surf(A). surf plots an interpolated 3D surface where the intensity of each element in the matrix is the Z-coordinate of the surface and the column and row indices are the X,Y values.