ML & DL 실습

Machine Learning

  • 데이터 -> 특징 선택 -> 학습 -> 결과
  • scikit-learn module (Classification, Regression) -> fit() : 학습 predict() : 예측

Deep Learning

  • 데이터 -> 학습 -> 결과
  • Pytorch, Tensorflow
  • Tensor : Array나 Matrix와 매우 유사한 특수한 자료구조로, 차원과 관련있음
length = bream_length + smelt_length
weight = bream_weight + smelt_weight

fish_data = [[l, w] for l, w in zip(length, weight)]

print(fish_data)
  • [[l, w] for l, w in zip(length, weight)] : zip(length, weight) : 두 개의 List에서 각각 원소를 하나씩 꺼내서 변수에 담아 for문 내부로 보내는 것. zip 안에 있는 List 끼리의 길이가 서로 같아야 함
  • Target Data (Ground truth) : 정답 데이터

Supervised Learning

  • Supervised Learning : Target이 주어지고, 이를 통해 학습
  • Unsupervised Learning : Target이 주어지지 않고 학습

Classification (분류)

1️⃣ KNN Classifier (K-Nearest Neighborhood)

  • 해당 데이터와 distance가 가장 가까운 k개의 데이터를 기반으로 class를 예측
kn = KNeighborsClassifier()

 

  • ML Model 구조 선언
  • 객체지향 프로그래밍에서는 이렇게 class Object를 선언하는 방식으로 모델을 정의 및 사용
kn.fit(X, y)
  • X : train data 
  • y : target data
  • ML Model 학습 -> (pytorch : train(), Tensorflow : fit())
kn.predict_proba(x)
  • 클래스 별 확률을 반환함
kn.score(X, y)
  • 학습한 ML Model 성능 검증
  • 모델에게 X data를 입력값으로 넣어준 후 나온 예측 결과를 y와 비교해 정확도를 [0.0 ~ 1.0] 사이 실수로 나타냄
  • 이러한 성능 평가 지표를 Accuracy (정확도) 라고 함
  • Bias : 현실에서는 편향적인 데이터가 많으므로 주의하여야 함
import numpy as np
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt

# Data Input
fish_length = [25.4, 26.3, 26.5, 29.0, 29.0, 29.7, 29.7, 30.0, 30.0, 30.7, 31.0, 31.0,
                31.5, 32.0, 32.0, 32.0, 33.0, 33.0, 33.5, 33.5, 34.0, 34.0, 34.5, 35.0,
                35.0, 35.0, 35.0, 36.0, 36.0, 37.0, 38.5, 38.5, 39.5, 41.0, 41.0, 9.8,
                10.5, 10.6, 11.0, 11.2, 11.3, 11.8, 11.8, 12.0, 12.2, 12.4, 13.0, 14.3, 15.0]
fish_weight = [242.0, 290.0, 340.0, 363.0, 430.0, 450.0, 500.0, 390.0, 450.0, 500.0, 475.0, 500.0,
                500.0, 340.0, 600.0, 600.0, 700.0, 700.0, 610.0, 650.0, 575.0, 685.0, 620.0, 680.0,
                700.0, 725.0, 720.0, 714.0, 850.0, 1000.0, 920.0, 955.0, 925.0, 975.0, 950.0, 6.7,
                7.5, 7.0, 9.7, 9.8, 8.7, 10.0, 9.9, 9.8, 12.2, 13.4, 12.2, 19.7, 19.9]

fish_data = [[l, w] for l, w in zip(fish_length, fish_weight)]
fish_target = [1] * 35 + [0] * 14 # 1 데이터를 도미, 0 데이터를 방어

# stratify : 데이터 클래스 별 비율 설정
X_train, X_test, y_train, y_test = train_test_split(fish_data, fish_target, test_size=0.28, random_state=1024, shuffle=True, stratify=fish_target)

X_train, X_test, y_train, y_test = np.array(X_train), np.array(X_test), np.array(y_train), np.array(y_test)

kn = KNeighborsClassifier() # 모델 선언
kn.fit(X_train, y_train) # 학습

# 산점도 시각화
plt.scatter(X_train[:, 0], X_train[:, 1])
plt.scatter(25, 150, marker="^") # 새로운 데이터
plt.xlabel("length") # x축
plt.ylabel("weight") # y축 
plt.show() # 시각화 보여주기

KNN Algorithm은 학습에 사용된 모든 X, y를 전부 Model 에서 기억하고 있어야 함 (kn._fit_X, kn._fit_y 에서 확인 가능)

그러므로 데이터가 너무 많은 경우에는 사용하기 어려우며, 직선거리 계산에도 많은 시간이 필요하다.

 

변수
1. parameter
인공 지능 모델이 가진 학습 가중치로, 인위적 변경을 거의 하지 않음
2. Hyperparameter
인위적인 값들로, configuration setting 값들이다. 어떤 것이 최적인지 모르므로 Tuning 이 필요하다.

 

2️⃣ Logistic Regression

  • 선형방정식을 학습하는 분류 모델
  • y = w1 * x1 + w2 * x2 + w3 * x3 + w4 * x4 + w5 * x5
  • x1 : Weight, x2 : Length, x3 : Diagonal, x4 : Height, x5 : Width
from sklearn.linear_model import LinearRegression

lr = LinearRegression() # 1차 함수
lr.fit(train_input, train_target)

print(f"길이 50일 때 예측 무게 : {lr.predict([[50]])}")
print(f"길이 100일 때 예측 무게 : {lr.predict([[100]])}")

# 그래프 시각화
plt.scatter(train_input, train_target)

plt.plot([15, 100], [15 * lr.coef_ + lr.intercept_, 100 * lr.coef_ + lr.intercept_], color = "r")
plt.scatter(50, lr.predict([[50]]), marker="^")
plt.scatter(100, lr.predict([[100]]), marker="^")
plt.xlabel("length")
plt.ylabel("weight")
plt.show()

 

Classification
1. Binary Classification (이중 분류)
output y 값에 sigmoid function을 적용해서 확률화,,
2. Multi-class Classification (다중 분류)
주요 Hyperparameter (max_iter : 반복 횟수, C : Regularization 을 제어하는 변수)

Sigmoid function
출처 : https://www.google.co.kr/url?sa=i&url=https%3A%2F%2Fbotpenguin.com%2Fglossary%2Fsoftmax-function&psig=AOvVaw0Dk96vS1fFyVF-ImrPqzgy&ust=1730345656171000&source=images&cd=vfe&opi=89978449&ved=0CAMQjB1qFwoTCIj81IOWtYkDFQAAAAAdAAAAABAJ

 

Pandas Library

  • pandas : Dataframe을 다루는 Python Library
  • Dataframe : 2차원 표 형식의 주요 데이터 구조 (row / col)
  • numpy와 scikit-learn 과 상호 변환이 좋음.

주요 method

  • Pd.read_csv() : 외부 csv file을 읽어서 프로그램에 올림
  • Dataframe.head() : Dataframe의 처음 5개의 행을 출력
  • Pd.unique() : 고유값을 추출 (중복 제거)
  • Dataframe.columns : Dataframe의 column name을 담은 List
  • Dataframe.columns.difference([column name]) : 해당 column name을 제외한 후 남은 column name

 

Regression

1️⃣ KNN Regression

  • 최근접 sample k개의 target(=y) 값 평균으로,,
Metric (성능 지표)
1. 결정 계수 (R^2)
R^2 = 1 - ((target - pred)^2 / (target - mean of target)^2)
-> 예측이 target에 아주 가까워지면 (모델의 성능이 좋다) 1에 가까워지고, 아니면 0에 가까워짐
2. MAE (Mean Absolute Error)
e = 1/n Σ |y - yd|
3. MSE (Mean Squared Error)
e = 1/n^2 Σ (y - yd)^2
=> 2, 3번 모두 sklearn.Metric에 존재한다.

Overfitting & Underfitting
Overfitting : train set의 예측 성능 (>= 학습 성능) 보다 test set의 성능이 지나치게 낮을 때, train set에 지나치가 fitting 되었음
Underfitting : train set의 성능이 너무 낮은 경우, 모델 학습이 제대로 되지 않았다는 증거가 될 수 있음
=> 일반적으로는, train set 에서의 성능이 test set에서의 성능보다 약간 좋은 수준이 이상적임

 

2️⃣ Linear Regression

  • 대략적인 관계 해석이나, 예측에 활용되지만 현실에서는 보통 다중 회귀 문제가 많음
  • x와 y가 선형관계가 있어 보일 때 사용
  • KNN Algorithm의 한계 : 이상치에 취약하고 일반화 능력이 떨어짐

So, Linear Regression 은 주변 데이터와 비교하지 않고, 현재 train set을 가장 잘 표현하는 직선 (y = wx + b) 를 찾는 훈련을 수행

w : lr.coef_ , b : lr.intercept_ (model parameter)

from sklearn.linear_model import LinearRegression

lr = LinearRegression() # 1차 함수
lr.fit(train_input, train_target)

print(f"길이 50일 때 예측 무게 : {lr.predict([[50]])}")
print(f"길이 100일 때 예측 무게 : {lr.predict([[100]])}")
# 시각화
point = np.arange(15, 100)
plt.scatter(train_input, train_target)
plt.plot(point, lr.coef_[0]*point**2 + lr.coef_[1]*point + lr.intercept_, color = "r")
plt.scatter(50, lr.predict([[50 ** 2, 50]]), marker="^")
plt.scatter(100, lr.predict([[100 ** 2, 100]]), marker="^")
plt.xlabel("length")
plt.ylabel("weight")
plt.show()

3️⃣ Polynomial Regression

  • 산점도를 통해 시각적 확인을 하고, 곡선 형태로 분포하는 경우 사용해볼 수 있음
  • y = wnx^n + ... + w1x + b
  • weight을 하나만 가지지 않고 n차항의 계수를 예측
  • 그래프 곡선
train_poly = np.column_stack((train_input ** 2, train_input)) # np.column_stack : 입력 데이터에 다항 특성을 추가하여 모델이 더 복잡한 비선형 관계를 학습할 수 있도록 함
test_poly = np.column_stack((test_input ** 2, test_input))

print(train_poly.shape, test_poly.shape)
lr = LinearRegression()
lr.fit(train_poly, train_target)
# 시각화
point = np.arange(15, 100)
plt.scatter(train_input, train_target)
plt.plot(point, lr.coef_[0]*point**2 + lr.coef_[1]*point + lr.intercept_, color = "r")
plt.scatter(50, lr.predict([[50 ** 2, 50]]), marker="^")
plt.scatter(100, lr.predict([[100 ** 2, 100]]), marker="^")
plt.xlabel("length")
plt.ylabel("weight")
plt.show()

Training Set & Test set

  1. Train set : 학습에 직접적으로 사용
  2. Test set : 학습 중간에 일반화 성능 평가를 위해 사용
  3. Valid set : 학습이 끝난 이후에 모델 성능 평가를 위해 사용

제일 많이 쓰는 방법은 scikit-learn 에서 train_test_split() function을 쓰는 것.

Index 기준으로 나눠도 좋음.

Data

  • 입력 (input) : X => 모델에 입력되는 데이터
  • 정답 (target) : y => 모델이 예측해야 하는 값의 정답
  • 특성 (feature) : 인공지능 모델 학습을 위해 사용되는 데이터의 중요한 특징
  • 특성 공학 (Feature engineering) : 인공지능 모델을 학습하기 위해서는 중요한 특징만 뽑아내서 사용해야 함.

주로 ML Model의 경우는 특징 선택 등, feature를 직접 선정해서 모델의 입력값으로 넣음.

=> Hand-Craft feature

DL model의 입력값은 대개 Image, 자연어(text), 연속된 신호값이라서 사람이 찾아주기 어려워 CNN 등의 Network를 사용해서 특징을 자동으로 추출,,

 

Sample bias를 피하기 위한 방법

  • train / test / valid 를 나눌 때는 데이터 속 클래스 비율을 고려해야 함
  • sklearn.model_selection.train_test_split(*arrays, test_size=None, random_state=None, shuffle=True, stratify=None) 사용
  • np.shffule()로 직접 섞기

arrays : 분할할 데이터셋 (numpy array) (x, y 둘 다)

test_size : 테스트셋으로 사용할 비율 (0.0 ~ 1.0)

train_size : 학습 셋으로 사용할 비율 (test를 쓰면 알아서 설정)

random_state : 데이터를 어떤 순서로 섞을지..(난수, 항상 동일하게 설정해야 함)

stratify : 데이터를 나눌 때 클래스 비율을 고려할지 설정.. target array를 넣으면 클래스별 빈도수에 맞춰서 비율 조정

 

Data Preprocessing

  • 모델에 훈련 데이터를 주입하기 전에 가공하는 단계로, 주로 CPU로 작동

Normalization & Standarization

  • 거리 기반 Algorithm 에서 특히 중요한데, 단위의 차이에서 오는 오류를 제거함
# Normalization
import numpy as np

max_ = X_train.max(axis = 0)
min_ = X_train.min(axis = 0)
normalized_X_train = (X_train / min_) / (max_ - min_)

# Standardization
import numpy as np
mean = np.mean(X_train, axis=0)
std = np.std(X_train, axis=0)

 

 

x축과 y축의 변수 scaling

❶ Normalization

(x - min) / (max - min) : [0, 1] 실수

❷ Standarization

표준편차와 평균을 사용해 범위를 정규분포 이내로 옮김 

(x - u) / σ

 

=> Train set, Test set, Valid set (train set의 (mean, std)로 scaling)

 

Decision Tree

  • Regression, Classifcation 모델 둘 다 사용 가능
  • 비선형 데이터, 소규모 dataset에 적합함 (크면 Overfitting 위험 => 깊이 제한, leaf node (맨 마지막 node) 최소 샘플 수를 설정하면 가능)
  • 여러 변수의 조합에 따라 분기를 만들어야 하는 경우 사용
  • 클래스가 뚜렷이 구분되는 경우 (Classification) 사용

출처: ratsgo's blog

 

from sklearn.tree import DecisionTreeClassifier
tree = DecisionTreeClassifier()

tree.fit(train_input, train_target)

predict = tree.predict(test_input)

# 시각화를 위한 import
from sklearn.tree import export_graphviz

export_graphviz(tree, out_file = 'tree.dot',
                class_names= train_target,
                feature_names= train_input.columns,
                filled = True)

import graphviz

with open('tree.dot', encoding='UTF8') as f:
    dot_graph = f.read()
    
display(graphviz.Source(dot_graph))

SVM (Support Vector Machine)

  • Regression, Classification 모델 둘 다 사용 가능
  • 숫자 데이터만 처리 가능

1️⃣ Classification

  • 명확한 경계로 구분할 수 있는 이진 분류 작업에서 Good
  • 데이터가 선형적으로 분리되지 않는 경우에도 효과적
  • kernel trick을 사용하여 Input Feature를 고차원 공간으로 Mapping 가능

2️⃣ Regression

  • 변수가 복잡한 관계를 가지고, 시계열 예측 등 연속적인 출력이 필요할 때 사용

So, 고차원 데이터, 비선형 관계, 소규모 dataset 사용하면 Good

 

  • PCA : 주성분 분석을 사용하여 고차원 데이터를 2차원으로 축소 -> 시각화 용이, 학습 성능 High
  • 주성분 분석 : 데이터 정규화 -> 공분산 행렬 계산 -> 고유값 분해 -> 주성분 선택 -> 데이터 변환
  • meshgrid : 주로 2D, 3D 그래프를 그릴 때 사용하고, 두 개의 1D 배열을 입력 받아 2D 격자 좌표를 완성
  • np.c_ : 여러 배열을 열 방향으로 결합
  • .ravel() : 배열을 1차원으로 평탄화
from sklearn.svm import SVC
from sklearn.metrics import classification_report, confusion_matrix
from sklearn.preprocessing import StandardScaler
import seaborn as sns

model = SVC(kernel = 'linear') # 또는 다른 커널 사용 가능 (예 : 'rbf', 'poly)
model.fit(train_scaled, train_target)

y_pred = model.predict(test_scaled)

cm = confusion_matrix(test_target, y_pred)

plt.figure(figsize=(8, 6))
sns.heatmap(cm, annot=True, fmt="d", cmap="Blues", xticklabels=np.unique(test_target), yticklabels=np.unique(test_target))
plt.xlabel("Predicted")
plt.ylabel("True")
plt.title("Confusion Matrix")
plt.show()

from sklearn.preprocessing import LabelEncoder
from sklearn.decomposition import PCA
from sklearn.svm import SVC
import numpy as np
import matplotlib.pyplot as plt

# data ready
X = train_scaled

y = train_target

# LabelEncoder를 사용해 문자열 레이블을 수치형으로 변환
label_encoder = LabelEncoder()
y_encoded = label_encoder.fit_transform(y)

# PCA를 사용해 2차원으로 변환
pca = PCA(n_components=2)
X_pca = pca.fit_transform(X)

# SVM model fit
model = SVC(kernel='linear')
model.fit(X_pca, y_encoded)

# 결정 경계 시각화 함수
def plot_decision_boundary(X, y, model):
    x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
    y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
    xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.01),
                         np.arange(y_min, y_max, 0.01))
    
    Z = model.predict(np.c_[xx.ravel(), yy.ravel()])
    Z = Z.reshape(xx.shape)
    
    # 결정 경계와 데이터 포인트 시각화
    plt.contourf(xx, yy, Z, alpha=0.3, cmap=plt.cm.coolwarm)
    plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.coolwarm, edgecolors='k', s=100)
    plt.title("SVM Decision Boundary with PCA")
    plt.show()
    
# 결정 경계 그리기
plot_decision_boundary(X_pca, y_encoded, model)

MLP (Neural Network)

  • 다층 퍼셉트론 (다층 신경망)으로, 복잡한 패턴을 학습하고 예측하는 데 좋음
  • 비선형 문제, Classification & Regression (Supervised Learning을 주로 함), 복잡한 패턴 학습할 때 사용하면 좋음

진행 과정

데이터 전처리 (Standarization, Scaling, Feature engineering) -> 데이터 분할 -> 초기화 (MLP Parameter (weight, bias) 초기화) -> 순전파 (loss function) -> 역전파 (weight, biaas 조정) -> Hyperparameter 조정 (그리드 검색 등) -> 훈련 과정 monitoring

 

  • Compose : 여러 개의 변환
  • GPU를 사용하여 학습을 할 경우, Tensor()로 변환
  • Normalize : Tensor의 pixel 값을 정규화 (mean, std) => 0.5, 0.5 (표쥰 정규 분포)
# framework -> tensorflow -> pytorch
# MNIST(숫자), Fashion-MNIST(의류), CIFAR-10(10가지 종류), CIFAR-100, ImageNet
import torch
from torchvision import datasets, transforms
from matplotlib import pyplot as plt
import numpy as np

# define a transform to normalize the data
transform = transforms.Compose([transforms.ToTensor(),
                                transforms.Normalize((0.5,), (0.5,))])

# Download and load the training data
trainset = datasets.FashionMNIST('~/.pytorch/F_MNIST_data/', download=True, train=False, transform=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=128, shuffle=True)

# Download and load the test data
testset = datasets.FashionMNIST('~/.pytorch/F_MNIST_data/', download=True, train=False, transform=transform)
testloader = torch.utils.data.DataLoader(testset, batch_size=128, shuffle=False)

import matplotlib.pyplot as plt
import numpy as np

def imshow(image, ax=None, title=None, normalize=True, stand=False):
    # imshow for tensor
    if ax is None:
        _, ax = plt.subplots()
    
    image = image.numpy().transpose((1, 2, 0)) # Convert tensor to numpy format for imshow
    
    if normalize:
        image = image / image.max() # Normalize to range[0, 1]
    
    elif stand:
        image = image.std() * image + image.mean() # Standardization
        
    ax.imshow(image)
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.spines['left'].set_visible(False)
    ax.spines['bottom'].set_visible(False)
    ax.tick_params(axis='both', length=0)
    ax.set_xticklabels('')
    ax.set_yticklabels('')
    
    if title:
        ax.set_title(title)
    
    return ax

# Assuming you have 'image' already loaded as a tensor
fig, axes = plt.subplots(1, 3, figsize=(15, 5))

image = next(iter(trainloader))[0]

# Original image (no normalization, no standardization)
imshow(image[0, :], ax=axes[0], normalize=False, stand=False)
axes[0].set_title("Original")

# Normalized image
imshow(image[0, :], ax=axes[1], normalize=True, stand=False)
axes[1].set_title("Normalized")

# Standardized image
imshow(image[0, :], ax=axes[2], normalize=False, stand=True)
axes[2].set_title("Standardized")

plt.show()

import torch.nn as nn
import torch.nn.functional as F

class Classifier(nn.Module):
    def __init__(self):
        super().__init__()
        self.fc1 = nn.Linear(784, 256) # 이미지의 크기가 28 x 28 x 1 (흑백 이미지는 1차워느 컬러 이미지는 3차원) => 784 길이의 vector
        self.fc2 = nn.Linear(256, 128)
        self.fc3 = nn.Linear(128, 64)
        self.fc4 = nn.Linear(64, 10)
        
    def forward(self, x): # flatten
        x = x.view(x.shape[0], -1)
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = F.relu(self.fc3(x))
        x = self.fc4(x)
        
        return x    


import torch.optim as optim
import torch.nn.functional as F

model = Classifier() # 인공신경망 모델 선언
criterion = nn.CrossEntropyLoss() # 학습하는 손실 함수 (예측과 정답 사이의 차이를 구하는 방법 -> MAE(pred-target))
optimizer = optim.Adam(model.parameters(), lr=0.003) # Adam, SGD, RMSProp 등 다양하게 있는데, 웬만해서는 Adam이 성능이 제일 좋다.

epochs = 50
steps = 0

train_losses, test_losses = [], []
for e in range(epochs):
    running_loss = 0
    model.train() # 파라미터가 바뀜
    # model.eval() # 파라미터가 고정
    
    for images, labels in trainloader:
        
        # # Debugging 하면서 image가 뭔지 궁금할 때, 주석 풀기 (어떤 이미지가 모델 입력으로 들어가는지 시각화)
        # plt.close('all')
        # fig, axes = plt.subplots(1, len(images), figsize=(15, 5))
        # for i in range(len(images)):
        #     aa = imshow(images[i], ax = axes[i])
        #     axes[i].set_title(f"{i}_st image")
        # plt.show()

        optimizer.zero_grad()
        
        log_ps = model(images) # Input(images) 128 x 1 x 28 x 28 --> Output(log_ps) 128 x 10 (해당 클래스일 확률)
        ### 선언한 모델로 이미지를 받고, 값을 예측
        loss = criterion(log_ps, labels) ## 예측값과 정답값을 비교 -> 계산한 loss (MAE loss)
        
        loss.backward()
        optimizer.step() # 스케줄러 lr 0.003 -> 0.0003 -> 0.00003
        running_loss += loss.item() # torch 값이 item() -> 실수 값을 얻어냄
        # for 문이 끝나면 실행한다.
        
    # validation step
    test_loss = 0
    accuracy = 0
    
    model.eval()
    
    # Turn off gradients for validation, saves memory and computations
    # 자동 미분을 꺼서 pytorch가 쓸 데 없는 짓을 안하게 한다 (test set에서 하는 작업이므로)
    with torch.no_grad():
        for images, labels in testloader:
            log_ps = model(images)
            test_loss += criterion(log_ps, labels)
            
            # 로그 확률에 지수 적용
            ps = torch.exp(log_ps)
            # topk는 k번째로 큰 숫자를 찾아내는 것이다.
            # dim=1 은 dimension을 의미
            top_p, top_class = ps.topk(1, dim=1)
            # labels를 top_class와 똑같은 형태로 만든 다음에, 얼마나 같은 게 있는지 확인한다
            equals = top_class == labels.view(*top_class.shape)
            # equals를 float으로 바꾸고 평균 정확도를 그린다
            accuracy += torch.mean(equals.type(torch.FloatTensor))
            
    train_losses.append(running_loss/len(trainloader))
    test_losses.append(test_loss/len(testloader))
    
    # CE loss는 정답에 해당하는 logit에서 구한 확률을 -log(확률) 처리해주어, 만약 모델이 확률을 낮게 예측하면 loss는 높아지고 반대로 높게 예측하면 loss는 낮아진다
    print("Epoch : {}/{}..".format(e+1, epochs),
          "Training Loss : {:.3f}..".format(running_loss/len(trainloader)),
          "Test Loss : {:.3f}..".format(test_loss/len(testloader)),
          "Test Accuracy : {:.3f}..".format(accuracy/len(testloader)))

'Data Engineer > AI' 카테고리의 다른 글

AI - Pytorch  (6) 2024.11.14
AI - DL  (0) 2024.11.12
AI - ChatGPT API (Day 2)  (4) 2024.11.11
AI - ChatGPT API (Day 1)  (4) 2024.11.10
AI - ML  (3) 2024.11.05