Octave绘图教程

plot(x,y,'rx','MarkerSize',10);
ylabel('Profit in $10,000s');
xlabel('Population of City in 10,000s');

首先解读第一句
x,y分别是要绘图的点数据,x,y分别是列向量
'rx’表示红色的x
‘MarkerSize’,10是每一个x的大小

下面给出官方文档的摘要加解析
plot(x, y, fmt)
1.如果x,y是标量,那么就画出一个点
2.如果x,y都是向量,那么就画出对应的点(x,y)
3.如果x是向量,y是矩阵,则首选是把y分成一个一个列yi,然后画出对应的(x,yi)
4.如果x是矩阵,y是向量,则首选是把x分成一个一个列xi,然后画出对应的(xi,y)
5.如果x,y都是矩阵,则两个矩阵要同型,画出一一对应的点

可以指定多个属性值,属性有"linestyle", “linewidth”, “color”, “marker”, “markersize”, “markeredgecolor”, “markerfacecolor”

这几个属性放在一个字符串里,如’-xr;nihao;’
第一个字符-是划线属性
第二个字符x是描点属性
第三个字符r是颜色属性
最后一个;displayname;是图例标签

linestyle:
	'-' 使用实线
	'--' 使用虚线
	':' 使用虚线,只不过更密集
	'-.' 使用点划线

 marker:(描点的符号)
 	                                                                                           
          '+'  
          'o'  
          '*'  
          '.'  
          'x'  
          's'  一个小正方形
          'd'  菱形
          '^'  正三角形
          'v'  倒三角形
          '>'  左三角形<|
          '<'  右三角形|>
          'p'  五角星
          'h'  六角星
color:
	                                                                                           
          'k'  blacK
          'r'  Red
          'g'  Green
          'b'  Blue
          'y'  Yellow
          'm'  Magenta
          'c'  Cyan
          'w'  White

xlabel是x轴的标签,这里是城市人口Population of City in 10,000s
ylabel是y轴的标签,这里是利润Profit in $10,000s

hold on; % keep previous plot visible
plot(X(:,2), X*theta, '-')
legend('Training data', 'Linear regression')
hold off % don't overlay any more plots on this figure

hold on 表示在上一张图上继续画
第二句表示根据点(X(:,2), Xtheta)画出直线
legend是画出图示标签,两个参数分别对应上面的参数,X(:,2)是训练数据, X
theta是线性回归

figure;
surf(theta0_vals, theta1_vals, J_vals)
xlabel('\theta_0'); ylabel('\theta_1');

surf是绘制3-D表面网格
使用阴影矩形绘制表面网格。顶点矩形[X,Y]中的一个通常是’meshgrid’的输出。在x-y平面的二维矩形区域上。 Z确定每个顶点平面上方的高度。

contour(theta0_vals, theta1_vals, J_vals, logspace(-2, 3, 20))
xlabel('\theta_0'); ylabel('\theta_1');
hold on;
plot(theta(1), theta(2), 'rx', 'MarkerSize', 10, 'LineWidth', 2);

contour是创建二维轮廓图。绘制矩阵z的轮廓图。

% Find Indices of Positive and Negative Examples 
pos = find(y==1); neg = find(y == 0);
% Plot Examples 
plot(X(pos, 1), X(pos, 2), 'k+','LineWidth', 2, 'MarkerSize', 7); 
plot(X(neg, 1), X(neg,2),'ko','MarkerFaceColor','y','MarkerSize', 7);

find是查找符合条件的索引。

pos=find(y==1)表示将y==1的数据索引存入pos向量中
neg=find(y==0)表示将y==0的数据索引存入neg向量中

算逻辑回归g(z)的时候发现e的指数不会。这里记录一下exp()函数,返回的是e^

function g = sigmoid(z)
g = zeros(size(z));
g = 1./(1+exp(-z));

写逻辑回归的costFunction时一直报错,才发现对hθ(x)的理解不够,这里实际算的是g(z),g函数已经写成sigmoid()函数,但是这个参数z其实是θ转置乘x,由于X变成了设计矩阵,所以z=X*θ。

function [J, grad] = costFunction(theta, X, y)
m = length(y); 
J = 0;
grad = zeros(size(theta));
value = 0;
for i=1:m
  value = value + y(i)*log(sigmoid(X(i,:)*theta)) + (1-y(i))*log(1-sigmoid(X(i,:)*theta));
endfor
J = (-1)/m*value;
theta_len = size(theta);
for j=1:theta_len
  value = 0;
  for i=1:m
    value = value + (sigmoid(X(i,:)*theta) - y(i))*X(i,j);
  endfor
  grad(j) = 1/m*value;
endfor
end

优化函数

options = optimset('GradObj', 'on', 'MaxIter', 400);
[theta, cost] = fminunc(@(t)(costFunction(t, X,y)),initial_theta, options);

options是作为一个数据结构返回
‘GradObj’是梯度目标参数,设置为’on’
'MaxIter’是迭代次数,设置为400
theta是返回最优的θ参数,cost是代价
fminuc是优化函数,调用costFunction函数,参数的初始值,梯度值

在此代码段中,我们首先定义了与fminunc一起使用的选项。
具体来说,我们将GradObj选项设置为on,这告诉fminunc我们的函数同时返回成本和梯度参数。
当最小化函数时,这允许fminunc使用渐变。
此外,我们将MaxIter选项设置为400,以便fminunc在终止之前最多运行400个步骤。
为了指定我们要最小化的实际函数,我们使用“简写形式”以@(t)(costFunction(t,X,y))指定函数。
这将创建一个带有参数t的函数,该函数调用costFunction。
这使我们可以包装costFunction与fminunc一起使用。
如果您正确完成了costFunction,fminunc将收敛于正确的优化参数,并返回成本和θ的最终值。
注意,通过使用fminunc,您不必自己编写任何循环,也不必像对梯度下降那样设置学习率。
这一切都由fminunc完成:您只需要提供一个计算成本和梯度的函数即可。
一旦fminunc完成,ex2.m将使用最佳参数θ调用costFunction函数。您应该看到成本约为0.203。然后,该最终θ值将用于在训练数据上绘制决策边界

下面是画决策边界的代码

function plotDecisionBoundary(theta, X, y)
%PLOTDECISIONBOUNDARY Plots the data points X and y into a new figure with
%the decision boundary defined by theta
%   PLOTDECISIONBOUNDARY(theta, X,y) plots the data points with + for the 
%   positive examples and o for the negative examples. X is assumed to be 
%   a either 
%   1) Mx3 matrix, where the first column is an all-ones column for the 
%      intercept.
%   2) MxN, N>3 matrix, where the first column is all-ones

% Plot Data
plotData(X(:,2:3), y);
hold on

if size(X, 2) <= 3
    % Only need 2 points to define a line, so choose two endpoints
    plot_x = [min(X(:,2))-2,  max(X(:,2))+2];

    % Calculate the decision boundary line
    plot_y = (-1./theta(3)).*(theta(2).*plot_x + theta(1));

    % Plot, and adjust axes for better viewing
    plot(plot_x, plot_y)
    
    % Legend, specific for the exercise
    legend('Admitted', 'Not admitted', 'Decision Boundary')
    axis([30, 100, 30, 100])
else
    % Here is the grid range
    u = linspace(-1, 1.5, 50);
    v = linspace(-1, 1.5, 50);

    z = zeros(length(u), length(v));
    % Evaluate z = theta*x over the grid
    for i = 1:length(u)
        for j = 1:length(v)
            z(i,j) = mapFeature(u(i), v(j))*theta;
        end
    end
    z = z'; % important to transpose z before calling contour

    % Plot z = 0
    % Notice you need to specify the range [0, 0]
    contour(u, v, z, [0, 0], 'LineWidth', 2)
end
hold off

end

size(X,1)是返回X矩阵的行数
size(X,2)是返回X矩阵的列数
这里用if语句判断了下,一个是画特征小于三个的图,另一个是画特征大于三个的图。
如果是画只有两个特征的决策边界,只需要连接最大值和最小值就行。
不过这里不知到为什么要将最小值X减2,最大值加2.

  • 2
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值