Loop 문법과 속도



필자는 ArrayList를 즐겨쓰기 때문에 for문을 어떻게 쓰건 거의 상관없지만

LinkedList를 쓴다면 for문에 따라 속도영향이 있다.



0. list가 다음과 같이 있다고 가정

List<Integer> linkedList = new LinkedList<>();

List<Integer> arrayList = new ArrayList<>();


for (int i = 0; i < 100000; i++) {

linkedList.add(i);

arrayList.add(i);

}



1. 기본 3항 for문: 'for ( ;  ; )'

for (int i = 0; i < list.size(); i++) {

Integer value = list.get(i);

}

- 시간: 5382ms (arraylist의 경우: 4ms)



2. for each문: 'for (a : A)'

for (Integer value : list) {

}

- 시간: 2ms (arraylist의 경우: 4ms)

- JAVA 5에서 추가됨



3. while + iterator 문: 'while (iterator.hasNext())'

Iterator<Integer> iterator = list.iterator();


while (iterator.hasNext()) {

Integer value = iterator.next();

}

- 시간: 3ms (arraylist의 경우: 3ms)



4. 'forEach()' 문

list.forEach((value) -> {

});

- 시간: 42ms (arraylist의 경우: 46ms)

JAVA 8에서 추가됨

- 조금느릴 수 있지만 Parallel을 지원한다.



5. 결론

- linkedList의 경우: for-each문, while + iterator 문 이 빠르다.

- arrayList의 경우: 크게 차이없다.



위 내용에 대한 코드는 github에서 확인하실 수 있습니다.

https://github.com/ndukwon/Duk_Java_library/blob/master/src/com/duk/lab/java/FundamentalTest.java



Reference:

- https://dzone.com/articles/devoxx-2012-java-8-lambda-and


'Program Languages > Java' 카테고리의 다른 글

Custom Annotation 만들기  (0) 2017.06.26

객체지향 프로그래밍 (Object Oriented Programming) 의 특징



1. 캡슐화(Encapsulation)

- 은닉화(data hiding)를 포함하는 개념

- data를 private으로 하고 외부에서는 Method에 의한 접근만 허용하는 것

The idea of encapsulation is to keep classes separated and prevent them from having tightly coupled with each other.

- 강한 커플링을 방지하여 분리된 class로 두기 위함 -> 추후 변화에 대한 유연성

- 실사용 예: Hash table



2. 상속(Inheritance)

Inheritance is the mechanism by which an object acquires the some/all properties of another object.

- 다른 객체의 속성이나 기능을 물려받는 개념

- 계층적 구조



3. 다형성(Polymorphism)

Polymorphism is the capability of a method to do different things based on the object that it is acting upon. In other words, polymorphism allows you define one interface and have multiple implementations.

- 하나의 Method(같은이름)의 기능을 다양하게 할 수 있다.

- Overloading을 통해 method의 static 다형성을 지원

- Overriding을 통해 상위 method의 dynamic 다형성을 지원



4. 추상화(Abstraction)

- 유사한 클래스의 공통점을 묶어 하나의 추상클래스로 만드는 것



Reference:

- https://stackify.com/oops-concepts-in-java/

- https://www.tutorialspoint.com/java/java_encapsulation.htm

- http://beginnersbook.com/2013/03/oops-in-java-encapsulation-inheritance-polymorphism-abstraction/



'Program Languages' 카테고리의 다른 글

언어별 표기법들  (0) 2017.02.24

Quick sort(퀵 정렬)



원칙1: pivot을 고른다.(주로 첫번째 또는 마지막 값을 선정하는 편이다.)

원칙2: pivot값을 기준으로 작은쪽, 큰쪽으로 나누어 서로간의 swap으로 위치를 교환한다.(증가될 수 없는 배열이라고 가정....)

원칙3: swap이 끝나면 그 나눈 중심에 pivot을 두고 작은쪽, 큰쪽을 각각 퀵소트한다.



Best case: O(n

Average case: O()

Worst case: O() 


# 재귀함수로 구현한 Quick sort

public class QuickSort implements ISort {


    @Override

    public void sort(Comparable[] array) {

        quickSort(array, 0, array.length - 1);

    }


    private void quickSort(Comparable[] array, int startIndex, int endIndex) {

        if (startIndex >= endIndex) {

            return;

        }


        final Comparable pivot = array[startIndex];

        int left = startIndex + 1;

        int right = endIndex;


        do {

            while (array[left].compareTo(pivot) < 0 && left < endIndex) {

                left++;

            }

            while (array[right].compareTo(pivot) > 0 && startIndex < right) {

                right--;

            }


            if (left < right) {

                swap(array, left, right);

            }


        } while (left < right && left < endIndex && startIndex < right);

        swap(array, startIndex, right);


        quickSort(array, startIndex, right - 1);

        quickSort(array, right + 1, endIndex);

    }


    private void swap(Comparable[] array, int i, int j) {

        Comparable temp = array[i];

        array[i] = array[j];

        array[j] = temp;

    }

}


Reference:

- https://en.wikipedia.org/wiki/Quicksort


'Algorithms > Sorting' 카테고리의 다른 글

Merge sort(병합 정렬)  (0) 2017.02.08
Selection sort(선택 정렬)  (0) 2017.02.08
Insertion sort(삽입 정렬)  (0) 2017.02.06
Bubble sort(거품? 정렬)  (0) 2017.02.06

Process와 Thread의 비교


1. 개념이 다르다: Process는 Thread의 상위개념이다.


- Process가 생성된다는 것은 1개의 Process와 그 안에 1개의 Thread 가 생성되는 것.

- Multithreaded process는 이 안에 Thread가 여러개 생성될 수 있다는 것.

- 따라서 차이는 Single Thread process와 Multi Thread process를 비교하는 것이 효과적이다.



2. Memory 구성의 차이

출처: https://randu.org/tutorials/threads/

- Process는 개별적 Kernel, Code, Data, Heap, Stack 영역을 가지고 있다.

   대부분의 OS에서 Inter-Process Communication(IPC혹은 RPC)을 지원하여 Shared memory를 통해서 Process간의 제한적인 공유가 가능하다.

- Thread는 개별적 Stack, Register, PC등을 가지고 있다. 나머지는 Process의 것을 공유한다.



2-1. Process Memory 구성(Linux)


Kernel space: Kernel을 위한 영역으로 물리주소와의 매핑하며 언제든지 Switching이 일어날 수 있도록 준비하는 영역이다.

   user mode로는 접근할 수 없는 영역, 보통 설명시 생략된다.

Text(Code) Segment: 실행하는 코드를 저장하는 영역(bin을 올린다.)

- Data, BSS Segment: 전역변수/상수 등을 저장, 보통 통틀어 Data영역으로 부른다.

   구분하자면  Data - 초기화된 변수들, BSS - 초기화되지 않은 변수들

Heap: 동적할당된 부분 저장

Stack: ??  UNIX는 각 Thread의 stack을 여기에 할당해주는 것으로 보임.



2-2. Thread Memory 구성(POSIX)

Stack: Thread만의 지역변수, 매개변수, 리턴값을 저장.

  Windows - Virtual Memory에 할당

  UNIX - Process stack에 할당

  LINUX - ?? 커널이 할당해줌

Stack pointer

Program Counter(PC)

Registers: ?? CPU에 등록되는 그 레지스터를 의미하는지 잘 모르겠음

- 나머지는 Process 자원을 공용



2. 실행의 차이

- 기본적으로 OS는 Process단위로 스케줄링을 한다.

   따라서 User Level Thread(ULT)들은 Process가 block되면 모두 block된다.

- Kernel Level Thread(KLT)의 경우는 ULT보다 비용은 비싸지만 독립적 실행이 가능하다.

  따라서 Kernel-supported-threads 혹은 lightweight process라고 부르기도 한다.



3. Process보다 Thread를 쓰는 장점

- Process를 만들고 종료하는 것보다 Thread로 하는 것이 더 빠르다.

- Thread가 Context switching이 빠르다.

- IPC 통신을 하지 않아도 된다.

- 자원의 효율적 사용



3-1. Thread를 써서 장점을 보는 예

- 화면과 Background를 나누어 실행

- 주기적 백업 실행

- 파일을 나누어 읽기



4. Thread보다 Process를 쓰는 장점(Thread 단점)

- Thread를 많이 생성하면 오히려 저하가 일어날 수 있다.

- Single processer에서는 효과를 기대하기 어렵다.

- Thread는 디버깅이 어렵다.



Reference:

- Operating Systems Internals and Design Principles - William Stallings

- http://duartes.org/gustavo/blog/post/anatomy-of-a-program-in-memory/

- https://computing.llnl.gov/tutorials/pthreads/

- https://randu.org/tutorials/threads/

- https://www.tutorialspoint.com/operating_system/os_multi_threading.htm

- http://sfixer.tistory.com/entry/%EB%A9%94%EB%AA%A8%EB%A6%AC-%EC%98%81%EC%97%ADcode-data-stack-heap

- http://lalwr.blogspot.kr/2016/02/process-thread.html

Singleton pattern : getInstance()


1. 기본 개념과 형식

public class Singleton {


    private Singleton() {

    }


    private static Singleton sInstance;

    public static Singleton getInstance() {

        if (sInstance == null) {

            sInstance = new Singleton();

        }


        return sInstance;

    }

}

- 어디든 누구든 getInstance() 를 호출하면 항상 같은 Instance를 줘야 한다는 개념이다.

- getter의 명칭 또한 똑같이 쓰기 때문에 구현방식에 대한 포멧같은 느낌



2. 동기화 문제

- 위 코드는 멀티 Thread 상황에서 A Thread가 instance 생성하고 저장하지 않은 시점에 B Thread가 생성하고 저장하고 나갈 수 있는 경우가 생긴다.

  이를 해결하는 방안으로

1) Synchronized를 method에 걸어서 해결

2) static block으로 생성하여 해결

3) Lazy Holder class 이용하여 해결

4) Enum class 로 만들어 해결

  이 있다.



2-1. Synchronized를 method에 걸어서 해결

public class Singleton {


    private Singleton() {

    }


    private static Singleton sInstanceSync;

    public static synchronized Singleton getInstanceSync() {

        if (sInstanceSync == null) {

            sInstanceSync = new Singleton();

        }


        return sInstanceSync;

    }

}

- (차이설명을 위해 명칭을 변경함)

- 말 그대로 synchronized를 걸면 된다.

- 장점: Lazy initialize 가능, Thread safe

- 단점: synchronized의 비용이 비싸다. 즉, 매번 오래걸린다.



2-2. static block으로 생성하여 해결

public class Singleton {


    private Singleton() {

    }


    private static final Singleton STATIC_INSTANCE = new Singleton();

    public static Singleton getInstanceStatic() {

        return STATIC_INSTANCE;

    }

}

- class load되는 시점에 static이 실행되며 객체도 생성된다.

- 장점: Thread safe

- 단점: 필요한 상황에 만들어지는 것은 아니다. 즉, 미리 만들어져 있다.



2-3. Lazy Holder class 이용하여 해결 (좀 더 정확한 명칭은 Initialization-on-demand holder idiom)

public class Singleton {


    private Singleton() {

    }


    private static class LazyHolder {

        public static final Singleton INSTANCE = new Singleton();

    }

    

    public static Singleton getInstanceLazyHolder() {

        return LazyHolder.INSTANCE;

    }

}

- static block과 유사하지만 내부 클래스가 로딩되는 시점에 static이 실행된다.

- 장점: Lazy initialize 가능, Thread safe

- 많이 쓰는 편이라고 한다.



2-4. Enum class 로 만들어 해결

public enum SingletonEnum {

    INSTANCE;

    

    // TODO: your methods

}

- Enum에 메소드를 다는 방식

- 장점: Lazy initialize 가능, Thread safe

- Effective Java 2/E에 나온 방법



3. Singleton instance를 Reflection으로 생성한다면 이 모든 노력은 무용지물

- private 으로 생성자를 막아도 생성이 가능하기 때문




이 내용에 대한 코드는 Github에서도 확인하실 수 있습니다.

https://github.com/ndukwon/Duk_Java_library/tree/master/src/com/duk/lab/java/pattern



Reference

http://jusungpark.tistory.com/16

- https://blog.seotory.com/post/2016/03/java-singleton-pattern

- http://changsuk.me/?p=1433

- https://en.wikipedia.org/wiki/Initialization-on-demand_holder_idiom




TensorFlow 예제 따라하기(lab 3)


Linear Regression: H(x) = Wx + b 계속...


1. W에 따른 cost의 추이를 그래프로 표현하기

# TensorFlow 불러오기

import tensorflow as tf


# Matplotlib 불러오기

import matplotlib

Matplotlib backend 설정

matplotlib.use('TkAgg')

import matplotlib.pyplot as plt


X = [1, 2, 3]

Y = [1, 2, 3]


W = tf.placeholder(tf.float32)


# H(x) = Wx

hypothesis = X * W


# Cost: 1/m * ∑(H(x) - y)^2

cost = tf.reduce_mean(tf.square(hypothesis - Y))


# Session 생성

sess = tf.Session()


# Global variable 초기화

sess.run(tf.global_variables_initializer())

W_val = []

cost_val = []


# -3 ~ 5 까지 W(기울기)를 0.1씩 바꿔보면서 W에 따른 cost 값을 구한다

for i in range(-30, 50):

    feed_W = i * 0.1

    curr_cost, curr_W = sess.run([cost, W], feed_dict={W: feed_W})

    W_val.append(curr_W)

    cost_val.append(curr_cost)


# matplotlib으로 표현하기

plt.plot(W_val, cost_val)

plt.show()

- 결과:


2. GradientDescentOptimizer를 직접 구현하기

  Before


  # Gradient Descent Magic

 optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.1)

 train = optimizer.minimize(cost)


  After

# Gradient Descent 구현

# 한번 학습을 반영하는 비율
learning_rate = 0.1

# Cost의 미분(cost의 기울기)
gradient = tf.reduce_mean((W * X - Y) * X)

# 학습된 W(linear 함수의 기울기)를 반영
descent = W - learning_rate * gradient
train = W.assign(descent)




3. W값을 지정하여 학습시키기

 Before


 # W 초기 랜덤값 적용

 W = tf.Variable(tf.random_normal([1]), name="weight") 


 After


 # W 초기값을 지정하여 수행


 # W = tf.Variable(5.0)

 W = tf.Variable(-3.0)




4. Gradient 값 수정하기

 Before


  # Gradient Descent Magic

 optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.1)

 train = optimizer.minimize(cost)


 After

 # Gradient 계산값 구하여 수동 적용


 gvs = optimizer.compute_gradients(cost)

 # TODO: gvs 수정

 train = optimizer.apply_gradients(gvs)




# gradient를 계산한 값 구해서 적용하기(compute_gradient, apply_gradient)

# Loading TensorFlow
import tensorflow as tf

x_data = [1, 2, 3]
y_data = [1, 2, 3]

# W = tf.Variable(5.0)
W = tf.Variable(-3.0)
X = tf.placeholder(tf.float32)
Y = tf.placeholder(tf.float32)

# H(x) = Wx
hypothesis = X * W

# Cost: 1/m * ∑(H(x) - y)^2
cost = tf.reduce_mean(tf.square(hypothesis - Y))
gradient = tf.reduce_mean(((W * X - Y) * X) * 2)

# Gradient Descent Magic
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.1)

# Gradient 계산값 구하여 수동 적용
# train = optimizer.minimize(cost)
gvs = optimizer.compute_gradients(cost)
# TODO: gvs 수정
train = optimizer.apply_gradients(gvs)

# Session 생성
sess = tf.Session()

# Global variable 초기화
sess.run(tf.global_variables_initializer())

for step in range(10):
print(step, sess.run([gradient, W, gvs], feed_dict={X: x_data, Y: y_data}))
sess.run(train, feed_dict={X: x_data, Y: y_data})

'''
Result
0 [-37.333332, -3.0, [(-37.333336, -3.0)]]
1 [-2.4888866, 0.73333359, [(-2.4888866, 0.73333359)]]
2 [-0.1659257, 0.98222226, [(-0.16592571, 0.98222226)]]
3 [-0.011061668, 0.99881482, [(-0.011061668, 0.99881482)]]
4 [-0.00073742867, 0.99992096, [(-0.00073742867, 0.99992096)]]
5 [-4.9630802e-05, 0.9999947, [(-4.9630802e-05, 0.9999947)]]
6 [-3.0994415e-06, 0.99999964, [(-3.0994415e-06, 0.99999964)]]
7 [-6.7551929e-07, 0.99999994, [(-6.7551935e-07, 0.99999994)]]
8 [0.0, 1.0, [(0.0, 1.0)]]
9 [0.0, 1.0, [(0.0, 1.0)]]
'''



# 여기의 모든 소스는 github에... -> https://github.com/ndukwon/learning_TensorFlow



Reference

- https://www.youtube.com/watch?v=Y0EF9VqRuEA&feature=youtu.be

'Machine Learning > TensorFlow' 카테고리의 다른 글

TensorFlow 예제 따라하기(lab 1 ~ 2)  (0) 2017.06.12
TensorFlow의 시작과 설치  (0) 2017.06.07

virtualenv에 matplotlib 설치하기(MAC OS)


1단계: virtualenv로 가서 pip 명령을 이용해 설치한다.

$ source [설치한 경로]/bin/activate

(설치폴더이름) $ pip3 install matplotlib

이렇게 하면 알아서 depentent library도 설치해가며 완료가 된다.



2단계: import matplotlib as plt 해도 에러가 난다.

Traceback (most recent call last):

  File "/Users/[user]/workspace/learning_TensorFlow/cpu_python3/learning_lab3_1.py", line 3, in <module>

    import matplotlib.pyplot as plt

  File "/Users/[user]/tf_py_3/lib/python3.6/site-packages/matplotlib/pyplot.py", line 115, in <module>

    _backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup()

  File "/Users/[user]/tf_py_3/lib/python3.6/site-packages/matplotlib/backends/__init__.py", line 32, in pylab_setup

    globals(),locals(),[backend_name],0)

  File "/Users/[user]/tf_py_3/lib/python3.6/site-packages/matplotlib/backends/backend_macosx.py", line 19, in <module>

    from matplotlib.backends import _macosx

RuntimeError: Python is not installed as a framework. The Mac OS X backend will not be able to function correctly if Python is not installed as a framework. See the Python documentation for more information on installing Python as a framework on Mac OS X. Please either reinstall Python as a framework, or try one of the other backends. If you are using (Ana)Conda please install python.app and replace the use of 'python' with 'pythonw'. See 'Working with Matplotlib on OSX' in the Matplotlib FAQ for more information.

설치를 했는데 이건 또 뭔가...

이건 https://github.com/dsmbgu8/image_annotate.py/issues/4 에 잘 나와있다.

3단계에서 해결해보자.



3단계: matplotlib의 backend를 변경해준다.

1) 스크립트 상에서

import matplotlib

matplotlib.use('TkAgg')

import matplotlib.pyplot as plt


2) virtualenv bash 상에서

(설치폴더이름) $ echo "backend: TkAgg" >> ~/.matplotlib/matplotlibrc



4단계: matplotlib의 backend가 뭐길래...

- Graph등을 그릴때 Python을 실행하는 환경에 대한 지원을 해주는 부분이고 이것을 입맛대로 골라서 쓰면된다.

  설명대로라면 어떤이는 콘솔에서 띄우고 싶고, 어떤이는 툴에서 띄우고 싶고, 어떤이는 서버에서 띄우고...

  이런 다양한 환경을 지원하는 것이 "backend" 라고 한단다.

- 다양한 backend는 https://matplotlib.org/faq/usage_faq.html 에서 확인할 수 있다.



Reference

- https://github.com/dsmbgu8/image_annotate.py/issues/4

- https://stackoverflow.com/questions/29433824/unable-to-import-matplotlib-pyplot-as-plt-in-virtualenv

- https://matplotlib.org/faq/usage_faq.html

bash 명령어로 설치한 virtualenv 독립환경 Pycharm과 연결시키기


두가지 방법이 있다.

1. Pycharm으로 virtualenv 독립환경을 생성

2. 이미 만들어진 virtualenv 독립환경을 Pycharm으로 가져오기


1번은 당연하고

2번도 당연하지만 필자에겐 생소해서 정리해 본다.


# Pycharm > Preference > Project:your_project > Project Interpreter > 원하는 Interpreter를 선택



끝.

TensorFlow 예제 따라하기


1. TensorFlow 실행 및 버전 체크

# virtualenv에서 Python3 실행

$ source ~tf_py_3/bin/activate

(tf_py_3) $ python

Python 3.6.0 (v3.6.0:41df79263a11, Dec 22 2016, 17:23:13) 

[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin

Type "help", "copyright", "credits" or "license" for more information.

>>> 


# TensorFlow 실행

>>> import tensorflow as tf


# Version 확인

>>> tf.__version__

'1.1.0'

>>>



2. TensorFlow로 "Hello TensorFlow!" 찍기

# 상수의  Default node 선언

>>> hellotensorflow = tf.constant("Hello TensorFlow!")


# Session을 생성

>>> sess = tf.Session()


# Python Print 명령으로 출력

>>> print(sess.run(hellotensorflow))

b'Hello, TensorFlow'


# Session 닫기

>>> sess.close()

- Session을 여는 이유: Session은 계산(Operation) / 평가(Evaluate)을 할 수 있는 객체이다.

- b 라는 문자가 찍히는 이유: Byte 문자형이라는 표현임



3. TensorFlow로 3.0 + 4.0 계산해보기(이후 Pycharm  editor 사용)

node1 = tf.constant(3.0, tf.float32)

node2 = tf.constant(4.0) # 암시적으로 tf.float32으로 설정된다

node3 = tf.add(node1, node2)


# Tensor 객체의 정보를 찍는다.

print("node1=", node1, "node2=", node2)

print("node3=", node3)

# node1= Tensor("Const_1:0", shape=(), dtype=float32) node2= Tensor("Const_2:0", shape=(), dtype=float32)

# node3= Tensor("Add:0", shape=(), dtype=float32)


sess = tf.Session()

print("sess.run([node1, node2])=", sess.run([node1, node2]))

print("sess.run(node3)=", sess.run(node3))

sess.close()

# sess.run([node1, node2])= [3.0, 4.0]

# sess.run(node3)= 7.0



4. 3번을 실행시 값 대입하도록 변경

a = tf.placeholder(tf.float32)

b = tf.placeholder(tf.float32)

adder_node = a + b # tf.add(a, b) 와 같다


sess = tf.Session()

print(sess.run(adder_node, feed_dict={a: 3, b: 4.5}))

print(sess.run(adder_node, feed_dict={a: [1, 3], b: [2, 4]}))

sess.close()

# 7.5

# [ 3. 7.]



5. Linear Regression: H(x) = Wx + b

# TensorFlow 실행

import tensorflow as tf


# train 값 사전 정의

x_train = [1, 2, 3]

y_train = [1, 2, 3]


# 가설: H(x) = Wx + b

W = tf.Variable(tf.random_normal([1]), name='weight')

b = tf.Variable(tf.random_normal([1]), name='bias')

hypothesis = x_train * W + b


# Cost: 1/m * H(x)

cost = tf.reduce_mean(tf.square(hypothesis - y_train))

optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01)

train = optimizer.minimize(cost)


sess = tf.Session()

sess.run(tf.global_variables_initializer())


for step in range(2001):

    sess.run(train)

    if step % 20 == 0:

        print(step, sess.run(cost), sess.run(W), sess.run(b))



6. 5번의 학습 데이터를 실행시 대입하도록 변경

# TensorFlow 실행

import tensorflow as tf


# train 할 값 나중에 정의

# shape=[None] : 여러개가 될 수 도 있다.

X = tf.placeholder(tf.float32, shape=[None])

Y = tf.placeholder(tf.float32, shape=[None])


# 가설: H(x) = Wx + b

W = tf.Variable(tf.random_normal([1]), name='weight')

b = tf.Variable(tf.random_normal([1]), name='bias')

hypothesis = X * W + b


# Cost: 1/m * H(x)

cost = tf.reduce_mean(tf.square(hypothesis - Y))


optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01)

train = optimizer.minimize(cost)


sess = tf.Session()

sess.run(tf.global_variables_initializer())


for step in range(2001):

    cost_val, W_val, b_val, _ = sess.run([cost, W, b, train], feed_dict={X: [1, 2, 3], Y: [1, 2, 3]})

    if step % 20 == 0:

        print(step, cost_val, W_val, b_val)



# 여기의 모든 소스는 github에... -> https://github.com/ndukwon/learning_TensorFlow



Reference

- https://www.youtube.com/watch?v=-57Ne86Ia8w&feature=youtu.be

- https://www.youtube.com/watch?v=mQGwjrStQgg&feature=youtu.be

- https://www.tensorflow.org/api_docs/python/tf/Session

'Machine Learning > TensorFlow' 카테고리의 다른 글

TensorFlow 예제 따라하기(lab 3)  (0) 2017.06.20
TensorFlow의 시작과 설치  (0) 2017.06.07

TensorFlow의 시작과 설치


1. TensorFlow란 무엇인가

- 머신러닝 라이브러리(오픈소스)

- 공식사이트: https://www.tensorflow.org/


2. TensorFlow를 위해 알아두어야 할 것

- TensorFlow는 CPU / GPU 버전 두개가 있고 말 그대로 CPU / GPU를 사용하는데 GPU는 NVIDIA CUDA GPU만 가능하다.

- Python을 독립적으로 동작시킬 가상화 Container 설치

- 가상화 환경에 Python 설치

- 가상화 환경에 TensorFlow 설치


2-1. 가상화(독립) 환경 설치(Mac OS 기준)

- 이유: Python은 R언어와 유사하게 라이브러리를 설치하고 로드한다고 한다. 이렇게 설치되고 로드된 라이브러리들이 서로 영향을 끼칠 수 있다고 하니 분리해야 한다.

- TensorFlow에서 지원하는 가상화 수단:

  1) virtualenv: TensorFlow에서 추천하는 수단. Python의 공식 가상화 Container이다.

  2) "native" pip: pip="Python Package Index" 라는 뜻이고 Mac에는 기본적으로 Python이 설치되어 있다. 이를 native라고 칭하고 있으며 이를 바로 사용한다면 가상화 환경을 설치하는 의미가 없겠다.

  3) Docker: virtualenv와 유사하지만 TensorFlow 가 완전히 설치된 이미지를 설치해야 해서 용량이 크고 mac에서는 CPU 버전 이미지만 있는 단점이 있다.

  4) Anaconda: 커뮤니티 버전은 있으나 공식적인 지원은 하지 않고 있다.



이 정도만 알면 이제 공식사이트를 읽으며 설치를 해도 무리가 없을 것이니 따라서 설치해보자.



필자는 2-1에서 mac 의 환경이고 virtualenv를 선택했다.


2-1. virtualenv 설치

$ sudo easy_install pip
$ sudo pip install --upgrade


2-2. 가상화 환경에 Python 설치

// Python 2.7

$ virtualenv --system-site-packages tf_py_2.7

$ source ~/tf_py_2.7/bin/activate

(tf_py_2.7) $


// Python 3.x

$ virtualenv --system-site-packages -p python3 tf_py_3

$ source ~/tf_py_3/bin/activate

(tf_py_3) $

- virtualenv의 방식은 원하는 Python 가상화 환경을 가져오는 것이고 tf_py_2.7 / tf_py_3 는 폴더명이다.

  폴더 안에서 관리된다고 보면 되고 폴더를 삭제하는것도 이 환경을 삭제하는 방법이다.

- 가상화tool을 이용하는 것은 명령어 앞에 접두어 virtualenv가 온다고 보면 되며 실행하는동안 앞에 폴더명이 나온다.


2-3. 가상화 환경에 TensorFlow 설치

// Python 2.7

(tf_py_2.7) $ pip install --upgrade tensorflow


// Python 3.x

(tf_py_3) $ pip3 install --upgrade tensorflow


 끝.



Reference

- https://www.tensorflow.org/install/install_mac

- http://hunkim.github.io/ml/

'Machine Learning > TensorFlow' 카테고리의 다른 글

TensorFlow 예제 따라하기(lab 3)  (0) 2017.06.20
TensorFlow 예제 따라하기(lab 1 ~ 2)  (0) 2017.06.12

+ Recent posts