//通过贝叶斯概率机器学习
const execMathExpress=require('exec-mathexpress');
//一个神经元,同过学习特征,判断是否发出信号
class Yuan {
constructor(props) {
this.props=props||{};
}
//学习特征
learn(props){
for(let k in props){
if(!this.props[k]){
this.props[k]='1/2'
}
const arr=this.props[k].split('/').map((num)=>parseInt(num));
if(props[k]){
arr[0]++;
}
arr[1]++;
this.props[k]=arr[0]+'/'+arr[1];
}
}
//判断是否发出信号
getFraction(props){
const gArr=[]
for(let k in props){
if(props[k]){
gArr.push(this.props[k]);
}else{
const arr=this.props[k].split('/').map((num)=>parseInt(num));
gArr.push(arr[1]-arr[0]+'/'+arr[1]);
}
}
return this.execByes(gArr);
}
//贝叶斯计算公式
execByes(gArr){
const arr1=[]
const arr2=[]
const Obj={}
for(let i=0;i<gArr.length;i++){
arr1.push('P'+i)
arr2.push('(1-P'+i+')')
Obj['P'+i]=gArr[i];
}
const str1=arr1.join('*');
const str2=arr2.join('*');
const str=str1+'/('+str1+'+'+str2+')';
return execMathExpress(str,Obj).toString();
}
}
//类别判断 神经元
class TagYuan {
constructor(data) {
this.props={};
if(data){
for(let Tag in data) {
this.props[Tag] = new Yuan(data[Tag])
}
}
}
learn(props,Tag){
this.props[Tag].learn(props)
}
getFraction(props,Tag){
const Obj={};
const arr=[]
for(let k in this.props){
Obj[k]=this.props[k].getFraction(props);
arr.push(k)
}
const str=Tag+'/('+arr.join('+')+')';
return execMathExpress(str,Obj).toString();
}
}
//初始化,或者历史数据
const oneYuan=new TagYuan({
'S':null,
'F':null,
})
//学习过程
oneYuan.learn({
longhars:1,
bigeye:0,
bigfoot:1,
},'S')
oneYuan.learn({
longhars:1,
bigeye:0,
bigfoot:1,
},'F')
//判断过程
const d=oneYuan.getFraction({
longhars:1,
bigeye:0,
bigfoot:1,
},'S')
console.log(d)