📜 ⬆️ ⬇️

Friends recommendations for social networks

Not long ago I wrote how to recommend goods in online stores or other places, using information about the user. Now I want to show an algorithm that allows you to recommend friends, for example in social networks.

The first step is to present the user information in the interval scale and recommend the user to friends using the Pearson correlation coefficient , which will measure the degree of linear relationship between the two interval variables. For example, we have 4 users: Dima, Anna, Petya and Sasha. We know about them the information we represent as numbers in an array (interests, blogs, age, etc.)

<?php
//Dima
$name[0]=array(1,4,5,5,4);
//Anna
$name[1]=array(3,5,6,5,4);
//Petr
$name[2]=array(3,2,4,2,1);
//Sasha
$name[3]=array(5,4,3,1,1);


Pearson coefficient looks like this:
')
image

where xi and yi are comparable quantitative traits
n is the number of compared observations

In the second step, we insert the value into the formula and see which users are suitable for Dima:
$n=5;
$x=$name[0];
$y=$name[1];

for ($j=1;$j<count($name);$j++) {
$x=$name[0];
$y=$name[$j];
//begin
$s_x=0;
$s_y=0;
$s_pow_x=0;
$s_pow_y=0;
$s_x_y=0;

//x*y
for ($i=0;$i<5;$xy[$i]=$x[$i]*$y[$i],$i++);
//x pow 2
for ($i=0;$i<5;$x_pow_2[$i]=$x[$i]*$x[$i],$i++);
//y pow 2
for ($i=0;$i<5;$y_pow_2[$i]=$y[$i]*$y[$i],$i++);
//Summa xi
for ($i=0;$i<5;$s_x+=$x[$i],$i++);
//Summa yi
for ($i=0;$i<5;$s_y+=$y[$i],$i++);
//Summa x pow 2
for ($i=0;$i<5;$s_pow_x+=$x_pow_2[$i],$i++);
//Summa y pow 2
for ($i=0;$i<5;$s_pow_y+=$y_pow_2[$i],$i++);
//Summa x*y
for ($i=0;$i<5;$s_x_y+=$xy[$i],$i++);

$r_x_y=(($n*$s_x_y)-($s_x*$s_y))/sqrt((($n*$s_pow_x) - ($s_x*$s_x))*(($n*$s_pow_y) - ($s_y*$s_y)));
print $r_x_y;
}


The more the value is close to 1, the more likely it is that their interests coincide with his interests:
Name
He is our friend
Output value
Anya
(80%)
0.880704845928
Petya
(0%)
-0.0800640769025
Sasha
(0%)
-0.697424162876

Source: https://habr.com/ru/post/82075/


All Articles