首页 后端开发 Python教程 软件工程师的机器学习

软件工程师的机器学习

Aug 06, 2024 pm 08:14 PM

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

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

<🎜>:泡泡胶模拟器无穷大 - 如何获取和使用皇家钥匙
4 周前 By 尊渡假赌尊渡假赌尊渡假赌
北端:融合系统,解释
4 周前 By 尊渡假赌尊渡假赌尊渡假赌
Mandragora:巫婆树的耳语 - 如何解锁抓钩
3 周前 By 尊渡假赌尊渡假赌尊渡假赌

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

热门话题

Java教程
1673
14
CakePHP 教程
1429
52
Laravel 教程
1333
25
PHP教程
1278
29
C# 教程
1257
24
Python与C:学习曲线和易用性 Python与C:学习曲线和易用性 Apr 19, 2025 am 12:20 AM

Python更易学且易用,C 则更强大但复杂。1.Python语法简洁,适合初学者,动态类型和自动内存管理使其易用,但可能导致运行时错误。2.C 提供低级控制和高级特性,适合高性能应用,但学习门槛高,需手动管理内存和类型安全。

学习Python:2小时的每日学习是否足够? 学习Python:2小时的每日学习是否足够? Apr 18, 2025 am 12:22 AM

每天学习Python两个小时是否足够?这取决于你的目标和学习方法。1)制定清晰的学习计划,2)选择合适的学习资源和方法,3)动手实践和复习巩固,可以在这段时间内逐步掌握Python的基本知识和高级功能。

Python vs.C:探索性能和效率 Python vs.C:探索性能和效率 Apr 18, 2025 am 12:20 AM

Python在开发效率上优于C ,但C 在执行性能上更高。1.Python的简洁语法和丰富库提高开发效率。2.C 的编译型特性和硬件控制提升执行性能。选择时需根据项目需求权衡开发速度与执行效率。

Python vs. C:了解关键差异 Python vs. C:了解关键差异 Apr 21, 2025 am 12:18 AM

Python和C 各有优势,选择应基于项目需求。1)Python适合快速开发和数据处理,因其简洁语法和动态类型。2)C 适用于高性能和系统编程,因其静态类型和手动内存管理。

Python标准库的哪一部分是:列表或数组? Python标准库的哪一部分是:列表或数组? Apr 27, 2025 am 12:03 AM

pythonlistsarepartofthestAndArdLibrary,herilearRaysarenot.listsarebuilt-In,多功能,和Rused ForStoringCollections,而EasaraySaraySaraySaraysaraySaraySaraysaraySaraysarrayModuleandleandleandlesscommonlyusedDduetolimitedFunctionalityFunctionalityFunctionality。

Python:自动化,脚本和任务管理 Python:自动化,脚本和任务管理 Apr 16, 2025 am 12:14 AM

Python在自动化、脚本编写和任务管理中表现出色。1)自动化:通过标准库如os、shutil实现文件备份。2)脚本编写:使用psutil库监控系统资源。3)任务管理:利用schedule库调度任务。Python的易用性和丰富库支持使其在这些领域中成为首选工具。

科学计算的Python:详细的外观 科学计算的Python:详细的外观 Apr 19, 2025 am 12:15 AM

Python在科学计算中的应用包括数据分析、机器学习、数值模拟和可视化。1.Numpy提供高效的多维数组和数学函数。2.SciPy扩展Numpy功能,提供优化和线性代数工具。3.Pandas用于数据处理和分析。4.Matplotlib用于生成各种图表和可视化结果。

Web开发的Python:关键应用程序 Web开发的Python:关键应用程序 Apr 18, 2025 am 12:20 AM

Python在Web开发中的关键应用包括使用Django和Flask框架、API开发、数据分析与可视化、机器学习与AI、以及性能优化。1.Django和Flask框架:Django适合快速开发复杂应用,Flask适用于小型或高度自定义项目。2.API开发:使用Flask或DjangoRESTFramework构建RESTfulAPI。3.数据分析与可视化:利用Python处理数据并通过Web界面展示。4.机器学习与AI:Python用于构建智能Web应用。5.性能优化:通过异步编程、缓存和代码优

See all articles