吴恩达机器学习课后作业单变量回归
前言
这是我今年考上深圳大学研究生以来第一次写博客,今后研究的方向主要也是机器学习,所以很想用博客写下日常所学的知识。首先申明数据和代码(python)用的别人的不是原创,就是学习笔记
一、数据介绍
数据集包含两列:第一列是城市人口数量,第二列是该城市小吃店利润
数据地址链接:https://pan.baidu.com/s/1gIprExuddNljRrYF_m34Mg
提取码:qn9o
二、实验步骤
1.读入数据(我用的是anacode下面的Jypyter Notebook)
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'])
2.数据加工处理
data.insert(0, 'Ones', 1)#插入一列
# 初始化X和y
cols = data.shape[1]
X = data.iloc[:,:-1]#X是data里的除最后列
y = data.iloc[:,cols-1:cols]#y是data最后一列
X = np.matrix(X.values)
y = np.matrix(y.values)
theta = np.matrix(np.array([0,0]))
3.构造代价函数和梯度下降函数
#代价函数
def computeCost(X, y, theta):
inner = np.power(((X * theta.T) - y), 2)
return np.sum(inner) / (2 * len(X))
#梯度下降函数
def gradientDescent(X, y, theta, alpha, iters):
temp = np.matrix(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 = 1500
4.进行实验的最后一步
g, cost = gradientDescent(X, y, theta, alpha, iters)
#g就是最后求得的参数矩阵
x = np.linspace(data.Population.min(), data.Population.max(), 100)
f = g[0, 0] + (g[0, 1] * x)
fig, ax = plt.subplots(figsize=(12,8))
ax.plot(x, f, 'r', label='Prediction')
ax.scatter(data.Population, data.Profit, label='Traning Data')
ax.legend(loc=2)
ax.set_xlabel('Population')
ax.set_ylabel('Profit')
ax.set_title('Predicted Profit vs. Population Size')
plt.show()
#原始数据以及拟合的直线
拟合了