MST

星途 面试题库

面试题:Ruby中如何实现简单的人工智能决策树算法

假设你要实现一个简单的决策树算法用于判断天气是否适合外出,决策依据为温度、湿度和风速。请用Ruby代码实现该决策树的构建和预测功能,简单说明思路并给出关键代码片段。
17.9万 热度难度
编程语言Ruby

知识考点

AI 面试

面试题答案

一键面试

思路

  1. 定义决策树的节点类,每个节点包含一个判断条件(如温度、湿度、风速相关条件)和子节点(不同条件分支对应的后续判断节点或最终决策结果)。
  2. 通过给定的训练数据来构建决策树,训练数据包含温度、湿度、风速以及对应的是否适合外出的结果。
  3. 根据构建好的决策树来进行预测,即输入新的温度、湿度和风速数据,通过遍历决策树得出是否适合外出的预测结果。

关键代码片段

# 决策树节点类
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) # 输出预测结果