这个直线拟合,说不定在数学建模中你就会需要哦
在拟合完成后会自行绘制拟合直线和用户传入的数据点
效果如下:
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()



