gpt4 book ai didi

json - 将 ctree 输出转换为 JSON 格式(用于 D3 树布局)

转载 作者:行者123 更新时间:2023-12-04 11:51:43 29 4
gpt4 key购买 nike

我正在做一个需要运行 ctree 的项目。然后以交互模式绘制它 - 就像“D3.js”树布局一样,我的主要障碍是转换 ctree输出到 json格式,以便稍后由 javascript 使用。

以下是我需要的(以虹膜数据为例):

> library(party)
> irisct <- ctree(Species ~ .,data = iris)
> irisct

Conditional inference tree with 4 terminal nodes

Response: Species
Inputs: Sepal.Length, Sepal.Width, Petal.Length, Petal.Width
Number of observations: 150

1) Petal.Length <= 1.9; criterion = 1, statistic = 140.264
2)* weights = 50
1) Petal.Length > 1.9
3) Petal.Width <= 1.7; criterion = 1, statistic = 67.894
4) Petal.Length <= 4.8; criterion = 0.999, statistic = 13.865
5)* weights = 46
4) Petal.Length > 4.8
6)* weights = 8
3) Petal.Width > 1.7
7)* weights = 46

现在我想转换 ctee使用某种算法输出为以下 JSON 格式(我是手动完成的),但是,这可能不是转换它的最佳方式:
{"name" : "Petal.Length <= 1.9  criterion = 1","value": 60, "children" : [
{"name" : "n=50" ,"value": 60},
{"name" : "Petal.Length > 1.9 criterion = 1","value": 60, "children": [
{"name" : "n=46","value": 60 },
{"name" : "Petal.Length > 4.8","value": 60, "children" :[
{"name" : "Petal.Width > 1.7" ,"value": 60},
{"name" : "46" ,"value": 60}
]}] }
]}

这是R和 D3.js的两张图片情节:

enter image description here
enter image description here

我已经尝试使用 RJSONIO在 ctree 对象上,这没有多大帮助。

有没有人将 ctree 对象/输出转换为 JSON 以使用 D3.js 树布局?如果没有,有没有人知道可以将一个输出转换为另一个输出的算法?

在此先感谢您的帮助!

最佳答案

诀窍是提取 irisct 的有用位。对象,并且只将它们转换为 JSON。像这样的东西:

get_ctree_parts <- function(x, ...)
{
UseMethod("get_ctree_parts")
}

get_ctree_parts.BinaryTree <- function(x, ...)
{
get_ctree_parts(attr(x, "tree"))
}

get_ctree_parts.SplittingNode <- function(x, ...)
{
with(
x,
list(
nodeID = nodeID,
variableName = psplit$variableName,
splitPoint = psplit$splitpoint,
pValue = 1 - round(criterion$maxcriterion, 3),
statistic = round(max(criterion$statistic), 3),
left = get_ctree_parts(x$left),
right = get_ctree_parts(x$right)
)
)
}

get_ctree_parts.TerminalNode <- function(x, ...)
{
with(
x,
list(
nodeID = nodeID,
weights = sum(weights),
prediction = prediction
)
)
}

useful_bits_of_irisct <- get_ctree_parts(irisct)
toJSON(useful_bits_of_irisct)

我通过明智地使用 unclass 找到了这个答案。功能。例如:
unclass(irisct)
unclass(attr(irisct, "tree"))
unclass(attr(irisct, "tree")$psplit)

包中的打印方法, party:::print.SplittingNodeparty:::print.TerminalNode也非常有用。 (输入 party:::print. 并自动完成以查看可用的内容。)

关于json - 将 ctree 输出转换为 JSON 格式(用于 D3 树布局),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25621611/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com