1. python Pandas 라이브러리 설치하기

   : pip install pandas


2. 샘플 엑셀파일 받기

   movies.xls


3. 소스보고 따라해보기

    

import pandas as pd excel_file = 'movies.xls' movies = pd.read_excel(excel_file) print(movies.head()) print(movies.shape) print('---------------------------------------------------------------') #sheet1 을 읽어온다. movies_sheet1 = pd.read_excel(excel_file, sheet_name=0, index_col=0) print(movies_sheet1.head()) print(movies_sheet1.shape) print('---------------------------------------------------------------') #sheet2 을 읽어온다 movies_sheet2 = pd.read_excel(excel_file, sheet_name=1, index_col=0) print(movies_sheet2.head()) print(movies_sheet2.shape) print('---------------------------------------------------------------') #sheet3 을 읽어온다. movies_sheet3 = pd.read_excel(excel_file, sheet_name=2, index_col=0) print(movies_sheet3.head()) print(movies_sheet3.shape) print('--------------------------------------------------------------') #위의 sheet1, 2, 3 을 모두 합친다. movies = pd.concat([movies_sheet1, movies_sheet2, movies_sheet3]) print(movies.shape)

---------------------------------------  실행결과 ----------------------------------------------------


                                               Title     ...      IMDB Score

0  Intolerance: Love's Struggle Throughout the Ages      ...             8.0

1                    Over the Hill to the Poorhouse      ...             4.8

2                                    The Big Parade      ...             8.3

3                                        Metropolis      ...             8.3

4                                     Pandora's Box      ...             8.0


[5 rows x 25 columns]

(1338, 25)

---------------------------------------------------------------

                                                   Year    ...     IMDB Score

Title                                                      ...               

Intolerance: Love's Struggle Throughout the Ages   1916    ...            8.0

Over the Hill to the Poorhouse                     1920    ...            4.8

The Big Parade                                     1925    ...            8.3

Metropolis                                         1927    ...            8.3

Pandora's Box                                      1929    ...            8.0


[5 rows x 24 columns]

(1338, 24)

---------------------------------------------------------------

                        Year    ...     IMDB Score

Title                           ...               

102 Dalmatians          2000    ...            4.8

28 Days                 2000    ...            6.0

3 Strikes               2000    ...            4.0

Aberdeen                2000    ...            7.3

All the Pretty Horses   2000    ...            5.8


[5 rows x 24 columns]

(2100, 24)

---------------------------------------------------------------

                                        Year    ...     IMDB Score

Title                                           ...               

127 Hours                             2010.0    ...            7.6

3 Backyards                           2010.0    ...            5.2

3                                     2010.0    ...            6.8

8: The Mormon Proposition             2010.0    ...            7.1

A Turtle's Tale: Sammy's Adventures   2010.0    ...            6.1


[5 rows x 24 columns]

(1604, 24)

---------------------------------------------------------------

(5042, 24)


만족하셨나요? ~~~~~~~

1. OpenCV란 무엇인가?

   : Open Source Computer Vision의 약자로 그래픽을 자유자재로 주무를 수 있는 라이브러리이다.


2. Python에서 OpenCV설치

   : pip install opencv-python

    (특정버전을 설치하려면 pip install python-opencv==버전번호)


3. 추가설치가 필요한 것들

   - 시각화하기 위한 라이브러리 설치 : pip install matplotlib

   - 이미지는 숫자의 집합으로 이루어져 있는데 이 형태를 주무르기 위한 틀을 제공하는 numpy 설치 

     : pip install numpy


4. 원하는 대상을 검출하기 위해 Haar알고리즘으로 미리 학습된 xml파일을 다운로드 받는다.

   향후에 실력이 붙으면 자기가 원하는 것을 인식할 수 있는 Haar파일을 만들 수도 있지만 

   지금은 만들어져 있는 파일을 사용하도록 하겠다.

   아래 링크에서 얼굴과 눈을 인식할 수 있는 파일만 다운로드 하겠다. (It's up to you~~)

   - 링크 : https://github.com/opencv/opencv/tree/master/data/haarcascades

     아래의 haarcascase_eye.xml 과 haarcascade_frontalface_default.xml 파일을 오른쪽 클릭 후 다른이름으로 링크 저장해서 

     하단의 예제소스와 같은 폴더상에 저장한다.

   


 5. 이제 python 코드를 한번 짜볼까?

    파일명은 아무렇게 지으면 되는데 본인은 detectFace.py 로 만들었다.

    혹시 사람몸을 인식하고자 하면 위에서 body 관련된놈을 다운받아서 xml 파일 읽어들이는 부분만 변경하면 되겠지....

## -*- coding: utf-8 -*-  # 한글 주석쓸려면 적기

import cv2

font = cv2.FONT_ITALIC

def faceDetect():
    eye_detect = False
    face_cascade = cv2.CascadeClassifier("./haarcascade_frontalface_default.xml")  # 얼굴찾기 haar 파일
    eye_cascade = cv2.CascadeClassifier("./haarcascade_eye.xml") # 눈찾기 haar 파일

    try:
        cam = cv2.VideoCapture(0)
    except:
        print("camera loading error")
        return

    while True:
        ret, frame = cam.read()
        if not ret:
            break

        if eye_detect:
            info = "Eye Detention ON"
        else:
            info = "Eye Detection OFF"

        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        faces = face_cascade.detectMultiScale(gray,1.3, 5)

        faces = face_cascade.detectMultiScale(gray, 1.3, 5)

        #카메라 영상 왼쪽위에 위에 셋팅된 info 의 내용 출력
        cv2.putText(frame, info, (5,15), font, 0.5, (255,0, 255),1)

        for(x,y, w,h) in faces:
            cv2.rectangle(frame, (x,y), (x+w, y+h), (255,0,0), 2)  #사각형 범위
            cv2.putText(frame, "Detected Face", (x-5, y-5), font, 0.5, (255,255,0),2)  #얼굴찾았다는 메시지
            if eye_detect:  #눈찾기
                roi_gray = gray[y:y+h, x:x+w]
                roi_color = frame[y:y+h, x:x+w]
                eyes = eye_cascade.detectMultiScale(roi_gray)
                for (ex,ey,ew,eh) in eyes:
                    cv2.rectangle(roi_color, (ex, ey), (ex+ew, ey+eh), (0,255,0), 2)

        cv2.imshow("frame", frame)
        k=cv2.waitKey(30)

        #실행 중 키보드 i 를 누르면 눈찾기를 on, off한다.
        if k == ord('i'):
            eye_detect = not eye_detect
        if k == 27:
            break
    cam.release()
    cv2.destroyAllWindows()

faceDetect()


위 파일을 실행시키면 아래와 같이 나온다. (이상하게 나온 인물을 이해해주기 바랍니다.^^)




만족하셨나요? ~~~~~~~


1. Tensorflow 처리의 기본과정 (전문가가 보면 이상한 부분도 있을 수 있음)

   1) Tensorflow는 먼저 가설(hypothesis)으로부터 시작한다..아래는 회귀(Linear Regression) 가설의 기본 식이다.

       


 ==> X에 대한 1차방정식으로 W(Weight, 기울기)와 b(bias,절편) 을 무한으로 변경하면서 비용이 최소값이 

       나오도록 하면 된다.

       위 공식은 tensorflow에서 y_model=tf.multiply(W, X) 으로 표현된다.

     

      위에서 언급된 비용함수는 Cost(W,b) 로 표현되고, 수식은 아래와 같다.

     

   <-- 미분  

       위 수식은 tensorflow에서 cost = tf.reduce_mean(tf.square(Y - y_model)) 로 표현된다.   (Y : 실측치, y_model : 예측치)


    결론 : 위 식에서 cost(비용)이 최소화가 되는 y_model을 찾는 것이다. (x와 b를 찾는 과정이다.)


2. 선행설치

   - 그래프를 그리기 위해 matplot라이브러리를 설치한다. : pip install matplotlib

   - 데이타를 tensor형태(1차원->2차원) 형태로 자유자재로 만들 수 있는 numpy를 설치한다. : pip install numpy

   - python을 편하게 실행하기 위해 jupyter notebook을 설치한다. : pip install jupyter

    


3. 예제소스 (python코드입력을 위해 command 창에서 jupyter notebook 입력-> 서버가 구동되면서 브라우저 창이 뜬다)

   : 미국 Portland, Oregon 집 크기에 따른 가격을 유추할 수 있는 단순회귀 예제임. 

   - 참고 : python 3.5 기준의 소스

import tensorflow as tf
import numpy
import matplotlib.pyplot as plt

# Train을 위한 data set 이다. 이것은 실제 발생한 데이타라고 보면 된다.

size_data = numpy.asarray([ 2104,  1600,  2400,  1416,  3000,  1985,  1534,  1427,
  1380,  1494,  1940,  2000,  1890,  4478,  1268,  2300,
  1320,  1236,  2609,  3031,  1767,  1888,  1604,  1962,
  3890,  1100,  1458,  2526,  2200,  2637,  1839,  1000,
  2040,  3137,  1811,  1437,  1239,  2132,  4215,  2162,
  1664,  2238,  2567,  1200,   852,  1852,  1203 ])
price_data = numpy.asarray([ 399900,  329900,  369000,  232000,  539900,  299900,  314900,  198999,
  212000,  242500,  239999,  347000,  329999,  699900,  259900,  449900,
  299900,  199900,  499998,  599000,  252900,  255000,  242900,  259900,
  573900,  249900,  464500,  469000,  475000,  299900,  349900,  169900,
  314900,  579900,  285900,  249900,  229900,  345000,  549000,  287000,
  368500,  329900,  314000,  299000,  179900,  299900,  239500 ])

# Test data set 
#이것은 위 데이타에 없는 다른 실제 발생한 값을 몇 개 추출하여 위에서 선형회귀로 만들어진 식에 테스트데이타를 대입해서 
#얼마나 오차가 발생하는지를 검증하기 위한 데이타셋이다.

size_data_test = numpy.asarray([ 1600, 1494, 1236, 1100, 3137, 2238 ])
price_data_test = numpy.asarray([ 329900, 242500, 199900, 249900, 579900, 329900 ])

#정규화식 함수 ==> 배열의 각 수에 평균을 뺀 후 표준편차로 나누어줌
def normalize(array): 
    return (array - array.mean()) / array.std()

# Normalize a data set
#데이터의 범위를 일치시키거나 분포를 유사하게 만들어 주는 등의 작업을 위해 데이타를 정규화한다.
size_data_n = normalize(size_data)
price_data_n = normalize(price_data)

#테스트 데이타를 정규화한다.
size_data_test_n = normalize(size_data_test)
price_data_test_n = normalize(price_data_test)

# Display a plot
#정규화한 값들을 그래프에 그려본다.
plt.plot(size_data, price_data, 'ro', label='Samples data')
plt.legend()
plt.draw()

samples_number = price_data_n.size

# TF graph input
X = tf.placeholder("float")
Y = tf.placeholder("float")

# Create a model

# Set model weights
# 위에 설명했던 Weight 과 bias  ==> 변경시킬값들을 선언한다.
W = tf.Variable(numpy.random.randn(), name="weight")
b = tf.Variable(numpy.random.randn(), name="bias")

# Set parameters
# learning_rate를 cost가 최소가 되는 점에 선을 그을때(기울기가 최소인 점을 찾는 과정) step간격을 어느정도 할것이냐 설정하는것이다.
# 너무크면 큼직하게 간격을 두고 선을 긋기 때문에 자칫 최소가 되는 지점을 지나칠 수가 있다.
# 그러나 너무 작으면 그만큼 촘촘하게 많이 체크해야하므로 시간도 많이 걸리고 학습횟수내에서 cost가 최저가 되는 지점에 도달할 수 없을 수도 있다.
# 그래서 정확도가 제대로 안나올 경우 이 값을 약간씩 조정해 줄 필요가 있다.
learning_rate = 0.1 
training_iteration = 200

# Construct a linear model
# 위에서 설명한 모델을 tensorflow 수식으로 표현
model = tf.add(tf.multiply(X, W), b)

# Minimize squared errors,   tensorflow에는 여러 optimizer 함수가 있는데 이후의 글에서 추가설명하도록 하겠다.
cost_function = tf.reduce_sum(tf.pow(model - Y, 2))/(2 * samples_number) #L2 loss   Cost함수
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost_function) #Gradient descent,  

# Initialize variables 
# 항상 초기화를 해주고 시작한다.
init = tf.global_variables_initializer()

# Launch a graph
with tf.Session() as sess:
    sess.run(init)

    display_step = 20
    # Fit all training data
    for iteration in range(training_iteration):
        for (x, y) in zip(size_data_n, price_data_n):
            sess.run(optimizer, feed_dict={X: x, Y: y})

        # Display logs per iteration step  위에 display_step을 20으로 했으니 20번째씩 학습했을때의 값을 찍어주는것이다.
        if iteration % display_step == 0:   
            print("Iteration:", '%04d' % (iteration + 1), "cost=", "{:.9f}".format(sess.run(cost_function, 
                  feed_dict={X:size_data_n, Y:price_data_n})),"W=", sess.run(W), "b=", sess.run(b))
                
    tuning_cost = sess.run(cost_function, feed_dict={X: normalize(size_data_n), Y: normalize(price_data_n)})            
    print ("Tuning completed:", "cost=", "{:.9f}".format(tuning_cost), "W=", sess.run(W), "b=", sess.run(b))
    
    # Validate a tuning model    
    ##위에서 학습 다 했으면 테스트데이타를 넣어 얼마나 정확한지 확인해본다.
    testing_cost = sess.run(cost_function, feed_dict={X: size_data_test_n, Y: price_data_test_n})    
    print("Testing data cost:" , testing_cost)
    
    # Display a plot
    plt.figure()
    plt.plot(size_data_n, price_data_n, 'ro', label='Normalized samples')
    plt.plot(size_data_test_n, price_data_test_n, 'go', label='Normalized testing samples')
    plt.plot(size_data_n, sess.run(W) * size_data_n + sess.run(b), label='Fitted line')
    plt.legend()
    
    plt.show() #실제 그래프를 보여준다.

-------------------------------------------------------------------------------------------------------------------------------------

실행결과

-------------------------------------------------------------------------------------------------------------------------------------



만족하셨나요? ~~~~~~~


1. 성공하는 설치환경 조합 

    : Anaconda는 사용하지 않음. Python3.5를 지원하는 Anaconda는 CUDA8.0까지만 지원하는것 같음. (가능한 사람은 설정건드려서 해보기 바람)

   1) OS : Windows 10

   2) Python3.5  (numpy는 1.14.3 사용)

   3) CUDA 9.0

   4) cuDNN v7.0

   5) Tensorflow 1.6

      - CPU로 돌리고 싶으면 설치시 pip install tensorflow 로 GPU로 돌리고 싶으면 pip install tensorflow-gpu 로 설치하면 됨

      - tensorflow 1.8로 설치해보니 계속 오류나고 그래서 1.6으로 다시 설치함.   

   6) 내 노트북은 Nvidia 그래픽카드를 MX150을 사용


2. 설치상세

   1) Python3.5 설치

      - 아래 링크를 클릭하여 Python 3.5 버전 적당한거 받아서 설치한다. (여기서는 D:\ML_Program\Python35 에 설치함)

        링크 : https://www.python.org/downloads/

 

    


  



    2) Python의 path를 잡아준다.

       - 내PC아이콘을 오른쪽 클릭해서 설정을 클릭한다.  ==> 왼쪽에 "고급시스템 설정" 클릭 ==> 고급탭 클릭 후 하단의 환경변수 클릭

         ==> 아래 시스템변수에 보면 PATH 라는게 있다. (더블클릭, 없으면 새로생성해서 PATH를 만들어라)

       - 아래의 3개를 추가한다.

          D:\ML_Program\Python35                 ==> 여기에 python.exe 가 있음.

          D:\ML_Program\Python35\Scripts      ==> 여기에 pip 등 여러 python 실행파일들이 있음.

          D:\ML_Program\Python35\Lib\venv\scripts\nt   ==> 여기에 tensorflow 환경을 activate, deactivate 하는 실행파일이 있음.


    3) CUDA9.0 설치

       - 링크를 클릭해서 CUDA 9.0을 다운로드 후 설치한다.   [다운로드링크]

         (Base 파일과 패치파일이 있는데 모두 다운로드해서 순서대로 설치하면 된다.)

       - 설치시 CUDA 의 Path는 자동으로 셋팅된다.

       


    4) CuDNN 설치

       : CuDNN은 다운로드 후 위에 CUDA설치(CUDA Toolkit 설치폴더)한 위치에 동일한 구조로 덮어쓰기로 복사하면 된다.

         CuDNN을 다운로드 받기 위해서는 먼저 회원가입을 해야한다. 회원가입 후 아래 다운로드를 클릭하자.


        [다운로드 링크]   

        

        



  

    5) Tensorflow 1.6 설치

       - windows의 cmd.exe를 연다.

       - 다음 명령어로 설치한다.


         pip install tensorflow-gpu==1.6     (CPU버전은 pip install tensorflow 라고 입력하면 됨)


     6) Tensorflow가 잘 작동하는지 간단히 테스트해본다.

        - windows의 cmd.exe 실행

        - python 실행 : 콘솔창에서 python 을 치면 python 프로그래밍 입력으로 전환된다.

        - 아래 명령어 입력 (tensorflow에서 hello라는 string을 출력하는 간단한 프로그램)

          

          import tensorflow as tf

          hello=tf.constant('hello')

          sess=tf.Session()

          print(sess.run(hello))


          결과 ==> b'hello'


      이렇게 하면 Tensorflow GPU는 설치완료



만족하셨나요? ~~~~~~~



CentOS7을 초기설치 후 한번은 전체 업데이트를 해준다.

이럴 때 yum update 명령을 치면 아래와 같이 메시지가 나와 당황할때가 있다.

One of the configured repositories failed (Inconnu),

and yum doesn't have enough cached data to continue. At this point the only
safe thing yum can do is fail. There are a few ways to work "fix" this:

     1. Contact the upstream for the repository and get them to fix the problem.

     2. Reconfigure the baseurl/etc. for the repository, to point to a working
        upstream. This is most often useful if you are using a newer
        distribution release than is supported by the repository (and the
        packages for the previous distribution release still work).

     3. Disable the repository, so yum won't use it by default. Yum will then
        just ignore the repository until you permanently enable it again or use
        --enablerepo for temporary usage:

            yum-config-manager --disable <repoid>

     4. Configure the failing repository to be skipped, if it is unavailable.
        Note that yum will try to contact the repo. when it runs most commands,
        so will have to try and fail each time (and thus. yum will be be much
        slower). If it is a very temporary problem though, this is often a nice
        compromise:

            yum-config-manager --save --setopt=<repoid>.skip_if_unavailable=true

Cannot find a valid baseurl for repo: base/7/x86_64



* 해결방법

: 아래와 같이 명령어를 한번만 입력하고 다시 yum update를 하면 정상적으로 처리된다.

  잠깐 설명하면 아래와 같이 입력하면 자동으로 알아서 DNS를 설정해주는 명령어이다.


> dhclient       


만족하셨나요? ~~~~~~~


+ Recent posts