在neo4j中设置决策树

时间:2016-05-26 13:45:33

标签: neo4j py2neo

假设我有一个如下所示的决策树:

enter image description here

我写了一个密码查询来创建决策树:

create (_0 {`name`:"Spins?", `type`:"split"})

create (_1a {`name`:"Weight", `type`:"split"})
create (_1b {`name`:"Weight", `type`:"split"})

create (_2a {`name`:"Spider", `type`:"terminal"})
create (_2b {`name`:"Spider Man", `type`:"terminal"})
create (_2c {`name`:"Ant", `type`:"terminal"})
create (_2d {`name`:"Ant Man", `type`:"terminal"})

create (_0)-[:`CON` {`lt`:.5}]->(_1a)
create (_0)-[:`CON` {`gte`:.5}]->(_1b)

create (_1a)-[:`CON` {`lt`:200}]->(_2a)
create (_1a)-[:`CON` {`gte`:200}]->(_2b)

create (_1b)-[:`CON` {`lt`:200}]->(_2c)
create (_1b)-[:`CON` {`gte`:200}]->(_2d)
;

几个问题:

  1. 这是在neo4j中设置决策树的最佳方式吗?
  2. 如何编写cypher查询以加入图表并获取带有输入数据的结果节点?例如说我有数据{'旋转?' :False,'权重':500},如何编写查询以有效地返回“Ant Man”节点?

1 个答案:

答案 0 :(得分:1)

允许对模型进行少量更改:

MERGE (_0:DT:Split  {name: 'Spins', l:0, i:0})
MERGE (_1a:DT:Split {name: 'Weight', l:1, i:0})
MERGE (_1b:DT:Split {name: 'Weight', l:1, i:1})

MERGE (_2a:DT:Terminal {name:'Spider', l:2, i:0})
MERGE (_2b:DT:Terminal {name:'Spider Man', l:2, i:0})
MERGE (_2c:DT:Terminal {name:'Ant', l:2, i:0})
MERGE (_2d:DT:Terminal {name:'Ant Man', l:2, i:0})

MERGE (_0)-[:DT {type:'Left', value: 0.5, propname:'Spins'}]->(_1a)
MERGE (_0)-[:DT {type:'Right', value: 0.5, propname:'Spins'}]->(_1b)
MERGE (_1a)-[:DT {type:'Left', value: 50, propname:'Weight'}]->(_2a)
MERGE (_1a)-[:DT {type:'Right', value: 50, propname:'Weight'}]->(_2b)
MERGE (_1b)-[:DT {type:'Left', value: 50, propname:'Weight'}]->(_2c)
MERGE (_1b)-[:DT {type:'Right', value: 50, propname:'Weight'}]->(_2d)

并查询:

// Input parameters:
WITH {Spins: 0.6, Weight: 500} as Cor
// Get all decision paths:
MATCH p = (S:DT:Split {l:0,i:0})-[:DT*]->(T:DT:Terminal)
// Test single decision path:
WHERE ALL(r in relationships(p) WHERE 
        (r.type='Left' AND Cor[r.propname]<r.value) OR // Left variant
        (r.type='Right' AND Cor[r.propname]>=r.value) // Right variant
      )
RETURN T