首页  >  文章  >  后端开发  >  软件工程师的机器学习

软件工程师的机器学习

WBOY
WBOY原创
2024-08-06 20:14:151189浏览

Machine Learning for Software Engineers

如果您觉得这篇文章有价值,请告诉我,我会继续努力!

第 1 章 - 线性模型

最简单但强大的概念之一是线性模型。

在机器学习中,我们的主要目标之一是根据数据进行预测。 线性模型就像机器学习的“Hello World”——它很简单,但却构成了理解更复杂模型的基础。

让我们建立一个模型来预测房价。在此示例中,输出是预期的“房价”,您的输入将是“sqft”、“num_bedrooms”等...

def prediction(sqft, num_bedrooms, num_baths):
    weight_1, weight_2, weight_3 = .0, .0, .0  
    home_price = weight_1*sqft, weight_2*num_bedrooms, weight_3*num_baths
    return home_price

您会注意到每个输入都有一个“权重”。这些权重创造了预测背后的魔力。这个例子很无聊,因为权重为零,所以它总是输出零。

那么让我们来看看如何找到这些权重。

寻找权重

寻找权重的过程称为“训练”模型。

  • 首先,我们需要一个具有已知特征(输入)和价格(输出)的房屋数据集。例如:
data = [
    {"sqft": 1000, "bedrooms": 2, "baths": 1, "price": 200000},
    {"sqft": 1500, "bedrooms": 3, "baths": 2, "price": 300000},
    # ... more data points ...
]
  • 在我们创建更新权重的方法之前,我们需要知道我们的预测有多偏差。我们可以计算我们的预测和实际值之间的差异。
home_price = prediction(1000, 2, 1) # our weights are currently zero, so this is zero
actual_value = 200000

error = home_price - actual_value # 0 - 200000 we are way off. 
# let's square this value so we aren't dealing with negatives
error = home_price**2

现在我们有一种方法可以知道一个数据点的偏差(误差)有多大,我们可以计算所有数据点的平均误差。这通常称为均方误差。

  • 最后,以减少均方误差的方式更新权重。

当然,我们可以选择随机数并在进行过程中不断保存最佳值 - 但这是低效的。因此,让我们探索一种不同的方法:梯度下降。

梯度下降

梯度下降是一种优化算法,用于为我们的模型找到最佳权重。

梯度是一个向量,它告诉我们当我们对每个权重进行微小改变时误差如何变化。

侧边栏直觉
想象一下站在丘陵地貌上,您的目标是到达最低点(误差最小)。梯度就像一个指南针,总是指向最陡的上升点。通过与梯度方向相反的方向,我们正在向最低点迈进。

其工作原理如下:

  1. 从随机权重(或零)开始。
  2. 计算当前权重的误差。
  3. 计算每个权重的误差梯度(斜率)。
  4. 通过向减少误差的方向移动一小步来更新权重。
  5. 重复步骤 2-4,直到误差停止显着减小。

我们如何计算每个错误的梯度?

计算梯度的一种方法是对权重进行小幅调整,看看这对我们的误差有何影响,并看看我们应该从哪里移动。

def calculate_gradient(weight, data, feature_index, step_size=1e-5):
    original_error = calculate_mean_squared_error(weight, data)

    # Slightly increase the weight
    weight[feature_index] += step_size
    new_error = calculate_mean_squared_error(weight, data)

    # Calculate the slope
    gradient = (new_error - original_error) / step_size

    # Reset the weight
    weight[feature_index] -= step_size

    return gradient

逐步分解

  • 输入参数:

    • 权重:我们模型的当前权重集。
    • 数据:我们的房屋特征和价格数据集。
    • feature_index:我们计算梯度的权重(0 表示平方英尺,1 表示卧室,2 表示浴室)。
    • step_size:我们用来稍微改变权重的一个小值(默认为1e-5或0.00001)。
  • 计算原始误差:

   original_error = calculate_mean_squared_error(weight, data)

我们首先用当前权重计算均方误差。这给了我们我们的起点。

  • 稍微增加重量
   weight[feature_index] += step_size

我们将权重增加了一点点(step_size)。这使我们能够看到权重的微小变化如何影响我们的误差。

  • 计算新错误
   new_error = calculate_mean_squared_error(weight, data)

稍微增加权重后,我们再次计算均方误差。

  • 计算斜率(梯度)
   gradient = (new_error - original_error) / step_size

这是关键的一步。我们要问:“当我们稍微增加重量时,误差变化了多少?”

  • 如果 new_error > Original_error,梯度为正,意味着增加这个权重会增加误差。
  • 如果 new_error
  • 大小告诉我们误差对该权重的变化有多敏感。

    • 重置体重
   weight[feature_index] -= step_size

我们将权重恢复到其原始值,因为我们正在测试更改它会发生什么。

  • 返回梯度
   return gradient

我们返回该权重的计算梯度。

This is called "numerical gradient calculation" or "finite difference method". We're approximating the gradient instead of calculating it analytically.

Let's update the weights

Now that we have our gradients, we can push our weights in the opposite direction of the gradient by subtracting the gradient.

weights[i] -= gradients[i]

If our gradient is too large, we could easily overshoot our minimum by updating our weight too much. To fix this, we can multiply the gradient by some small number:

learning_rate = 0.00001
weights[i] -= learning_rate*gradients[i]

And so here is how we do it for all of the weights:

def gradient_descent(data, learning_rate=0.00001, num_iterations=1000):
    weights = [0, 0, 0]  # Start with zero weights

    for _ in range(num_iterations):
        gradients = [
            calculate_gradient(weights, data, 0), # sqft
            calculate_gradient(weights, data, 1), # bedrooms
            calculate_gradient(weights, data, 2)  # bathrooms
        ]

        # Update each weight
        for i in range(3):
            weights[i] -= learning_rate * gradients[i]

        if _ % 100 == 0:
            error = calculate_mean_squared_error(weights, data)
            print(f"Iteration {_}, Error: {error}, Weights: {weights}")

    return weights

Finally, we have our weights!

Interpreting the Model

Once we have our trained weights, we can use them to interpret our model:

  • The weight for 'sqft' represents the price increase per square foot.
  • The weight for 'bedrooms' represents the price increase per additional bedroom.
  • The weight for 'baths' represents the price increase per additional bathroom.

For example, if our trained weights are [100, 10000, 15000], it means:

  • Each square foot adds $100 to the home price.
  • Each bedroom adds $10,000 to the home price.
  • Each bathroom adds $15,000 to the home price.

Linear models, despite their simplicity, are powerful tools in machine learning. They provide a foundation for understanding more complex algorithms and offer interpretable insights into real-world problems.

以上是软件工程师的机器学习的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn