这是我参加8月更文应战的第23天,活动概况检查:8月更文应战

Notes of Andrew Ng’s Machine Learning —— (5) Octave Tutorial

GNU Octaveshelley英文名怎样读 是一种选用高级编程言语的首要用于数值分析的Element软件。Octave有助于以数值办法处理线性和非线性问题,并运用与elementsMATLAB兼容的言语进行其他element是什么牌子数值实验。它也能够作为面向批处理的言语运用。因为它是GNU计划的一部分,所以它是GNU通用公共许工商银行可证条款下的清闲软件。

Octave 是 MATLAB 的首要清闲替代品之一。

—— Wikipedia

Octave 官网:www.gnu.org/software/oc…

官网宫崎骏给出的界说:Scientific Programming L宫颈癌anguage

  • Powerful mathematics-oriented syntax with built-in 2D/3D plotting andelementary是什么意思 visualization tools
  • Free software, runs on GNU/Linux, ma宫颈癌前期症状cOS, BSD, and Microsoft Windows
  • Drop-in compatible with many Matlab scripts

Basic Operations

Elementary Operations

+, -, *, /, ^.

>> 5 + 6
ans =  11
>> 20 - 1
ans =  19
>> 3 * 4
ans =  12
>> 8 / 2
ans =  4
>> 2 ^ 8
ans =  256

Logical Operations

==, ~=, &&, |elementanimation|, xor().

Note that a宫崎骏 not equal sign is ~=, and not !=.

>> 1 == 0
ans = 0
>> 1 ~= 0
ans = 1
>> 1 && 0
ans = 0
>> 1 || 0
ans = 1
>> xor(1, 0)
ans = 1

Change the Prompt

We can change the prompt via PS软件技术专业1():

>> PS1("octave: > ")
octave: > PS1(">> ")
>> PS1(shell怎样读"oct宫崎骏ave: > ")
octave: > PS1("SOMETHING > ")
SOMETHING > PS1(">> ")
>> % Prompt changed

VariablesElement

>> a = 3
a =  3
>> a = 3;    % semicolon supressinshell脚本入门g output
>> c = (3 >= 1);
>> c
c = 1

Display variables

>> a = pi;
>> a
a =  3.1416
>> disp(a)
3.1416
>> disp(sprintf('2 decimals: %0.2f', a))
2 decimals: 3.14

We can alsoShell set the default lelementuien工商银行gth of decimal plashell脚本ces by entering formatgoogle short/long:

>> a
a =  3.1416
>> format long
>> a
a =  3.141592653589793
>> format short
>> a
a =  3.1416

Create MatrGoices

>> A = [1, 2, 3; 4, 5, 6]
A =
1   2   3
4   5   6
>> B = [1 3 5; 7 9 11]
B =
1    3    5
7    9   11
>> B = [1, 2, 3;
> 4, 5, 6;
> 7, 8, 9]
B =
1   2   3
4   5   6
7   8   9
>> C = [1, 2, 4, 8]
C =
1   2   4   8
>> D = [1; 2; 3; 4]
D =
1
2
3
4

There are some useful methods tshell脚本根本指令o generate matrices:

  • Generate vector of a range
>> v = 1:10    % start:end
v =
1    2    3    4    5    6    7    8    9   10
>> v = 1:0.1:2软件    % starelementst:step:end
v =
Columns 1 th宫崎骏rough 8:
1.0000    1.1000    1.2000    1.3000    1.4000    1.5000    1.6000    1.7000
Columns 9 through宫颈癌前期症状 11:
1.8000    1.9000
  • Generate matrices of all ones/zeros
>> ones(2, 3)
ans =
1   1   1
1   1   1
>> zeshell怎样读ros(3, 2)
ans =
0   0
0   0
0   0
>> C = 2 * ones(4, 5)
C =
2   2   2   2   2
2   2appreciate   2   2   2
2   2   2   2   2
2   2   2   2   2
  • Generate ide龚俊ntity matrices
>> eye(3)
ans =
Diagonal Matrix
1   0   0
0   1   0
0   0   1
  • Genera公积金te matrices of random values

Uniform distribution beelement是什么牌子tween 0 and 1:

>> D = rand(1, 3)
D =
0.14117   0.81424   0.83745

Gaussian random:

>> D = randn(1, 3)
D =
0.22133  -2.00002   1.61025

We can generate a gaussian random vector with 10000 elements, andShell plot a h软件istogram:

>> randn(1, 10000);
>> hist(w)

Output figure:

机器学习 (5) Octave/MATLAB 入门

We can also plot a histograppreciateam with more buckets, 50 bins for example:

>> hist(w, 50)

机器学习 (5) Octave/MATLAB 入门

G工商银行et Help

>> help
For help with individual commands and functions type
help NAME
......
>> help eye
'eye' is a built-in function from the file libinterp/corefcn/data.cc
......
>&gapplicationt; help help
......

Moving Datashell脚本根本指令 Around

Selement结构ize of matrix

size()shelley英文名怎样读: get the size of a matrix, return [rows, columns].

>&gtelementary怎样读英语; A = [1, 2; 3, 4; 5, 6]
A =
1   2
3   4
5   6
>> size(A)    % get the selement结构ize of A
ans =
3   2
>> sz = size(A);    % actually, size return a 1x2 matrix
>> size(sz)
ans =
1   2
>> size(A, 1)    % get the first dimension of A (i.e. the number of rowsshell脚本根本指令)
ans =  3
>> sapproachize(A, 2)    % the number of columns
ans =  2

length(): return the size of the longest dimension.

>> length(A)    % get the size of the longest dimension. Confusishell脚本入门ng, not recommend
ans =  3
>> v = [1, 2, 3, 4];
>>软件snapchat length(v)    % We often lengshell是什么意思th() to get the length of a软件库蓝奏云 vshellyector
ans =  4

Load data

W枸杞e can use bashell脚本编程100例sic shell commands to findappearance data that we want.

>> pwd
ans = /Users/c
>> cd MyP软件rogGo/octave/
&枸杞gt;> pwd
ans = /Users/c/MyProg/octave
>> ls
featureX.dat featureY.dat
>> ls -l
total 16
-rw-r--r--  1 c  staff  188 Sep  8 10:00 featureX.dat
-rw-r--r--  1 c  staff工商银行客服电话  135 Sep  8 10:00 featureY.dat

load command can load data from a file.

>> load featureX.dat
>> loelementary是什么意思ad('featureY.dat')

The data from file is now comed into matrices after load

>> featureX
featureX =
2104      3
1600      3
2400      3
1416      2
......
>> size(featureX)
anshell编程s =
27    2

Show variables

who/whos: show variables in memory currently.

>> who
Variables in the current scope:
A软件snapchat         ans       featureX  featureY  sz        v         w
>> whos    % for more details
Variables in the current scope:
Attr Name          Size                     Bytes  Class
====软件snapchat ====          ====                     =====  =====
A             3x2                         4枸杞8  double
ans           1x2                         16  double
featureX     27x2                        432  double
feashellfishtureshell脚本入门Y     27x1                        216  double
sz            1x2                         16  double
v             1x4                         32  double
w             1x10000                  80000  double
Total is 10095 elem软件ents using 80760 bytes

Clear variables

clappleear command can help us to clear vashell编程riashellybles that are no lon工商银行客服电话ger useful.

&g软件商铺t;> who
Vapproveariables in the current scope:
A         a软件技术ns       featureX  featureY  sz        v         w
>> clear Ashell脚本入门    % clear a variable
>> clear sz v w    % clear variables
>> whos
Variables inAPP the current scope:
Attr Name          Size                     Bytes  Classshellfish
==elementary=shell脚本根本指令= ====          ====                     =====  =====
ans           1x2                         16  double
featureX     27x2                        432  double
featureY     27x1                        216  double
Total is 83 elements using 664 bytes
&gt软件商铺;> clear    % clear all variables
>> whos
&gt软件商铺;>

Save data

Take aelement结构 part of a vector.

>> v = featureY(1:5)
v =
3999element什么意思
3299
3690
2320
5399
>> whos
Variab狗狗币les in the current scope:
Atshell怎样读tr Name          Size                     Bytes  Class
==== ====          ====                     =====  =====
featureX     27x2                        432  doubshellyle
featureY     27x1                        216  double
v             5x1                         40  double
Total is 86 elements using 688 bytes

Save data to disk: sa软件技术专业ve file_name variable [-ascii]

>&gtelementui; save hello.mat v    % save as a binary format
>> ls
featappearureX.dat featureY.dat hello.mat
>> save hello.txt v -ascii;    % save as a ascii txt
>>

Then we can clear it from memory and load v back from disk:

>> clear vshelley英文名怎样读
>> whos
Variables in the current scope:
Attr Name          Size                     Bytes  Class
==== ====          ====                     =====  =====
featureXshell怎样读     27x2                        432  double
featureY     27x1                        216  double
Total is 81 elements using 648 bytes
&g狗狗币t;> load hello.mat
>> wshellfishhos
Variables in the cShellurrent scope:
Attr Name          Size                     Bytes  Class
==== ====          =shell怎样读===                     =====  =====
featureX     27x2                        432  double
featureY     27x1                        216  double
v             5x1                         40  double
Total is 86 elements using 688 bytes
>>

Manipulate data

Get element from a matrix:

>> A = [1, 2; 3, 4; 5,application 6]
A =
1   2
3   4
5   6
>> A(3, 2)    % get a elemeshellynt of melementary怎样读英语atrix
ans =  6
>> A(2, :)    % ":" me宫崎骏ans every eshell是什么意思lement软件技术专业 along that row/column
ans =
3公积金   4
>> A(:, 1)
ansappreciate =
1
3
5
>> A([APP1, 3],shell脚本入门 :)    % get the elements along row 1 & 3
ans =
1   2
5   6

Change the element公积金s of a matrix:

>> A = [1, 2; 3, 4; 5, 6]
A =
1   2
3   4
5   6
>> A(:, 2) = [10, 11, 12]
A =
1   10
3   11
5   12
>> A(1, 1) = 0
A =
0   10
3   11
5   12
>> A = [A, [100; 101; 102]]    % apshell脚本编程100例pend another column vector to right
A =
0    10   100
3    11   101
5    12   102
>>shell编程 A =appstore [1, 2; 3, 4; 5, 6]
A =
1   2
3   4
5   6
>> B = A + 10
B =
11   12
13   14
15   16
>> C = [Ashell是什么意思, B]
C =
1    2   11   12
3    4   13   14
5    6   15   16
>> D = [A; B];
>> selementary是什么意思ize(D)
ans =
6   2

Put all elements of a matrix into a single column vector:

>> A
Aelementary是什么意思 =
0    10   100
3    11   101
5    12   102
>> A(:)    % put all elements of A into a single vector
ans =
0
3
5
10
11
12
100
101
102

Computing on Datshell是什么意思a

Element-wise operations

Use .&ltShell;operator> instead of <operator> for element-wiselementary是什么意思e operations (i.e. operations between elements).

>> A = [1, 2; 3, 4; 5, 6];
>> B = [11, 12; 13, 14; 15, 16];
>> C = [1 1; 2 2];
>> v = [shell脚本根本指令1, 2, 3];
>> A .* B    % element-wise multiplication (ans = [A(1,1)*软件库B(1,1), A(1,2)*B(1,2公积金); ...])
ans =
1软件商铺下载1   24
39   56
75   96
&gt工商银行客服电话;> A .^ 2    % squaring each element of A
ans =
1    4
9   1appstore6
25   36
>> 1 ./ A
ans =
1.00000   0.50000
0.33333   0.shell是什么意思25000
0.20000   0.16667
>> v .+ 1    % equalsappstore to `v + 1` &a软件库mp; `v + ones(1, length(v))`
ans =
2   3   4

Element-wise comparis工商银行on:

>> a
a =
1.00000   15.00000    2.00000    0.50000
>> a < 3
ans =
1  0  1  1
>&gtelement结构; find(a < 3)    % to finelement什么意思d the elements that are lesshell编程s then 3 in a狗狗币, returnshell脚本入门 their indices
ans =
1   3   4
>> A
A =
1   2
3   4
5   6
>> [r, c] = find(A < 3)
r =
1
1
c =
1
2

Functions are element-wise:

>> v = [1, 2, 3]
v =
1   2   3
>> log(v)
ans =
0.00000   0.69315   1.09861
>shell脚本根本指令> exp(v)
aGons =
2.7183    7.3891   2elementary怎样读英语0.0855
>> abs([-1, 2, -3, 4])
ans =
1   2   3   4
>&gtappointment; -v    % -1 * v
ans =
-1approve  -2  -3

Floor and Ceil of elements:approve

>> a
a =
1shell是什么意思.00000   15.00000    2.00000    0.50000
>软件库&gt软件工程; flo软件应用or(a)
ans =
1   15    2    0
>> ceil(a)
ans =
1   15    2    1

Matrix operations

Matrix multiplication:

>>龚俊 A = [1, 2; 3, 4; 5, 6];
>&gtappreciate; C = [1 1; 2 2宫颈癌前期症状];
>> A * C    % matrix multiplication
ans =
5    5
11   11
17   17

Transpose:

>> A = [1, 2; 3, 4; 5, 6];
>> A'    % transposed
ans =
1   3   5
2   4   6

Get the max element of a vector | matrix:

>> a = [1 15 2 0.5];
>> A = [1, 2; 3, 4; 5, 6];
>&gtelements; max_val = max(a)
max_val =  15
>> [val, index] = max(a)
val =  15
inde软件库x =  2软件工程专业
>> max(A)    % `max(<Matrix>)` does a columnshell怎样读-wise maximum
ans =
5   6
&gtAPP;> max(A, [], 1shell是什么意思)    % max per column
ans =shell脚本
5   6
>&elementary是什么意思gt; max(A, [], 2)    % max p狗狗币er ro宫颈癌前期症状w
ans =
2
4
6
>> max(appstoremax(A))    % the max element of whole melementary是什么意思atrix
ans =element结构  6
>> max(A(:))
an软件应用s =  6

Sum & prod of vector:

>> a
a =
1.00000   15.00000    2.00000    0.50000
>> A
A =
1   2
3   4
5   6
>> sum(a)
ans =  18.500
>> su工商银行客服电话m(A)
ans =
9   12
>> sum(A, 1)
ans =
9   12
&gt工商银行客服电话;> sum(A, 2)
ans =
3
7
11
>> prod(a)
ans =  15
>&shell脚本根本指令gt; prod(Aelement什么意思)
ans =
15   48

Get the diagonal elements:

>> A = magic(4)
A =
16    2    3   13
5   11   10    8
9    7    6   12
4   14   15    1
>> A .* eye(4)
ans =
16    0    0    0
0   11    0    0
0    0    6    0
0    0    0    1
&gtshell脚本入门;> sum(A .*Element eye(4))
ans =
16   11    6    1
>> flipud(eye(4))    % flip up down
ans =
Permutation Matrix
0   0   0   1
0   0   1   0
0   1   0   0
1   0   0   0
>> sum(A狗狗币 .* flipud(eye(4)))
ans =
4    7   10   13

I软件库蓝奏云nverse:

>> A = magic软件商铺下载(3)
A =
8   1   6
3   5   7
4   9   2
>> pinv(A)
ans =
0.147222  -0.144444   0.063889
-软件技术0.061111   0.022222   0.105556
-0.019444   0.188889  -0.102778
&elementary怎样读英语gt;>elementary怎样读英语 pinv(A) * A    % get identity mat软件商铺rix
ans =
1.0000e+00   2.0817e-16  -3.1641e-15
-6.1062e-15   1.0000eapple+00   6.2450e-appointment15
3.053龚俊1e-15   4.1633e-17   1.0000e+00

Plotelementuiting Data

Plotting aelementary怎样读英语 function

>> clear
>> t = [0:0.01:0.98];
>&枸杞gt; size(approacht)
ans =
1   99
>> y1 = sin(2*pi*4*t);
>> plot(t, y1);

It will show you a figure like this:

机器学习 (5) Octave/MATLAB 入门

>> y2 = cos(2*pi*4*t);
>> plot(t, y2);

This will replace the sin figure wit软件应用h a new cos figure.

If we want to have both the sin and coselementui plots, the hold on command will help:

>> plot(t, y1);
>&g软件库蓝奏云t; hold oapproachn;
>> plot(t, y2, 'r');

We can set some text on thw figure:

&软件工程专业gt;> xlabel("time");
>> ylabel("value");
>> legend('sin', 'cos');    % Show wh软件应用at the 2 lines are
>> tAPPitle('my plot');

Now, we get this:

机器学习 (5) Octave/MATLAB 入门

Then, we save it and close the plotting window:

>> print -dpng 'myPlot.png'    % save it to $(pwd)
>> close

We can show two figures at theshell编程 same time:

>&软件应用gt; fshell编程igure(1); plot(t, y1);
>> figure(Element2); plot(t, y2);

Then, we can also generate fElementigures like this:

机器学习 (5) Octave/MATLAB 入门

What we need to do is using a subplot:

>> subplot(1, 2, 1);    % Divides plot a 1x2 grid, access first element
>> plot(t, y1);
>> subplot(1, 2, 2);
>appstore> plo公积金t(软件snapchatt, y2);
>> axis([0.5, 1, -1, 1])    % change the range of axis

Use clf to clear a figure:

>&shell脚本入门gt; clf;

Showing a matrElementix

>> A = magic(5)
A =
17   24    1    8   15
23    5    7   14   16
4    6   13   20   22
10   12   19   21    3
11   18   25    2    9
>> imagesc(A), colorbar

It gives us a figure like this:

机器学习 (5) Octave/MATLAB 入门

The different colors correspond to the different values.

Another example:

>> B = magic(10);
>> imagesc(B),elementary是什么意思 colorbar, colormap gray;

Output:

机器学习 (5) Octave/MATLAB 入门

Contr龚俊iol SAPPtatements

for

>> v = zer公积金os(10, 1)
v =
0
0
0
0
0
0
0
0
0
0
>> for i =软件库蓝奏云 1: 10,
>appear     v(i) = 2^i;
> end;
>> v'
ans =
2      4      8     16     32     64    128    256    512   1024

while

>> i = 1;
>> while i <= 5,
>     v(i) = 100;
>软件工程专业     i = i + 1;
> end;
>> v'
ans =
100    100    100    100    100     64    128    256    512   1024

if

>> for i = 1: 10,
>     if v(i) > 100,
>         disp(v(i));
&工商银行gt;     end;
>shell脚本 end;
128Shell
256
512
1024

Or, we can progelementuiram like this,

x = 1;
if (x == 1)
disp ("one");
elseif (x == 2)
disp ("two");
else
disp ("not one or two");
endif

break & continue

i = 1;
while true,
vappreciate(i) = 999;
i = i + 1;
if i == 6,
break;
end;
end;

Output:

v =
999
999
999
999
999
64
128
256
512
1024

Function

Crapplicationeate a Function

To create a function, typeelement翻译 the function code in a text ediappletor (e.g. gedit or notepad), and save the file as functionName.m

Example function:

function y = squareThisNumber(x)
y = x^2;

To call this function iAPPn Octave,软件商铺下载 do either:

  1. cd to the directory of the functionName.m file and call the function:
% Navigate to directory:
cd /path/to/function
% Call the function:
functionName(args)
  1. Add theelement翻译 directory of the function file to the load path:
% To add the path for the current session of Octave:
addpath('/pathshelley英文名怎样读/to/function/')
% To remember the path for future sessions of OcElementtave, after executing addpath above, also do:
savepath

Function with multiple return values

Octave’s functiElementons can return狗狗币 more than one value:

function [square, cube] = squareAndCubeThisNumber(x)
square = x^2;
cube = x^3appearance;
&gshellfisht;> [s, c] = squareAndCubeThisNumber(5)
s =  25
c =  125

Practice

Let’s say I have a data set that looks like t软件工程专业his, with data poiapproachntshellys at (1, 1), (2, 2), (3, 3). And what I’dapple like to d工商银行o isshell编程 to define an octave function to compute the cost function J of theta for different val狗狗币ues of theta.

机器学习 (5) Octave/MATLAB 入门

First, put the data into octave:

X = [1, 1; 1, 2; 1, 3]    % Design matrix
y = [1; 2; 3]软件库蓝奏云
theta = [0; 1]

Output:

X =
1   1
1   2
1   3
y =
1
2
3
theta =
0
1

Then define the cost function:

% costFunctionJ.m
function J = costFunctionJ(X, y, theta)
% X is the *design matrix* containing our training examplesapprove.
% y is the class labels
m = size(X, 1);    % number of trainingapple examples
predictions = X * theta;    %app下载 predictions of hypothesis on all m examples
sqrErrors = (predictions - y) .^ 2;    %element翻译 squared erroes
J = 1 / (2*m) * sum(sqrErrors);

Now, use the软件技术专业 costFunctionJ:

>> j = costFunctionJ(X, y, theta)
j = 0

Got j = 0 because we set theta as [0; 1] which is fitting our data set perfec软件工程tly.

Vectorization

Vectorization is the process of taking code that relies on loops aElementnd converting it into matrix oGoperations. It is more efficient, more elegant, and more conci龚俊se.

As an example, let’s compute our prediction from a hypothesis. Theta is the vector of fields for theshell脚本根本指令 hypothesis and x is a vector of variables.

With lshelley英文名怎样读oops:

predictio软件商铺n = 0.0;
for j = 1:n+1,
prediction += theta(appearj) *软件技术专业 x(j);
end;

With vect枸杞orization:

prediction = theta' * x;

If you recall the de软件工程专业finition multiplying vectors, you’ll see that this one operation does the element-wise multiplication and overall sum in a very concise notation.