博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【matlab】stanford线性回归,logistic regression 实验
阅读量:6216 次
发布时间:2019-06-21

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

1、找到衡量误差的函数costFunction

2、拟合参数theta,使costFunction最小。用梯度下降,迭代n次,迭代更新theta,让costFunction减小

3、找到了合适的参数theta,进行预测

一、linear regression

computeCost:

for i=1:m    h = X(i,:) * theta;    J = J + (h - y(i))^2;endJ = J / (2*m);

梯度下降过程,拟合参数theta

for iter = 1:num_iters    sum = zeros(size(theta,1),1);    for j = 1:size(theta,1)        for i = 1:m            h = X(i,:) * theta;            sum(j) = sum(j) + (h - y(i))*X(i,j);        end        % theta(j) = theta(j) - alpha * sum / m;         %go wrong! simultaneously update theta    end        theta = theta - sum .* alpha ./ m;    % Save the cost J in every iteration        J_history(iter) = computeCostMulti(X, y, theta);end

 

二、Logistic Regression

costFunction

function [J, grad] = costFunctionReg(theta, X, y, lambda)%COSTFUNCTIONREG Compute cost and gradient for logistic regression with regularization%   J = COSTFUNCTIONREG(theta, X, y, lambda) computes the cost of using%   theta as the parameter for regularized logistic regression and the%   gradient of the cost w.r.t. to the parameters. % Initialize some useful valuesm = length(y); % number of training examples% You need to return the following variables correctly J = 0;grad = zeros(size(theta));for i=1:m    J = J - y(i)*log(h_fun(X(i,:), theta)) - (1-y(i))*log(1-h_fun(X(i,:),theta));endJ = J / m;reg = 0;for j=2:size(theta)    reg = reg + theta(j)^2;endreg = reg * lambda /(2*m);J = J + reg;for i=1:m    grad(1) = grad(1) + (h_fun(X(i,:),theta) - y(i))*X(i,1);endgrad(1) = grad(1) / m;for j=2:size(theta)    for i=1:m        grad(j) = grad(j) + (h_fun(X(i,:),theta) - y(i)) * X(i,j) + lambda*theta(j)/m;    end    grad(j) = grad(j) / m;endend

参数拟合

% Initialize fitting parametersinitial_theta = zeros(size(X, 2), 1);% Set regularization parameter lambda to 1 (you should vary this)lambda = 0;% Set Optionsoptions = optimset('GradObj', 'on', 'MaxIter', 400);% Optimize[theta, J, exit_flag] = ...    fminunc(@(t)(costFunctionReg(t, X, y, lambda)), initial_theta, options);

 

转载于:https://www.cnblogs.com/549294286/archive/2013/04/21/3033800.html

你可能感兴趣的文章
Linux搭建FTP
查看>>
MongoDB(四)之副本集
查看>>
SurfaceTexture,TextureView, SurfaceView和GLSurfaceView
查看>>
我的友情链接
查看>>
linux下 软链接与硬链接的区别
查看>>
Java报错系列——split
查看>>
ulimit -SHn 65535 含义
查看>>
关于升级lync或者安装lync的时候出现的中央管理服务器(cms)解决方法
查看>>
java HttpsURLConnection 实现https请求
查看>>
为什么你的员工执行力总是那么差?
查看>>
连接mysql数据库并写入
查看>>
Druid连接池 一个设置 removeAbandonedTimeout
查看>>
maven js css 压缩
查看>>
lucene4.7 锁机制(十)
查看>>
Spark与Flink:对比与分析
查看>>
执行mvn 命令出现的duplicated in the reactor问题
查看>>
3.1网络传输介质
查看>>
Ace - Responsive Admin Template
查看>>
redis数据存储系统原理
查看>>
tengine(nginx)安装,lua模块安装
查看>>