服务器端 Swift 中的决策树

Get Involved with Perfect!

Star Perfect On Github Stack Overflow Follow Perfect on Twitter Join the Perfect Slack

Swift 4.0 Platforms OS X | Linux License Apache PerfectlySoft Twitter Slack Status

这是一个基于 Swift 4.0 的决策树数据结构自动化库,参考了维基百科的定义。

树节点已被抽象成如下接口:

class DecisionTree {
  public init(_ id: String, branches: [String: Any])
  public func search(_ data:[String: String]) throws -> String
}

目标数据源中的所有值必须是离散的,并转换为字符串类型。

快速开始

Package.swift

.package(url: "https://github.com/RockfordWei/DecisionTree.git", from: "0.3.0")

注意,需要修改Package.swift文件,显式声明依赖项。

dependencies: ["DecisionTree"]

然后你就可以导入该库了

import DecisionTree

机器学习

目前,有两种通过扫描数据表构建树的方法。

假设我们期望构建一个如下的树:

let windy = DecisionTree("windy", 
	branches: ["true": "false", "false": "true"])
      
let humid = DecisionTree("humid", 
	branches: ["false": "true", "true": "false"])
      
let outlook = DecisionTree("outlook", 
	branches: ["sunny":humid, "overcast": "true", "rain": windy])

它来自如下数据表,使用 ID3 信息熵算法。

  let discreteRecords: [[String: String]] = [
    ["outlook": "sunny",    "humid": "true", "windy": "false", "play": "false"],
    ["outlook": "sunny",    "humid": "true", "windy": "true",  "play": "false"],
    ["outlook": "overcast", "humid": "true", "windy": "false", "play": "true" ],
...
    ["outlook": "rain",     "humid": "true", "windy": "true",  "play": "false"],
  ]

通过应用这样的树,可以根据历史模式进行预测。

// if input a new record in form of [String:String]
let prediction = try tree.search(newRecord)

// prediction is the result of the outcome,
// for example, if the new record outlook is "overcast", 
// then the outcome prediction will be "true"

Perfect DecisionTree 模块提供了两种不同的解决方案,具体取决于数据源的类型 - 内存中的 Array/Dictionary 或数据库连接。

内存玩具示例

您可以使用 DTBuilderID3Memory 通过 Swift 字典 - 数组 创建这样的树

let tree = try DTBuilderID3Memory.Build(
	"play", from: discreteRecords)

此方法是单线程函数,旨在用于教育目的,以帮助开发人员理解教科书中的算法。

请查看测试脚本中的示例数据。

基于 MySQL 的生产级构建器

此库还提供了一个由 MySQL 驱动的强大构建器,它可以惊人的速度扫描整个表并完成任务 - 假设上述数据已传输到数据库中存储的 golf 表。

let tree = try DTBuilderID3MySQL.Build(
	"play", from: mysqlConnection, tag: "golf")

它将在线程队列中递归地将表拆分为视图,而无需移动或写入任何数据。 主要成本是深度遍历的堆栈内存,没有其他成本。

请查看测试脚本以了解其工作原理。

更多信息

有关 Perfect 项目的更多信息,请访问 perfect.org

现在提供微信订阅号 (中文)