Predicting Iris Flower Types with XGBoost

  • Share this:

Code introduction


This function uses the XGBoost library to train a classifier to predict the type of Iris flower in the Iris dataset. It first loads the data, then splits it into training and test sets, creates and trains an XGBoost model, and finally calculates and returns the model's accuracy.


Technology Stack : XGBoost, scikit-learn

Code Type : Function

Code Difficulty : Intermediate


                
                    
def predict_iris_features(features):
    import xgboost as xgb
    from sklearn.datasets import load_iris
    from sklearn.model_selection import train_test_split
    from sklearn.metrics import accuracy_score

    # 加载数据
    iris = load_iris()
    X, y = iris.data, iris.target

    # 划分训练集和测试集
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

    # 创建XGBoost分类器
    model = xgb.XGBClassifier(use_label_encoder=False, eval_metric='mlogloss')

    # 训练模型
    model.fit(X_train, y_train)

    # 预测测试集结果
    y_pred = model.predict(X_test)

    # 计算准确率
    accuracy = accuracy_score(y_test, y_pred)

    return accuracy