吴恩达机器学习作业1---linear regression

linear regression

1. 代码演示
1.单变量的线性回归

本次作业在jupyter notebook上完成

首先,导入需要用到的类库

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d, Axes3D
from matplotlib import cm
import itertools

%matplotlib inline

加载文件ex1dara1.txt

datafile = 'data/ex1data1.txt'

#','为分隔符,抽出第0列和第1列,转置
cols = np.loadtxt(datafile,delimiter=',',usecols=(0,1),unpack=True) #Read in comma separated data

#X为第0列,y为第1列
X = np.transpose(np.array(cols[:-1]))
y = np.transpose(np.array(cols[-1:]))
m = y.size 

#在矩阵第一列前加上全为1的一列,目的是1到时候就是常数
X = np.insert(X,0,1,axis=1)

画图看看数据的分布

plt.figure(figsize=(10,6))
plt.plot(X[:,1],y[:,0],'rx',markersize=10)
plt.grid(True) #Always plot.grid true!
plt.ylabel('Profit')
plt.xlabel('Population')

在这里插入图片描述
定义两个函数,一个用于计算线性回归值,一个用于计算损失值
在这里插入图片描述

#线性假设函数
def h(theta,X): #Linear hypothesis function
    return np.dot(X,theta)

#利用公式计算损失值
def computeCost(mytheta,X,y): 
    return float((1/(2*m)) * np.dot((h(mytheta,X)-y).T,h(mytheta,X)-y))

定义迭代次数和学习率

iterations = 1500
alpha = 0.01
#测试,返回32.07
test_theta = np.zeros((X.shape[1],1))
print(computeCost(test_theta, X ,y))

定义梯度下降函数

#Actual gradient descent minimizing routine
def descendGradient(X, y, theta_start = np.zeros(2),alpha=0.01,iterations=1500):
    theta = theta_start
    #损失值的列表,len=1500
    costList = []
    #theta值列表,len=1500
    theta_history = []
    for i in range(iterations):
        tmp_theta = theta
        #计算损失值并记录
        costList.append(computeCost(theta,X,y))
        theta_history.append(list(theta[:,0]))
        #同时对每个特征进行更新
        for j in range(len(tmp_theta)):
            tmp_theta[j] = theta[j] - (alpha/m)*np.sum((h(initial_theta,X) - y)*np.array(X[:,j]).reshape(m,1))#梯度下降
        #theta更新
        theta = tmp_theta
    return theta, theta_history, costList

初始化参数,定义绘制cost函数迭代图像的函数

#初始化参数theta
initial_theta = np.zeros((X.shape[1],1))
theta, theta_history, costList = descendGradient(X,y,initial_th
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值