Coding/Python 삽질기2022. 2. 21. 23:37

PyTorch에서 GPU를 사용해보기로 하고, 삽질한 기록을

미래의 나를 위하여, 기록하였습니다.

1. 노트북 그래픽 카드 확인

 

2. Pytorch 사이트에서 CUDA 버전을 확인한다.

https://pytorch.org/get-started/locally/

 

PyTorch

An open source machine learning framework that accelerates the path from research prototyping to production deployment.

pytorch.org

 PyTorch 1.10.2에 Pip로 CUDA 10.2를 선택하면, 아래에 pip3 명령어가 보인다.  이를 사용하여 pytorch를 설치한다.

 

3. CUDA library 설치

PyTorch 사이트에서 확인한 CUDA 10.2 버전을 설치한다.

 

* 간혹 NVIDIA experience가 동작을 안하는 경우에는 아래와 같이

NVIDIA LocalSystem Controller 에서 로컬 시스템 계정 항목을 체크해 준다.

4. 파이썬을 실행해서 확인 해 본다.

 

'Coding > Python 삽질기' 카테고리의 다른 글

[Python] C 함수 호출 하기  (0) 2022.04.23
생일 문제  (0) 2021.06.21
[Python/C] 휴대폰 패턴의 가지수  (0) 2021.02.21
Posted by chobocho
Coding/Python 삽질기2021. 6. 21. 23:46

기차표 예매를 위하여 줄을 섰을 때, 이들 중 생일이 같은 사람이 존재 할 확률은 얼마일까?

계산을 해보면, 23명 이상 일 때 부터 50%가 넘어가고, 57명이 넘어가면 99%가 넘어간다.

 

 

파이썬으로 짜보면 아래와 같다.

import matplotlib.pyplot as plt

prev = 1
result = [0]
for m in range(57):
    prev = prev * (365-m)/365
    result.append(1-prev)

x = [ n for n in range(len(result))]

plt.scatter(x, result)
plt.axvline(x=23, color='RED', linestyle='-', linewidth=0.2)
plt.axhline(y=0.5, color='RED', linestyle='-', linewidth=0.2)
plt.show()

Posted by chobocho
Coding/Python 삽질기2021. 2. 21. 23:27

인터넷에서 4개의 점 이상을 지나는 휴대폰 패턴의 가지수는 모두 몇 가지인가 라는 문제롤 보고 파이썬으로 풀어 보았다.

0: 9
1: 56
2: 320
3: 1624
4: 7152
5: 26016
6: 72912
7: 140704
8: 140704

4-9 patterns count: 389112

 

작성코드는 아래와 같다

 

import time
import math

def is_valid(used_pattern, stack, max_point):
    if len(stack) < max_point:
        return 0
                
    checked_point = [False] * 9
    checked_point[stack[0]] = True   

    for i in range(1, len(stack)):
        prev_x = stack[i-1] % 3
        prev_y = math.floor(stack[i-1] / 3)
        cur_x = stack[i] % 3
        cur_y = math.floor(stack[i] / 3)
        
        """
        0 1 2
        3 4 5
        6 7 8
        
        아래와 같은 이동한 경우,
        이동시 가운데 점이 기존 패턴에 포함 되지 않은 경우
        유효 하지 않다.
        
        0 <-> 2 | 0 <-> 6 | 0 <-> 8
        2 <-> 8 | 6 <-> 8 | 2 <-> 6
        1 <-> 7 | 3 <-> 5 

        예)
        0 -> 1 -> 0 -> 2 : OK
        0 -> 2 : Not OK
        
        유효하지 않은 경우를 판단하기 위하여
        각 버튼의 위치를 (y, x)로 나타내면 (0,0) ... (2,2) 까지이다.
         
        0 -> 2  =>  (0,0) -> (0, 2)
        0 -> 6  =>  (0,0) -> (2, 0)

        여기서 문제 경우의 
        두 좌표의 합을 구하면 x, y가 모두 2의 배수가 된다.
        그래서 아래와 같이 이동 전후의 좌표의 합이 모두 2의 배수가 되는 경우에서
        Not OK 경우만 걸러 주면 된다.
        
        0 -> 1 -> 0 -> 2 : OK
        0 -> 2 : Not OK

        """
        if ((prev_x + cur_x) % 2 == 0) and ((prev_y + cur_y) % 2 == 0):
            mid_x = math.floor((prev_x + cur_x) / 2)
            mid_y = math.floor((prev_y + cur_y) / 2)
            if checked_point[mid_y * 3 + mid_x] == False:
                return 0
                
        checked_point[stack[i]] = True
        
    return 1


def check_pattern(used_pattern, stack, max_point):
    if len(stack) > max_point:
       return 0
    
    result = is_valid(used_pattern, stack, max_point)
    
    for p in range(0, 9):
        if used_pattern[p]:
            continue
        used_pattern[p] = True
        stack.append(p)
        result = result + check_pattern(used_pattern, stack, max_point)
        stack.pop()
        used_pattern[p] = False
        
    return result

    
def main():
    used_pattern = [False] * 9
    stack = []
    result = []
  
    
    for max_point in range(1, 10):
        result.append(check_pattern(used_pattern, stack, max_point))
        
   
    for c in range(0, len(result)):
        print ("{0}: {1}".format(c, result[c]))
        
    print("4-9 patterns count:", sum(result[3:]))

if __name__ == '__main__':
    start_time = time.time() 
    main()
    print('\n', time.time() - start_time)
    

 


위 코드를 C로 바꾸면 아래와 같다.

#include <stdio.h>


int stack_idx;
int stack[9] = {0, };


int is_valid(int used) {
    int checked = 0;
    
    if (stack_idx < 4) {
        return 0;
    }

    checked |= 1 << stack[0];

    for (int i = 1; i < stack_idx; i++) {
        int prev_x = stack[i-1] % 3;
        int prev_y = stack[i-1] / 3;
        int cur_x = stack[i] % 3;
        int cur_y = stack[i] / 3;

        if (((prev_x + cur_x) % 2 == 0) &&
            ((prev_y + cur_y) % 2 == 0)) {

                 int mid_x = (prev_x + cur_x) / 2;
                 int mid_y = (prev_y + cur_y) / 2;
                 int pos = mid_y*3 + mid_x; 

                 if (!(checked & (1 << pos))) {
                     return 0;
                 }
        }
        checked |= (1 << stack[i]);
    }

    return 1;
}


int check_pattern(int used) {
    int result = 0;

    if (stack_idx == 10) {
        return 0;
    }

    result = is_valid(used);

    for (int i = 0; i < 9; i++) {
        if (used & (1 << i)) {
            continue;
        }

        stack[stack_idx++] = i;
        result += check_pattern(used | (1 << i));
        --stack_idx;
    }
    return result;
}


int main(int argc, char **argv) {
    printf("%d\n", check_pattern(0));
    return 0;
}
Posted by chobocho
Coding/Python 삽질기2021. 1. 17. 23:23

인터넷 커뮤티니에서 본 모대학 수학문제를 풀어 보았다.

약간 변경해서, 1^1 + 2^2 + ... + 10000^10000 의 결과 중 끝 50자리를 출력하는 형식으로 바꿔보았다.

from multiprocessing import Pool
import time

MAX_COUNT = 10**50


def mypower(num):
    result = 1
    
    for i in range(num):
        result = result * num
        if result < MAX_COUNT:
            continue
        result = result % MAX_COUNT         
        
    return result
    

def get_sum(num):
   
   assert num > 0
   
   numbers = [i for i in range(1, num+1)]
   assert len(numbers) == num
   
   pool = Pool(processes=4)
   return sum(list(pool.map(mypower, numbers))) % MAX_COUNT
   

if __name__ == '__main__':
    start_time = time.time() 
    print(get_sum(10000))
    print(time.time() - start_time)
    
16026394753230301057223656223127837280816237204500
3.0160417556762695
Posted by chobocho
Coding/Python 삽질기2020. 10. 28. 22:32
Posted by chobocho
Coding/Python 삽질기2020. 8. 25. 23:00

'Coding > Python 삽질기' 카테고리의 다른 글

[Python] 폴더 안의 파일 이름 검색하기  (0) 2020.10.28
[Python][AI] XOR 예제  (0) 2020.08.03
[Python][AI] Perceptron 예제  (0) 2020.07.28
Posted by chobocho
Coding/Python 삽질기2020. 8. 3. 22:33

아래와 같이 1개의 은닉층을 가진 신경망을 구성해 보았습니다.

 

import numpy as np

def sigmoid(x):
    return 1/(1+np.exp(-x))


def DeltaSGD(W1, W2, X, D):
    alpha = 0.9
    
    idx = 0
    for k in X:
        a1 = np.dot(W1, k)
        z1 = sigmoid(a1)
        
        a2 = np.dot(W2, z1)
        y = sigmoid(a2)
        
        e = D[idx] - y
        delta = y * (1-y) * e
        
        e1 = W2 * delta
        delta1 = z1 * (1-z1) * e1

        dw1 = alpha * delta1
        dw1 = dw1.reshape(4,1)
        x = k.reshape(1,3)
        W1 += np.dot(dw1, x)
        
        dw2 = alpha * delta * z1
        W2 += dw2
        idx+=1

        
def Train(epoch, x, y, W1, W2):
    for ep in range (epoch):
        DeltaSGD(W1, W2, x, y)

        
def main():
    W1 = np.random.randn(4,3)
    W2 = np.random.randn(4)
    x = np.array([[0, 0, 1], [0, 1, 1], [1, 0, 1], [1, 1, 1]])
    y = np.array([0, 1, 1, 0])
    trainCount = 10000

    print('---Before Training---')
    print(W1)
    print(W2)
    print('---After Training---')
    Train(trainCount, x, y, W1, W2)
    print(W1)
    print(W2)
    
    print('---Result---')
    for k in x:
        a1 = np.dot(W1, k)
        z1 = sigmoid(a1)
        
        a2 = np.dot(W2, z1)
        y = sigmoid(a2)
        print(y) 
        
        
if __name__ == '__main__':       
    main()        
---Before Training---
[[-0.82542712 -0.65157477  0.09131077]
 [-0.12367401  1.07601221 -1.43941252]
 [-1.00401084 -0.04547823  0.97194216]
 [ 0.02719329 -0.22932678 -0.45809196]]
[ 0.16840571 -0.55206913  1.75255171 -0.54203599]
---After Training---
[[-6.3608461  -6.35976778  2.71126418]
 [ 3.61918383  3.62562196 -5.65337702]
 [-3.70117648 -3.70158904  5.76910815]
 [-1.51981715 -1.56682777 -0.58710802]]
[-11.12882426  -6.71646542   6.50908732  -1.52377049]
---Result---
0.01083108954199271
0.9896067125952175
0.9895881791368779
0.01040259419256147

 

'Coding > Python 삽질기' 카테고리의 다른 글

[Pygame] Paper Plane Game 만들기  (0) 2020.08.25
[Python][AI] Perceptron 예제  (0) 2020.07.28
[Python] fisher-yates shuffle  (0) 2020.07.20
Posted by chobocho
Coding/Python 삽질기2020. 7. 28. 23:56

 

import numpy as np

def sigmoid(x):
    return 1/(1+np.exp(-x))


def DeltaSGD(W, X, D):
    alpha = 0.9
    dwSum = np.array([0] * 3)
    
    idx = 0
    for k in X:
        a1 = np.dot(k, W)
        y = sigmoid(a1)
        
        e = D[idx] - y
        delta = y * (1-y) * e
        
        dw = alpha * delta * k
        W += dw
        idx+=1

        
def Train(epoch, x, y, W1):
    for ep in range (epoch):
        DeltaSGD(W1, x, y)

        
def main():
    W1 = np.random.randn(3)
    x = np.array([[0, 0, 1], [0, 1, 1], [1, 1, 1], [1, 0, 0]])
    y = np.array([1, 1, 1, 0])

    Train(10000, x, y, W1)
    
    for k in x:
        a1 = np.dot(k, W1)
        z1 = sigmoid(a1)
        print(z1)    
        
        
if __name__ == '__main__':       
    main()  

 

0.9962960119369554
0.9999259998523653
0.9929612087250037
0.010332095384834877

'Coding > Python 삽질기' 카테고리의 다른 글

[Python][AI] XOR 예제  (0) 2020.08.03
[Python] fisher-yates shuffle  (0) 2020.07.20
강아지 나이 계산기  (0) 2020.07.16
Posted by chobocho
Coding/Python 삽질기2020. 7. 20. 23:27
import random

number = [1, 2, 3, 4, 5, 7, 8]

def shuffle(number):
   for i in range (len(number)-1, 0, -1):
       j = random.randint(0, i)
       number[j], number[i] = number[i], number[j]
    
shuffle(number)

 동작을 보면 아래와 같이 변화 한다

[1, 2, 3, 4, 5, 7, 8]
[1, 8, 3, 4, 5, 7, 2]
[1, 8, 3, 4, 5, 7, 2]
[1, 8, 3, 4, 5, 7, 2]
[1, 8, 3, 4, 5, 7, 2]
[3, 8, 1, 4, 5, 7, 2]
[3, 8, 1, 4, 5, 7, 2]

* 참고: https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle

'Coding > Python 삽질기' 카테고리의 다른 글

[Python][AI] Perceptron 예제  (0) 2020.07.28
강아지 나이 계산기  (0) 2020.07.16
[Python] 소인수 분해  (0) 2020.07.10
Posted by chobocho
Coding/Python 삽질기2020. 7. 16. 00:19

강아지 나이를 인간 나이로 바꿔주면 위와 같은 그래프가 나온다고 한다.

강아지 나이 와 인간 나이 변환표

소스코드: https://github.com/chobocho/dog_age

'Coding > Python 삽질기' 카테고리의 다른 글

[Python] fisher-yates shuffle  (0) 2020.07.20
[Python] 소인수 분해  (0) 2020.07.10
[ChoboTimer] Version 0.17 Release  (0) 2020.04.22
Posted by chobocho