参考吴恩达<机器学习>, 进行 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. QT开发之旅三串口设备调试工具

    这里首先说明一下,这个为什么叫串口设备调试工具而不是串口调试工具,是因为这个工具比网络上的串口调试工具多出了一些真实需要的用来调试设备的功能,首先一点就是大部分的串口调试工具收到数据都是立即返回,这样 ...

  2. vue案例 - vue-awesome-swiper实现h5滑动翻页效果

    说到h5的翻页,很定第一时间想到的是swiper.但是我当时想到的却是,vue里边怎么用swiper?! 中国有句古话叫:天塌下来有个高的顶着. 在前端圈里,总有前仆后继的仁人志士相继挥洒着热汗(这里 ...

  3. CSS - 移动端 常见小bug整理与解决方法总结【更新中】

    常见问题总结与整理系列~ 1. border一像素在手机上看着有点粗的问题: 原理是因为:1px在手机上是使用2dp进行渲染的.换成 border: 0.5像素?是不行的! 解决方法: 把border ...

  4. java(6) ArrayList源码

    系统环境: JDK 1.7 成员变量 //默认的初始化数组大小 private static final int DEFAULT_CAPACITY = 10; //空的对象数组 private sta ...

  5. LeetCode 45 Jump Game II(按照数组进行移动)

    题目链接:https://leetcode.com/problems/jump-game-ii/?tab=Description   给定一个数组,数组中的数值表示在当前位置能够向前跳动的最大距离. ...

  6. openstack nova 用户管理

    用户管理      创建管理员用户      用法:      nova-manage user admin name [access] [secret]      其中access 和secret可 ...

  7. 画一条0.5px的边

    1.scale方法 { height: 1px; transform: scaleY(0.5); transform-origin: 50% 100%; // 要指定origin值, 要不然会模糊 c ...

  8. CentOS 6.8下Apache绑定多个域名的方法

    如何通过设置Apache的http.conf文件,进行多个域名的绑定(假设我们要绑定的域名是discuz11.com和discuz22.com,独立IP为25.25.25.25). 域名/IP地址 域 ...

  9. srilm使用杂记

    训练n-gram语言模型 ngram-count -text train.txt -order -lm model -kndiscount -interpolate -gt3min -gt4min 计 ...

  10. 【巷子】---Mock---基本使用

    一.mock解决的问题 开发时,后端还没完成数据输出,前端只好写静态模拟数据.数据太长了,将数据写在js文件里,完成后挨个改url.某些逻辑复杂的代码,加入或去除模拟数据时得小心翼翼.想要尽可能还原真 ...