You can wrap the codes into a function like this:

import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import f1_score
from sklearn.model_selection import cross_val_score

def train_model(filename):
    # 1. Load data
    data = pd.read_csv(filename)

    # 2. Preprocessing
    # Dimension reduction
    corr = data.corr().loc[:, "label"]
    corr_bigger_001 = corr[(corr > 0.02) | (corr < -0.02)]
    data = data[corr_bigger_001.index]

    # Handle missing values
    data = data.fillna(data.mean())

    # Scale data
    scaler = MinMaxScaler()
    X = scaler.fit_transform(data.iloc[:, :-1])
    Y = data.iloc[:, -1]

    # Split into train and test sets
    X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.33, random_state=42)

    # 3. Select model
    model = DecisionTreeClassifier(max_depth=5)

    # 4. Train model
    model.fit(X_train, y_train)

    # 5. Evaluate model
    y_pred = model.predict(X_test)
    score = f1_score(y_pred, y_test, average="macro")

    return model, score

You can then call the train_model function and pass the filename of your dataset to train the model and get the model object and the evaluation score

import pandas as pdimport matplotlibpyplot as pltfrom sklearnensemble import RandomForestClassifierAdaBoostClassifierfrom sklearnmodel_selection import train_test_splitfrom sklearnpreprocessing import

原文地址: https://www.cveoy.top/t/topic/hWoR 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录