单一特征:一元一次 import numpy as np import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression x=np.linspace(2,10,20).reshape(-1,1) #f(x)=wx+b y=np.random.randint(1,6,size=1)*x+np.random.randint(-5,5,size=1) #加入噪声 y+=np.random.randn(20,1)*0.5 # plt.show() lr=LinearRegression() lr.fit(x,y) # print(lr.coef_) w=lr.coef_[0,0] b=lr.intercept_[0] print(w,b) x1=np.linspace(1,11,50) plt.scatter(x,y,color="red") plt.plot(x1,w*x1+b,color="green") plt.show() #使用梯度下降解决一元一次的线性问题 class LinearModel(object): def __init__(self): self.w=np.random.randn(1)[0] self.b=np.random.randn(1)[0] # 数学建模:将数据x和目标值关系用数学公式表达 def model(self,x): #模型,f(x)=wx+b return self.w*x+self.b def loss(self,x,y):#线性回归的损失函数是最小二乘法 cost=(y-self.model(x))**2 #偏导数,求解两个未知数,