【机器学习】线性回归

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 modelArgs:x (ndarray (m,)): Data, m examples w,b (scalar)    : model parameters  Returnsy (ndarray (m,)): target values"""m = x.shape[0]f_wb = np.zeros(m)for i in range(m):f_wb[i] = w * x[i] + breturn f_wb

调用 compute_model_output 函数并绘制输出

w = 100
b = 100tmp_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: buttlegend.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 7030A0axes.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-largepatch.edgecolor: f0f0f0
patch.linewidth: 0.5svg.fonttype: pathgrid.linestyle: -
grid.linewidth: 1.0
grid.color: cbcbcbxtick.major.size: 0
xtick.minor.size: 0
ytick.major.size: 0
ytick.minor.size: 0savefig.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 smallerfont.family:  sans-serif
font.style:   normal
font.variant: normal
font.weight:  normal
font.stretch: normal
font.size:    8.0font.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.mzph.cn/news/64353.shtml

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

相关文章

2010-2021年上市公司和讯网社会责任评级CSR数据/和讯网上市公司社会责任数据

2010-2021年上市公司和讯网社会责任评级CSR数据 1、时间:2010-2021年 2、指标:股票名称、股票代码、年份、总得分、等级、股东责任、员工责任、供应商、客户和消费者权益责任、环境责任、社会责任、所属年份 3、样本量:4万 4、来源&#…

数据结构与算法基础-学习-31-交换排序之冒泡排序、快速排序

排序的其他相关知识点和源码分享可以参考之前的博客: 《数据结构与算法基础-学习-30-插入排序之直接插入排序、二分插入排序、希尔排序》 一、交换排序基本思想 两两比较,如果发生逆序则交换位置,直到所有数据记录都排好序为止。 二、冒…

linux下C程序查看内存剩余大小

嵌入式linux中很多内存资源都比较小&#xff0c;所以很多程序中在malloc时就需要提前知道内存剩余的大小 下面是一种调用 sysinfo接口来实现。 示例代码如下&#xff1a; #include <stdio.h> #include <linux/kernel.h> #include <linux/unistd.h> #includ…

大模型理解之CLIP

前言 2021年2月份&#xff0c;CLIP模型被提出&#xff0c;想法很简单&#xff0c;性能高效&#xff0c;而且具备很好的泛化性。我在这里简单谈论下我对CLIP模型的理解&#xff0c;以及发现的一些问题。 我是在沐神的视频中了解的CLIP, 里面提到CLIP最大的贡献在于打破了固定类…

四轴飞行器的电池研究(MatlabSimulink仿真)

&#x1f4a5;&#x1f4a5;&#x1f49e;&#x1f49e;欢迎来到本博客❤️❤️&#x1f4a5;&#x1f4a5; &#x1f3c6;博主优势&#xff1a;&#x1f31e;&#x1f31e;&#x1f31e;博客内容尽量做到思维缜密&#xff0c;逻辑清晰&#xff0c;为了方便读者。 ⛳️座右铭&a…

全球免费编程教育网站:Code.org

全球免费编程教育网站&#xff1a;Code.org 官网地址注册使用 你还在为小朋友的编程教育而发愁吗&#xff1f; 你还在为小朋友放假无聊而头疼吗&#xff1f; 他来了他来了&#xff0c;全球免费编程教育网站来了。 2013年成立的Code.org是一个非营利组织。 它致力于为年轻女子、…

Xilinx UltraScale架构之可配置逻辑块CLB

目录 一、概览 二、UltraScale架构 2.1 UltraScale/UltraScale特点 2.2 与7系列CLB差异 三、 CLB结构 3.1 LUT 3.2 FF 3.3 多路选择器Multiplexers 3.4 进位链Carry Chain 四、应用 4.1 分布式RAM 4.2 移位寄存器 4.3 进位链Carry Chain 五、参考资料 一、概览 二…

专门针对开发人员,攻击者利用Rust获取操作系统信息

近日&#xff0c;研究人员在 Rust 编程语言的 crate 注册表中发现了一些恶意软件包&#xff0c;专门针对开发人员。 Phylum 在上周发布的一份报告中称&#xff0c;这些库是由一个名为 "amaperf "的用户在 2023 年 8 月 14 日至 16 日之间上传的。现已删除的软件包名…

【LeetCode-中等题】114. 二叉树展开为链表

文章目录 题目方法一&#xff1a;前序遍历&#xff08;构造集合&#xff09; 集合&#xff08;构造新树&#xff09;方法二&#xff1a;原地构建方法三&#xff1a;前序遍历--迭代&#xff08;构造集合&#xff09; 集合&#xff08;构造新树&#xff09; 题目 方法一&#x…

el-select 选择一条数据后,把其余数据带过来

1. 案例&#xff1a; ps: 票号是下拉框选择&#xff0c;风险分类、场站名称以及开始时间是选择【票号】后带过来的。 2. 思路: 使用官网上给的方法&#xff0c;选择之后&#xff0c;触发change方法从而给其余字段赋值 3. 代码 <el-form-itemlabel"票号&#xff1a;&…

buildAdmin的使用笔记

安装buildAdmin 下载完整包&#xff0c;解压进入 buildadmin 的文件夹&#xff0c; 输入命令 composer install 启动的时候使用&#xff0c; php think run 就可以了 为什么启动只需要&#xff0c; php think run 这种启动方式&#xff0c; 我是头一回看见 &#xff0c;后来才…

如何在IT技术面试中脱颖而出?

前序 在竞争激烈的IT领域&#xff0c;技术面试是进入理想工作的关键一步。然而&#xff0c;要在面试中脱颖而出&#xff0c;您需要更多的准备和策略。以下是一些实际且深入的方法&#xff0c;可以帮助您在IT技术面试中脱颖而出。 准备和策略 确保深入了解公司和职位 在面试前…

Android 手游聚合SDK小知识(一)

Android 手游聚合SDK小知识(一) Android 手游聚合SDK小知识(二) 聚合分包 前言 回头想想&#xff0c;在安卓游戏SDK这个领域&#xff0c;我也呆了4年了&#xff0c;从啥都不懂的小菜鸟&#xff0c;逐渐靠自己不断学习&#xff0c;对这个行业也算有了一些理解&#xff0c;趁着…

如何击败那个令程序员绝望的Bug

灵异事件&#xff01;程序里发现了新Bug但是它正常运行啦&#xff01;人生处处有Bug&#xff0c;但有些Bug实在令人目瞪口呆&#xff0c;久久不能忘怀。 有一天&#xff0c;我正忙着维护一个庞大的软件项目&#xff0c;数以百万计的行代码交织成复杂的网络。项目中的一个模块引…

[贪心] 拼接最小数

这道题思路并不难&#xff0c;我主要想学习其一些对于字符串的处理。 代码如下&#xff1a; #include <iostream> #include <string> #include <algorithm> using namespace std;const int MAXN 10000; string nums[MAXN];bool cmp(string a, string b) {…

柯桥外贸英语培训哪家表专业,零基础可以学吗

“我也是”一出口&#xff0c;紧跟着就是 “Me too! / I think so. / I agree with you. 等等”。 今天&#xff0c;咱们换个说法&#xff0c;来表达一下两个人不谋而合、意见一致吧~~ 01 影视对接 02 Subtitle WA: And these are her puppies. Come here, come here, littl…

useEffect 不可忽视的 cleanup 函数

在 react 开发中&#xff0c; useEffect 是我们经常会使用到的钩子&#xff0c;一个基础的例子如下&#xff1a; useEffect(() > {// some code here// cleanup 函数return () > {doSomething()} }, [dependencies])上述代码中&#xff0c; cleanup 函数的执行时机有如下…

js 获得元素的offsetLeft

要获得元素相对于其offsetParent元素左侧边缘的距离&#xff08;即offsetLeft&#xff09;&#xff0c;可以使用如下代码&#xff1a; var el document.getElementById(your-element-id); var offsetLeft el.offsetLeft;其中&#xff0c;el为要获取offsetLeft的元素对象&…

【4】索引缓冲区的使用为什么使用

glDrawArrays(GL_TRIANGLES, 0, 6); 这个函数绘制三角形是按照顶点的顺序来的&#xff0c;那么绘制一个矩形就需要绘制两个三角形&#xff0c;每个三角形需要提供三个顶点&#xff0c;那么在positon数组里就有6个顶点的数据&#xff0c;每个顶点占两个float数&#xff08;假如是…

设计模式第九讲:常见重构技巧 - 去除不必要的!=

设计模式第九讲&#xff1a;常见重构技巧 - 去除不必要的! 项目中会存在大量判空代码&#xff0c;多么丑陋繁冗&#xff01;如何避免这种情况&#xff1f;我们是否滥用了判空呢&#xff1f;本文是设计模式第九讲&#xff0c;讲解常见重构技巧&#xff1a;去除不必要的! 文章目录…