一个用于简单计算欧几里得距离的包,同时可以快速、直观地比较推荐结果,无需条件限制。

1.0.0 2020-11-16 13:28 UTC

This package is auto-updated.

Last update: 2024-09-16 22:29:36 UTC


README

一个用于简单计算欧几里得距离的包,同时可以快速、直观地比较推荐结果,无需条件限制。


它是如何工作的?

想象一下,你正在构建一个电影应用程序,比如Netflix。

当电影结束时,你想向用户推荐一部电影,但这部电影应该和他刚才看过的电影相似。

数据库中的电影必须包含每个类别的百分比,例如:爱情、动作、冒险、小说等。

对于每部电影,你输入每个类别的百分比

一个愚蠢的例子

[
    "title" => "Robin Hood",
    "categories" => [
        "adventure" => "1" // 100%,
        "romance" => "0.2" // 20%,
        "action" => "0.6", // 60%,
        ...
    ]
]

算法将使用这些百分比来进行计算

要了解欧几里得计算是如何工作的,请访问此链接

入门

1 - 使用composer在你的项目中安装

composer require wellingtonbarbosa/knn

2 - 在你的php文件中使用类

<?php
require_once(__DIR__ . '\vendor\autoload.php');

use WellingtonBarbosa\Knn\Knn;

3 - 创建一些项目进行测试
在我们的例子中,$defaultItem是用户刚刚看过的电影,而$itemsToCompare是从数据库中抽取的电影。让我们看看哪一部电影更接近用户刚刚看过的电影?那么,让我们开始吧!

//The item to compare (four indices)
$defaultItem = [0.4, 0.2, 0.4, 1];

//The items to be compared (four indices in each item)
$itemsToCompare = [
    [
        0.2, 0.3, 0, 1
    ],
    [
        0.4, 0.2, 0.3, 1
    ],
    [
        0.4, 0.2, 0.4, 1
    ],
    [
        0.4, 0.2, 0.4, 1
    ]
];

! 注意,所有项目都有4个索引。所有项目必须有相同数量的索引,否则将无法工作

4 - 在变量中实例化类
传递的最后一个参数是所有项目都具有的索引数量。

/**
 * Starts the object with the values
 * 
 * First param -> The item to compare
 * Second param -> The items to be compared
 * Third param ->  Number of indices in each item to be compared
 */
$knn = new Knn($defaultItem, $itemsToCompare, 4);

5 - 对每个项目执行欧几里得距离计算

//Performs Euclidean distance calculation
$results = $knn->calculate();

6 - 最后,我们将得到推荐给用户的项目的索引(或索引)
注意,除了计算结果外,推荐方法中还有一个参数。这是因为计算中可能会有相同的结果。如果您传递TRUE,该方法将返回所有结果重复的索引。如果您传递FALSE,则返回第一个找到的索引

/**
 * Returns the index of the item to be recommended
 * 
 * First param -> The results of Euclidean distance calculation for all compared items
 * 
 * If the second param is true, it will return an array of close results.
 * If false, it will return the first index found
 * 
 */
$recomendation = $knn->recomend($results, true);

$recomendation = $knn->recomend($results, false);

7 - 现在,只需查找我们将推荐的项目

//Multiple items
    foreach($recomendation as $key) {
        echo "Euclidian distances for item (" . $key . ") =>> "  . $result[$key];
        echo "<br>";
        foreach($itemsToCompare[$key] as $item) {
            echo $item . " | ";
        }
        echo "<hr>";
    }

//Single item
echo "Recomended item: " . $recomendation;
echo "<br>";
foreach($itemsToCompare[$key] as $item) {
    echo $item . " | ";
}

您可以点击此处查看此完整文件点击这里

贡献

您可以通过fork存储库并开发新功能和增量,然后发送pull请求来为此包做出贡献!

作者

Wellington Carneiro Barbosa Wellington Barbosa
Instagram | LinkedIn | Facebook

许可

此包受MIT许可约束。

有任何问题,请在GitHub上告诉我!我会帮你的。