机器学习之梯度下降法

前言

  从linux camera驱动, 到qcom平台 camera图像效果,再到opencv图像处理,终于进入本篇的机器学习的开始。
    前路漫漫,吾只愿风雨兼程。

简介

  本篇开始是学习机器学习的第一篇,本章主要是使用opencv,用c语言实现机器学习之一元线性回归、梯度下降法。
关于这部分的原理,可以参考:
        1、 http://studentdeng.github.io/blog/2014/07/28/machine-learning-tutorial/
        2、 https://www.coursera.org/learn/machine-learning/home/info


具体实现

大致流程

  首先创建了一个400x400的空白图片,在图片上,随机初始化了8个坐标点。这些坐标点的x和y坐标分别就是代替对应的数据集(比如x轴坐标代表
房屋面积,y坐标表示房屋价格)。
  接着利用公式:
     
       
       
       
来连续迭代拟合出更加优秀的结果参数,并在之前的空白图片上不断更新出来。

实现代码

#include <opencv2/core/core.hpp>                                                                                                     
#include <opencv2/highgui/highgui.hpp>
#include <math.h>
#include <string.h>
#include <opencv/cv.h>
#include <stdio.h>
#include "opencv2/photo/photo.hpp"
#include <unistd.h> 
 
using namespace cv;
 
#define specimenNum  8
#define cir 5
 
char inputWindow[20] = "input";
Mat mat1;
int normalWidth=400, normalHeight=400;
int specimenAddr[specimenNum][2] = {{50, 150}, {150, 50}, {220, 220},{150, 150}, {300,300}, {70, 120}, {120, 70}, {160, 160}};
int funcNum[2] = {0, 0};
double k0=1, k1=10, j_tmp= 0;
bool step_flag = true;
 
/*******************************************
*********样本点初始化显示*******************
*******************************************/
void specimenInit(void){
	int i;
 
	mat1 = Mat(normalWidth, normalHeight, CV_8UC3, cv::Scalar(0, 0, 0));
	for(i=0; i<specimenNum; i++){
		Point center = Point(specimenAddr[i][0], specimenAddr[i][1]);
		circle(mat1, center, cir, Scalar(128,128,255), -1);		
	}
	imshow(inputWindow, mat1);
}
 
/******************************************
*********画出当前学习曲线******************
*******************************************/
void drawmachinaline(void){
	double i, j, m, n;
	Mat matTmp;
 
	mat1.copyTo(matTmp);
	for(i=0; i< normalWidth; i++){
		n = (double)i;
		m = k0 + k1 * n;
		if(m <= normalHeight){
			Point center = Point((int)n, (int)m);
			circle(matTmp, center, 2, Scalar(255, 255, 255), -1);
		}
	}
	imshow(inputWindow, matTmp);
	waitKey(10);
}
 
/*******************************************
*********键值处理,按下q则退出**************
*******************************************/
void mykey(void){
	while(1){
		char c;
		c = waitKey(0);
		if(c == 'q'){
			break;	
		}
	}
}
 
void computeCost(void){
	double j, tmp;
	int i;
 
	for(i=0; i<specimenNum; i++){
		tmp = tmp + (k0 + k1 * specimenAddr[i][0] - specimenAddr[i][1]) * \
		          (k0 + k1 * specimenAddr[i][0] - specimenAddr[i][1]);
	}
	j = tmp / specimenNum / 2;
 
	if(j < j_tmp){
		if(j_tmp - j  < 0.02){
			step_flag = false;		
		}
		j_tmp = j;	
	}else{
		if(j_tmp == 0){
			j_tmp = j;
		}else{
			step_flag = false;	
		}
	}
	drawmachinaline();
	printf("j:%lf\n", j);
}
 
/*******************************************
*********计算最佳函数参数*******************
*******************************************/
void getfuncNum(void){
	double tmp0, tmp1, temp0, temp1;
	int i;
	bool flag = false;
	double aa = 100000;
 
	while(step_flag){
		temp0 = 0;
		temp1 = 0;
 
		for(i=0; i<specimenNum; i++){
			temp0 = temp0 + k0 + k1 * specimenAddr[i][0] - specimenAddr[i][1];
		}
		temp0 = temp0 / specimenNum / aa;
		tmp0 = k0 - temp0;
 
		for(i=0; i<specimenNum; i++){
			temp1 = temp1 + (k0 + k1 * specimenAddr[i][0] - specimenAddr[i][1]) * specimenAddr[i][0];
		}
		temp1 = temp1 / specimenNum / aa;
		tmp1 = k1 - temp1;
		if(k1 == tmp1){
			break;	
		}
		k0 = tmp0;
		k1 = tmp1;
		computeCost();
		sleep(1);
	}
	printf("k0:%lf, k1:%lf\n", k0, k1);
}
 
int main(int argc, char *argv[]){
 
	specimenInit();
	getfuncNum();
	mykey();
 
	return 0;
}

代码讲解

  1、首先是进行对应初始化操作。创建了一个空白图片,然后将代表数据集的样本点,画在图像对应位置。
void specimenInit(void){
	int i;
 
	mat1 = Mat(normalWidth, normalHeight, CV_8UC3, cv::Scalar(0, 0, 0));
	for(i=0; i<specimenNum; i++){
		Point center = Point(specimenAddr[i][0], specimenAddr[i][1]);
		circle(mat1, center, cir, Scalar(128,128,255), -1);		
	}
	imshow(inputWindow, mat1);
}
  2、根据之前提到的公式,进行迭代更新参数。每次更新后的参数,放入k0和k1中,接着使用computeCost,计算代价函数值和将当前迭代的参数效果。
void getfuncNum(void){
	double tmp0, tmp1, temp0, temp1;
	int i;
	bool flag = false;
	double aa = 100000;
 
	while(step_flag){
		temp0 = 0;
		temp1 = 0;
 
		for(i=0; i<specimenNum; i++){
			temp0 = temp0 + k0 + k1 * specimenAddr[i][0] - specimenAddr[i][1];
		}
		temp0 = temp0 / specimenNum / aa;
		tmp0 = k0 - temp0;
 
		for(i=0; i<specimenNum; i++){
			temp1 = temp1 + (k0 + k1 * specimenAddr[i][0] - specimenAddr[i][1]) * specimenAddr[i][0];
		}
		temp1 = temp1 / specimenNum / aa;
		tmp1 = k1 - temp1;
		if(k1 == tmp1){
			break;	
		}
		k0 = tmp0;
		k1 = tmp1;
		computeCost();
		sleep(1);
	}
	printf("k0:%lf, k1:%lf\n", k0, k1);
}
  3、将当前迭代参数更新在图像上(k0,k1表示当前迭代参数),然后将图像显示出来。
void drawmachinaline(void){
	double i, j, m, n;
	Mat matTmp;
 
	mat1.copyTo(matTmp);
	for(i=0; i< normalWidth; i++){
		n = (double)i;
		m = k0 + k1 * n;
		if(m <= normalHeight){
			Point center = Point((int)n, (int)m);
			circle(matTmp, center, 2, Scalar(255, 255, 255), -1);
		}
	}
	imshow(inputWindow, matTmp);
	waitKey(10);
}

效果演示

  迭代的效果演示如下:
  
  
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
线性回归是机器学习中的一种基本算法,梯度下降法是线性回归中常用的优化算法。下面是线性回归梯度下降法实现步骤: 1.读取数据集,包括自变量和因变量。 2.初始化相关参数,包括学习率、迭代次数、截距和斜率等。 3.定义计算代价函数,常用的代价函数是均方误差(MSE)。 4.梯度下降,通过不断迭代更新截距和斜率,使得代价函数最小化。 5.执行梯度下降算法,得到最优的截距和斜率。 下面是Python代码实现: ```python import numpy as np # 读取数据集 def load_data(file_path): data = np.loadtxt(file_path, delimiter=',') x_data = data[:, :-1] y_data = data[:, -1] return x_data, y_data # 初始化相关参数 def init_params(): b = 0 k = 0 learning_rate = 0.01 num_iterations = 1000 return b, k, learning_rate, num_iterations # 定义计算代价函数 def compute_cost(b, k, x_data, y_data): total_error = 0 for i in range(len(x_data)): total_error += (y_data[i] - (k * x_data[i] + b)) ** 2 cost = total_error / float(len(x_data)) return cost # 梯度下降 def gradient_descent(b, k, x_data, y_data, learning_rate, num_iterations): m = float(len(x_data)) for i in range(num_iterations): b_gradient = 0 k_gradient = 0 for j in range(len(x_data)): b_gradient += (1/m) * ((k * x_data[j] + b) - y_data[j]) k_gradient += (1/m) * ((k * x_data[j] + b) - y_data[j]) * x_data[j] b = b - (learning_rate * b_gradient) k = k - (learning_rate * k_gradient) return b, k # 执行梯度下降算法 def linear_regression(file_path): x_data, y_data = load_data(file_path) b, k, learning_rate, num_iterations = init_params() print("Starting parameters: b = {0}, k = {1}, cost = {2}".format(b, k, compute_cost(b, k, x_data, y_data))) b, k = gradient_descent(b, k, x_data, y_data, learning_rate, num_iterations) print("After {0} iterations: b = {1}, k = {2}, cost = {3}".format(num_iterations, b, k, compute_cost(b, k, x_data, y_data))) # 调用线性回归函数 linear_regression('data.csv') ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值