본문 바로가기

Python

자주 찾게되는 Python 팁 정리

Python이 왜 중요한가?

 AI/ML이 발전함에 따라 Python은 2023년 현재 Programming Language Ranking에서 압도적 1위를 차지하고 있습니다. 요즘 프로그래머들도 Python은 기본으로 다룰줄 알아야 하죠. 저는 CS/ECE쪽 대학원을 다니고 있는 대학원생인데 AI/ML 용도, Script짜는 용도, Data Visualization하는 용도 등으로 Python을 워낙 많이 사용하다보니 구글링을 자주 하게 되는데, 반복적으로 검색하게 되는 것들이 있더라구요. 그래서 불필요하게 구글링하는 것을 막고자 저를 위해(?) 그리고 저와 비슷한 경험을 하고 있을 많은 분들을 위해 Python 정리 노트를 하나 만들어보면 어떨까 해서 글을 작성하게 되었습니다.

 

 그래서 앞으로 여러 포스트들로 나눠서 정리해볼까 하는데, 크게 3가지 카테고리에서 정리해볼 예정입니다.

  1. Pytorch + Numpy for AI/ML
  2. Data Visualization (i.e., Matplotlib)
  3. Script 관련 (e.g., file search, generation)

맛보기 예시들

1. Pytorch + Numpy for AI/ML

1) torch + cuda installation

특정 CUDA version에 맞는 torch를 manual하게 깔고 싶을 때 두 가지 옵션

1)

$ pip install torch==1.13.1+cu117 # torch 1.13.1, cuda 11.7 compatible

OR

2)

https://download.pytorch.org/whl/torch

 

https://download.pytorch.org/whl/torch

 

download.pytorch.org

에서 원하는 torch version과 cuda version 확인 후 다음 command 입력

# torch 1.13.1, cuda 11.7 python 3.10 compatible
$ pip install 1.13.1+cu117-cp310-cp310-linux_x86_64.whl

 

2) torch에서 GPU를 제대로 인식했는지 확인

import torch

# GPU 사용 여부 Check
torch.cuda.is_available()
> True

 

torch가 GPU를 인식했는지 확인하는 방법

 

2. Data Visualization

1) 간단한 line graph plot하고 저장하기

tight layout option은 사진 저장 시 그래프 잘림 없이 저장해준다.

import matplotlib.pyplot as plt

# Sample data
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]

# Create a new figure and axis
plt.figure(figsize=(8, 6))
plt.plot(x, y, marker='o', linestyle='-', color='b', label='Data Points')

# Add labels and title
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Simple Line Plot')
plt.legend()

# Display the plot
plt.grid(True)
plt.show()

# Save the figure with tight layout
plt.tight_layout()
plt.savefig('line_plot.pdf', dpi=300)  # Specify file name and DPI (dots per inch)

plt.close()

 

3. Script 관련 (e.g., file I/O)

1) 특정 확장자를 가진 파일들을 모두 찾아 확장자를 바꾸어주기

os, glob 모듈을 이용한 간단한 코드 예제.

root_directory 아래에 있는 모든 txt file을 찾아(recursive manner) csv file로 바꿔준다.

import os
import glob

def find_and_replace_suffix(root_directory, old_suffix, new_suffix):
    search_pattern = os.path.join(root_directory, f'**/*{old_suffix}')
    for old_path in glob.iglob(search_pattern, recursive=True): # recursive search
        if os.path.isfile(old_path):
            new_path = old_path.replace(old_suffix, new_suffix) # .txt -> .csv
            os.rename(old_path, new_path) # file name change
            print(f"Renamed: {old_path} -> {new_path}")

root_directory = "/path/to/your/directory"
old_suffix = ".txt"
new_suffix = ".csv"

find_and_replace_suffix(root_directory, old_suffix, new_suffix)