brunch

You can make anything
by writing

C.S.Lewis

by 라인하트 Oct 14. 2020

앤드류 응의 머신러닝 정리 (5-4):데이터 시각화

   온라인 강의 플랫폼 코세라의 창립자인 앤드류 응 (Andrew Ng) 교수는 인공지능 업계의 거장입니다. 그가 스탠퍼드 대학에서 머신 러닝 입문자에게 한 강의를 그대로 코세라 온라인 강의 (Coursera.org)에서 무료로 배울 수 있습니다. 이 강의는 머신러닝 입문자들의 필수코스입니다. 인공지능과 머신러닝을 혼자 공부하면서 자연스럽게 만나게 되는 강의입니다. 


Octave / Matlab Tutorial 

옥타브 / 매트랩 튜토리얼  


Plotting Data (데이터 시각화)


   When developing learning algorithms, very often a few simple plots can give you a better sense of what the algorithm is doing and just sanity check that everything is going okay and the algorithms doing what is supposed to. For example, in an earlier video, I talked about how plotting the cost function J of theta can help you make sure that gradient descent is converging. Often, plots of the data or of all the learning algorithm outputs will also give you ideas for how to improve your learning algorithm. Fortunately, Octave has very simple tools to generate lots of different plots and when I use learning algorithms, I find that plotting the data, plotting the learning algorithm and so on are often an important part of how I get ideas for improving the algorithms. And in this video, I'd like to show you some of these Octave tools for plotting and visualizing your data.


   학습 알고리즘을 개발할 때 간단한 그래프들은 알고리즘의 역할과 제대로 동작하는 지를 확인할 수 있는 좋은 도구입니다. 예를 들어, 비용 함수 J(θ)의 그래프를 도식화하여 경사 하강법이 최소값에 수렴하는 지를 확인했습니다. 데이터와 학습 알고리즘의 결과를 그래프로 도식화하면 학습 알고리즘을 개선할 수 있는 아이디어를 얻을 수 있습니다. 데이터와 학습 알고리즘을 시각화하는 것은 정말 중요합니다. 옥타브 프로그램은 다양한 그래프를 그릴 수 있는 간단한 명령어를 제공합니다. 이번 강의에서 옥타브 프로그램으로 데이터를 도식화하고 시각화하는 방법을 설명합니다.   



   Here's my Octave window. Let's quickly generate some data for us to plot. So I'm going to set T to be equal to, you know, this array of numbers. Here's T, set of numbers going from 0 up to 0.98. 


   여기 옥타브 창이 있습니다. 우리가 도식화할 데이터를 빠르게 생성합니다.


   t = [0:0.01:0.98]   % 0부터 0.98까지 0.01씩 증가하는 행 벡터 t를 생성


   t는 0부터 0.98까지의 숫자들의 배열한 행 벡터입니다.  



   Let's set y1 equals sine of 2 pie 40 and if I want to plot the sine function, it's very easy. I just type plot T comma Y 1 and hit enter. And up comes this plot where the horizontal axis is the T variable and the vertical axis is y1, which is the sine you saw in the function that we just computed. 


    y1 = sin(2*pi*4*t)         % 변수 y1은 데이터 t에 대한 싸인 함수의 값 

   plot(t, y1)                     % 수평축의 값이 t 일 때 수직축에 y1의 값을 도식화 


   변수 y1을 선언하고 데이터 t를 sin(2π4t) 함수에 대입하여 변수 y1에 입력합니다. 싸인 함수 y1을 도식화하는 것은 진짜 쉽습니다. 'plot(t, y1)' 명령어는 수평축의 값이 t 일 때 y1의 값을 그립니다. 수평축은 변수 t이고 수직축은 변수 y1입니다. 그래프는 방금 계산한 싸인 함수의 그래프입니다.  



   Let's set y2 to be equal to the cosine of two pi, four T, like so. And if I plot T comma y2, what octave will I do is I'll take my sine plot and it will replace with this cosine function and now, you know, cosine of xi of 1. 


   y2 = cos(2 * π * 4 * t)     % 변수 y2는 데이터 t를 코사인 함수의 값으로 변형한 값

   plot(t, y1)                      % 수평축의 값이 t 일 때 수직축에 y2의 값을 도식화 


   변수 y2을 선언하고 데이터 t를 cos(2π4t) 함수에 대입하여 변수 y2에 입력합니다. 그리고, 'plot(t, y1)' 명령어는 수평축의 값이 t 일 때 y2의 값을 그래프로 그립니다. 옥타브 프로그램은 싸인 함수 대신에 코싸인 함수를 그려줍니다. 코싸인 함수는 1부터 시작합니다. 



   Now, what if I want to have both the sine and the cosine plots on top of each other? What I'm going to do is I'm going to type plot t, y1. So here's my sine function, and then I'm going to use the function hold on. And what hold does it closes octaves to now figures on top of the old one and let me now plot t y2. I'm going to plot the cosine function in a different color.  So, let me put there r in quotation marks there and instead of replacing the current figure, I'll plot the cosine function on top and the r indicates the what is an event color. 


   plot(t, y1)

   hold on             % 기존의 그래프 창에 다음 그래프를 그림 

   pilot(t, y2, 'r')    % 수평축이 값이 데이터 t일 때 수직축의 y2의 값을 붉은색으로 도식화


   만약에 sin함수와 cos함수를 동시에 그래프에 출력하려면 어떻게 해야 할까요? 'plot(t, y1)' 명령어로 sin 함수를 그립니다. 'hold on' 명령어는 옥타브 프로그램에게 기존 그래프에 새로운 그래프를 그립니다. cos함수 y2는 다른 색깔로 그립니다.  'pilot(t, y2, 'r')'명령어는 수평축 t의 데이터에 수직축 y2의 데이터를 빨간색으로 그립니다. 원래 있던 그래프가 사라지지 않았습니다. 기존의 파란색 sin 함수의 그래프 위에 빨간색 cos 함수의 그래프를 그립니다. 'r'은 빨간색을 의미합니다.

 


   And here additional commands - x label times, to label the X axis, or the horizontal axis. And Y label values A, to label the vertical axis value, and I can also label my two lines with this command: legend sine cosine and this puts this legend up on the upper right showing what the 2 lines are, and finally title my plot is the title at the top of this figure. 


   추가적인 명령어들이 있습니다. 


   xlabel('time')        % 수평축 X에 라벨을 'time'으로 지정

   ylabel('value')      % 수직축 Y에 라벨을 ' value'로 지정 

  legend('sin', 'cos') % 첫 번째 그래프와 두 번째 그래프에 대해 범례를 만듦

   title('my plot')      % 그래프의 맨 위에 제목 지정 



   두 개의 그래프에도 라벨을 붙일 수 있습니다. 범례를 만들어 오른쪽 상단에 붙습니다. 범례를 만드는 명령어는 'legend('sin', 'cos')' 명령어입니다. 



   Lastly, if you want to save this figure, you type print -dpng myplot. png. So PNG is a graphics. file format, and if you do this it will let you save this as a file. If I do that, let me actually change directory to, let's see, like that, and then I will print that out. So this will take a while depending on how your Octave configuration is setup, may take a few seconds, but change directory to my desktop and Octave is now taking a few seconds to save this. If I now go to my desktop, Let's hide these windows. Here's myplot.png which Octave has saved, and you know, there's the figure saved as the PNG file. Octave can save thousand other formats as well. So, you can type help plot, if you want to see the other file formats, rather than PNG, that you can save figures in. 


   print -dpng 'myplot.png'    % 그래프를 디폴트 디렉터리에 PNG 이미지 파일로 저장


   마지막으로 'print -dpng 'myplot.png' 명령어는 그래프를 디폴트 디렉터리에 PNG 이미지 파일 포맷으로 저장합니다. 저장할 디렉터리 위치를 변경할 수 있습니다. 이미지 저장 시간은 옥타브 설정에 따라 몇 초에서 몇십 초 정도 걸립니다. 하지만, 저장 위치를 지정하면 더 빨리 저장합니다. 저장 위치 myplot.png파일이 있습니다. PNG 파일 포맷으로 그래프가 저장되어 있습니다. PNG 이외의 수천 개의 다른 포맷으로 저장이 가능합니다. 'help plot' 명령어로 확인합니다. 



   And lastly, if you want to get rid of the plot, the close command causes the figure to go away. As I figure if I type close, that figure just disappeared from my desktop. Octave also lets you specify a figure and numbers. You type figure 1 plots t, y1. That starts up first figure, and that plots t, y1. And then if you want a second figure, you specify a different figure number. So figure two, plot t, y2 like so, and now on my desktop, I actually have 2 figures. So, figure 1 and figure 2 thus 1 plotting the sine function, 1 plotting the cosine function. Here's one other neat command that I often use, which is the subplot command. 


   close           % 그래프 창을 닫고 그래프를 제거  

  figure(1); plot(t, y1)    % Figure 1이라는 이름의 그래프를 그림

  figure(2); plot(t, y2)    % 기존 그래프 창을 두고 Figure 2라는 이름의 그래프를 그림 


   마지막으로 'close' 명령어는 그려진 그래프를 지웁니다. 그래프 창이 사라집니다. 옥타브 프로그램은 한 번에  여러 그래프에 각각 숫자를 부여합니다. 'figure(1); plot(t, y1)' 명령어는 Figure 1이라는 이름의 첫 번째 그래프를 그립니다. 'figure(2); plot(t, y2)' 명령어는 기존 그래프를 그대로 두고 Figure 2라는 이름의 두 번째 그래프를 그립니다. 새로운 그래프가 생성되어 2 개의 개별 그래프가 만들어집니다.  Figure 1과 Figure 2는 그래프의 이름입니다. Figure 1 은 sin 함수를 Figure 2는  cos함수를 나타냅니다. 



   So, we're going to use subplot 1 2 1. What it does it sub-divides the plot into a one-by-two grid with the first 2 parameters are, and it starts to access the first element. That's what the final parameter 1 is, right? So, divide my figure into a one by two grid, and I want to access the first element right now. And so, if I type that in, this product, this figure, is on the left. And if I plot t, y1, it now fills up this first element. 


   subplot(1, 2, 1)  % 그래프 창을 1 X 2 격자 구조로 분할하고 첫 번째부터 시작

   plot(t, y1)                % 첫 반째 성분을 차지


   비슷한 명령어로 subplot()라는 명령어가 있습니다. 'subplot(1, 2, 1)' 명령어는 앞 두 개의 파라미터 1과 2에 의해 화면을 1 X 2 격자 구조로 분할하고 마지막 파라미터 1은 첫 번째 1 X 2 격자의 첫 번째 성분부터 시작한다는 것을 의미합니다. 즉, 하나의 창에 두 개의 그래프를 그릴 수 있습니다. 첫 번째 분할 화면부터 시작합니다. 보시는 것처럼 이렇게 화면이 뜨고 분할된 화면의 왼쪽에 그래프가 있습니다. 여기서 'plot(t, y1)'는 을 치면 첫 번째 분할 화면을 채웁니다. 



   And if I I'll do subplot 122. I'm going to start to access the second element and plot t, y2. Well, throw in y2 in the right hand side, or in the second element. 


   subplot(1, 2, 2)  % 그래프 창을 1 X 2 격자 구조로 분할하고 두 번째부터 시작

   plot(t, y2)          % 두 번째 성분을 차지


   그리고 'subplot(1, 2, 2)' 명령어는 격자 구조의 2 번째인 오른쪽 격자를 지정합니다. 여기서 'plot(t, y2)'는 을 치면 첫 번째 분할 화면을 채웁니다.



   And last command, you can also change the axis scales and change axis these to 1.51 minus 1 1 and this sets the x range and y range for the figure on the right, and concretely, it assess the horizontal major values in the figure on the right to make sure 0.5 to 1, and the vertical axis values use the range from minus one to one. And, you know, you don't need to memorize all these commands. If you ever need to change the access or you need to know is that, you know, there's an access command and you can already get the details from the usual octave help command. 


   axis([0.5 1 -1 1])     % x축과 y축의 범위를 설정


   마지막으로 배울 명령어를 이용해서 가로축/세로축의 스케일을  바꿉니다. 'axis([0.5 1 -1 1])'명령어는 왼쪽의 그래프의 x축과 y축의 범위를 설정합니다. 구체적으로 x축의 범위를 0.5에서부터 1로 지정하고  y축의 범위를 -1부터 1까지로 지정합니다. 모든 명령어들을 외울 필요는 없습니다. 작업을 하다가 x/y축의 범위를 바꿔야 할 순간에 이 명령어를 기억하면 됩니다. axis() 명령어를 기억했다가 구체적인 사용 방법은 'help axis' 명령어가 알려줍니다.



   Finally, just a couple last commands CLF clear is a figure and here's one unique trait. 


  clf            % 그래프 창에서 그래프를 제거


   마지막으로 명령어 몇 가지를 더 알려드리자면 'clf' 명령어는 그래프 창에서 그래프를 지워줍니다. 



   Let's set a to be equal to a 5 by 5 magic squares a. So, a is now this 5 by 5 matrix does a neat trick that I sometimes use to visualize the matrix, which is I can use image sc of a what this will do is plot a five by five matrix, a five by five grid of color. where the different colors correspond to the different values in the A matrix. 


   A =  magic(5)       % 5 X 5 마방진을 생성  

   imagesc(A)          % 5 X 5 격자를 만들고 서로 다른 색으로 표현 


   여기에 'A =  magic(5)' 명령어는 5x5의 마방진의 정방 행렬을 생성합니다. imagesc() 함수는 행렬을 깔끔하게 색깔별로 보여줍니다. 'imagesc(A)' 명령어는 5x5행렬을 격자로 나누어 서로 다른 색을 칠해 행렬을 표현합니다. 다른 색들이 각각 다른 값에 대응해 A 행렬을 표현합니다. 



So concretely, I can also do color bar. Let me use a more sophisticated command, and image sc A color bar color map gray. This is actually running three commands at a time. I'm running image sc then running color bar, then running color map gray. And what this does, is it sets 

a color map, so a gray color map, and on the right it also puts in this color bar. And so this color bar shows what the different shades of color correspond to. Concretely, the upper left element of the A matrix is 17, and so that corresponds to kind of a mint shade of gray. Whereas in contrast the second element of A--sort of the 1 2 element of A--is 24. Right, so it's A 1 2 is 24. So that corresponds to this square out here, which is nearly a shade of white. 

And the small value, say A--what is that? A 4 5, you know, is a value 3 over here that corresponds-- you can see on my color bar that it corresponds to a much darker shade in this image. 


    컬러 바 (기준 색의 표)를 이용할 수 있습니다. 좀 더 복잡 미묘한 명령어를 사용하겠습니다. 'images(A), colorbor, colormap grey' 명령어는 세 가지 명령어를 순차적으로 실행시킵니다. 'imagesc(A)' 명령어는 행렬의 값을 색깔로 표현합니다. 'colorbar' 명령어는 오른쪽에 컬러바를 표시합니다. 'colormap grey' 명령어는 색깔은 회색 계열을 사용합니다. 컬러 바는 주어진 색이 어떤 값에 대응하는 지를 표시합니다. 구체적으로 예를 들면, A행렬의 왼쪽 위의 원소인 17은 여기쯤 해당하는 회색으로 표시합니다. 행렬 A(1, 2)에 해당하는 값입니다. A(1, 2)는 24입니다. 이 값은 사각형에 해당하고 거의 흰색에 가까운 색입니다. 그리고 작은 숫자인 A(4,5)는 3입니다. 컬러 바에서 보면 이 즈음입니다. 전보다 훨씬 짙은 색으로 표시합니다. 



   So here's another example, I can plot a larger, you know, here's a magic 15 that gives you a 15 by 15 magic square and this gives me a plot of what my 15 by 15 magic squares values looks like. 

 

  또 하나의 예제가 있습니다.  'images(magic(15)), colorbor, clormap default' 명령어는 세 가지 명령어를 순차적으로 실행시킵니다. 15 x 15 마방진 행렬을 다음과 같은 이미지를 얻을 수 있습니다.



   And finally to wrap up this video, what you've seen me do here is use comma chaining of function calls. Here's how you actually do this. If I type A equals 1, B equals 2, C equals 

3, and hit Enter, then this is actually carrying out three commands at the same time. 

Or really carrying out three commands, one after another, and it prints out all three results. 

And this is a lot like A equals 1, B equals 2, C equals 3, except that if I use semicolons instead 

of a comma, it doesn't print out anything. So, this, you know, this thing here we call comma chaining of commands, or comma chaining of function calls. And, it's just another convenient way in Octave to put multiple commands like image sc color bar, colon map to put multi-commands on the same line.


   마지막으로 오늘 배운 내용을 정리합니다. 여기 있는 명령어들은 콤마(,)를 써서 명령어들이 순차적으로 실행되게 하였습니다. 이것이 사용하는 방법입니다. 'a = 1, b = 2, c = 3' 명령어는 3 개의 명령어를 한 번에 실행합니다. 또는 각각의 명령을 순차적으로 실행한다고도 할 수 있습니다. 각각의 출력 값은 나옵니다. 

이렇게 하는 대신에 'a = 1; b = 2; c = 3;' 명령어는 출력 값을 표시하지 않습니다. ';'명령어는 은 아무것도 출력하지 않습니다. 이렇게 연속으로 실행하는 것을 콤마 체이닝 (comma chaining)이라고 합니다. 옥타브 프로그램에서 여러 가지 명령어를 좀 더 편하게 사용하는 방법입니다. 조금 전처럼 imagesc, colorbar, color map을 같은 줄에 함께 수행한 것과 마찬가지입니다.


 So, that's it. You now know how to plot different figures and octave, and in next video the next main piece that I want to tell you about is how to write control statements like if, while, for statements and octave as well as hard to define and use functions


   끝입니다. 옥타브 프로그램에서 데이터를 시각화하는 방법을 배웠습니다. 다음 강의에서 중요한 부분을 이야기할 것입니다.  프로그램의 실행을 제어하는 if, while, for과 같은 제어 구문(control statement)과 

어떻게 함수를 선언하고 사용하는지에 대해 이야기하겠습니다.


앤드류 응의 머신러닝 동영상 강의 




정리하며 - 데이터 시각화


 1) 도식화

     plot(t, y1)                 : 수평축의 값이 t 일 때 y1의 변화량을 나타내는 그래프

      hold on                    : 기존 그래프에 새로운 그래프를 추가  

      pilot(t, y2, 'r')            : 수평축 t의 데이터에 수직축 y2의 변화량을 나타내는 빨간 그래프 



2) 그래프 이름 넣기

    xlabel('time')            : X 축(수평축)에 time 라벨

    ylabel('value')           : Y축(수직축)에 value 라벨 

     legend('sin', 'cos')     : 오른쪽 상단에 그래프 별 범례

     title('my plot')           : 맨 위 중앙에 제목 표시


3) 그래프 관리

    print -dpng 'myplot.png'  : 디폴트 디렉터리에 PNG 이미지 파일 포맷으로 저장

   close                                  : 그래프 창을 닫음  

   clf                                       : 그래프 창에서 그래프를 지움  


    figure(1); plot(t, y1)           : Figure 1이라는 이름의 첫 번째 그래프 창

   figure(2); plot(t, y2)           : Figure 2라는 이름의 두 번째 그래프 창  


    subplot(1, 2, 1)                  : 그래프 창을 1 X 2 격자구조 분할 후 다음 그래프를 왼쪽에 삽입

   sunplot(1, 2, 2)                  : 그래프 창을 1 X 2 격자구조 분할 후 다음 그래프 오른쪽에 삽입


    axis([0.5 1 -1 1]                   : 그래프의 x축과 y축의 범위 설정 

   imagesc(A)                          : 5 X 5 행렬을 차원의 수만큼 격자로 나누어 색칠


4) 콤마 체이닝

    a = 1, b = 2, c = 3               :  콤마는 명령어들을 순차적으로 실행






매거진의 이전글 앤드류 응의 머신러닝 정리 (5-3):옥타브 데이터계산
작품 선택
키워드 선택 0 / 3 0
댓글여부
afliean
브런치는 최신 브라우저에 최적화 되어있습니다. IE chrome safari