MCPcopy Create free account
hub / github.com/dmlc/xgboost / native

Function native

demo/guide-python/cat_pipeline.py:58–101  ·  view source on GitHub ↗

Using the native XGBoost interface.

()

Source from the content-addressed store, hash-verified

56
57
58def native() -> None:
59 """Using the native XGBoost interface."""
60 X, y, cat_feats = make_example_data()
61
62 X_train, X_test, y_train, y_test = train_test_split(
63 X, y, random_state=1994, test_size=0.2
64 )
65
66 # Create an encoder based on training data.
67 enc = OrdinalEncoder(handle_unknown="use_encoded_value", unknown_value=np.nan)
68 enc.set_output(transform="pandas")
69 enc = enc.fit(X_train[cat_feats])
70
71 def enc_transform(X: pd.DataFrame) -> pd.DataFrame:
72 # don't make change inplace so that we can have demonstrations for encoding
73 X = X.copy()
74 cat_cols = enc.transform(X[cat_feats])
75 for i, name in enumerate(cat_feats):
76 # create pd.Series based on the encoder
77 cat_cols[name] = pd.Categorical.from_codes(
78 codes=cat_cols[name].astype(np.int32), categories=enc.categories_[i]
79 )
80 X[cat_feats] = cat_cols
81 return X
82
83 # Encode the data based on fitted encoder.
84 X_train_enc = enc_transform(X_train)
85 X_test_enc = enc_transform(X_test)
86 # Train XGBoost model using the native interface.
87 Xy_train = xgb.QuantileDMatrix(X_train_enc, y_train, enable_categorical=True)
88 Xy_test = xgb.QuantileDMatrix(
89 X_test_enc, y_test, enable_categorical=True, ref=Xy_train
90 )
91 booster = xgb.train({}, Xy_train)
92 booster.predict(Xy_test)
93
94 # Following shows that data are encoded consistently.
95
96 # We first obtain result from newly encoded data
97 predt0 = booster.inplace_predict(enc_transform(X_train.head(16)))
98 # then we obtain result from already encoded data from training.
99 predt1 = booster.inplace_predict(X_train_enc.head(16))
100
101 np.testing.assert_allclose(predt0, predt1)
102
103
104def pipeline() -> None:

Callers 1

cat_pipeline.pyFile · 0.85

Calls 7

make_example_dataFunction · 0.85
enc_transformFunction · 0.85
QuantileDMatrixMethod · 0.80
fitMethod · 0.45
trainMethod · 0.45
predictMethod · 0.45
inplace_predictMethod · 0.45

Tested by

no test coverage detected