
声明:仅作为个人学习使用
吴恩达机器学习ex1:单变量线性回归
需要根据城市人口数量,预测开小吃店的利润
数据在ex1data1.txt里,第一列是城市人口数量,第二列是该城市小吃店利润。
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
datapath = './data/ex1data1.txt'
#读取数据
#read_csv:返回数据类型为Dataframe(二维标记数据结构)
#path:文件URL;
#header:指定行数作为列名,若文件中没有列名,默认为0,否则设置为None,如果明确设定header=0 就会替换掉原来存在列名;
#names:用于结果的列名列表,如果数据文件中没有列标题行,就需要执行header=None;
data = pd.read_csv(datapath,header = None,names=['population','profit'])
print(data)
#展示数据
data.plot(kind = 'scatter',x='population',y='profit',figsize = (12,8))
plt.show()
#计算代价函数
def computecost(X,y,theta):
inner = np.power(((X*theta.T)-y),2) #power(x,y):计算x的y次方;theta.T:np.matrix().T:返回矩阵转置
return np.sum(inner)/(2*len(X)) #sum():对矩阵中所有元素求和
#梯度下降函数
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
#我们要为加入一列x,用于更新theta0,然后我们将theta1初始化为0,学习率初始化为0.01,迭代次数为1500次
#h(x) = theta0 +theta1*x
data.insert(0, 'Ones', 1)
#初始化theta,X,y
#shape返回的是行数和列数
#shape[0]返回的是行数,有几行
#shape[1]返回的是列数,有几列
cols = data.shape[1] #返回列数
#iloc()通过行号获取行数据
X = data.iloc[:,:-1] #X是data里除去最后列,是一个矩阵
y = data.iloc[:,cols-1:cols] #y是data最后一列,是一个列向量
#values:对应的二维NumPy值数组
X = np.matrix(X.values)
y = np.matrix(y.values)
theta = np.matrix(np.array([0,0])) #numpy数组转换为numpy矩阵
print(X.shape, theta.shape, y.shape)
#初始化学习速率和迭代次数
alpha = 0.01
iters = 15000
h, cost = gradientDescent(X, y, theta, alpha, iters)
print(h)
#预测35000和70000城市规模的小吃摊利润
predict1 = [1,3.5]*h.T
print("predict1:",predict1)
predict2 = [1,7]*h.T
print("predict2:",predict2)
x = np.linspace(data.population.min(), data.population.max(), 100)
f = h[0, 0] + (h[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()
结果如图: