본문 바로가기

머신러닝&딥러닝

머신러닝 #2 파이썬

1. Python의 Data Type

list - 다른 언어의 array와 비슷한 성질을 가짐 / (-) 인덱스도 지원
  // a = [10, 20, 30, 40, 50]  -->  a[0] == a[-5] == 10
     - 서로 다른 데이터타입을 가질 수 있음
  // b = [10, 20, "Hello", [True, 3.14]] 
     - append() : 리스트에 원소를 추가  // c=[] c.append(100)
     - 슬라이싱 : 콜론( : )을 이용하여 리스트의 범위를 지정해주는 방식 ... 부분 리스트를 얻을 수 있음!!
  // a[ : 2] == [10, 20]
tuple - list와 비슷한 성질을 가짐 (슬라이싱, 인덱스 기능)
  // a = (10, 20, 30, 40, 50)
        - 튜플 내의 한번 지정된 원소는 값을 변경할 수 없음  // a[0] = 100 --> error 발생
dictionary - (key, value)를 한 쌍으로 데이터를 저장하는 자료구조, hash/map과 비슷한 구조
  // score = {"KIM" : 90, "LEE" : 85, "JUN" : 95}  # dictionary 생성
  // score['HAN'] = 100  # 새 원소 추가
  // score key|value|items == score.keys()|values()|items() == dict_keys([])|_values([])|_items([]) # 원소 검색
string - '' " 를 사용하여 생성
         - split() : 문자열을 분리하여 list로 반환
  // a = 'A73, CD',  a = a+', EFG'  # 문자열 생성, 추가
  // b = a.split(',')  -> b = ['A75', 'CD', 'EFG']  # split()

  ※ 기타 함수들

type() data type을 반환
len() data 요소의 개수를 반환
size() data 내 모든 원소를 반환
list() data type을 list로 변경
str() data type을 string으로 변환
int() data type을 문자열(숫자)/소수점을 정수로 반환

 

2. if / for / while 문

  ▷ 조건문 - if
   1) if condition:

a = 1

print("a ==", a)
if a > 0:
    print("positive")
elif a == 0:
	print("zero")
else:
	print("negative")

   2) if condition in list/dictionary:

list_data = [ 10, 20, 30, 40, 50 ]
dict_data = { 'key1' : 1, 'key2' : 2 }

if 45 in list_data:
	print("45 is in list_data")
else:
	print("45 is not in list_data")
    
if 'key1' in dict_data:
	print("key1 is in dict_data")
else:
	print("key1 is not in dict_data)

 

 ▷ 반복문 - for
   1) for variable in range(...):

for data in range(10):  # data라는 변수에 0부터 10까지 1씩 증가하여 대입
	print(data, " ", end='')  # end='' : 같은 줄에 출력
    
for data in range(0, 10):  # data라는 변수에 5부터 10까지 1씩 증가하여 대입
	print(data, " ", end='') 
    
for data in range(0, 10, 2)  # data라는 변수에 0부터 10까지 2씩 증가하여 대입
	print(data, " ", end='')


    2) for variable in list/dictionary:

list_data = [10, 20, 30, 40, 50]
dict_data = { 'key1' : 1, 'key2' : 2 }

for data in list_data:
	print(data, " ", end='')
    
for data in dict_data:
	print(data, " ", end='')
    
for key, value in dict_data.items():
	print(key, "", value)

    3) List Comprehension
      리스트의 요소들을 for 반복문을 사용하여 정의하는 방법

list_data = [ x**2 for x in range(5) ]
print(list_data)  # [ 0, 1, 4, 9, 16 ]

raw_data = [ [1, 10], [2, 15], [3, 30], [4, 55] ]

all_data = [ x for x in raw_data ]
x_data = [ x[0] for x in raw_data ]  # [1, 2, 3, 4]
y_data = [ x[1] for x in raw_data ]  # [10, 15, 30, 55]

 ▷ 반복문 - while, break, continue

data = 5

while data >= 0:
	print("data ==", data)
    data -= 1
    
    if data == 2:
    	print("break here")
        break
    else:
    	print("continue here")
        continue


3. 함수와 람다 (function & lambda)

○ 함수의 정의와 return 값
       - Python에서의 함수는 입력값에 data type이 정의되지 않음 -> 다양한 타입의 data를 입력받을 수 O
       - Python 함수는 1개 이상의 return 값을 반환할 수 있음

def multi_ret_func(x):
	return x+1, x+2, x+3   # return (x+1, x+2, x+3)
    
x = 100
y1, y2, y3 = multi_ret_func(x)

print(y1, y2, y3)

○ default parameter & mutable/immutable parameter
  default parameter - 함수 호출시 입력 parameter가 명시적인 값을 전달받지 못했을 경우 기본으로 지정한 값을 사용

def print_name(name, count=2):  # count의 default값 = 2로 설정
	for i in range(count):
    	print("name ==", name)
        
print_name("Dave")
print_name("Dave", 5)

  mutable / immutable parameter - 입력 변수가 mutable 타입(list, dictionary, numpy 등)일 경우 함수 내에서 data가 변할 수 있음 / immutable 타입(숫자, 문자, tuple 등)일 경우 함수 내에서 data가 변하지 않음

def mut_func(input_x, input_list):
	input_x += 1
    input_list.append(100)
    
x = 1
test_list = [1, 2, 3]

mut_func(x, test_list)

print("x == ", x, ", test_list == ", test_list)
# x == 1, test_list == [1, 2, 3, 100]

○ Lambda
 - 한줄로 함수를 작성하는 방법, anonymous(익명) 함수 / lambda expression 등으로 불림
 - 머신러닝에서 수치미분, 활성화함수 등을 표현할 때 많이 사용
 - 함수명 = lambda par1, par2, ..., : 대체되는 표현식

f = lambda x : x**2

for i in range(5):
	print(f(i))
    
# 0 1 4 9 16

 

4. Class, Exception, With 구문

  ○ Class
    Python 클래스는 class 키워드를 이용하여 자신만의 data type을 만들 수 있다
    생성자(__init__ 메서드)가 존재 --> 인스턴스 생성시 한 번만 호출된다
    멤버 메서드는 첫 번째 인수로 '자신의 인스턴스'를 나타내는 self를 반드시 포함한다
    기본적으로 Python에서 method와 attribution은 모두 public이다

class 클래스명:
    def __init__(self, 인수, ...): #생성자
    def method1(self, 인수, ...): #메서드
class Person:
	def __init__(self, name): #생성자
		self.name = name
		print(self.name + " is initialized")
	def work(self, company): #메서드1
		print(self.name + " is working in " + company)
	def sleep(self): #메서드2
		print(self.name + " is sleeping")

# Person 인스턴스 생성
obj = Person("Mike")

# method call
obj.work("ABC University")
obj.sleep()

# 속성에 직접 접근(public)
print("current person object is ", obj.name)

# Mike is initialized
# Mike is working in ABC University
# Mike is sleeping
# current person object is Mike)

  class variable(클래스 변수) : 해당 클래스로 생성된 모든 인스턴스가 공유하는 변수
  --> 클래스명.클래스 변수명으로 접근 가능

  class method(클래스 메서드) : class variable을 인수로 받는 메서드로 반드시 앞에 @classmethod를 표시하고 클래스를 의미하는 cls 파라미터를 받아야함

class Person:

	count = 0 # class variable
    
	def __init__(self, name):
    		Person.count += 1
		self.name = name
		print(self.name + " is initialized")
        
	def work(self, company):
		print(self.name + " is working in " + company)
        
	def sleep(self):
		print(self.name + " is sleeping")
        
	@classmethod
	def getCount(cls): # class method
		return cls.count
        
obj1 = Person("Mike")
obj2 = Person("Dave")

print("the number of person objects is ", Person.getCount)
print(Person.count)

# Mike is initialized
# Dave is initialized
# the number of person objects is 2
# 2

  private variable, method : 외부에서 직접 접근이 어려운 변수, 메서드 / __변수명, __함수명으로 선언

class PrivateTest:

	def __init__(self, name1, name2):
		self.name1 = name1
		self.__name2 = name2 # private으로 선언
        
	def getNames(self):
		self.__printNames()
		return self.name1, self.__name2
        
	def __printNames(self): # private method 선언
		print(self.name1, self.__name2)
        
# 인스턴스 생성
obj = PrivateTest("Mike", "Dave")

print(obj.name1) # Mike
print(obj.getNames()) # Mike, Dave   ('Mike', 'Dave')
print(obj.__printNames()) # error 발생 (외부에서 접근 불가)
print(obj.__name2) # error 발생 (외부에서 접근 불가)

  클래스 내부/외부에 동일한 이름의 method가 존재할 경우 -> self를 이용하여 클래스 내부의 함수/변수를 이용할 것을 명시해주어야 함

def write(name):
	print("[Public] ", name)
    
class Class:

	def __init__(self, name):
		self.name = name
        
	def write(self, name):
		print("[Class] ", self.name)
        
	def whoAreU(self):
		write(self.name) # public write()
		self.write(self.name) # Class write()
        
obj.whoAreU()  
# [Public] Mike 
# [Class] Mike

  ○ Exception (예외 처리)
    try~except을 통해 예외를 처리
     - try 블럭에서 에러 발생시 except문으로 이동하여 예외 처리 수행
    pass문을 이용하여 발생한 exception 무시 가능
    raise문을 이용하여 개발자가 에러를 던질 수 있음
    finally문을 이용하여 try 블럭에서의 exception 발생 유무와 관계없이 코드 실행 가능

def calc(list_data):

	sum = 0
    
	try:
		sum = list_data[0]+list_data[1]+list_data[2] # IndexError 발생
		if sum < 0:
			raise Exception("Sum is minus") # Exception 발생
            
	except IndexError as err: # IndexError 처리
		print(str(err))
        
	except Exception as err: # Exception 처리
		print(str(err))
        
	finally:
		print(sum)
        
calc([1, 2]) 
# list index out of range
# 0 (sum을 갱신하기 전에 예외 발생하므로 초기값 0이 출력)

calc([1, 2, -100])
# Sum is minus
# -97 (sum을 갱신한 후 예외 발생하므로 -97 출력)

○ with 구문
  일반적으로 file/session을 사용할 때 순서는
  open() -> read()/write() -> close() 순으로 실행
  with구문을 이용하면 close()를 명시하지 않아도 with 구문을 벗어나면 자동으로 close()수행
  TensorFlow의 session 사용시 자주 이용

# 일반 케이스

f = open("./file_test", 'w')
f.write("Hello, Python")
f.close()


# with구문을 이용한 케이스

with open("./file_test", 'w') as f:
	f.write("Hello, Python")

'머신러닝&딥러닝' 카테고리의 다른 글

머신러닝 #1 Introduction  (0) 2019.12.26