Python AI and Machine Learning


14. 인공지능과 머신러닝(Artificial Intelligence and Machine Learning)

Scikit-learn을 이용한 머신러닝 모델 학습 및 평가 (Training and Evaluating Machine Learning Models with Scikit-learn)

Scikit-learn은 Python에서 가장 널리 사용되는 머신러닝 라이브러리 중 하나로, 다양한 머신러닝 알고리즘과 도구를 제공합니다.

데이터 준비 및 모델 학습

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score

# 데이터 로드
iris = load_iris()
X = iris.data
y = iris.target

# 훈련 데이터와 테스트 데이터로 분할
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

# 모델 학습
clf = RandomForestClassifier(n_estimators=100, random_state=42)
clf.fit(X_train, y_train)

# 예측
y_pred = clf.predict(X_test)

# 정확도 평가
accuracy = accuracy_score(y_test, y_pred)
print(f'Accuracy: {accuracy}')

위 예제에서는 Iris 데이터셋을 로드하고, 데이터를 훈련 세트와 테스트 세트로 분할한 후, 랜덤 포레스트 모델을 학습시켰습니다. 모델의 예측 결과를 바탕으로 정확도를 평가했습니다.

모델 평가

모델의 성능을 더 깊이 평가하기 위해 혼동 행렬, 정밀도, 재현율 등의 지표를 사용할 수 있습니다.

from sklearn.metrics import confusion_matrix, precision_score, recall_score, f1_score

# 혼동 행렬
conf_matrix = confusion_matrix(y_test, y_pred)
print('Confusion Matrix:')
print(conf_matrix)

# 정밀도, 재현율, F1 점수
precision = precision_score(y_test, y_pred, average='macro')
recall = recall_score(y_test, y_pred, average='macro')
f1 = f1_score(y_test, y_pred, average='macro')

print(f'Precision: {precision}')
print(f'Recall: {recall}')
print(f'F1 Score: {f1}')

TensorFlow와 Keras를 이용한 딥러닝 모델 개발 (Developing Deep Learning Models with TensorFlow and Keras)

TensorFlow와 Keras는 딥러닝 모델을 개발하기 위한 강력한 라이브러리입니다. TensorFlow는 강력한 오픈 소스 딥러닝 프레임워크이고, Keras는 사용하기 쉬운 고수준의 딥러닝 API입니다.

딥러닝 모델 구축

import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.datasets import mnist
from tensorflow.keras.utils import to_categorical

# 데이터 로드 및 전처리
(X_train, y_train), (X_test, y_test) = mnist.load_data()
X_train = X_train.reshape(-1, 784).astype('float32') / 255.0
X_test = X_test.reshape(-1, 784).astype('float32') / 255.0
y_train = to_categorical(y_train, 10)
y_test = to_categorical(y_test, 10)

# 모델 정의
model = Sequential([
    Dense(128, input_shape=(784,), activation='relu'),
    Dense(64, activation='relu'),
    Dense(10, activation='softmax')
])

# 모델 컴파일
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])

# 모델 학습
model.fit(X_train, y_train, epochs=10, batch_size=32, validation_split=0.2)

# 모델 평가
loss, accuracy = model.evaluate(X_test, y_test)
print(f'Test Accuracy: {accuracy}')

위 예제에서는 MNIST 데이터셋을 로드하고, 데이터를 전처리한 후, 간단한 다층 퍼셉트론 모델을 정의하고 학습시켰습니다. 모델의 성능을 테스트 데이터로 평가하여 정확도를 확인했습니다.

딥러닝 모델 예측

모델을 사용하여 새로운 데이터에 대해 예측을 수행할 수 있습니다.

# 새로운 데이터 예측
import numpy as np

# 테스트 데이터에서 첫 번째 이미지 예측
predicted_class = np.argmax(model.predict(X_test[:1]))
print(f'Predicted Class: {predicted_class}')

TensorFlow와 Keras를 사용하면 딥러닝 모델을 쉽게 정의하고 학습할 수 있습니다. Scikit-learn을 사용하여 머신러닝 모델을 학습하고 평가하는 과정과 함께, 이 두 가지 라이브러리를 통해 다양한 머신러닝과 딥러닝 모델을 개발하고 응용할 수 있습니다.


Leave a Reply

Your email address will not be published. Required fields are marked *