큰 NumPy 배열을 포함하는 객체를 저장하고 로드하는데 효율적
import joblib
from sklearn.linear_model import LinearRegression
from sklearn.datasets import make_regression
# 샘플 데이터 생성 및 학습
X, y = make_regression(n_samples=100, n_features=1, noise=0.1)
model = LinearRegression()
model.fit(X, y)
# 파일 저장
joblib.dump(model, 'linear_model.pkl', compress=3)
print("Model saved successfully.")
import joblib
from sklearn.datasets import make_regression
X, y = make_regression(n_samples=100, n_features=1, noise=0.1)
# 모델 로드
loaded_model = joblib.load('linear_model.pkl')
print("Model loaded successfully.")
# 모델 사용
y_pred = loaded_model.predict(X)
print(y_pred)
Python 객체를 직렬화/역직렬화 하는데 사용
import pickle
from sklearn.linear_model import LinearRegression
from sklearn.datasets import make_regression
# 샘플 데이터 생성 및 학습
X, y = make_regression(n_samples=100, n_features=1, noise=0.1)
model = LinearRegression()
model.fit(X, y)
# 모델 저장
with open('linear_model2.pkl', 'wb') as f: # 'wb': 쓰기 모드로 저장
pickle.dump(model, f)
print("Model saved successfully.")
import pickle
from sklearn.datasets import make_regression
X, y = make_regression(n_samples=100, n_features=1, noise=0.1)
# 모델 로드
with open('linear_model2.pkl', 'rb') as f:
loaded_model = pickle.load(f)
print("Model loaded successfully.")
# 모델 사용
y_pred = loaded_model.predict(X)
print(y_pred)
import numpy as np
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.utils import to_categorical
# 데이터 생성
np.random.seed(42)
X = np.random.rand(100, 10)
y = np.random.randint(0, 2, 100)
y = to_categorical(y)
# 모델 생성 및 학습
model = Sequential([
Dense(32, activation='relu', input_shape=(10,)),
Dense(2, activation='softmax')
])
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
model.fit(X, y, epochs=5, batch_size=10, verbose=0)
# 모델 저장 (.keras 형식)
model.save('classification_model.keras')
print("Model saved successfully in .keras format.")
import numpy as np
from tensorflow.keras.models import load_model
# 모델 로드
loaded_model = load_model('classification_model.keras')
print('Model loaded successfully.')
# 새로운 데이터에 대한 예측
sample_data = np.random.rand(1, 10)
prediction = loaded_model.predict(sample_data)
print(f'Prediction for {sample_data}: {prediction}')
Google Cloud 주피터(Jupyer) 노트북 기반으로 머신러닝 교육 및 연구에 널리 사용되는 툴