最近在学习吴恩达老师的机器学习,做的课后作业1供分享参考
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
alpha = 0.01#学习率
iters = 1000#迭代次数设置为1000
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=(10,8))
#求损失函数
def computeCost(X, y, thera):
inner = np.power(((X*thera.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)) *