利用jupyter notebook进行python编程,演示梯度下降算法,求解函数最小值,模拟线性回归分析

利用jupyter notebook进行python编程,演示梯度下降算法,求解函数最小值,模拟线性回归分析

在实际工作中,对于各种算法模型(线性回归)来讲,我们需要获取θ, n, p的值
θ的求解其实就是算法模型的求解,-般不需要开发人员参与(算法已经实现)
主要需要求解的是X和p的值,这个过程就叫调参(超参)
交叉验证:将训练数据分为多份,其中一份进行数据验证并获取最优的超参:λ和p;比如:十折交叉验证、五折交叉验证(scikit-learn中默认) 等
本次博客,林君学长将带领小伙伴利用python编程模拟线性回归函数,求解其最小值,进而进行分析!

一、打开jupyter notebook

1、在Windows的终端cmd中输入jupyter notebook,打开web jupyter notebook编程
在这里插入图片描述
2、新建python文件,点击右上角。选择python2
在这里插入图片描述

二、python模拟函数y= f(x)=x*x,求解其最小值

1、在新建的python文件中写入如下代码,进行二次函数的运算,求出最小值

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
%matplotlib inline
#原函数
def f(x):
    return x**2
##导数
def h(x):
    return 2 * x
X=[]
Y=[]
x=2
step=0.8
f_change=f(x)
f_current=f(x)
X.append(x)
Y.append(f_current)
while f_change > 1e-10:
    x=x-step*h(x)
    tmp=f(x)
    f_change=np.abs(f_current-tmp)
    f_current=tmp
    X.append(x)
    Y.append(f_current)
print("输出结果为:(",x,",",f_current,")")

2、shift+enter运行该python代码,结果如下所示:

在这里插入图片描述

3、建立图像模型,进行函数回归分析,在下面一栏输入如下python代码:

fig = plt.figure()
X2 = np.arange(-2.1,2.15,0.05)
Y2=X2**2
plt.plot(X2,Y2,'-',color='#666666',linewidth=2)
plt.plot(X,Y,'bo-')
plt.title(u'$y=x^2$函数求解最小值,最终解为:x=%.2f,y=%.2f' % (x,f_current))
plt.show()

4、shift+enter运行程序,观察模拟特性:如下所示:

在这里插入图片描述

三、python模拟函数z=f(x,y)=xx+yy,求解其最小值

注意:在执行以下代码的时候,一定要将上面终止运行,这样才会继续运行下面的函数,不然会报错误

1、在接下来的一栏中写入如下python代码,进行函数z=f(x,y)=xx+yy的运算,求出最小值

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
%matplotlib inline
# 设置字符集,防止中文乱码
mpl.rcParams['font.sans-serif'] = [u'simHei']
mpl.rcParams['axes.unicode_minus'] = False
#原函数
def f(x,y):
    return x**2+y**2
#偏函数
def h(t):
    return 2 * t
X=[]
Y=[]
Z=[]
x=2
y=2
f_change=x**2+y**2
f_current=f(x,y)
step=0.1
X.append(x)
Y.append(y)
Z.append(f_current)
while f_change > 1e-10:
    x=x-step*h(x)
    y=y-step*h(y)
    f_change= f_current-f(x,y)
    f_current=f(x,y)
    X.append(x)
    Y.append(y)
    Z.append(f_current)
print("输出结果为:(",x,",",y,")")

2、shift+enter运行该python代码,结果如下所示:

在这里插入图片描述

3、建立3D图像模型,进行函数回归分析,在下面一栏输入如下python代码:

fig = plt.figure()
ax=Axes3D(fig)
X2 = np.arange(-2,2,0.2)
Y2 = np.arange(-2,2,0.2)
X2,Y2=np.meshgrid(X2,Y2)
Z2=X2**2+Y2**2
ax.plot_surface(X2,Y2,Z2,rstride=1,cstride=1,cmap='rainbow')
ax.plot(X,Y,Z,'ro-')
ax.set_title(u'z=x^2+y^2函数求解最小值,最终解为:x=%.2f,y=%.2f,z=%.2f' 
        % (x, y, f_current))
plt.show()

4、shift+enter运行程序,观察模拟特性:如下所示:

在这里插入图片描述
以上就是本次博客的全部内容了,觉得对自己又帮助的小伙伴记得给林君点赞、评论、关注哦!
陈一月的又一天编程岁月!

发布了38 篇原创文章 · 获赞 32 · 访问量 5980

猜你喜欢

转载自blog.csdn.net/qq_42451251/article/details/104652522
今日推荐