//通过贝叶斯概率机器学习
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];
}
}
//判断是否发出信号
is(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){
console.log(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();
}
}
//初始化,或者历史数据
const oneYuan=new Yuan()
//学习过程
oneYuan.learn({
longhars:1,
bigeye:1,
bigfoot:1,
})
oneYuan.learn({
longhars:1,
bigeye:0,
bigfoot:1,
})
oneYuan.learn({
longhars:0,
bigeye:0,
bigfoot:0,
})
//学习的结果数据
console.log(oneYuan.props)
//判断过程,d是否大于1/2
const d=oneYuan.is({
longhars:1,
bigeye:0,
bigfoot:1,
})
console.log(d)