import numpy as np import pandas as pd import matplotlib.pyplot as plt plt.rcParams['font.sans-serif']=["SimHei"] #单使用会使负号显示错误 plt.rcParams['axes.unicode_minus']=False #把负号正常显示 # 读取北京房价数据 path='data.txt' data=pd.read_csv(path,header=None,names=['mianji','jiage']) # data.head() # data.describe() # 绘制散点图 data.plot(kind='scatter',x='mianji',y='jiage') plt.show() def computeCost(X,y,theta): inner=np.power((X*theta.T),2) return np.sum(inner)/(2*len(X)) data.insert(0,'Ones',1) clos=data.shape[1] X=data.iloc[:,0:clos-1] y=data.iloc[:,clos-1:clos] X=np.matrix(X.values) y=np.matrix(y.values) theta=np.matrix(np.array[0,0]) computeCost(X,y,theta) def gradientDescent(X,y,theta,alpha,iters): temp=np.atrix(np.zeros(theta.shape)) parameters=int(theta.ravel().shape[1]) cost=np.zeros(iters) for i in range(iters): error=(X*theta.T)-y for j in range(parameters): term=np.multiply(error,X[:,j]) temp[0,j]=theta[0,j]-((alpha/len(X))*np.sum(term)) theta=temp cost[i]=computeCost(X,y,theta) return theta,cost alpha=0.01 iters=1000 g,cost=gradientDescent(X,y,theta,alpha,iters) x=np.linspace(data.mianji.min(),data.mianji.max(),100) f=g[0,0]+(g[0,1]*X) fig,ax=plt.subplots(figsize=(12,8)) ax.plot(x,f,'r',label='北京房价') ax.scatter(data.mianji,data.jiage,label='Traning data') ax.legend(loc=4) ax.set_xlabel=('房子面积') ax.set_ylabel=('房子价格') ax.set_title("北京房价格回归图") plt.show()