Cosine similarity implements PHP data analysis

高洛峰
Release: 2016-11-29 10:04:47
Original
844 people have browsed it

<?php
/**
 * 数据分析引擎
 * 分析向量的元素 必须和基准向量的元素一致,取最大个数,分析向量不足元素以0填补。
 * 求出分析向量与基准向量的余弦值
 * @php爱好者
 */
 
 
/**
 * 获得向量的模
 * @param unknown_type $array 传入分析数据的基准点的N维向量。|eg:array(1,1,1,1,1);
 */
function getMarkMod($arrParam){
$strModDouble = 0;
foreach($arrParam as $val){
$strModDouble += $val * $val;
}
$strMod = sqrt($strModDouble);
//是否需要保留小数点后几位
return $strMod;
}
 
/**
 * 获取标杆的元素个数
 * @param unknown_type $arrParam
 * @return number
 */
function getMarkLenth($arrParam){
$intLenth = count($arrParam);
return $intLenth;
}
/**
 * 对传入数组进行索引分配,基准点的索引必须为k,求夹角的向量索引必须为 &#39;j&#39;.
 * @param unknown_type $arrParam
 * @param unknown_type $index
 * @ruturn $arrBack
 */
function handIndex($arrParam, $index = &#39;k&#39;){
 foreach($arrParam as $key => $val){
  $in = $index.$key;
  $arrBack[$in] = $val;
 }
 return $arrBack;
}
 
/**
 *
 * @param unknown_type $arrMark标杆向量数组(索引被处理过)
 * @param unknown_type $arrAnaly 分析向量数组 (索引被处理过) |array(&#39;j0&#39;=>1,&#39;j1&#39;=>2....)
 * @param unknown_type $strMarkMod标杆向量的模
 * @param unknown_type $intLenth 向量的长度
 */
function getCosine($arrMark, $arrAnaly, $strMarkMod ,$intLenth){
$strVector = 0;
$strCosine = 0;
for($i = 0; $i < $intLenth; $i++){
$strMarkVal = $arrMark[&#39;k&#39;.$i];
$strAnalyVal = $arrAnaly[&#39;j&#39;.$i];
$strVector += $strMarkVal * $strAnalyVal;
}
$arrAnalyMod = getMarkMod($arrAnaly); //求分析向量的模
$strFenzi = $strVector;
$strFenMu = $arrAnalyMod * $strMarkMod;
$strCosine = $strFenzi / $strFenMu;
if(0 !== (int)$strFenMu){
$strCosine = $strFenzi / $strFenMu;
}
return $strCosine;
}
?>
Copy after login


Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template