机器学习(二)监督学习:线性回归

一、单变量的线性回归

1、举例:预测房价

m表示训练样本个数,x表示特征量,y表示输出变量
输入房子面积---->函数h---->预测的房价
h?(?) = ?0 + ?1?

2、如何选择合适的参数?0 , ?1

2.1 目标:

最小化下面式子,即求函数最低点的?0 , ?1值

在这里插入图片描述
=函数 ?(?0, ?1)(平方误差代价函数)

2.2采用的算法:梯度下降法

在这里插入图片描述
(1) 梯度:在微积分里,对多元函数的参数求∂偏导数,把求得的各个参数的偏导数以向量的形式写出来,就是梯度,比如函数f(x,y), 分别对x,y求偏导数,求得的梯度向量就是(∂f/∂x, ∂f/∂y)T,简称grad f(x,y)或者▽f(x,y)。
(2)算法过程:
1)确定代价函数的梯度,表达式为:
在这里插入图片描述
2) 用学习速率乘以代价函数的梯度,得到当前位置下降的距离,得到表达式:(学习速率相当于下山途中当前这一步所在位置沿着最陡峭最易下山的位置走的那一步的长度。)。
在这里插入图片描述
3)更新所有的θ,对于θi,其更新表达式如下:
在这里插入图片描述
注:
若学习速率太大,梯度下降法可能会越过最低点;学习速率太小,就需要很多步才能到达最低点
3)总结:
在梯度下降法中,当我们接近局部最低点时,梯度下降法会自动采取更小的 幅度,这是因为当我们接近局部最低点时,很显然在局部最低时导数等于零,所以当我们接近局部最低时,导数值会自动变得越来越小,所以梯度下降将自动采取较小的幅度,这就是梯度下降的做法。

2.3 梯度下降的线性回归:

在这里插入图片描述

3、吴恩达《机器学习》作业:(ex1)

题目:假如你是一家餐馆的CEO,在各个不同的城市有分店,现在考虑在某个城市新增一家分店,这里有不同城市的利润额和人口数据。这些数据帮助你决定在哪个城市扩充分店。

3.1 导入库

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

3.2 绘制样本图像

print('Plotting Data...')
#delimiter是分隔符
data = np.loadtxt('ex1data1.txt', delimiter=',', usecols=(0, 1))
X = data[:, 0]#取第一列人口数作为横坐标
y = data[:, 1]#取第二列利润作为纵坐标
m = y.size    #m=训练样本的个数
X = X.reshape((m, 1))#
y = y.reshape((m, 1))
plt.scatter(X,y,alpha=0.6)#alpha代表透明度
plt.xlabel('Population of city in 10,000s')
plt.ylabel('Profit in $10,000s')
plt.show()

在这里插入图片描述

3.3 函数

(1)代价函数

在这里插入图片描述

def computeCost(X,y,theta):
    m=y.size
    cost=0
    cost=sum((np.dot(X,theta)-y)**2)/(2*m)
    return cost
(2)梯度下降函数

在这里插入图片描述

def gradientDescent(X,y,theta,alpha,iterations):
    m=y.size
    J_history=np.zeros((iterations,1))#一列全为0的数列
    for i in range(iterations):
        XT=X.T
        theta=theta-alpha/m*sum(np.dot(XT,np.dot(X,theta)-y))
        J_history[i]=computeCost(X,y,theta)
        return theta,J_history

3.4 计算参数值theta

print('Running Gradient Descent...')

X = np.c_[np.ones(m), X]#新增全为1的列
theta = np.zeros((2, 1))#初始化theta为2行1列,值全为0

iterations = 1500 #迭代次数=1500
alpha = 0.01      #学习率=0.01
print('Initial cost : ' + str(computeCost(X, y, theta)) + ' (This value should be about 32.07)')#调用代价函数
theta, J_history = gradientDescent(X, y, theta, alpha, iterations)#调用梯度下降函数
print('Theta found by gradient descent: ' + str(theta.reshape(2)))
#绘制拟合直
plt.plot(X[:,1],np.dot(X,theta),'-')
plt.legend(['Linear regression','Training data'])
plt.show()

输出:

Running Gradient Descent...
Initial cost : [ 32.07273388] (This value should be about 32.07)
Theta found by gradient descent: [ 0.71167985  0.71167985]

在这里插入图片描述

3.5预测利润

#预测人口达到35000和70000时,可达到的利润额
predict1 = np.dot(np.array([1, 3.5]), theta)
print('For population = 35,000, we predict a profit of %f\n'%(predict1[0]*10000))
predict2 = np.dot(np.array([1, 7]), theta)
print('For population = 70,000, we predict a profit of %f\n'%(predict2[0]*10000))
input('Program paused. Press ENTER to continue')

3.6可视化J(theta0, theta1)

print('Visualizing J(theta0, theta1) ...')
theta0_vals = np.linspace(-10, 10, 100)#范围是-10到10,有100个数
theta1_vals = np.linspace(-1, 4, 100)

xs, ys = np.meshgrid(theta0_vals, theta1_vals)
J_vals = np.zeros(xs.shape)

for i in range(len(theta0_vals)):
    for j in range(len(theta1_vals)):
        t = np.array([theta0_vals[i], theta1_vals[j]]).reshape((2, 1))
        J_vals[i, j] = computeCost(X, y, t)

J_vals = J_vals.T
from mpl_toolkits.mplot3d import Axes3D

fig = plt.figure()
ax = Axes3D(fig)
ax.plot_surface(theta0_vals, theta1_vals, J_vals, rstride=1, cstride=1, cmap='rainbow')
plt.xlabel('theta_0')
plt.ylabel('theta_1')

# 画出等高线
plt.figure()
# 填充颜色,20是等高线分为几部分
plt.contourf(theta0_vals, theta1_vals, J_vals, 20, alpha=0.6, cmap=plt.cm.hot)
plt.contour(theta0_vals, theta1_vals, J_vals, colors='black')
plt.plot(theta[0], theta[1], 'r', marker='x', markerSize=10, LineWidth=2)  # 画点
plt.show()

图1:横纵坐标代表theta0、theta1

在这里插入图片描述
图二:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值