ium_487187/train.py

102 lines
3.2 KiB
Python
Raw Normal View History

2023-05-11 00:32:25 +02:00
import mlflow
import mlflow.keras
from mlflow.models.signature import infer_signature
from mlflow.models import Model
import pandas as pd
2023-05-10 19:49:38 +02:00
from sacred import Experiment
2023-05-11 00:11:04 +02:00
from sacred.observers import MongoObserver, FileStorageObserver
2023-05-10 21:51:16 +02:00
import os
2023-05-11 01:01:37 +02:00
import tensorflow as tf
from tensorflow.python.framework import tensor_spec
2023-05-11 01:06:21 +02:00
import numpy as np
2023-05-10 21:51:16 +02:00
2023-05-10 22:02:47 +02:00
os.environ["SACRED_NO_GIT"] = "1"
2023-05-10 22:00:04 +02:00
ex = Experiment('s487187-training', interactive=True, save_git_info=False)
2023-05-10 20:50:43 +02:00
ex.observers.append(MongoObserver(url='mongodb://admin:IUM_2021@172.17.0.1:27017', db_name='sacred'))
2023-05-11 00:32:25 +02:00
mlflow.set_tracking_uri("http://172.17.0.1:5000")
mlflow.set_experiment("s487187")
2023-05-11 00:11:04 +02:00
2023-05-10 20:50:43 +02:00
@ex.config
def my_config():
2023-05-11 00:11:04 +02:00
data_file = 'data.csv'
model_file = 'model.h5'
2023-05-10 20:50:43 +02:00
epochs = 10
batch_size = 32
test_size = 0.2
random_state = 42
2023-05-10 20:50:43 +02:00
@ex.capture
def train_model(data_file, model_file, epochs, batch_size, test_size, random_state):
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
import tensorflow as tf
from imblearn.over_sampling import SMOTE
2023-05-11 00:11:04 +02:00
smote = SMOTE(random_state=random_state)
2023-05-11 01:06:21 +02:00
data = pd.read_csv(data_file, sep=';', header=0)
2023-05-11 00:11:04 +02:00
print('Total rows:', len(data))
print('Rows with medal:', len(data.dropna(subset=['Medal'])))
2023-05-11 00:11:04 +02:00
data = pd.get_dummies(data, columns=['Sex', 'Medal'])
data = data.drop(columns=['Name', 'Team', 'NOC', 'Games', 'Year', 'Season', 'City', 'Sport', 'Event'])
2023-05-11 00:11:04 +02:00
scaler = MinMaxScaler()
data = pd.DataFrame(scaler.fit_transform(data), columns=data.columns)
2023-05-11 00:11:04 +02:00
X = data.filter(regex='Sex|Age')
y = data.filter(regex='Medal')
y = pd.get_dummies(y)
2023-05-11 00:11:04 +02:00
X = X.fillna(0)
y = y.fillna(0)
2023-05-11 00:11:04 +02:00
y = y.values
2023-05-11 00:11:04 +02:00
X_resampled, y_resampled = smote.fit_resample(X, y)
X_train, X_test, y_train, y_test = train_test_split(X_resampled, y_resampled, test_size=test_size, random_state=random_state)
2023-05-11 00:11:04 +02:00
model = tf.keras.models.Sequential()
model.add(tf.keras.layers.Dense(64, input_dim=X_train.shape[1], activation='relu'))
model.add(tf.keras.layers.Dense(32, activation='relu'))
model.add(tf.keras.layers.Dense(y.shape[1], activation='softmax'))
2023-05-11 00:11:04 +02:00
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
2023-05-11 00:11:04 +02:00
model.fit(X_train, y_train, epochs=epochs, batch_size=batch_size)
loss, accuracy = model.evaluate(X_test, y_test)
print('Test accuracy:', accuracy)
print('Test loss:', loss)
2023-05-10 23:54:20 +02:00
2023-05-14 15:13:13 +02:00
model.save("model.h5")
2023-05-14 15:31:15 +02:00
X_train_numpy = X_train.values
signature = infer_signature(X_train_numpy, model.predict(X_train_numpy))
input_example = X_train.head(1).values
2023-05-14 15:22:54 +02:00
# input_signature = {
# 'input': tensor_spec.TensorSpec(shape=X_train.iloc[0].shape, dtype=X_train.dtypes[0])
# }
2023-05-11 00:32:25 +02:00
mlflow.keras.log_model(model, "model")
mlflow.log_artifact("model.h5")
2023-05-14 15:31:15 +02:00
# Use the ndarray form for infer_signature and input_example
signature = infer_signature(X_train_numpy, model.predict(X_train_numpy))
input_example = X_train.head(1).values
mlflow.keras.save_model(model, "model", signature=signature, input_example=input_example)
2023-05-11 00:32:25 +02:00
2023-05-14 15:13:13 +02:00
return accuracy
2023-05-10 19:49:38 +02:00
2023-05-10 20:50:43 +02:00
@ex.main
def run_experiment():
accuracy = train_model()
ex.log_scalar('accuracy', accuracy)
ex.add_artifact('model.h5')
2023-05-10 22:03:08 +02:00
2023-05-11 00:32:25 +02:00
ex.run()