Exercise 1:Linear Regression---实现一个线性回归
在本次练习中,需要实现一个单变量的线性回归。假设有一组历史数据<城市人口,开店利润>,现需要预测在哪个城市中开店利润比较好?
历史数据如下:第一列表示城市人口数,单位为万人;第二列表示利润,单位为10,000$
5.5277 9.1302
8.5186 13.6620
7.0032 11.8540
.....
......
代码
import numpy as np import pandas as pd import matplotlib.pyplot as plt # #单变量线性回归 # path = 'ex1data1.txt' data = pd.read_csv(path,header=None,names=['population','profit']) data.head() #查看前5行数据(默认) ,data.head(3)则是前三行 data.describe() #得到data数据的整体概括 print(data.describe()) #添加一列 data.insert(0,'ones',1) # 就是在第一列(0) 添加名字为 ones 的一列数据,他的数值都是 1 #偏置数值x0 = 1 !!! #展示数据 data.plot(kind = 'scatter' , x = 'population' , y = 'profit' ) # 设置画板类型,figsize是画板大小 plt.show() def computeCost(x,y,theta): #初始化单变量线性回归 inner = np.power(((x*theta.T) - y),2) #power(x,2) , 就是将x数组里面的元素都2次方 return np.sum(inner) / (2*len(x)) #初始化变量 cols = data.shape[1] x = data.iloc[:,0:cols - 1] #x是所有的行 , 去掉最后一列 y = data.iloc[:,cols - 1:cols] # y就是最后一列数据 #初始化数据 x = np.matrix(x.values) #转化成 矩阵形式 y = np.matrix(y) theta = np.matrix(np.array([0,0])) #theta就是一个(1,2)矩阵 costFunction = computeCost(x,y,theta) print(costFunction) # # 批量梯度下降 # def gradientDescent(x,y,theta,alpha,iters): #alpha = 学习速率 ,iters = 迭代次数 temp = np.matrix(np.zeros(theta.shape)) print(temp) parameters = int(theta.ravel().shape[1]) # ravel就是合并矩阵 print(parameters) 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]) #multiply 对应元素乘法 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 gradientDescent(x,y,theta,alpha,iters) g,cost = gradientDescent(x,y,theta,alpha,iters) print(cost) print(computeCost(x,y,g)) #绘制拟合曲线 x = np.linspace(data.population.min(),data.population.max(),100) #llinspace(start,stop,num) num就是生成的样本数 f = g[0,0] + (g[0,1] * x) #g[0,0] 代表theta0 , g[0,1] 代表theta1 fig,ax = plt.subplots() ax.plot(x,f,'r',label = 'prediction') ax.scatter(data.population,data.profit,label = 'training data') ax.legend(loc=2) ax.set_xlabel('population') ax.set_ylabel('profit') plt.show()