Octave教程 Octave Tutorial

Octave教程 Octave Tutorial

转载:

http://blog.csdn.net/pipisorry/article/details/43565653

本文教你掌握octave基本知识。

Octave Tutorial Octave教程

为什么学习机器学习要学octave等 较高级的原型语言?

If you want to build a large scale deployment of a learning algorithm, what people will often do is prototype and the language is Octave.Which is a great prototyping language.So you can sort of get your learning algorithms working quickly.
prototyping language(原型语言):The most common prototyping language use for machine learning are: Octave, MATLAB,Python, NumPy, and R.
Octave is nice because open sourced.
And MATLAB works well too, but it is expensive for to many people.
If you know Python, NumPy or if you know R.But, people usually end up developing somewhat more slowly, Because the Python, NumPy syntax is just slightly clunkier than the Octave syntax.

安装Octave

ubuntu下安装octave最新版

sudo apt-add-repository ppa:octave/stable
sudo apt-get update
sudo apt-get install octave  -y
  #直接安装是3.8版本,添加最新稳定版的源安装的是4.2版本

[Octave for Debian systems: Octave's Personal Package Archive (PPA) for Ubuntu]

[Octave for GNU/Linux]

windows下安装octave

[https://class.coursera.org/ml-008/wiki/octave-matlab#windows]

[Installation]

octave安装拓展包

使用octave运行matlab代码时可能出错,因为没有对应的包,如warning: the 'col2im' function belongs to the image package from Octave Forge which seems to not be installed in your system.这时就要安装对应的包了。

有的包甚至可能在matlab中没有实现的,如warning: the 'clearvars' function is not yet implemented in Octave。

注意,低版本的octave可能会安装不成功,如包image needs octave >= 4.0.0。

下载

首先在网站Packages中找到要安装的包(要安装的包名称一般会在出错提示中告诉你)下载到octave-workspace目录下,如(wget可能会下载不成功,注意应该下载的文件大小)

pika:/media/pika/files/mine/matlab_workspace/PCAS$wget http://downloads.sourceforge.net/project/octave/image-2.4.1.tar.gz -o ./image-2.4.1.tar.gz

如果上面不能下载成功,还可以直接到sourcefoge直接搜索下载。

安装

先安装依赖:pika:~$sudo apt-get install liboctave-dev

>> pkg install image-2.4.1.tar.gz

或者>> pkg install -forge image   (好像安装不成功,而且会自动删除下载好的文件)

安装成功的输出

>> pkg install image-2.4.1.tar.gz
For information about changes from previous versions of the image package, run 'news image'.
>> pkg list
Package Name  | Version | Installation directory
--------------+---------+-----------------------
       image  |   2.4.1 | /home/pika/octave/image-2.4.1

load

安装好后不能直接使用,使用前要load

warning: the 'col2im' function belongs to the image package from Octave Forge which you have installed but not loaded.  To load the package, run 'pkg load image' from the Octave prompt.

出错及处理

1 >> pkg install image-2.4.1.tar.gz
pkg: please install the Debian package "liboctave-dev" to get the mkoctfile command
error: called from '__gripe_missing_component__' in file /usr/share/octave/4.0.2/m/help/__gripe_missing_component__.m near line 53, column 3
提示要安装liboctave-dev

pika:~$sudo apt-get install liboctave-dev

2 >> pkg install -forge image
gzip: /media/pika/files/mine/matlab_workspace/PCAS/image-2.4.1.tar.gz: not in gzip format
unpack: unarchiving program exited with status: 2
tar: This does not look like a tar archive
tar: Exiting with failure status due to previous errors

可能是因为下载的文件不完整,下载不成功(lz常见这种情况)。

3 pkg install -forge可能不行,总是出错,所以lz都是先下载好了,再通过pkg install image-2.4.1.tar.gz安装的

octave:6> pkg install -forge col2im
error: cellfun: C must be a cell array
error: called from:
error:   /usr/share/octave/3.8.1/m/pkg/private/get_forge_pkg.m at line 71, column 14
error:   /usr/share/octave/3.8.1/m/pkg/private/get_forge_download.m at line 26, column 12
error:   /usr/share/octave/3.8.1/m/pkg/pkg.m at line 385, column 29

[Installing packages]

[Installing and Removing Packages]

[how-can-i-install-a-package-from-octave-forge]

octave学习文档

[http://www.gnu.org/software/octave/doc/interpreter/]

皮皮blog

Octave的使用

打开linux的一个terminal,输入octave就进入octave环境了。(lz使用的是ubuntu安装的octave)

pika:~$octave &
[1] 5280

如果提示octave启动某个文件无权限/home/pika/.config/octave/qt-settings,lz发现是这个文件夹安装后所有权居然是root:root,改成当前用户就可以了:

root:/home/pika#chown pika:pika -R .

Note:

1 octave中的矩阵下标同matlab一样从1开始

2 帮助命令 help eye   (查看生成单位阵的函数)

3 octave3.8输入octave是直接在terminal上的命令行形式,而octave4.0以上安装后是gui图形化界面,类似matlab了。

octave中可以直接使用linux命令行命令,如pwd, ls等等。

使用示例

octave命令行输入:

cd '/media/pika/files/mine/matlab_workspace/PCAS'

load PlaneParts.mat

who

pkg load image

showpcs(Ws)

[示例代码]

octave的基本设置

可以在octave图形化界面中设置初始路径。edit > preference > general > octave startup > path

查看和修改当前路径

octave:1> pwd
ans = /home/pika

octave:4> cd /media/pika/files/mine/study/大数据优化算法/PCAS
octave:5> pwd
ans = /media/pika/files/mine/study/大数据优化算法/PCAS

进入路径后还有ls等等命令,感觉就完全就是linux terminal的命令(ubuntu中应该就是吧可能)。

运行写好的matlab代码如gen_data.m

octave:10> gen_data
[Octave matlab中运行.m文件方式对比 ]

octave的基本使用

载入数据会在workspace自动显示出来

皮皮blog

Basic Operations(octave语言中的基本操作)

基本操作:四则运算、逻辑运算、常量、结果显示

矩阵操作

矩阵创建和生成

In Octave, many functions work on single numbers, vectors, and matrices. For example, thesin function when applied to a matrix will return a new matrix with the sin of each element.

e.g.  X = ones(7) ;   log(X) will compute the log of every element

生成-10到10之间100个数

theta0_j = linspace(-10, 10, 100);}

生成随机数矩阵

rand() - matrix of all random numbers drawn from the uniform distribution between zero and one.7
randn() - values drawn from a Gaussian distribution with mean zero and variance or standard deviation equal to one.

Note: 可以使用hist(randn())查看绘图结果。

生成单位矩阵

计算矩阵大小(维度)

Note:

1. length() - gives you the size of the longest dimension.

2. 矩阵维度计算代码

1> [m, n] = size(X);

2> m = size(X, 1);
      n = size(X, 2);

矩阵切片和选择操作

Note: 1:2中起点1和终点2都包含在内

查找数据

neg = find(y == 0);        #查找label y==0时对应的下标

转置

X‘

皮皮blog

Moving Data Around(load data and find data on the file system)

查看文件和目录

{Note : 将文件目录加入路径中 addpath('c:\users\.....')}

载入数据

Note: Octave use single quotes to represent strings

查看变量

{Note: 

who - shows me what variables I have in my Octave workspace.shows me whether the variables that Octave has in memory currently.

whos - gives you the detailed view.}

选取数据

清除数据

保存数据


Note: save - save the data in a binary format,a somewhat more compressed binary format by default.

Manipulate data(操纵数据)

数据选取和拓展

Note: A(2) = 3而不是3 4;  A(2, :)才是 3 4

{Note: appended another column vector to the right}

Computing on Data(在数据上的计算)

{Note1:A * B是矩阵相乘, 且不能写成AB

By default, Octave interprets math operators to be matrix operators.
 If you don't want matrix multiplication, you need to add the \dot" notation to specify this to Octave.

For example, A*B does a matrix multiply, while A.*B does an element-wise multiplication.

Note2:

函数参数为matrix时,先对matrix的列进行处理,e.g.  mean(X)计算的结果是先对每列计算平均值,相当于mean(X, 1)

要对行计算处理,可以使用mean(X, 2) }

magic() - this matrices called magic squares.that all of their rows and columns and diagonals sum up to the same thing.


prod: multiply them together


max():

1. the maximum of the first column is eight, max of the second column is nine; This 1 means to take the max along the first dimension of A.

2. If your examples are in rows, then, you can use max(A, [], 2) to obtain the max for each row.

[r,c] = (max(X * all_theta', [], 2));

help max

A = magic(9)


sum(A, 1) - Every column adds up to 369 as of the same thing.

皮皮blog
 

绘制数据Plotting Data

存图片并关闭图形界面

{Note:

figure;    %创建一个新图

plot(...);

hold on;    %在当前图上继续绘图

plot(...);

hold off;    %不再在当前图上继续绘图

figure;    %再创建一个新图, 旧图也同时显示

plot(...);  }

change the axis scales

{Note: actually running three commands at a time.running image sc then color bar, then running color map gray.
it sets a color map, so a gray color map, and on the right it also puts in this color bar.this color bar shows what the different shades of color correspond to.}


% Surface plot

% Because of the way meshgrids work in the surf command, we need to transpose J_vals before calling surf, or else the axes will be flipped

J_vals = ...;

theta0_j = linspace(-10, 10, 100);
theta1_j = linspace(-1, 4, 100);
J_vals = J_vals';
surf(theta0_vals, theta1_vals, J_vals);

% Contour plot
% Plot J_vals as 15 contours spaced logarithmically between 0.01 and 100;     z的取值范围为[10^-2, 10^2]时
contour(theta0_vals, theta1_vals, J_vals, logspace(-2, 3, 20)); 

%% Clear and Close Figures
clear ; close all; clc

Note:plot常用参数设置:

plot(x, y, 'rx', 'MarkerSize', 2, 'LineWidth', 2);% Plot the data with    颜色 red    标记形状 x    标记大小 2    线宽 2*
neg = find(y == 0);
plot(X(neg, 1), X(neg, 2), 'ko', 'MarkerFaceColor', 'y', 'MarkerSize', 7);

axis('equal');       %x, y轴以正常比例显示
xlim([4, 24]);        %x轴坐标范围
xlabel('Population of City in 10,000s');
title('Training data with linear regression fit');
legend('training data', 'Linear regression', 'location', 'southeast');         %图例, 图中mark标记说明; 并设置好位置
hold off % don't overlay any more plots on this figure

ref: help legend

【http://www.gnu.org/software/octave/doc/interpreter/ 中Graphics Object Properties

皮皮blog
 

控制语句Control Statements_ for, while, if statements

function 函数

Note: window's notepad sometimes messes up the spacing when open txt file.

Octave has  that many other programming languages don't is that it can also let you define functions that return multiple values or multiple arguments.

define an octave function to compute the cost function J of theta for different values of theta.


皮皮blog
 

向量化Vectorization

(take advantage of linear algebra libraries or these numerical linear algebra libraries and mix the routine calls to them)

run more quickly and take better advantage of any parallel hardware your computer may have and so on.
And second, it also means that you end up with less code that you need to write.

Example 1 :

c++:

Example 2:

Octave中提交代码

1.通过octave提交代码

打开octave

改变路径到写好代码的目录下,如: cd 'E:\machine_learning\Machine_learning\MachineLearning_andrewNg(2015)\machine_learnning-sherrylml\Machine_Learnning-sherrylml\mlclass-ex2-007\mlclass-ex2-007\mlclass-ex2'

再在octave中输入submit

按提示选择一个数字,如:9       #代表all of the above,提交所有要提交的代码

输入login用户名:*****             #courera上的登录名

submission passwd:****       #不是courera上的登录密码,而是programming exercise编程练习中提示的密码

2.通过web提交

打开octave

改变路径到写好代码的目录下,如: cd 'E:\machine_learning\Machine_learning\MachineLearning_andrewNg(2015)\machine_learnning-sherrylml\Machine_Learnning-sherrylml\mlclass-ex2-007\mlclass-ex2-007\mlclass-ex2'

再在octave中输入submitWeb,在当前目录下会生成对应web提交文件submit_ex2_part1-n

进入coursera网站,点击web submission,选择对应的生成文件提交就可以了

from:http://blog.csdn.net/pipisorry/article/details/43565653

ref: [octave官网]

Machine Learning - Andrew NG courses:  V. Octave Tutorial

版权声明:本文为博主皮皮http://blog.csdn.net/pipisorry原创文章,未经博主允许不得转载。 https://blog.csdn.net/pipisorry/article/details/43565653

猜你喜欢

转载自blog.csdn.net/uunubt/article/details/81509322
今日推荐