当前位置: 首页 > news >正文

【机器学习】Linear Regression

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

相关文章:

【机器学习】Linear Regression

Model Representation 1、问题描述2、表示说明3、数据绘图4、模型函数5、预测总结附录 1、问题描述 一套 1000 平方英尺 (sqft) 的房屋售价为300,000美元,一套 2000 平方英尺的房屋售价为500,000美元。这两点将构成我们的数据或训练集。面积单位为 1000 平方英尺&a…...

STM32 中断优先级管理(二)

NVIC中断管理相关函数主要在HAL库关键文件stm32f1xx_hal_cortex.c中定义。 中断优先级分组函数 void HAL_NVIC_SetPriorityGrouping(uint32_t PriorityGroup);这个函数的作用是对中断的优先级进行分组,这个函数在系统中只需要被调用一次。 void HAL_NVIC_SetPrio…...

17-汽水瓶

题目 某商店规定:三个空汽水瓶可以换一瓶汽水,允许向老板借空汽水瓶(但是必须要归还)。 小张手上有n个空汽水瓶,她想知道自己最多可以喝到多少瓶汽水。 数据范围:输入的正整数满足 1≤n≤100 注意&…...

Mindar.JS——实现AR图像追踪插入图片或视频

Mindar.JS使用方式 注意&#xff1a;此篇文章需要启动https才可调用相机权限 图像追踪示例 需要用到两个js库 <script src"./js/aframe.min.js"></script><script src"./js/mindar-image-aframe.prod.js"></script>下面看一下标签…...

JVM源码剖析之JIT工作流程

版本信息&#xff1a; jdk版本&#xff1a;jdk8u40思想至上 Hotspot中执行引擎分为解释器、JIT及时编译器&#xff0c;上篇文章描述到解释器过度到JIT的条件。JVM源码剖析之达到什么条件进行JIT优化 这篇文章大致讲述JIT的编译过程。在JDK中javac和JIT两部分跟编译原理挂钩&a…...

【投资笔记】(23/7/31)下半年消费复苏的机会来了?

本文为本人投资逻辑验证&#xff0c;不作为任何建议&#xff1b; 政策面 汽车&#xff1a;&#xff08;一&#xff09;优化汽车购买使用管理&#xff08;二&#xff09;扩大新能源汽车消费&#xff0c;重点在于新能源汽车&#xff1b;房地产&#xff1a;&#xff08;三&#x…...

MySQL二进制日志(binlog)配置、二进制日志binlog查看、mysqlbinlog查看二进制日志、二进制日志binlog清理等详解

提示&#xff1a;MySQL 中的日志比较重要的有 binlog&#xff08;归档日志&#xff09;、redo log&#xff08;重做日志&#xff09;以及 undo log&#xff0c;那么跟我们本文相关的主要是 binlog&#xff0c;另外两个日志松哥将来有空了再和大家详细介绍。 文章目录 1、二进制…...

Python内存管理解析:高效利用资源的关键

推荐阅读 AI文本 OCR识别最佳实践 AI Gamma一键生成PPT工具直达链接 玩转cloud Studio 在线编码神器 玩转 GPU AI绘画、AI讲话、翻译,GPU点亮AI想象空间 引言 在当今互联网时代&#xff0c;Python已经成为最受欢迎的编程语言之一。它的简洁、灵活和强大的生态系统使其成为…...

解决Debian10乱码以及远程连接ssh的问题

文章目录 解决Debian10乱码Debian10配置ssh 解决Debian10乱码 下载locales apt-get install locales配置语言 dpkg-reconfigure locales输入上述命令后会进入到以下页面【空格为选中&#xff0c;回车下一个页面】 在这个页面里我们按空格选中如图的选项&#xff0c;然后回…...

C# 泛型(Generic)

方法重载&#xff1a;方法名称相同&#xff0c;参数个数和参数类型不同&#xff1b; 优势&#xff1a;可以节约方法名称 劣势&#xff1a;方法过多 语法&#xff1a;public void writeContent(T t) 原理&#xff1a;普通的C#代码他是运行在前端进行编译&#xff0c;所有的类型需…...

Golang之路---02 基础语法——流程控制(if-else , switch-case , for-range , defer)

流程控制 条件语句——if-else if 条件 1 {分支 1 } else if 条件 2 {分支 2 } else if 条件 ... {分支 ... } else {分支 else }注&#xff1a; Golang编译器&#xff0c;对于 { 和 } 的位置有严格的要求&#xff0c;它要求 else if &#xff08;或 else&#xff09;和 两边…...

HTTP——HTTP报文内的HTTP信息

HTTP 通信过程包括从客户端发往服务器端的请求及从服务器端返回客户端的响应。本章就让我们来了解一下请求和响应是怎样运作的。 HTTP 一、HTTP报文二、请求报文及响应报文的结构三、编码提升传输速率1、报文主体和实体主题的差异2、压缩传输的内容编码3、分割发送的分块传输编…...

RocketMQ工作原理

文章目录 三.RocketMQ工作原理1.消息的生产消息的生产过程Queue选择算法 2.消息的存储1.commitlog文件目录与文件消息单元 2.consumequeue目录与文件索引条目 3.对文件的读写消息写入消息拉取性能提升 3.indexFile1.索引条目结构2.文件名的作用3.查询流程 4.消息的消费1.推拉消…...

Jenkins+Docker+Docker-Compose自动部署,SpringCloud架构公共包一个任务配置

前言 Jenkins和docker的安装&#xff0c;随便百度吧&#xff0c;实际场景中我们很多微服务的架构&#xff0c;都是有公共包&#xff0c;肯定是希望一个任务能够把公共包的配置加进去&#xff0c;一并构建&#xff0c;ok&#xff0c;直接上干货。 Jenkins 全局环境安装 pwd e…...

spring boot 2 配置上传文件大小限制

一、起因&#xff1a;系统页面上传一个文件超过日志提示的文件最大100M的限制&#xff0c;需要更改配置文件 二、经过&#xff1a; 1、在本地代码中找到配置文件&#xff0c;修改相应数值后交给运维更新生产环境配置&#xff0c;但是运维说生产环境没有这行配置&#xff0c;遂…...

Jmeter —— 录制脚本

1. 第一步&#xff1a;添加http代理服务器&#xff0c;在测试计划--》添加--》非测试元件--》http代理服务器 2. 第二步&#xff1a;添加线程组&#xff08;这个线程组是用来放录制的脚本&#xff0c;不添加也可以&#xff0c;就直接放在代理服务器下&#xff09; 测试计划--》…...

从零开始学Docker(一):Docker的安装部署

前述&#xff1a;本次学习与整理来至B站【Python开发_老6哥】老师分享的课程&#xff0c;有兴趣的小伙伴可以去加油啦&#xff0c;附链接 宿主机环境&#xff1a;RockyLinux 9 版本管理 Docker引擎主要有两个版本&#xff1a;企业版&#xff08;EE&#xff09;和社区版&#…...

【ROS 02】ROS通信机制

机器人是一种高度复杂的系统性实现&#xff0c;在机器人上可能集成各种传感器(雷达、摄像头、GPS...)以及运动控制实现&#xff0c;为了解耦合&#xff0c;在ROS中每一个功能点都是一个单独的进程&#xff0c;每一个进程都是独立运行的。更确切的讲&#xff0c;ROS是进程&#…...

uniapp 选择城市定位 根据城市首字母分类排序

获取城市首字母排序&#xff0c;按字母顺序排序 <template><view class"address-wrap" id"address"><!-- 搜索输入框-end --><template v-if"!isSearch"><!-- 城市列表-start --><view class"address-sc…...

flex盒子 center排布,有滚动条时,拖动滚动条无法完整显示内容

文章目录 问题示例代码解决问题改进后的效果 问题 最近在开发项目的过程中&#xff0c;发现了一个有趣的事情&#xff0c;与flex盒子有关&#xff0c;不知道算不算是一个bug&#xff0c;不过对于开发者来说&#xff0c;确实有些不方便&#xff0c;感兴趣的同学不妨也去试试。 …...

使用docker在3台服务器上搭建基于redis 6.x的一主两从三台均是哨兵模式

一、环境及版本说明 如果服务器已经安装了docker,则忽略此步骤,如果没有安装,则可以按照一下方式安装: 1. 在线安装(有互联网环境): 请看我这篇文章 传送阵>> 点我查看 2. 离线安装(内网环境):请看我这篇文章 传送阵>> 点我查看 说明&#xff1a;假设每台服务器已…...

装饰模式(Decorator Pattern)重构java邮件发奖系统实战

前言 现在我们有个如下的需求&#xff0c;设计一个邮件发奖的小系统&#xff0c; 需求 1.数据验证 → 2. 敏感信息加密 → 3. 日志记录 → 4. 实际发送邮件 装饰器模式&#xff08;Decorator Pattern&#xff09;允许向一个现有的对象添加新的功能&#xff0c;同时又不改变其…...

进程地址空间(比特课总结)

一、进程地址空间 1. 环境变量 1 &#xff09;⽤户级环境变量与系统级环境变量 全局属性&#xff1a;环境变量具有全局属性&#xff0c;会被⼦进程继承。例如当bash启动⼦进程时&#xff0c;环 境变量会⾃动传递给⼦进程。 本地变量限制&#xff1a;本地变量只在当前进程(ba…...

基于距离变化能量开销动态调整的WSN低功耗拓扑控制开销算法matlab仿真

目录 1.程序功能描述 2.测试软件版本以及运行结果展示 3.核心程序 4.算法仿真参数 5.算法理论概述 6.参考文献 7.完整程序 1.程序功能描述 通过动态调整节点通信的能量开销&#xff0c;平衡网络负载&#xff0c;延长WSN生命周期。具体通过建立基于距离的能量消耗模型&am…...

定时器任务——若依源码分析

分析util包下面的工具类schedule utils&#xff1a; ScheduleUtils 是若依中用于与 Quartz 框架交互的工具类&#xff0c;封装了定时任务的 创建、更新、暂停、删除等核心逻辑。 createScheduleJob createScheduleJob 用于将任务注册到 Quartz&#xff0c;先构建任务的 JobD…...

【AI学习】三、AI算法中的向量

在人工智能&#xff08;AI&#xff09;算法中&#xff0c;向量&#xff08;Vector&#xff09;是一种将现实世界中的数据&#xff08;如图像、文本、音频等&#xff09;转化为计算机可处理的数值型特征表示的工具。它是连接人类认知&#xff08;如语义、视觉特征&#xff09;与…...

EtherNet/IP转DeviceNet协议网关详解

一&#xff0c;设备主要功能 疆鸿智能JH-DVN-EIP本产品是自主研发的一款EtherNet/IP从站功能的通讯网关。该产品主要功能是连接DeviceNet总线和EtherNet/IP网络&#xff0c;本网关连接到EtherNet/IP总线中做为从站使用&#xff0c;连接到DeviceNet总线中做为从站使用。 在自动…...

selenium学习实战【Python爬虫】

selenium学习实战【Python爬虫】 文章目录 selenium学习实战【Python爬虫】一、声明二、学习目标三、安装依赖3.1 安装selenium库3.2 安装浏览器驱动3.2.1 查看Edge版本3.2.2 驱动安装 四、代码讲解4.1 配置浏览器4.2 加载更多4.3 寻找内容4.4 完整代码 五、报告文件爬取5.1 提…...

解读《网络安全法》最新修订,把握网络安全新趋势

《网络安全法》自2017年施行以来&#xff0c;在维护网络空间安全方面发挥了重要作用。但随着网络环境的日益复杂&#xff0c;网络攻击、数据泄露等事件频发&#xff0c;现行法律已难以完全适应新的风险挑战。 2025年3月28日&#xff0c;国家网信办会同相关部门起草了《网络安全…...

基于Java+VUE+MariaDB实现(Web)仿小米商城

仿小米商城 环境安装 nodejs maven JDK11 运行 mvn clean install -DskipTestscd adminmvn spring-boot:runcd ../webmvn spring-boot:runcd ../xiaomi-store-admin-vuenpm installnpm run servecd ../xiaomi-store-vuenpm installnpm run serve 注意&#xff1a;运行前…...