吴恩达机器学习笔记(六)–Octave/Matlab教程
1.Basic operations
~=
means̸=disp(sprint("...")
just like the “printf()” in C- “
format long
” restores the default to print a large number of digits. The same to “format short
” A = [ 1 2; 3 4; 5 6 ]
use this command to generate a matrix.V = 1:01:2
set V to the bunch of elements that start from 1, and increment steps of 0.1 til 2ones(2,3)
generate a matrix of all oneszeros(1,3)
generate a matrix of all zerosrand(3,4)
generate a matrix of all random numbers drawn from the uniform distribution between 0 and 1randn(1,3)
generate a Gaussian matrix at randomeye(5)
generate a unit matrixhist(w)
plot a histogram of whelp
<the function you want to get more information about>size(m)
returns the dimension of m. It is a 1*2 matrixlength(m)
returns the longer dimension of m
2. Moving data around
pwd
shows the current directoryload features.dat
who
shows the variables in the workspace, whilewhos
gives you the detailed viewclear features
delet the variablesave filename.mat variable
save filename.txt variable -ascii
A(3,2)
refers to the element at the third row and the second column of matrix AA([1,3], :)
refers to the elements in the first and the third rows of matrix AA(:)
put all elements of A into a single column of vector
3. Computing on data
.*
element multiply by the corresponding elementlog(v)/exp(v)
A'
transposeA<3
to judge whether every element of A is less than 3find(A<3)
to find the elements in A that is less than three, turn others to zerosum(a)
to sum up a, if put 1 as the second parameter, it will sum up every column and if put 2as the second parameter, it will sumup every rowflipud(A)
flip up down
4. Plotting data
plot(t, y,'r')
plot y in redhold on
plot on the last figurelegend('name')
label the lineprint -dpng 'myplot.png'
to save the plot as a filefigure(1)
switch figuressubplot(1,2,1)
divide the figure into a 1 by 2 grid and access the first element right nowaxis([ 0 1 0 1 ])
set the scales of x and yclf
clear the figureimagesc(A)
take A to plot a grid of colorsimagesc(A), colorbar, colormap gray
set a gray color map
5. Logical statements
for i = 1:10,
v(i) = 2^i;
end;
while i<=5,
v(i) = 100;
end;
if v(1) == 1,
disp('one');
elseif v(1) == 2,
disp('two');
else
disp('other');
end;
To definite a new function:
function J=costFunction(X, y, theta)
m=size(X, 1);
predictions = X*theta;
sqrErrors = (predictions - y).^2;
J = 1/(2*m) * sum(sqrErrors);
6. Vectorization
All of the languages have either built into them or have readily and easily accessible different numerical liner algebra libraries. When you are implementing machine learning algorithm, if you are able to take advantage of these liner algebra libraries and mix the routine calls to them, you will get the code that “first is more efficient” and have a simpler implementation and also more likely to be bug free.
For example:
hθ(x)=∑i=0nθjxj
Instead of using the for loop, we can simply use transposing function:
hθ(x)=θTx