根据给出的数据,对这些数据进行线性回归拟合,从而达到一些预测的目的。
一.单变量线性回归
假设你是一家连锁餐饮店的老板,你想要扩展你的分店数目,但是不知道应该在哪里开设,你将根据给出的数据(包含人口数和利润数),来进行预测,从而决定在哪里开设。
用到的数学公式如下:
实现代码如下:
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'])
#print(data.head())
#print(data.describe())
data.plot(kind='scatter', x='Population', y='Profit', figsize=(9,5))
#plt.show()
def computeCost(X, y, theta):
inner = np.power(((X * theta.T) - y), 2)
return np.sum(inner) / (2 * len(X))
data.insert(0, 'Ones', 1)#在最前列插入名为'Ones',值为1的列
#print(data.head())
#set X (trainning data) and y (target variable)
cols = data.shape[1]
X = data.iloc[:,0:cols-1]#x是所有行,去掉最后一列
y = data.iloc[:,cols-1:cols]#y是所有行,最后一列
#print(x.head())
#print(y.head())
X = np.matrix(X.values)
y = np.matrix(y.values)
theta = np.matrix(np.array([0,0]))
#print(theta)
#print(X.shape)
#print(theta.shape)
#print(y.shape)
a = computeCost(X, y, theta)
print(a)
#批量梯度下降
def gradientDescent(X, y, theta, alpha, iters):
temp = np.matrix(np.zeros(theta.shape))#初始化一个(1,2)的0矩阵
parameters = int(theta.ravel().shape[1])#参数theta的数量
cost = np.zeros(iters)#初始化一个array,包含每次iters的cost
for i in range(iters):
error = (X * theta.T) - y
for j in range(parameters):
term = np.multiply(error, X[:,j])
temp[0,j] &