参考吴恩达<机器学习>, 进行 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. 【Spring Boot && Spring Cloud系列】在spring-data-Redis中如何使用切换库

    前言 Redis默认有16个库,默认连接的是index=0的那一个.这16个库直接是相互独立的. 一.在命令行中切换 select 1; 二.在Spring中如何切换 1.在RedisConnecti ...

  2. About LOCAL_PRIVATE_PLATFORM_APIS in Android.mk

    LOCAL_PRIVATE_PLATFORM_APIS := true设置后,会使用sdk的hide的api來编译 在Android.mk中如果有LOCAL_SDK_VERSION 这个编译配置,就会 ...

  3. Android O 获取APK文件权限 Demo案例

    1. 通过 aapt 工具查看 APK权限 C:\Users\zh>adb pull /system/priv-app/Settings . /system/priv-app/Settings/ ...

  4. JavaScript中Array

    一,针对于数组 const arr = ['a','b','c','d']; Array.indexOf  将“返回第一次出现给定元素的索引”; console.log(arr.indexOf('b' ...

  5. [原]linux下将网卡设置为混杂模式

    设置为混杂模式ifconfig eth2 promisc取消设置ifconfig eth2 -promisc ------------------------------------------ 下面 ...

  6. 【转】Windows socket基础

    转自:http://blog.csdn.net/ithzhang/article/details/8448655 Windows socket 基础 Windows socket是一套在Windows ...

  7. 如何玩facebook app上的H5游戏

    一.下载facebook app facebook链接 二.下载vpn 国内是访问不了的,必须vpn 因为vpn被封了厉害 我随便百度了个狸猫加速器,没付费,时断时续... 没有推荐的vpn,哪位大佬 ...

  8. 23种设计模式之迭代器模式(Iterator)

    迭代器模式是一种对象的行为型模式,提供了一种方法来访问聚合对象,而不用暴露这个对象的内部表示.迭代器模式支持以不同的方式遍历一个聚合对象,复杂的聚合可用多种方法来进行遍历:允许在同一个聚合上可以有多个 ...

  9. SOA架构商城二 框架搭建

    1.创建父工程 创建Maven工程pingyougou-parent,选择packaging类型为pom ,在pom.xml文件中添加锁定版本信息dependencyManagement与plugin ...

  10. STM32下多串口用法

    一个项目用到32下的多个串口,一般STM32C8T6型号拥有3个USART,串口的配置都很简单,但是要使用的话就得解决他们之间的矛盾, printf函数到底输出在哪一个串口中? 先看这函数: //重定 ...