【机器学习】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 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.mfbz.cn/a/51431.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

数据可视化 - 动态柱状图

基础柱状图 通过Bar构建基础柱状图 from pyecharts.charts import Bar from pyecharts.options import LabelOpts # 使用Bar构建基础柱状图 bar Bar() # 添加X轴 bar.add_xaxis(["中国", "美国", "英国"]) # 添加Y轴 # 设置数值标签在右侧 b…

乌班图22.04安装wireguard实现异地组网

1. 前言: wireguard是新型的异地组网工具,在此之前,又已经被抛弃的pptp,l2tp,有配置复杂的openvpn,wireguard被linux作者linus赞叹优雅,于linux 5.6合并至linux内核主线。 2. 安装过程&#…

【1.3】Java微服务:Spring Cloud版本说明

✅作者简介:大家好,我是 Meteors., 向往着更加简洁高效的代码写法与编程方式,持续分享Java技术内容。 🍎个人主页:Meteors.的博客 💞当前专栏: 微服务 ✨特色专栏: 知识分享 &#x…

【Java面试丨消息中间件】Kafka

一、kafka是如何保证消息不丢失 1. 介绍 使用kafka在消息的收发过程都有可能会出现消息丢失 (1)生产者发送消息到broker丢失 (2)消息在broker中存储丢失 (3)消费者从broker接收消息丢失 2. 生产者发送消…

Day47 算法记录|动态规划14子序列

子序列 1143. 最长公共子序列1035.不相交的线53. 最大子数组和 1143. 最长公共子序列 这道题和718. 最长重复子数组的区别:这道题的子序列可以不连续 这个视频讲解的很好 class Solution {public int longestCommonSubsequence(String text1, String text2) {char…

[Linux]线程基本知识

概念 进程 一个正在执行的程序,它是资源分配的最小单位 进程中的事情需要按照一定的顺序逐个进行 进程出现了很多弊端: 一是由于进程是资源拥有者,创建、撤消与切换存在较大的时空开销,因此需要引入轻型进程; 二是由于对称多…

高德地图JS API升级到2.0版本

项目上反馈高德地图底图信息更新不及时,不利于进行点位规划。经研究发现高德地图JS API 1.4.15版本相对于2.0版本,确实地图切片上的标注信息较少。通过工单的形式询问高德的技术工程师认识到1.4.15版本数据更新有延迟,1.4.15版本地图的数据以…

【微软知识】微软相关技术知识分享

微软技术领域 一、微软操作系统: 微软的操作系统主要是 Windows 系列,包括 Windows 10、Windows Server 等。了解 Windows 操作系统的基本使用、配置和故障排除是非常重要的。微软操作系统(Microsoft System)是美国微软开发的Wi…

7.27 Qt

制作简易小闹钟 Timer.pro QT core gui texttospeechgreaterThan(QT_MAJOR_VERSION, 4): QT widgetsCONFIG c11# The following define makes your compiler emit warnings if you use # any Qt feature that has been marked deprecated (the exact warnings # dep…

进程_PCB 的理解

目录 一. PCB 的概念 1. 为什么需要PCB 2. PCB的属性 二. task struct 1. task struct 介绍 2. 查看进程指令 3. PID 4. PPID 父进程是什么? 为什么要有父进程? 5. fork 创建子进程 1) fork 后的现象 为什么会打印两次? 2) 的返…

matplotlib从起点出发(6)_Tutorial_6_Animations

1 在matplotlib中使用动画 基于其绘图功能,matplotlib还提供了一个使用动画模块生成动画animation的接口。动画是一系列帧,其中每个帧对应于图形Figure 上的一个绘图。本教程介绍了有关如何创建此类动画的一般准则以及可用的不同选项。 import matplot…

掌握Python的X篇_16_list的切片、len和in操作

接上篇掌握Python的X篇_15_list容器的基本使用,本篇进行进一步的介绍。 文章目录 1. list的索引下标可以是负数2. 切片(slice)2.1 切片基础知识2.2 如何“取到尽头”2.3 按照步长取元素2.4 逆序取值 3. len函数获取lis的元素个数4. in操作符…

自动驾驶感知系统--惯性导航定位系统

惯性导航定位 惯性是所有质量体本身的基本属性,所以建立在牛顿定律基础上的惯性导航系统(Inertial Navigation System,INS)(简称惯导系统)不与外界发生任何光电联系,仅靠系统本身就能对车辆进行连续的三维定位和三维定向。卫星导…

【嵌入式Linux项目】基于Linux的全志H616开发板智能家居项目(语音控制、人脸识别、安卓APP和PC端QT客户端远程操控)有视频功能展示

目录 一、功能需求 二、开发环境 1、硬件: 2、软件: 3、引脚分配: 三、关键点 1、设计模式之工厂模式 2、wiringPi库下的相关硬件操作函数调用 3、语音模块的串口通信 4、线程 5、摄像头的实时监控和拍照功能 6、人脸识别 四、编…

Python web实战 | 使用 Django 搭建 Web 应用程序 【干货】

概要 从社交媒体到在线购物,从在线银行到在线医疗,Web 应用程序为人们提供了方便快捷的服务。Web 应用程序已经成为了人们日常生活中不可或缺的一部分。搭建一个高效、稳定、易用的 Web 应用程序并不是一件容易的事情。本文将介绍如何使用 Django 快速搭…

Python基础入门教程(上)

目录 一、你好Python 1.1、Python安装 win版 Linux版 1.2、第一个Python程序 二、Python基本语法 2.1、字面量 2.2、注释 2.3、变量 2.4、数据类型 type()函数 字符串类型的不同定义方式 2.5、数据类型转换 ​编辑 2.6、标识符 2.7、运算符 2.8、字符串扩展 …

Linux安装kafka3.5.1

要在Ubuntu上安装Apache Kafka,请按照以下步骤操作: 1、安装Java运行时环境(Ubuntu): 如果已经安装jdk不用执行 sudo apt update sudo apt install default-jre2、下载Kafka: wget https://downloads.apache.org/kafka/3.5.1/…

【【51单片机的红外遥控】】

红外遥控,完全把控 红外遥控 利用红外光进行通信的设备,由红外LED将调制后的信号发出,再由专门的红外接收头进行解调输出 通信方式:单工 异步 红外LED波长:940nm 通信协议标准:NEC标准 用那种一体化红红外…

下级平台级联视频汇聚融合平台EasyCVR,层级显示不正确的原因排查

视频汇聚平台安防监控EasyCVR可拓展性强、视频能力灵活、部署轻快,可支持的主流标准协议有GB28181、RTSP/Onvif、RTMP等,以及厂家私有协议与SDK接入,包括海康Ehome、海大宇等设备的SDK等,能对外分发RTSP、RTMP、FLV、HLS、WebRTC等…

如何使用 After Effects 导出摄像机跟踪数据到 3ds Max

推荐: NSDT场景编辑器助你快速搭建可二次开发的3D应用场景 在本教程中,我将展示如何在After Effects中跟踪实景场景,然后将相机数据导出到3ds Max。 1. 项目设置 步骤 1 打开“后效”。 打开后效果 步骤 2 转到合成>新合成以创建新合…