ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [30 Days of ML] Day 5 - part 2
    Program/[Kaggle] 30 Days of ML 2021. 8. 9. 00:27
    반응형

    Tutorial


    Loop

    가장 기본적인 형태의 반복문

    사용할 변수의 이름(planet), 반복할 집합(planets), in 으로 연결하여 사용

    planets = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']
    for planet in planets:
        print(planet, end = ' ')
    Mercury Venus Earth Mars Jupiter Saturn Uranus Neptune 

    range()while 을 통해 반복할 수 있음


    List comprehensions

    아래는 기본 코드

    def count_negatives(nums):
        """Return the number of negative numbers in the given list.
    
        >>> count_negatives([5, -1, -2, 0, 3])
        2
        """
        n_negative = 0
        for num in nums:
            if num < 0:
                n_negative = n_negative + 1
        return n_negative

    좀 더 간단히 하면

    def count_negatives(nums):
        return len([a for a in nums if a<0])

    더 간단히!

    def count_negatives(nums):
        # Reminder: in the "booleans and conditionals" exercises, we learned about a quirk of 
        # Python where it calculates something like True + True + False + True to be equal to 3.
        return sum([num < 0 for num in nums])

    boolean 을 이용해서 아주 간단하게 표현할 수 있음


    Exercise


    1.

    리스트에 7의 배수가 있는 경우 True 반환하는 함수

    def has_lucky_number(nums):
        """Return whether the given list of numbers is lucky. A lucky list contains
        at least one number divisible by 7.
        """
        for num in nums:
            if num % 7 == 0:
                return True
        return False

    any() 메소드 사용해서 간단하게 표현

    def has_lucky_number(nums):
        return any([num % 7 == 0 for num in nums])

    any() 메소드는 원소가 하나라도 True인 경우 True를 반환함

    [ ] 이나 [0] 인 경우 False 반환


    2.

    아래와 같이 리스트와 정수와의 비교는 불가능 함

    [1, 2, 3, 4] > 2

    리스트 내의 원소별로 비교해야 함


    3.

    내 코드

    def menu_is_boring(meals):
        """Given a list of meals served over some period of time, return True if the
        same meal has ever been served two days in a row, and False otherwise.
        """
        a=[]
    
        for i in range(len(meals)-1):
            if meals[i]==meals[i+1]:
                a.append(True)
            else:
                a.append(False)
        return any(a)

    답 코드

    def menu_is_boring(meals):
        # Iterate over all indices of the list, except the last one
        for i in range(len(meals)-1):
            if meals[i] == meals[i+1]:
                return True
        return False

    난 쓸데 없는 변수 써가면서 코드를 작성하는 듯 함...


    4.

    4번은 몬테카를로 개념이 등장한다.

    몬테카를로란 반복적인 무작위 추출을 통해 함수의 값을 확률적으로 얻는 방법으로 정확한 답이 아닌 근사치를 구하는 방법이다.

    예를 들어 원의 넓이 구하는 공식을 모른다고 가정하고 원의 넓이를 구할 때 다음과 같이 한 변의 길이가 2인 정사각형 안에 있는 원 그림에 점을 무작위로 뿌린다. 이 때 아래와 같은 공식이 성립한다.

    정사각형 내부의 점의 개수:원 안의 점의 개수=원의 넓이(x):4

    비례식을 통해 원의 넓이 x를 구할 수 있다!

    무작위로 뿌리는 점의 개수가 많아질수록 pi 값에 근사하게 된다.

    Monte-Carlo-4panel

    문제를 요약하면 다음과 같다.

    play_slot_machine 을 호출하면 0, 1.5, 5 달러를 얻을 수 있고 플레이 비용은 1임

    몬테카를로를 이용해 각 pull의 평균값을 추정할 수 있음

    def estimate_average_slot_payout(n_runs):
        """Run the slot machine n_runs times and return the average net profit per run.
        Example calls (note that return value is nondeterministic!):
        >>> estimate_average_slot_payout(1)
        -1
        >>> estimate_average_slot_payout(1)
        0.5
        """
        sum_ = 0
        i = 1
    
        while(i <= n_runs):
            sum_+=(play_slot_machine() - 1) # pull 할 때마다 1달러씩 지불
            i+=1
        return sum_/n_runs

    시행 결과는 다음과 같음

    반응형

    'Program > [Kaggle] 30 Days of ML' 카테고리의 다른 글

    [30 Days of ML] Day 7  (0) 2021.08.12
    [30 Days of ML] Day 6  (0) 2021.08.11
    [30 Days of ML] Day 5 - part 1  (0) 2021.08.08
    [30 Days of ML] Day 4  (0) 2021.08.08
    [30 Days of ML] Day 3  (0) 2021.08.05

    댓글

Designed by Tistory.