机器学习---梯度下降代码

news2025/3/17 20:38:12

1. 归一化

# Read data from csv
pga = pd.read_csv("pga.csv")
print(type(pga))

print(pga.head())

# Normalize the data 归一化值 (x - mean) / (std)
pga.distance = (pga.distance - pga.distance.mean()) / pga.distance.std()
pga.accuracy = (pga.accuracy - pga.accuracy.mean()) / pga.accuracy.std()
print(pga.head())

plt.scatter(pga.distance, pga.accuracy)
plt.xlabel('normalized distance')
plt.ylabel('normalized accuracy')
plt.show()

2. 线性回归 

from sklearn.linear_model import LinearRegression
import numpy as np

# We can add a dimension to an array by using np.newaxis
print("Shape of the series:", pga.distance.shape)
print("Shape with newaxis:", pga.distance[:, np.newaxis].shape)

# The X variable in LinearRegression.fit() must have 2 dimensions
lm = LinearRegression()
lm.fit(pga.distance[:, np.newaxis], pga.accuracy)
theta1 = lm.coef_[0]
print (theta1)

       这段代码是一个示例,展示了如何使用np.newaxisLinearRegression来进行线性回归。

       首先,通过np.newaxis将一维数组pga.distance添加一个新的维度,从而将其转换为二维数

组。通过打印数组的形状,可以看到在添加np.newaxis之前,pga.distance是一个一维数组,形状

(n,),而添加了np.newaxis之后,形状变为(n, 1)

       然后,创建了一个LinearRegression的实例lm。使用lm.fit()方法,将转换后的特征数据

pga.distance[:, np.newaxis]和目标数据pga.accuracy作为参数,对线性回归模型进行训练拟

合。

       最后,通过lm.coef_获取训练后的模型系数(权重),并将第一个特征的系数赋值给变量

theta1pga.distancepga.accuracy是示例数据,你需要根据实际情况替换为你自己的数据。

3. 代价函数

# The cost function of a single variable linear model# The c 
# 单变量 代价函数
def cost(theta0, theta1, x, y):
    # Initialize cost
    J = 0
    # The number of observations
    m = len(x)
    # Loop through each observation
    # 通过每次观察进行循环
    for i in range(m):
        # Compute the hypothesis 
        # 计算假设
        h = theta1 * x[i] + theta0
        # Add to cost
        J += (h - y[i])**2
    # Average and normalize cost
    J /= (2*m)
    return J

# The cost for theta0=0 and theta1=1
print(cost(0, 1, pga.distance, pga.accuracy))

theta0 = 100
theta1s = np.linspace(-3,2,100)
costs = []
for theta1 in theta1s:
    costs.append(cost(theta0, theta1, pga.distance, pga.accuracy))

plt.plot(theta1s, costs)
plt.show()

       一个简单的单变量线性回归模型的代价函数实现,并且计算了在给定一组参数theta0theta1

的情况下的代价。在这段代码中,cost()函数接受四个参数:theta0theta1是线性模型的参数,

x是输入特征,y是目标变量。函数的目标是计算模型的代价。

       首先,初始化代价J为0。然后,通过循环遍历每个观察值,计算模型的预测值h。代价J通过累

加每个观察值的误差平方来计算。最后,将代价J除以观察值的数量的两倍,以平均和归一化代

价。在这段代码的后半部分,使用一个给定的theta0值和一组theta1值,计算每个theta1对应的代

价,并将结果存储在costs列表中。然后,使用plt.plot()theta1scosts进行绘制,显示出代

价函数随着theta1的变化而变化的趋势。

4. 绘制三维图

import numpy as np
from mpl_toolkits.mplot3d import Axes3D

# Example of a Surface Plot using Matplotlib
# Create x an y variables
x = np.linspace(-10,10,100)
y = np.linspace(-10,10,100)

# We must create variables to represent each possible pair of points in x and y
# ie. (-10, 10), (-10, -9.8), ... (0, 0), ... ,(10, 9.8), (10,9.8)
# x and y need to be transformed to 100x100 matrices to represent these coordinates
# np.meshgrid will build a coordinate matrices of x and y
X, Y = np.meshgrid(x,y)
#print(X[:5,:5],"\n",Y[:5,:5])

# Compute a 3D parabola 
Z = X**2 + Y**2 

# Open a figure to place the plot on
fig = plt.figure()
# Initialize 3D plot
ax = fig.gca(projection='3d')
# Plot the surface
ax.plot_surface(X=X,Y=Y,Z=Z)

plt.show()

# Use these for your excerise 
theta0s = np.linspace(-2,2,100)
theta1s = np.linspace(-2,2, 100)
COST = np.empty(shape=(100,100))
# Meshgrid for paramaters 
T0S, T1S = np.meshgrid(theta0s, theta1s)
# for each parameter combination compute the cost
for i in range(100):
    for j in range(100):
        COST[i,j] = cost(T0S[0,i], T1S[j,0], pga.distance, pga.accuracy)

# make 3d plot
fig2 = plt.figure()
ax = fig2.gca(projection='3d')
ax.plot_surface(X=T0S,Y=T1S,Z=COST)
plt.show()

 

       使用Matplotlib绘制三维图形,包括一个二次曲面图和一个代价函数的图。

       首先,通过使用np.linspace()函数,创建了从-10到10的等间距的100个点,分别赋值给变量

xy

       接下来,使用np.meshgrid()函数将xy转换为100x100的网格矩阵,分别赋值给XY。这

样,XY矩阵中的每个元素表示一个(x, y)坐标对。

       然后,根据二次曲面方程Z = X**2 + Y**2计算出Z矩阵,其中Z矩阵中的每个元素表示对应坐

标点的高度。

       通过plt.figure()创建一个新的图形,并通过fig.gca(projection='3d')初始化一个三维图形

的坐标系。使用ax.plot_surface()函数绘制曲面图,其中XYZ分别表示X、Y和Z矩阵。

       最后,使用plt.show()显示图形。

       在后半部分的代码中,首先创建了两个包含100个均匀分布数值的数组theta0stheta1s,分

别表示theta0和theta1的取值范围。

       接下来,使用np.empty()创建一个空的100x100的数组COST,用于存储代价函数的计算结果。

通过使用np.meshgrid()函数,将theta0stheta1s转换为网格矩阵T0ST1S

       然后,通过两个嵌套的循环遍历所有可能的参数组合,并使用cost()函数计算每个参数组合对

应的代价,并将结果存储在COST数组中。

       最后,使用plt.figure()创建一个新的图形,并通过fig.gca(projection='3d')初始化一个三

维图形的坐标系。使用ax.plot_surface()函数绘制代价函数的曲面图,其中XYZ分别表示

T0ST1SCOST矩阵。使用plt.show()显示图形。

5. 求导函数

线性回归模型的偏导数公式可以通过最小化代价函数推导得到。以下是推导过程:

线性回归模型假设函数为:h(x) = theta0 + theta1 * x

代价函数为均方差函数(Mean Squared Error):J(theta0, theta1) = (1/2m) * Σ(h(x) - y)^2

其中,m 是样本数量,h(x) 是模型的预测值,y 是观测值。

为了求解最优的模型参数 theta0 和 theta1,我们需要计算代价函数对这两个参数的偏导数。

首先,计算代价函数对 theta0 的偏导数:

∂J/∂theta0 = (1/m) * Σ(h(x) - y)

然后,计算代价函数对 theta1 的偏导数:

∂J/∂theta1 = (1/m) * Σ(h(x) - y) * x


# 对 theta1 进行求导# 对 thet 
def partial_cost_theta1(theta0, theta1, x, y):
    # Hypothesis
    h = theta0 + theta1*x
    # Hypothesis minus observed times x
    diff = (h - y) * x
    # Average to compute partial derivative
    partial = diff.sum() / (x.shape[0])
    return partial

partial1 = partial_cost_theta1(0, 5, pga.distance, pga.accuracy)
print("partial1 =", partial1)

# 对theta0 进行求导
# Partial derivative of cost in terms of theta0
def partial_cost_theta0(theta0, theta1, x, y):
    # Hypothesis
    h = theta0 + theta1*x
    # Difference between hypothesis and observation
    diff = (h - y)
    # Compute partial derivative
    partial = diff.sum() / (x.shape[0])
    return partial

partial0 = partial_cost_theta0(1, 1, pga.distance, pga.accuracy)
print("partial0 =", partial0)

       计算代价函数对参数theta1theta0的偏导数。

       首先,定义了一个名为partial_cost_theta1()的函数,接受四个参数:theta0theta1是线

性模型的参数,x是输入特征,y是目标变量。这个函数用于计算代价函数对theta1的偏导数。在函

数内部,首先计算假设值h,然后计算(h-y)*x,得到假设值与观察值之间的差异乘以输入特征x

最后,将这些差异的和除以输入特征的数量,得到对theta1的偏导数。然后,通过调用

partial_cost_theta1()函数并传入参数05,计算出对应的偏导数partial1

        接下来,定义了一个名为partial_cost_theta0()的函数,接受四个参数:theta0

theta1是线性模型的参数,x是输入特征,y是目标变量。这个函数用于计算代价函数对theta0的偏

导数。在函数内部,首先计算假设值h,然后计算假设值与观察值之间的差异。最后,将这些差异

的和除以输入特征的数量,得到对theta0的偏导数。然后,通过调用partial_cost_theta0()函数

并传入参数11,计算出对应的偏导数partial0

6. 梯度下降

# x is our feature vector -- distance
# y is our target variable -- accuracy
# alpha is the learning rate
# theta0 is the intial theta0 
# theta1 is the intial theta1
def gradient_descent(x, y, alpha=0.1, theta0=0, theta1=0):
    max_epochs = 1000 # Maximum number of iterations 最大迭代次数
    counter = 0       # Intialize a counter 当前第几次
    c = cost(theta1, theta0, pga.distance, pga.accuracy)  ## Initial cost 当前代价函数
    costs = [c]     # Lets store each update 每次损失值都记录下来
    # Set a convergence threshold to find where the cost function in minimized
    # When the difference between the previous cost and current cost 
    #        is less than this value we will say the parameters converged
    # 设置一个收敛的阈值 (两次迭代目标函数值相差没有相差多少,就可以停止了)
    convergence_thres = 0.000001  
    cprev = c + 10   
    theta0s = [theta0]
    theta1s = [theta1]

    # When the costs converge or we hit a large number of iterations will we stop updating
    # 两次间隔迭代目标函数值相差没有相差多少(说明可以停止了)
    while (np.abs(cprev - c) > convergence_thres) and (counter < max_epochs):
        cprev = c
        # Alpha times the partial deriviative is our updated
        # 先求导, 导数相当于步长
        update0 = alpha * partial_cost_theta0(theta0, theta1, x, y)
        update1 = alpha * partial_cost_theta1(theta0, theta1, x, y)

        # Update theta0 and theta1 at the same time
        # We want to compute the slopes at the same set of hypothesised parameters
        #             so we update after finding the partial derivatives
        # -= 梯度下降,+=梯度上升
        theta0 -= update0
        theta1 -= update1
        
        # Store thetas
        theta0s.append(theta0)
        theta1s.append(theta1)
        
        # Compute the new cost
        # 当前迭代之后,参数发生更新  
        c = cost(theta0, theta1, pga.distance, pga.accuracy)

        # Store updates,可以进行保存当前代价值
        costs.append(c)
        counter += 1   # Count
        
    # 将当前的theta0, theta1, costs值都返回去
    return {'theta0': theta0, 'theta1': theta1, "costs": costs}

print("Theta0 =", gradient_descent(pga.distance, pga.accuracy)['theta0'])
print("Theta1 =", gradient_descent(pga.distance, pga.accuracy)['theta1'])
print("costs =", gradient_descent(pga.distance, pga.accuracy)['costs'])

descend = gradient_descent(pga.distance, pga.accuracy, alpha=.01)
plt.scatter(range(len(descend["costs"])), descend["costs"])
plt.show()

 

       使用梯度下降法求解线性回归模型中的偏导数以及更新参数的过程。其中,gradient_descent

函数接受输入特征 x 和观测值 y,以及学习率 alpha、初始参数 theta0 和 theta1。在函数中,设

置了最大迭代次数 max_epochs 和收敛阈值 convergence_thres,用于控制算法的停止条件。初始

时,计算了初始的代价函数值 c,并将其存储在 costs 列表中。

       在迭代过程中,使用偏导数的公式进行参数更新,即 theta0 -= update0 和 theta1 -=

update1。同时,计算新的代价函数值 c,并将其存储在 costs 列表中。最后,返回更新后的参数

值 theta0 和 theta1,以及代价函数值的变化过程 costs

       最后,调用了 gradient_descent 函数,并打印了最终的参数值和代价函数值。然后,绘制了

代价函数值的变化过程图。

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

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

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

相关文章

centos7部署openldap开启memberof并接入jumpserver

文章目录 前言1.yum安装openldap2.配置密码3.导入配置4.定义域5.配置memberof6.配置base dn7.安装phpldapadmin管理8.调整httpd的配置9.调整php的配置10.登陆php管理页面11.同步旧ldapsever用户数据(可省略)12.客户端配置13.对接jumpserver 前言 介绍如何在centos7上部署openl…

SpringBoot复习:(29)静态资源的配置路径

WebMvcAutoConfiguration 首页处理&#xff1a;

Linux用户管理命令

一、系统存储用户信息的文件 &#xff08;1&#xff09;/etc/passwd 存储用户基本信息&#xff1a; 通过vi /etc/passwd查看用户基本信息&#xff1a; &#xff08;2&#xff09;/etc/group 存储用户组的信息&#xff1a; 通过vi /etc/group查看用户组信息&#xff1a; &…

SAP MM学习笔记16-在库品目评价

在库品目评价是指评估物料。具体比如物料价格&#xff0c;数量&#xff0c;保管场所等发生变化的时候&#xff0c;判断是否发生了变化&#xff0c;要不要生成 FI票&#xff0c;用哪个FI科目来进行管理等内容就叫在库品目评价。 在库品目评价有很多层级&#xff0c;这里先讲3兄弟…

【C++手撕系列】——设计日期类实现日期计算器

【C手撕系列】——设计日期类实现日期计算器&#x1f60e; 前言&#x1f64c;C嘎嘎类中六大护法实现代码&#xff1a;获取每一个月天数的函数源码分享构造函数源码分享拷贝构造函数源码分享析构函数源码分享赋值运算符重载函数源码分享取地址和const取地址运算符重载函数源码分…

如何写一篇吸引人的新闻稿?揭秘新闻稿写作的技巧!

一篇高质量的新闻稿不仅能够吸引读者的眼球&#xff0c;还能提高文章的曝光量。下面&#xff0c;伯乐网络传媒将给大家揭秘新闻稿写作的十大技巧&#xff0c;帮助大家写出更有吸引力的新闻稿。 1. 选择热门而有吸引力的话题或爆点 要想写出一篇吸引人的新闻稿&#xff0c;首先…

【前端】CSS水平居中的6种方法

左右两边间隔相等的居中 文章目录 flex绝对定位margin:auto绝对定位margin:负值定位transformtext-align: center;margin: 0 auto;思维导图 flex display: flex;justify-content: center; <div classparent><div class"son"></div> </div>…

【VUE】7、VUE项目中集成watermark实现页面添加水印

在网站浏览中&#xff0c;常常需要网页水印&#xff0c;以便防止用户截图或录屏暴露敏感信息后&#xff0c;方便追踪用户来源。 1、安装 watermark 在 package.json 文件 dependencies 节点增加 watermark-dom 依赖 "watermark-dom": "2.3.0"然后执行命…

fastadmin 自定义搜索分类和时间范围

1.分类搜索&#xff0c;分类信息获取----php 2.对应html页面&#xff0c;页面底部加搜索提交代码&#xff08;这里需要注意&#xff1a;红框内容&#xff09; 图上代码----方便直接复制使用 <script id"countrySearch" type"text/html"><!--form…

初识鸿蒙跨平台开发框架ArkUI-X

HarmonyOS是一款面向万物互联时代的、全新的分布式操作系统。在传统的单设备系统能力基础上&#xff0c;HarmonyOS提出了基于同一套系统能力、适配多种终端形态的分布式理念&#xff0c;能够支持手机、平板、智能穿戴、智慧屏、车机等多种终端设备&#xff0c;提供全场景&#…

vue项目里面有多个模块的服务,前端处理url转发

先看下vue的代理配置里面&#xff1a; 现在是在 /pca 基础上增加了 2个模块的服务&#xff1a; /dca、 /api 现在服务器的nginx 没有在/pca 服务里面做转发接受 /dca、 /api的服务&#xff0c;所以需要前端自己去配置每个服务模块对应的 URL 先拿登录的api 做示例吧: 先定义…

多用户微商城多端智慧生态电商系统搭建

多用户微商城多端智慧生态电商系统的搭建步骤如下&#xff1a; 系统规划&#xff1a;在搭建多用户微商城多端智慧生态电商系统之前&#xff0c;需要进行系统规划。包括确定系统的目标、功能、架构、技术选型、开发流程等方面。市场调研&#xff1a;进行市场调研&#xff0c;了…

解决createRoot is not a function

报错&#xff1a; 出现的原因&#xff1a;在于把react18使用的vite构建&#xff0c;在开发中因react版本太高与其他库不兼容&#xff0c;而在降级的时候&#xff0c;出现以上dom渲染出现报错。 解决&#xff1a;将 src/index.j文件改成如下 import React from react; import…

玩转C链表

链表是C语言编程中常用的数据结构&#xff0c;比如我们要建一个整数链表&#xff0c;一般可能这么定义&#xff1a; struct int_node {int val;struct int_node *next;}; 为了实现链表的插入、删除、遍历等功能&#xff0c;另外要再实现一系列函数&#xff0c;比如&#xff1a…

微星游戏本旗舰性价比爆款:泰坦GP68 HX新品开启预售

微星游戏本金字塔尖的旗舰泰坦系列&#xff0c;讲究的就是一个“极致的性能释放”&#xff1a;除了机皇泰坦GT&#xff0c;旗舰性能的泰坦GE以外&#xff0c;泰坦GP则成为了泰坦系列中、甚至所有旗舰游戏本产品中的“旗舰游戏本的守门员”&#xff0c;让更多性能控玩家&#xf…

linux pwn 基础知识

环境搭建 虚拟机安装 镜像下载网站为了避免环境问题建议 22.04 &#xff0c;20.04&#xff0c;18.04&#xff0c;16.04 等常见版本 ubuntu 虚拟机环境各准备一份。注意定期更新快照以防意外。虚拟机建议硬盘 256 G 以上&#xff0c;内存也尽量大一些。硬盘大小只是上界&#…

Mongodb:业务应用(1)

环境搭建参考&#xff1a;mongodb&#xff1a;环境搭建_Success___的博客-CSDN博客 需求&#xff1a; 在文章搜索服务中实现保存搜索记录到mongdb 并在搜索时查询出mongdb保存的数据 1、安装mongodb依赖 <dependency><groupId>org.springframework.data</groupI…

rknn3588如何查看npu使用情况

cat /sys/kernel/debug/rknpu/load在Linux中&#xff0c;你可以使用一些工具和命令来绘制某一进程的实时内存折线图。一个常用的工具是gnuplot&#xff0c;它可以用来绘制各种图表&#xff0c;包括折线图。 首先&#xff0c;你需要收集进程的实时内存数据。你可以使用pidstat命…

餐馆包厢隔断装修该怎么去设计

餐馆包厢隔断装修设计需要综合考虑以下几个方面&#xff1a; 1. 功能布局&#xff1a;根据包厢的面积和形状来确定餐桌、椅子、电视等家具的摆放方式&#xff0c;保证客人的用餐舒适度和便利性。 2. 音响设备&#xff1a;安装合适的音响设备&#xff0c;提供一定的音乐背景&…

商城-学习整理-基础-库存系统(八)

一、整合ware服务 1、配置注册中心 2、配置配置中心 3、配置网关&#xff0c;重启网关 二、仓库维护 http://localhost:8001/#/ware-wareinfo 在前端项目module中创建ware文件夹保存仓库系统的代码。 将生成的wareinfo.vue文件拷贝到项目中。 根据功能&#xff0c;修改后台接…