思路
- 定义决策树的节点类,每个节点包含一个判断条件(如温度、湿度、风速相关条件)和子节点(不同条件分支对应的后续判断节点或最终决策结果)。
- 通过给定的训练数据来构建决策树,训练数据包含温度、湿度、风速以及对应的是否适合外出的结果。
- 根据构建好的决策树来进行预测,即输入新的温度、湿度和风速数据,通过遍历决策树得出是否适合外出的预测结果。
关键代码片段
# 决策树节点类
class TreeNode
attr_accessor :condition, :left, :right
def initialize(condition)
@condition = condition
@left = nil
@right = nil
end
end
# 构建决策树,这里只是简单示意,实际需根据训练数据更复杂构建
def build_decision_tree
root = TreeNode.new("温度 > 20")
root.left = TreeNode.new("湿度 < 60")
root.left.left = TreeNode.new("适合外出")
root.left.right = TreeNode.new("不适合外出")
root.right = TreeNode.new("风速 < 5")
root.right.left = TreeNode.new("适合外出")
root.right.right = TreeNode.new("不适合外出")
root
end
# 预测函数
def predict(tree, temperature, humidity, wind_speed)
current = tree
while current.left && current.right
if eval(current.condition.gsub("温度", temperature.to_s).gsub("湿度", humidity.to_s).gsub("风速", wind_speed.to_s))
current = current.left
else
current = current.right
end
end
current.condition
end
# 使用示例
tree = build_decision_tree
puts predict(tree, 25, 50, 4) # 输出预测结果