博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Coursera机器学习编程作业Python实现(Andrew Ng)—— 1.2 Linear regression with multiple variables...
阅读量:6948 次
发布时间:2019-06-27

本文共 1703 字,大约阅读时间需要 5 分钟。

1.2 Linear regression with multiple variables

import numpy as npimport pandas as pdimport matplotlib.pyplot as plt

数据读取

data2 = pd.read_csv('ex1data2.txt', sep=',', header=None, names=['size', 'bedrooms', 'price'])

数据预处理

data2.iloc[:,:-1] = (data2.iloc[:,:-1] - data2.iloc[:,:-1].mean())/data2.iloc[:,:-1].std()data2.insert(0, 'ones', 1)X = data2.values[:,:-1]y = data2.values[:,-1]y = y.reshape((-1,1))

定义假设函数

def h(X, theta):    return np.dot(X, theta)

定义代价函数

def computeCost(X, theta, y):    return 0.5 * np.mean(np.square(h(X, theta) - y))

定义梯度下降函数

def gradientDescent(X, theta, y, iterations, alpha):    Cost = []    Cost.append(computeCost(X, theta, y))    grad = np.zeros(len(theta))    for _ in range(iterations):        for j in range(len(theta)):            grad[j] = np.mean((h(X, theta) - y) * (X[:,j].reshape([len(X), 1])))        for k in range(len(theta)):            theta[k] = theta[k] - alpha * grad[k]        Cost.append(computeCost(X, theta, y))    return theta, Cost

参数初始化

iterations = 200lr = [1, 0.3, 0.1, 0.03, 0.01]
_,ax = plt.subplots(figsize=(10,6))for l in lr:    theta = np.zeros((X.shape[1], 1))    _, Cost = gradientDescent(X, theta, y, iterations, l)    ax.plot(Cost, label='lr=%.2f'%(l))ax.set_xlabel('iterations')ax.set_ylabel('Cost')ax.legend()plt.show()
theta = np.zeros((X.shape[1], 1))theta_result, Cost_result = gradientDescent(X, theta, y, iterations, 0.3)theta_result
array([[340412.65957447],       [110631.05027879],       [ -6649.47427076]])

正规方程

theta_ref = np.linalg.inv(X.T @ X) @ X.T @ y theta_re
array([[340412.65957447],       [110631.05027885],       [ -6649.47427082]]) 梯度下降和正规方程求出来的解非常接近。

转载于:https://www.cnblogs.com/shouzhenghouchuqi/p/10586029.html

你可能感兴趣的文章
记一次服务器被恶意攻击的情况
查看>>
一个例子:HelloWorld
查看>>
排序算法及分析(插入、希尔、选择、冒泡)
查看>>
[转]Redmine 配置163邮箱
查看>>
C#--属性
查看>>
文本自动分割算法
查看>>
http://blog.csdn.net/i_bruce/article/details/39555417
查看>>
shell 调试手段总结
查看>>
CSharpGL(17)重构CSharpGL
查看>>
AVFoundation播放视频时显示字幕,切换音轨
查看>>
Spark笔记:复杂RDD的API的理解(上)
查看>>
java单例设计模式
查看>>
Druid.io索引过程分析——时间窗,列存储,LSM树,充分利用内存,concise压缩
查看>>
【emWin】例程十六:窗口管理器
查看>>
HTTP 403详解
查看>>
WPF实现在电脑重启或关机时执行某些逻辑
查看>>
PCA(主成分分析)的简单理解
查看>>
[Asp.net web api]缓存
查看>>
结构化、半结构化和非结构化数据
查看>>
thinkPHP 快速上手
查看>>