From 7d0bcdd15df13190cb5bfcc4ebe1fe71f359321d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EB=B0=95=EB=AF=BC=EC=84=A0?= Date: Wed, 9 Jul 2025 16:26:19 +0900 Subject: [PATCH 1/6] Update _config.yml --- _config.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/_config.yml b/_config.yml index 85149179e6cd..bef04344c764 100644 --- a/_config.yml +++ b/_config.yml @@ -22,7 +22,7 @@ title_separator : "-" subtitle : # site tagline that appears below site title in masthead name : "Your Name" description : "An amazing website." -url : # the base hostname & protocol for your site e.g. "https://mmistakes.github.io" +url : "https://koala-0614.github.io" baseurl : # the subpath of your site, e.g. "/blog" repository : # GitHub username/repo-name e.g. "mmistakes/minimal-mistakes" teaser : # path of fallback teaser image, e.g. "/assets/images/500x300.png" From 03fa40d4f4d929d0eeee278714f21b7062e53f25 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EB=B0=95=EB=AF=BC=EC=84=A0?= Date: Wed, 9 Jul 2025 16:44:24 +0900 Subject: [PATCH 2/6] Create 2025-07-09-first.md --- _posts/2025-07-09-first.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 _posts/2025-07-09-first.md diff --git a/_posts/2025-07-09-first.md b/_posts/2025-07-09-first.md new file mode 100644 index 000000000000..17ca5bfae8b1 --- /dev/null +++ b/_posts/2025-07-09-first.md @@ -0,0 +1 @@ +[test.md](https://github.com/user-attachments/files/21137541/test.md) From d6f87e4521de52a87c7451f29b56de89097ad302 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EB=B0=95=EB=AF=BC=EC=84=A0?= Date: Wed, 9 Jul 2025 16:45:25 +0900 Subject: [PATCH 3/6] Update 2025-07-09-first.md --- _posts/2025-07-09-first.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/_posts/2025-07-09-first.md b/_posts/2025-07-09-first.md index 17ca5bfae8b1..a10075a2a4a3 100644 --- a/_posts/2025-07-09-first.md +++ b/_posts/2025-07-09-first.md @@ -1 +1,3 @@ -[test.md](https://github.com/user-attachments/files/21137541/test.md) +```python +import +``` From 175b96b1ed3e5f143b2b8d54bf5f05ca43fc500a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EB=B0=95=EB=AF=BC=EC=84=A0?= Date: Wed, 9 Jul 2025 16:46:33 +0900 Subject: [PATCH 4/6] Update 2025-07-09-first.md --- _posts/2025-07-09-first.md | 296 ++++++++++++++++++++++++++++++++++++- 1 file changed, 295 insertions(+), 1 deletion(-) diff --git a/_posts/2025-07-09-first.md b/_posts/2025-07-09-first.md index a10075a2a4a3..88d0fb88758f 100644 --- a/_posts/2025-07-09-first.md +++ b/_posts/2025-07-09-first.md @@ -1,3 +1,297 @@ + +# 1. 기본 모델 +![](https://velog.velcdn.com/images/koala_0614/post/5bd9e7b7-6b00-458a-aeaa-b879681aa171/image.png) + + +### 데이터 정의 ```python -import +import torch +from torch.utils.data import TensorDataset +from torch.utils.data import DataLoader + +# 입력 데이터(x)와 정답 데이터(y)를 텐서로 정의하고, (6, 1) 모양으로 reshape +x_train = torch.Tensor([1, 2, 3, 4, 5, 6]).view(6,1) # shape: (6, 1) +y_train = torch.Tensor([3, 4, 5, 6, 7, 8]).view(6,1) # shape: (6, 1) + +from torch.utils.data import Dataset, DataLoader # Dataset과 DataLoader 모듈 임포트 + + +dataset = TensorDataset(x_train, y_train) +dataloader = DataLoader(dataset, batch_size=32, shuffle=True) +# dataset과 dataloader는 PyTorch에서 제공하는 기본 class +# 미니배치 학습, 데이터 셔플, 멀티 프로세싱 등을 간단하게 수행 가능 +``` + + +### 신경망 모델 구축 +```python +class MyNeuralNetwork(nn.Module): + + def __init__(self): + super().__init__() + self.linear_relu_stack = nn.Sequential( + nn.Linear(1,1) + ) # 모델을 구성하는 layer 정의 + + def forward(self, x): + logits = self.linear_relu_stack(x) + return logits # 그림의 3번 과정, feedforward를 수행하고 결과값을 리턴함 + +model = MyNeuralNetwork() # 모델 인스턴스 생성 왼료 +``` + + + +### 손실함수 계산 +```python +loss_function = nn.MSELoss() +# 손실함수 정의 +#일반적인 회귀 데이터에서는 nn.MSELoss(), 분류 데이터에서는 nn.CrossEntropyLoss()를 사용함 + +optimizer = torch.optim.SGD(model.parameters(), lr=1e-2) +# SGD 말고도 ADAM,RMSProp 등 다양한 옵티마이져가 있음 + +nums_epoch = 2000 + +for epoch in range(nums_epoch+1): + + prediction = model(x_train) + loss = loss_function(prediction, y_train) +# model에 x_train을 주면 feed forward 수행 되어서 prediction이 나오고 이것과 y_train 값을 비교해서 loss를 계산함 + + optimizer.zero_grad()### + loss.backward()### + optimizer.step()### back propagation 세줄 코드 + + if epoch % 100 == 0: + print('epoch = ', epoch, ' current loss = ', loss.item()) +``` + + +### 테스트 데이터 예측 +```python +x_test = torch.Tensor([-3.1, 3.0, 1.2, -2.5]).view(4,1) + +pred = model(x_test) + +print(pred) +``` + + +# 2. CustomDataset DataLoader + +![](https://velog.velcdn.com/images/koala_0614/post/a65cea39-8ddb-453d-8326-1743788b818b/image.png) +### CustomDataset 정의 +```python +from torch.utils.data import Dataset, DataLoader + +# Dataset 클래스를 상속받아 나만의 데이터셋(CustomDataset)을 정의 +class CustomDataset(Dataset): # PyTorch에서 데이터셋을 만들 땐 Dataset을 상속받아야 함 + + def __init__(self, x_train, y_train): + # 생성자: 객체가 만들어질 때 자동으로 실행됨 + # 학습 데이터(x)와 정답(y)를 받아서 내부 변수(self.x_train, self.y_train)에 저장 + self.x_train = x_train + self.y_train = y_train + + def __getitem__(self, index): + # 주어진 index에 해당하는 데이터 한 쌍(x, y)을 반환 + # DataLoader가 데이터를 하나씩 꺼낼 때 이 함수가 자동으로 호출됨 + return self.x_train[index], self.y_train[index] + + def __len__(self): + # 전체 데이터의 길이를 반환 + # DataLoader가 몇 번 반복할지 결정할 때 이 길이를 참고함 + return self.x_train.shape[0] # 또는 len(self.x_train)도 가능 + +``` + +### Dataset & DataLoader 인스턴스 생성 +```python +dataset = CustomDataset(x_train, y_train) # CustomDataset 클래스를 이용해 x, y 데이터를 하나의 Dataset 객체로 만듦 + +train_loader = DataLoader(dataset=dataset, # 위에서 만든 dataset을 DataLoader에 전달 + batch_size=3, # 한 번에 3개씩 데이터를 가져오도록 설정 (mini-batch 학습용) + shuffle=True) # 각 epoch마다 데이터를 섞어서 학습 (일반적으로 overfitting 방지에 도움됨) + +``` +### 옵티마이저 설정 +```python +for epoch in range(2): # 전체 학습을 2번 반복 (epoch: 전체 데이터를 한 번 다 사용하는 주기) + + for idx, batch_data in enumerate(train_loader): # train_loader에서 배치 단위로 데이터를 꺼냄 + 인덱스(idx)도 같이 가져옴 + + x_train_batch, y_train_batch = batch_data # 배치 데이터를 입력(x)과 정답(y)으로 나눔 + + output_batch = model(x_train_batch) # 모델에 현재 배치 입력을 넣어 예측값(output) 생성 + + # 현재 학습 상태 출력 (epoch 번호, 배치 인덱스, 각 텐서의 크기 출력) + print('==============================================') + print('epoch =', epoch+1, ', batch_idx =', idx+1, ',', + len(x_train_batch), len(y_train_batch), len(output_batch)) + print('==============================================') + + loss = loss_function(output_batch, y_train_batch) # 예측값과 실제값 사이의 손실(loss) 계산 + + optimizer.zero_grad() # 이전 배치에서 계산된 gradient 초기화 (안 지우면 gradient가 누적됨) + loss.backward() # 역전파 수행: 손실을 기준으로 각 파라미터의 gradient 계산 + optimizer.step() # 계산된 gradient를 바탕으로 파라미터(가중치) 업데이트 + +``` + + +# 3. Deep learning +### data set +| 공부시간 $x$ | Fail/Pass $t$ | +| :------: | :-----------: | +| 2 | 0 | +| 4 | 0 | +| 6 | 0 | +| 8 | 0 | +| 10 | 0 | +| 12 | 0 | +| 14 | 1 | +| 16 | 1 | +| 18 | 1 | +| 20 | 1 | + +입력데이터가 12 이하 => 0 +입력데이터가 14 이상 => 1 + +### 데이터 정의 +```python +import torch + +x_train = torch.Tensor([2, 4, 6, 8, 10, + 12, 14, 16, 18, 20]).view(10,1) +y_train = torch.Tensor([0, 0, 0, 0, 0, + 0, 1, 1, 1, 1]).view(10,1) + +print(x_train.shape, y_train.shape) +``` +torch.Size([10, 1]) torch.Size([10, 1]) + +### 신경망 모델 구축 +```python +from torch import nn # PyTorch의 신경망 모듈을 불러옴 +class MyDeepLearningModel(nn.Module): # PyTorch의 nn.Module을 상속받아 사용자 정의 모델 클래스 생성 + def __init__(self): + super().__init__() # 부모 클래스(nn.Module)의 초기화 메서드 호출 (필수) + + # 신경망 구성 정의 (1개의 입력 → 8개의 은닉노드 → 1개의 출력 → 시그모이드 함수) + self.deeplearning_stack = nn.Sequential( + nn.Linear(1, 8), # 첫 번째 선형 계층: 입력 1차원 → 출력 8차원 (은닉층) + nn.Linear(8, 1), # 두 번째 선형 계층: 은닉 8차원 → 출력 1차원 + nn.Sigmoid() # 출력값을 0~1 사이로 변환 (이진 분류에서 주로 사용) + ) + def forward(self, data): + prediction = self.deeplearning_stack(data) # 입력 데이터를 신경망에 통과시켜 예측값 생성 + return prediction # 예측 결과 반환 +``` +``` +deeplearning_stack Parameter containing: +tensor([[ 0.8563], + [ 0.2287], + [-0.9602], + [ 0.2007], + [ 0.5503], + [ 0.3265], + [ 0.0729], + [ 0.4172]], requires_grad=True) # 입력층-은닉층 가중치 8개 (1*8) + +deeplearning_stack Parameter containing: +tensor([-0.7311, 0.0009, 0.3659, -0.6176, -0.8870, -0.8870, 0.2865, 0.0695], + requires_grad=True) # 은닉층 바이어스 8개 +deeplearning_stack Parameter containing: +tensor([[-0.0181, -0.2728, -0.2050, 0.1117, -0.0905, -0.1740, 0.1518, -0.0790]], + requires_grad=True) # 은닉층-출력층 가중치 8개 (8*1) +deeplearning_stack Parameter containing: +tensor([0.1045], requires_grad=True) # 출력층 바이어스 1개 +``` + +### 손실함수 및 옵티마이저 설정 +```python +# 모델 인스턴스 생성 +deeplearning_model = MyDeepLearningModel() +# 위에서 정의한 MyDeepLearningModel 클래스의 객체를 생성함 +# 이 객체는 실제로 학습과 예측을 수행하는 모델이 됨 + +# 손실 함수 및 옵티마이저 정의 +loss_function = nn.BCELoss() +# Binary Cross Entropy Loss (이진 분류 문제에 적합한 손실 함수) + +optimizer = torch.optim.SGD(deeplearning_model.parameters(), lr=0.1) +# SGD: Stochastic Gradient Descent (확률적 경사하강법) +# 모델의 파라미터(deeplearning_model.parameters())를 업데이트할 때 사용 +# 학습률(learning rate)은 0.1로 설정됨 + +nums_epoch = 5000 # 전체 학습 반복 횟수 (epoch)를 5000으로 설정 + +for epoch in range(nums_epoch + 1): # 0부터 5000까지 총 5001번 반복 + for x_batch, y_batch in train_loader: + # train_loader로부터 배치 단위의 데이터를 하나씩 불러옴 + # x_batch: 입력 데이터 텐서 (예: 공부 시간) + # y_batch: 정답 텐서 (예: pass or fail) + outputs = deeplearning_model(x_batch) + # 현재 배치 데이터를 모델에 넣어 예측 결과(outputs)를 얻음 + # outputs는 sigmoid를 통과한 0~1 사이의 값 (확률 형태) + loss = loss_function(outputs, y_batch) + # 예측값과 실제값 사이의 오차(손실)를 계산함 + # loss는 현재 배치에 대한 평균적인 예측 오차를 의미 + optimizer.zero_grad() + # 이전 배치에서 계산된 gradient를 모두 초기화 + # 이걸 하지 않으면 gradient가 누적되어 잘못된 업데이트가 됨 + loss.backward() + # 역전파(backpropagation)를 수행하여, + # 손실 함수를 기준으로 각 파라미터에 대한 gradient(기울기)를 계산함 + optimizer.step() + # 계산된 gradient를 바탕으로 모델의 파라미터를 업데이트함 + # 이 단계에서 실제 학습이 이루어짐 + + # 100 epoch마다 현재 손실값을 출력해서 학습 상태를 모니터링함 + if epoch % 100 == 0: + print('epoch =', epoch, ' current loss =', loss.item()) + # loss.item()은 텐서 값을 float 숫자로 변환하여 출력함 +``` +``` +epoch = 0 current loss = 0.7203410863876343 +epoch = 100 current loss = 0.389792263507843 +epoch = 200 current loss = 0.31200623512268066 +epoch = 300 current loss = 0.2660113275051117 +... +epoch = 4800 current loss = 0.019202910363674164 +epoch = 4900 current loss = 0.017444582656025887 +epoch = 5000 current loss = 0.015960771590471268 +# loss가 0.7에서 0.015정도로 많이 줄어듦 +``` +```python +deeplearning_model.eval() +# 모델을 "평가 모드"로 전환함 (학습 중과 다르게 동작함) +# Dropout, BatchNorm 등의 레이어가 있을 경우, eval()이 필수임 +# 여기서는 없어도 되지만, 관례적으로 사용함 +test_data = torch.Tensor([0.5, 3.0, 3.5, 11.0, 13.0, 31.0]).view(6, 1) +# 테스트할 입력 데이터 정의 (총 6개 샘플) +# .view(6, 1): (6,) 1차원 텐서를 (6,1) 2차원으로 reshape하여 모델 입력 형태에 맞춤 +pred = deeplearning_model(test_data) +# 모델에 테스트 데이터를 넣어 예측값(prediction)을 얻음 +# pred는 0~1 사이의 값으로 나옴 (Sigmoid 통과한 결과) +logical_value = (pred > 0.5).float() +# 예측값이 0.5보다 크면 1.0 (True), 작으면 0.0 (False) +# 이렇게 하면 확률 → 이진 분류 결과로 변환됨 +print(pred)# 각 입력에 대한 모델의 예측 확률 출력 +print(logical_value)# 위 예측을 0.5 기준으로 이진화한 결과 출력 (0 또는 1) +``` +``` +tensor([[2.9347e-14], + [1.5186e-11], + [5.2994e-11], + [7.2894e-03], + [5.2127e-01], + [1.0000e+00]], grad_fn=) +tensor([[0.], + [0.], + [0.], + [0.], + [1.], + [1.]]) ``` From 20b6fcaf784c9861e40d5a31c0bce0fe09adc060 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EB=B0=95=EB=AF=BC=EC=84=A0?= Date: Mon, 25 Aug 2025 12:33:29 +0900 Subject: [PATCH 5/6] Add MathJax test post --- _posts/2025-08-25.md | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 _posts/2025-08-25.md diff --git a/_posts/2025-08-25.md b/_posts/2025-08-25.md new file mode 100644 index 000000000000..e69de29bb2d1 From 5f41594ec93a18f9a379ad918fbb5ca63e0f977d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EB=B0=95=EB=AF=BC=EC=84=A0?= Date: Mon, 25 Aug 2025 12:35:32 +0900 Subject: [PATCH 6/6] Enable MathJax and add test post --- _config.yml | 8 +++++--- _posts/2025-08-25.md | 13 +++++++++++++ 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/_config.yml b/_config.yml index bef04344c764..27fff35badc6 100644 --- a/_config.yml +++ b/_config.yml @@ -17,11 +17,11 @@ minimal_mistakes_skin : "default" # "air", "aqua", "contrast", "dark", "dirt" # Site Settings locale : "en-US" rtl : # true, false (default) # turns direction of the page into right to left for RTL languages -title : "Site Title" +title : "Koala" title_separator : "-" subtitle : # site tagline that appears below site title in masthead -name : "Your Name" -description : "An amazing website." +name : "minseon Park" +description : "paper reviw & my projects" url : "https://koala-0614.github.io" baseurl : # the subpath of your site, e.g. "/blog" repository : # GitHub username/repo-name e.g. "mmistakes/minimal-mistakes" @@ -310,6 +310,8 @@ compress_html: ignore: envs: development +# MathJax support +mathjax: true # Defaults defaults: diff --git a/_posts/2025-08-25.md b/_posts/2025-08-25.md index e69de29bb2d1..6b45932d7958 100644 --- a/_posts/2025-08-25.md +++ b/_posts/2025-08-25.md @@ -0,0 +1,13 @@ +--- +layout: single +title: "MathJax 테스트" +mathjax: true +--- + +인라인 수식: \\( E = mc^2 \\) + +블록 수식: + +$$ +\int_{-\infty}^{\infty} e^{-x^2} dx = \sqrt{\pi} +$$