Hola, me llamo Miguel y esta vez les traigo este nuevo post.
Octave es un lenguaje de programación de alto nivel de código abierto diseñado para realizar cálculos numéricos eficientes resolviendo ecuaciones lineales y no lineales. Además, Octave ofrece al usuario la posibilidad de utilizar estadísticas y análisis de datos.
Debido a su tiempo de desarrollo rápido y su sintaxis fácil de aprender, Octave es uno de los lenguajes de programación más utilizados para Machine Learning junto con Python y R.
Al ser un idioma más productivo, es una buena opción para estudiantes y principiantes en ML. En general, la gente tiende a prototipar solo en Octave y solo después de tener éxito, procede a implementaciones a mayor escala de los algoritmos en lenguajes como C ++ y Java, o cualquier otro lenguaje de bajo nivel que sea más eficiente que Octave cuando se trata de tiempo.
Ahora voy a presentar todo lo que necesita saber para dominar Octave y usarlo para implementar sus modelos en Machine Learning.
Índice
Operaciones básicas
Esta sección tiene como objetivo brindarle conocimientos básicos sobre operaciones lógicas, asignación de variables y otros conceptos simples para prepararlo para operaciones más complejas.
Nota rápida
La sangría no es necesaria en Octave.
- Igual y no igual
1 == 1 % equal 1 ~= 2 % not equal
- Comentario
% this is a comment in Octave
- And operador y Or operador
1 && 2 % and operator 1 || 2 % or operator
- Asignar una variable
a = 76 % assign variable a an integer b = 'Octave' % assign variable b a string
- Imprimir con decimales
disp(sprintf('2 decimals: %0.2f', a)) % print variable a with 2 %decimals disp(sprintf('6 decimals: %0.6f', a)) % print variable a with 6 %decimals
- Formato de número decimal
format short % this is the default format format long % displays more decimals
- Matrices y vectores
% In Octave the semicolon implies go to the next line A = [1 2; 3 4; 5 6]; % this is a 3x2 matrix v = [1 2 3]; % this is a row vector or a 1x3 matrix x = [1; 2; 3] % this is a column vector or a 3x1 matrix
- Matrices especiales
A = ones(2,3); % creates a matrix of size 2x3 filled with 1 B = zeros(1,3); % creates a matrix of size 1x3 filled with 0 C = rand(3,4); % returns a matrix with random elements between (0,1) D = randn(1,3); % Gaussian-distribution matrix E = eye(3,3); % returns the identity matrix
- Incrementando
v = 1:0.1:2; % start from 1, increment with 0.1, up to 2 v = 1:6; % start from 1, increment with 1, up to 6
- Histograma
x = -5 + sqrt(4)*(randn(3, 10)); hist(x); % draws a histogram of x
Mover datos
Aquí discutiremos cómo jugar con las variables y los datos aprendidos anteriormente.
A = [1 2; 3 4; 5 6];
- Obtener dimensiones de la matriz
size(A) % returns the dimension of matrix 3x2 size(A, 1) % returns the first dimension of matrix size(A, 2) % returns the second dimension of matrix length(A) % returns the longest dimension
- Cargar archivo
load file.dat % loads a specific file in the current directory
- Mostrar variables en el espacio de trabajo actual
who % show all the variables declared in the current scope whos % for a more detailed version of who
- Obtener datos de archivo específico
v = cost(1:10);
- Cargar archivo
save helloWorld.txt v -ascii % saves a file in the current directory
- Acceso elementos en matriz
A(1, 2) % gives the number in row 1, column 2 A(2, 🙂 % gives all row 2 A(: ,2) % gives all column 2
- Reemplazar elementos
A(: ,2) = [100; 101; 102] % replace elements in column 2
- Concatenar matrices
A = [1 2; 3 4; 5 6]; B = [7 8; 9 10; 11 12]; C = [A B] % concatenate horizontally D = [A;B] % concatenate vertically
Computación de datos
Ahora que conoce los principios básicos de Octave, es hora de aprender a calcular diferentes variables y funciones.
A = [1 2; 3 4; 5 6]; B = [7 8; 9 10; 11 12]; C = [1 1; 2 2];
- Multiplica matrices
A * C % multiplies matrix A with matrix C % you should pay attention if the matrices can be multiplied
- Elemento a elemento operaciones
A .^ 2 % squares each cell in matrix A log(A) % logs each cell in matrix A exp(A) % exponentiates each cell in matrix A abs(A) % absolute value of each cell in matrix A A + 1 % add numbers to each cell in matrix A
- Transponer matriz
A' % transposes matrix A
- Valor máximo de matriz
max(A) % does column-wise maximum
- Operaciones matemáticas en matriz
sum(A) % sum of all elements in matrix A prod(A) % product of all elements in matrix A floor(A) % round down of all elements in matrix A ceil(A) % round up of all elements in matrix A
- Crear matriz aleatoria
rand(3) % creates a 3x3 random matrix
- Convertir matriz en vector
A(:) % convert matrix A to a vector
- Matriz inversa
pinv(A) % invert matrix A
Trazar datos
Una parte importante en el desarrollo de buenos algoritmos en ML es trazar datos. Al visualizar su conjunto de datos y su modelo, podría tener una mejor idea de lo que necesita mejorar.
t = [0:0.01:0.98]; y1 = sin(2 * pi * 4 * t); plot(t, y1); % plots function y1 with the help of t hold on; % allows you to print 2 graphs together y2 = cos(2 * pi * 4 * t); plot(t, y2) % plots function y2 with the help of t
- Etiquetar el eje de una parcela
xlabel('time') % names the x-axis of the plot ylabel('value') % names the y-axis of the plot legend('sin', 'cos') % creates a legend of the plot title('trigonometric plot') % sets the title o the plot
- Guardar la trama
rint -dpng 'trigoPlot.png' % saves the plot as an image
- Deshacerse de la figura
close % gets rid of the current figure
- Varias figuras en el tiempo de ahorro
figure(1); plot(t, y1) % plots the first figure figure(2); plot(t, y2) % plots the second figure
- Cambio los rangos en el eje
axis([0.5 1 -1 1]) % x-axis : 0.5 to 1 y-axis : -1 to 1
- Figura clara
clf % deletes the figure from memory
Declaraciones de control
En cualquier lenguaje de programación es necesario saber cómo utilizar las sentencias de control, ya que puede facilitar su trabajo y hacerlo más eficiente.
- For bucle
for i = 1:20, v(i) = (i + 1) * 2; end;
- While bucle
i = 1; while i <= 5, x(i) = i * 100; i = i + 1; end;
- If y else
Si no está completamente seguro de lo que hace un comando específico o si desea obtener más información sobre cómo funciona, puede escribir ayuda name_of_command para ver toda la información relacionada con ese comando.
Puede encontrar la documentación completa y descargar Octave desde aquí.
Recursos
[1]Andrew Ng, Aprendizaje automático, Curso de aprendizaje automático sobre Coursera.
Gracias por leer.
Añadir comentario