参考吴恩达<机器学习>, 进行 Octave, Python(Numpy), C++(Eigen) 的原理实现, 同时用 scikit-learn, TensorFlow, dlib 进行生产环境实现.

1. 原理

cost function

gradient descent

2. 原理实现

octave

cost function

function J = costFunction(X, Y, theta)
m = size(X, );
predictions = X * theta;
sqrErrors = (predictions - Y) .^ ;
J = / ( * m) * sum(sqrErrors);

Linear regression using gradient descent

function [final_theta, Js] = gradientDescent(X, Y, init_theta, learning_rate=0.01, max_times=)
convergence = ;
m = size(X, );
tmp_theta = init_theta;
Js = zeros(m, 1); for i=:max_times,
tmp = learning_rate / m * ((X * tmp_theta - Y)' * X)';
tmp_theta -= tmp;
Js(i) = costFunction(X, Y, tmp_theta);
end; final_theta = tmp_theta;

python

# -*- coding:utf8 -*-
import numpy as np
import matplotlib.pyplot as plt def cost_function(input_X, _y, theta):
"""
cost function
:param input_X: np.matrix input X
:param _y: np.array y
:param theta: np.matrix theta
:return: float
"""
rows, cols = input_X.shape
predictions = input_X * theta
sqrErrors = np.array(predictions - _y) ** 2
J = 1.0 / (2 * rows) * sqrErrors.sum() return J def gradient_descent(input_X, _y, theta, learning_rate=0.1,
iterate_times=3000):
"""
gradient descent
:param input_X: np.matrix input X
:param _y: np.array y
:param theta: np.matrix theta
:param learning_rate: float learning rate
:param iterate_times: int max iteration times
:return: tuple
"""
convergence = 0
rows, cols = input_X.shape
Js = [] for i in range(iterate_times):
errors = input_X * theta - _y
delta = 1.0 / rows * (errors.transpose() * input_X).transpose()
theta -= learning_rate * delta
Js.append(cost_function(input_X, _y, theta)) return theta, Js def generate_data():
"""
generate training data y = 2*x^2 + 4*x + 2
"""
x = np.linspace(0, 2, 50)
X = np.matrix([np.ones(50), x, x**2]).T
y = 2 * X[:, 0] - 4 * X[:, 1] + 2 * X[:, 2] + np.mat(np.random.randn(50)).T / 25
np.savetxt('linear_regression_using_gradient_descent.csv',
np.column_stack((X, y)), delimiter=',') def test():
"""
main
:return: None
"""
m = np.loadtxt('linear_regression_using_gradient_descent.csv', delimiter=',')
input_X, y = np.asmatrix(m[:, :-1]), np.asmatrix(m[:, -1]).T
# theta 的初始值必须是 float
theta = np.matrix([[0.0], [0.0], [0.0]])
final_theta, Js = gradient_descent(input_X, y, theta) t1, t2, t3 = np.array(final_theta).reshape(-1,).tolist()
print('对测试数据 y = 2 - 4x + 2x^2 求得的参数为: %.3f, %.3f, %.3f\n' % (t1, t2, t3)) plt.figure('theta')
predictions = np.array(input_X * final_theta).reshape(-1,).tolist()
x1 = np.array(input_X[:, 1]).reshape(-1,).tolist()
y1 = np.array(y).reshape(-1,).tolist()
plt.plot(x1, y1, '*')
plt.plot(x1, predictions)
plt.xlabel('x')
plt.ylabel('y')
plt.title('y = 2 - 4x + 2x^2') plt.figure('cost')
x2 = range(1, len(Js) + 1)
y2 = Js
plt.plot(x2, y2)
plt.xlabel('iterate times')
plt.ylabel('value')
plt.title('cost function') plt.show() if __name__ == '__main__':
test()

Python 中需要注意的是, numpy.array, numpy.matrix 和 list 等进行计算时, 有时会进行默认类型转换, 默认类型转换的结果, 往往不是期望的情况.

theta 的初始值必须是 float, 因为如果是 int, 则在更新 theta 时会报错.

测试数据:

Cost function:

c++

#include <iostream>
#include <vector>
#include <Eigen/Dense> using namespace Eigen;
using namespace std; double cost_function(MatrixXd &input_X, MatrixXd &_y, MatrixXd &theta) {
double rows = input_X.rows();
MatrixXd predictions = input_X * theta;
ArrayXd sqrErrors = (predictions - _y).array().square();
double J = 1.0 / ( * rows) * sqrErrors.sum(); return J;
} class Gradient_descent {
public:
Gradient_descent(MatrixXd &x, MatrixXd &y, MatrixXd &t,
double r=0.1, int m=): input_X(x), _y(y), theta(t),
learning_rate(r), iterate_times(m){}
MatrixXd theta;
vector<double> Js;
void run();
private:
MatrixXd input_X;
MatrixXd _y;
double rows;
double learning_rate;
int iterate_times;
}; void Gradient_descent::run() {
double rows = input_X.rows();
for(int i=; i < iterate_times; ++i) {
MatrixXd errors = input_X * theta - _y;
MatrixXd delta = 1.0 / rows * (errors.transpose() * input_X).transpose();
theta -= learning_rate * delta;
double J = cost_function(input_X, _y, theta);
Js.push_back(J);
}
} void generate_data(MatrixXd &input_X, MatrixXd &y) {
ArrayXd v = ArrayXd::LinSpaced(, , );
input_X.col() = VectorXd::Constant(, , );
input_X.col() = v.matrix();
input_X.col() = v.square().matrix();
y.col() = * input_X.col() - * input_X.col() + * input_X.col();
y.col() += VectorXd::Random() / ;
} int main() {
MatrixXd input_X(, ), y(, );
MatrixXd theta = MatrixXd::Zero(, );
generate_data(input_X, y);
Gradient_descent gd(input_X, y, theta);
gd.run();
cout << gd.theta << endl;
}

3. 生产环境

Python (Scikit-learn)

todo

Python (TensorFlow)

todo

C++ (dlib)

todo

Linear Regression Using Gradient Descent 代码实现的更多相关文章

  1. 线性回归、梯度下降(Linear Regression、Gradient Descent)

    转载请注明出自BYRans博客:http://www.cnblogs.com/BYRans/ 实例 首先举个例子,假设我们有一个二手房交易记录的数据集,已知房屋面积.卧室数量和房屋的交易价格,如下表: ...

  2. 斯坦福机器学习视频笔记 Week1 Linear Regression and Gradient Descent

    最近开始学习Coursera上的斯坦福机器学习视频,我是刚刚接触机器学习,对此比较感兴趣:准备将我的学习笔记写下来, 作为我每天学习的签到吧,也希望和各位朋友交流学习. 这一系列的博客,我会不定期的更 ...

  3. 斯坦福机器学习视频笔记 Week1 线性回归和梯度下降 Linear Regression and Gradient Descent

    最近开始学习Coursera上的斯坦福机器学习视频,我是刚刚接触机器学习,对此比较感兴趣:准备将我的学习笔记写下来, 作为我每天学习的签到吧,也希望和各位朋友交流学习. 这一系列的博客,我会不定期的更 ...

  4. Linear Regression and Gradient Descent

    随着所学算法的增多,加之使用次数的增多,不时对之前所学的算法有新的理解.这篇博文是在2018年4月17日再次编辑,将之前的3篇博文合并为一篇. 1.Problem and Loss Function ...

  5. Linear Regression and Gradient Descent (English version)

    1.Problem and Loss Function   Linear Regression is a Supervised Learning Algorithm with input matrix ...

  6. Logistic Regression and Gradient Descent

    Logistic Regression and Gradient Descent Logistic regression is an excellent tool to know for classi ...

  7. Logistic Regression Using Gradient Descent -- Binary Classification 代码实现

    1. 原理 Cost function Theta 2. Python # -*- coding:utf8 -*- import numpy as np import matplotlib.pyplo ...

  8. flink 批量梯度下降算法线性回归参数求解(Linear Regression with BGD(batch gradient descent) )

    1.线性回归 假设线性函数如下: 假设我们有10个样本x1,y1),(x2,y2).....(x10,y10),求解目标就是根据多个样本求解theta0和theta1的最优值. 什么样的θ最好的呢?最 ...

  9. machine learning (7)---normal equation相对于gradient descent而言求解linear regression问题的另一种方式

    Normal equation: 一种用来linear regression问题的求解Θ的方法,另一种可以是gradient descent 仅适用于linear regression问题的求解,对其 ...

随机推荐

  1. sencha touch 2.2 为list PullRefresh插件添加refreshFn方法

    sencha touch 2.2 list PullRefresh插件没有refreshFn方法 但是我们又需要他,所以需要自行扩展 代码如下 /** * 重写下拉刷新插件,以支持refreshFn事 ...

  2. [原]git的使用(四)---撤销修改

    8.撤销修改 $ cat readme.txt Git is a distributed version control system. Git is free software distribute ...

  3. 升级后重启造成fsck.ext3: Unable to resolve UUID

    这篇文章帮了我的大忙了:转载自:http://wilber82.blog.51cto.com/1124820/724472 今天在做服务器补丁部署,有一台ESX4.1的服务器在升级后重启过程中挂了,通 ...

  4. ELK系列二:Elasticsearch的架构原理和配置优化

    1.Elasticsearch的数据组织架构 1.1.Elasticsearch结构概念 集群(cluster):拥有相同cluster-name的elasticsearch结点的集合(每个结点其实就 ...

  5. 【CF802L】Send the Fool Further! (hard) 高斯消元

    [CF802L]Send the Fool Further! (hard) 题意:给你一棵n个节点的树,每条边有长度,从1号点开始,每次随机选择一个相邻的点走,走到一个叶子时就停止,问期望走的总路程. ...

  6. SAP全球企业官孙小群的生活智慧

    转自:http://www.programmer.com.cn/15373/ 一下为程序员杂志对孙小群(Xiaoqun Clever)的采访. 最早接触计算机是在高中,那时发现通过一个小小的Basic ...

  7. Xcode - Xcodeproject详解

    前言 在 iOS 开发过程中,我们经常会在 Xcode 里面做一些配置,比如添加系统库.第三方库,修改证书配置文件,修改编译属性等等. 在这个过程里面,一般大家仅仅只是根据经验来配置这些,并没有比较清 ...

  8. UVM phase的用法研究【zz】

    原文地址:http://bbs.eetop.cn/viewthread.php?tid=383872&extra=&authorid=828160&page=1 我相信很多朋友 ...

  9. pcl学习笔记(二):点云类型

    不同的点云类型 前面所说的,pcl::PointCloud包含一个域,它作为点的容器,这个域是PointT类型的,这个域是PointT类型的是pcl::PointCloud类的模板参数,定义了点云的存 ...

  10. 一次使用Python连接数据库生成二维码并安装为windows服务的工作任务

    最近有一个需求,在现有生产系统上的人员库中增加一个此人员关键信息的二维码,支持文字版和跳转版两种方式,与报表工具关联,可打印.以windows服务方式,定时检查,只要发现某人员没有此二维码信息,就生成 ...