【机器学习】Linear Regression

news2024/9/24 1:19:06

Model Representation

    • 1、问题描述
    • 2、表示说明
    • 3、数据绘图
    • 4、模型函数
    • 5、预测
    • 总结
    • 附录

1、问题描述

一套 1000 平方英尺 (sqft) 的房屋售价为300,000美元,一套 2000 平方英尺的房屋售价为500,000美元。这两点将构成我们的数据或训练集。面积单位为 1000 平方英尺,价格单位为 1000 美元。

Size (1000 sqft)Price (1000s of dollars)
1.0300
2.0500

希望通过这两个点拟合线性回归模型,以便可以预测其他房屋的价格。例如,面积为 1200 平方英尺的房屋价格是多少。

首先导入所需要的库

import numpy as np
import matplotlib.pyplot as plt
plt.style.use('./deeplearning.mplstyle')

以下代码来创建x_train和y_train变量。数据存储在一维 NumPy 数组中。

# x_train is the input variable (size in 1000 square feet)
# y_train is the target (price in 1000s of dollars)
x_train = np.array([1.0, 2.0])
y_train = np.array([300.0, 500.0])
print(f"x_train = {x_train}")
print(f"y_train = {y_train}")

2、表示说明

使用 m 来表示训练样本的数量。 (x ( i ) ^{(i)} (i), y ( i ) ^{(i)} (i)) 表示第 i 个训练样本。由于 Python 是零索引的,(x ( 0 ) ^{(0)} (0), y ( 0 ) ^{(0)} (0)) 是 (1.0, 300.0) , (x ( 1 ) ^{(1)} (1), y ( 1 ) ^{(1)} (1)) 是 (2.0, 500.0).

3、数据绘图

使用 matplotlib 库中的scatter()函数绘制这两个点。 其中,函数参数markerc 将点显示为红叉(默认为蓝点)。使用matplotlib库中的其他函数来设置要显示的标题和标签。

# Plot the data points
plt.scatter(x_train, y_train, marker='x', c='r')
# Set the title
plt.title("Housing Prices")
# Set the y-axis label
plt.ylabel('Price (in 1000s of dollars)')
# Set the x-axis label
plt.xlabel('Size (1000 sqft)')
plt.show()

在这里插入图片描述

4、模型函数

线性回归的模型函数(这是一个从 x 映射到 y 的函数)可以表示为 f w , b ( x ( i ) ) = w x ( i ) + b (1) f_{w,b}(x^{(i)}) = wx^{(i)} + b \tag{1} fw,b(x(i))=wx(i)+b(1)

计算 f w , b ( x ( i ) ) f_{w,b}(x^{(i)}) fw,b(x(i)) 的值,可以将每个数据点显示地写为:

对于 x ( 0 ) x^{(0)} x(0), f_wb = w * x[0] + b
对于 x ( 1 ) x^{(1)} x(1), f_wb = w * x[1] + b

对于大量的数据点,这可能会变得笨拙且重复。 因此,可以在for 循环中计算输出,如下面的函数compute_model_output 所示。

def compute_model_output(x, w, b):
    """
    Computes the prediction of a linear model
    Args:
      x (ndarray (m,)): Data, m examples 
      w,b (scalar)    : model parameters  
    Returns
      y (ndarray (m,)): target values
    """
    m = x.shape[0]
    f_wb = np.zeros(m)
    for i in range(m):
        f_wb[i] = w * x[i] + b
        
    return f_wb

调用 compute_model_output 函数并绘制输出

w = 100
b = 100

tmp_f_wb = compute_model_output(x_train, w, b,)

# Plot our model prediction
plt.plot(x_train, tmp_f_wb, c='b',label='Our Prediction')

# Plot the data points
plt.scatter(x_train, y_train, marker='x', c='r',label='Actual Values')

# Set the title
plt.title("Housing Prices")
# Set the y-axis label
plt.ylabel('Price (in 1000s of dollars)')
# Set the x-axis label
plt.xlabel('Size (1000 sqft)')
plt.legend()
plt.show()

在这里插入图片描述
很明显, w = 100 w = 100 w=100 b = 100 b = 100 b=100 不会产生适合数据的直线。

根据学过的数学知识,可以容易求出 w = 200 w = 200 w=200 b = 100 b = 100 b=100

5、预测

现在我们已经有了一个模型,可以用它来做出房屋价格的预测。来预测一下 1200 平方英尺的房子的价格。由于面积单位为 1000 平方英尺,所以 x x x 是1.2。

w = 200                         
b = 100    
x_i = 1.2
cost_1200sqft = w * x_i + b    

print(f"${cost_1200sqft:.0f} thousand dollars")

输出的结果是:$340 thousand dollars

总结

  • 线性回归建立一个特征和目标之间关系的模型
    • 在上面的例子中,特征是房屋面积,目标是房价。
    • 对于简单线性回归,模型有两个参数 w w w b b b ,其值使用训练数据进行拟合。
    • 一旦确定了模型的参数,该模型就可以用于对新数据进行预测。

附录

deeplearning.mplstyle 源码:

# see https://matplotlib.org/stable/tutorials/introductory/customizing.html
lines.linewidth: 4
lines.solid_capstyle: butt

legend.fancybox: true

# Verdana" for non-math text,
# Cambria Math

#Blue (Crayon-Aqua) 0096FF
#Dark Red C00000
#Orange (Apple Orange) FF9300
#Black 000000
#Magenta FF40FF
#Purple 7030A0

axes.prop_cycle: cycler('color', ['0096FF', 'FF9300', 'FF40FF', '7030A0', 'C00000'])
#axes.facecolor: f0f0f0 # grey
axes.facecolor: ffffff  # white
axes.labelsize: large
axes.axisbelow: true
axes.grid: False
axes.edgecolor: f0f0f0
axes.linewidth: 3.0
axes.titlesize: x-large

patch.edgecolor: f0f0f0
patch.linewidth: 0.5

svg.fonttype: path

grid.linestyle: -
grid.linewidth: 1.0
grid.color: cbcbcb

xtick.major.size: 0
xtick.minor.size: 0
ytick.major.size: 0
ytick.minor.size: 0

savefig.edgecolor: f0f0f0
savefig.facecolor: f0f0f0

#figure.subplot.left: 0.08
#figure.subplot.right: 0.95
#figure.subplot.bottom: 0.07

#figure.facecolor: f0f0f0  # grey
figure.facecolor: ffffff  # white

## ***************************************************************************
## * FONT                                                                    *
## ***************************************************************************
## The font properties used by `text.Text`.
## See https://matplotlib.org/api/font_manager_api.html for more information
## on font properties.  The 6 font properties used for font matching are
## given below with their default values.
##
## The font.family property can take either a concrete font name (not supported
## when rendering text with usetex), or one of the following five generic
## values:
##     - 'serif' (e.g., Times),
##     - 'sans-serif' (e.g., Helvetica),
##     - 'cursive' (e.g., Zapf-Chancery),
##     - 'fantasy' (e.g., Western), and
##     - 'monospace' (e.g., Courier).
## Each of these values has a corresponding default list of font names
## (font.serif, etc.); the first available font in the list is used.  Note that
## for font.serif, font.sans-serif, and font.monospace, the first element of
## the list (a DejaVu font) will always be used because DejaVu is shipped with
## Matplotlib and is thus guaranteed to be available; the other entries are
## left as examples of other possible values.
##
## The font.style property has three values: normal (or roman), italic
## or oblique.  The oblique style will be used for italic, if it is not
## present.
##
## The font.variant property has two values: normal or small-caps.  For
## TrueType fonts, which are scalable fonts, small-caps is equivalent
## to using a font size of 'smaller', or about 83%% of the current font
## size.
##
## The font.weight property has effectively 13 values: normal, bold,
## bolder, lighter, 100, 200, 300, ..., 900.  Normal is the same as
## 400, and bold is 700.  bolder and lighter are relative values with
## respect to the current weight.
##
## The font.stretch property has 11 values: ultra-condensed,
## extra-condensed, condensed, semi-condensed, normal, semi-expanded,
## expanded, extra-expanded, ultra-expanded, wider, and narrower.  This
## property is not currently implemented.
##
## The font.size property is the default font size for text, given in points.
## 10 pt is the standard value.
##
## Note that font.size controls default text sizes.  To configure
## special text sizes tick labels, axes, labels, title, etc., see the rc
## settings for axes and ticks.  Special text sizes can be defined
## relative to font.size, using the following values: xx-small, x-small,
## small, medium, large, x-large, xx-large, larger, or smaller


font.family:  sans-serif
font.style:   normal
font.variant: normal
font.weight:  normal
font.stretch: normal
font.size:    8.0

font.serif:      DejaVu Serif, Bitstream Vera Serif, Computer Modern Roman, New Century Schoolbook, Century Schoolbook L, Utopia, ITC Bookman, Bookman, Nimbus Roman No9 L, Times New Roman, Times, Palatino, Charter, serif
font.sans-serif: Verdana, DejaVu Sans, Bitstream Vera Sans, Computer Modern Sans Serif, Lucida Grande, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serif
font.cursive:    Apple Chancery, Textile, Zapf Chancery, Sand, Script MT, Felipa, Comic Neue, Comic Sans MS, cursive
font.fantasy:    Chicago, Charcoal, Impact, Western, Humor Sans, xkcd, fantasy
font.monospace:  DejaVu Sans Mono, Bitstream Vera Sans Mono, Computer Modern Typewriter, Andale Mono, Nimbus Mono L, Courier New, Courier, Fixed, Terminal, monospace


## ***************************************************************************
## * TEXT                                                                    *
## ***************************************************************************
## The text properties used by `text.Text`.
## See https://matplotlib.org/api/artist_api.html#module-matplotlib.text
## for more information on text properties
#text.color: black

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/810838.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

C++ 类和对象篇(零) 面向过程 和 面向对象

目录 一、面向过程 二、面向对象 三、两种编程思想的比较 四、C和C 一、面向过程 1.是什么? 是一种以解决问题的过程为中心的编程思想。即先分析出解决问题所需要的步骤,然后用函数把这些步骤一步一步实现。 2.为什么? 面向过程就纯粹是分析…

基于x-scan扫描线的3D模型渲染算法

基于x-scan算法实现的z-buffer染色。c#语言&#xff0c;.net core framework 3.1运行。 模型是读取3D Max的obj模型。 x-scan算法实现&#xff1a; public List<Vertex3> xscan() {List<Vertex3> results new List<Vertex3>();SurfaceFormula formula g…

SAP 自定义BADI增强点

应用场景 标准化代码中预留客制化部分&#xff0c;保证代码主体完整性&#xff0c;可以在预留增强位置预留两种类型的增强处理&#xff0c;其一为标准增强类型的&#xff0c;增强部分代码属于增加的逻辑&#xff0c;其二对于部分多样化的逻辑&#xff0c;使用优先执行默认逻辑&…

Java常用API:Object、Objects、包装类

Object类API toString 返回字符串类型 equals 默认比较的是地址 此时返回的是 false 可以在类中重写equals 方法 比较内容 如果内容一样就返回true clone 不能在测试类中用&#xff0c;必须在创建的类中重写克隆方法 还必须要有接口&#xff0c;说明这个对象有这个能力克隆 …

增量预训练baichuan-13b-chat遇到的那些坑

文章目录 前言资源deepspeed一、训练的坑二、推理的坑三、继续训练的坑总结前言 资源 单机两4090,如图 单卡24G,baichuan-13b-chat单卡推理需要至少26G,因此仅用一张卡,我们是无法加载百川13B的模型,所以,无论是推理还是训练,我们都必须并行! deepspeed 核心思想…

主干网络篇 | YOLOv8 更换主干网络之 VanillaNet |《华为方舟实验室最新成果》

论文地址:https://arxiv.org/pdf/2305.12972.pdf 代码地址:https://github.com/huawei-noah/VanillaNet 在基础模型的核心是“多样性即不同”,这一哲学在计算机视觉和自然语言处理方面取得了惊人的成功。然而,优化和Transformer模型固有的复杂性带来了挑战,需要转向简洁性…

Python-Python基础综合案例--数据可视化 - 地图可视化

版本说明 当前版本号[20230729]。 版本修改说明20230729初版 目录 文章目录 版本说明目录知识总览图Python基础综合案例--数据可视化 - 地图可视化基础地图使用案例效果视觉映射器 疫情地图-国内疫情地图案例效果实操设置全局配置选项 疫情地图-省级疫情地图案例效果实操 知…

spring拦截器 与统一格式

目录 前言模拟拦截器拦截器的实现原理什么是动态代理? 什么是静态代理静态代理与动态代理的区别两种常用的动态代理方式基于接口的动态代理基于类的动态代理 JDK Proxy 与 CGlib的区别 其他 统⼀访问前缀添加统⼀异常处理统⼀数据返回格式 前言 之前博客讲述了 , 关于SpringA…

Kotlin~Memento备忘录模式

概念 备忘录模式是一种行为型设计模式&#xff0c;用于捕获和存储对象的内部状态&#xff0c;并在需要时将对象恢复到之前的状态。 备忘录模式允许在不暴露对象内部实现细节的情况下&#xff0c;对对象进行状态的保存和恢复。 角色介绍 Originator&#xff1a;原发器&#x…

7.事件类型

7.1鼠标事件 案例-轮播图点击切换 需求&#xff1a;当点击左右的按钮&#xff0c;可以切换轮播图 分析: ①右侧按钮点击&#xff0c;变量&#xff0c;如果大于等于8&#xff0c;则复原0 ②左侧按钮点击&#xff0c;变量–&#xff0c;如果小于0&#xff0c;则复原最后一张 ③鼠…

Zotero ubuntu2023安装 关联 ubuntu文献翻译

一、准备下载的软件&#xff1a; Zotero | Downloads 1. Zotero-6.0.26_linux-x86_64.tar.bz2 下面是插件 zotfile-5.1.2-fx.xpi zotero-pdf-translate.xpi jasminum-v0.2.6.xpi 2.2.5 Tampermonkey 4.11.crx 所准备的文件&#xff0c;都已经在这个链接的压缩包下面 …

【机器学习】Multiple Variable Linear Regression

Multiple Variable Linear Regression 1、问题描述1.1 包含样例的X矩阵1.2 参数向量 w, b 2、多变量的模型预测2.1 逐元素进行预测2.2 向量点积进行预测 3、多变量线性回归模型计算损失4、多变量线性回归模型梯度下降4.1 计算梯度4.2梯度下降 首先&#xff0c;导入所需的库 im…

【Maven】让maven更高效,优化maven构建项目速度

打开idea的setting&#xff0c;找到maven&#xff0c;设置它多线程数&#xff0c;重启后即可&#xff01; 我这里是8&#xff0c;你们可以随便设置。 如下图&#xff1a;

Android 之 使用 Camera 拍照

本节引言 本节给大家带来的是Android中Camera的使用&#xff0c;简单点说就是拍照咯&#xff0c;无非两种&#xff1a; 1.调用系统自带相机拍照&#xff0c;然后获取拍照后的图片 2.要么自己写个拍照页面 本节我们来写两个简单的例子体验下上面的这两种情况~ 1.调用系统自带…

《向量数据库指南》:向量数据库Pinecone如何集成LangChain(二)

目录 创建嵌入 向量数据库 索引 创建向量存储并查询 生成式问答 创建嵌入 使用LangChain的OpenAI嵌入功能构建嵌入非常简单。我们首先需要运行下一个单元格,以添加我们的OpenAI API密钥: Python from getpass import getpassOPENAI_API_KEY = getpass("OpenAI…

CleanMyMac X4.14.1中文版如何清理 Mac系统?CleanMyMac 真的能断网激活吗?

CleanMyMac X4.14.1中文版如何清理 Mac系统&#xff1f;Mac系统在使用过程中都会产生大量系统垃圾&#xff0c;如不需要的系统语言安装包&#xff0c;视频网站缓存文件&#xff0c;mac软件卸载残留的注册表等。 随着时间推移&#xff0c;mac系统垃圾就会越来越多&#xff0c;电…

Spring事务创建与使用

目录 前言Spring中事务的实现声明式事务Transactional 作⽤范围Transactional 参数说明对于事务不回滚的解决方案 前言 在数据库中我们提到了 事务, 事务的定义为, 将一系列操作封装成一个整体去调用 , 要么一起成功, 要么一起失败 Spring中事务的实现 在Spring中事务的操作…

LLaMA:开放和高效的基础语言模型

Part1前言 我们介绍了LLaMA&#xff0c;这是一个参数范围从7B到65B的基础语言模型集合。我们在数以万亿计的标记上训练我们的模型&#xff0c;并表明有可能完全使用公开可用的数据集来训练最先进的模型&#xff0c;而不必求助于专有的和不可获取的数据集。特别是&#xff0c;L…

快解析内网穿透和nginx端口映射的比较

众所周知&#xff0c;Nginx是一个高性能的Web服务器和反向代理服务器&#xff0c;快解析是一种内网穿透工具&#xff0c;使内部设备可以通过互联网进行访问。虽然它们都涉及到网络连接和端口使用&#xff0c;但在功能和用途上有一些区别。下面就来具体分析一下。 1.Nginx端口映…

Java中的锁分类

Java中有很多的锁&#xff0c;但是并不全指锁&#xff0c;有些指锁的特性&#xff0c;设计&#xff0c;状态。 1.乐观锁 乐观锁认为在更新数据时&#xff0c;乐观的认为并发时并不会出现问题&#xff0c;即不加锁。 2.悲观锁 悲观锁认为多线程对同一个数据进行操作时&#…