栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python拟合直线,数模可用,代码自取,(机器学习)

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python拟合直线,数模可用,代码自取,(机器学习)

这个直线拟合,说不定在数学建模中你就会需要哦

在拟合完成后会自行绘制拟合直线和用户传入的数据点

效果如下:

x = [1,2,3,4,5,6],y=[4,4,5,6,7,8,7]

 代码如下:

​
import pandas as pd
# file_name = ''  读取文件名
import matplotlib.pyplot as plt
import numpy as np
##先创建回归直线h(x)=a+bx函数
def hhhhh(x,y):
    def h(a,b,x):
        return a+b*x
    m = len(x)
    print('len(x)=',m)
    alpha = 0.1
    def qiudao_aaaa(a,b,x,y):         #代价函数对a的求导
        dao = 0
        for i in range(m):
            dao += (h(a,b,x[i]) - y[i])/m        ##注意对a的求导是1
        print(dao)
        return dao
    def qiudao_bbbb(a,b,x,y):         #代价函数对b的求导
        dao = 0
        for i in range(m):
            dao += x[i]*(h(a,b,x[i]) - y[i])/m
        print(dao)
        return dao
    aa = 0.5
    bb = 0.5
    for i in range(1000):
        temp01 = qiudao_aaaa(aa,bb,x,y)
        temp02 = qiudao_bbbb(aa,bb,x,y)
        # print('temp01=',temp01,'temp02=',temp02)
        unit = (temp02**2+temp01**2)**(1/2)
        aa = aa - alpha*temp01/unit
        bb = bb - alpha*temp02/unit
        if temp01==0 and temp02==0:
            print('巧了')
            break
    return [aa,bb]

fp=pd.read_csv(input('请输入excel路径'))
list01 = [1,2,3,4,5,6]                     ##手动将list01(对应x) list02()对应y 修改位相应fp中数据就可以开始拟合
list02 = [4,4,5,7,8,7]
plt.scatter(list01,list02)
thetea = hhhhh(list01,list02)
print(thetea)
x = np.array(list01)
y = thetea[0]+thetea[1]*x                     ##这一条就是拟合直线
plt.plot(list01,y)

plt.show()

​

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/275217.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号