Categorical कॉलम्स को एन्कोड करना II: OneHotEncoder
ठीक है — अब आपके categorical कॉलम्स संख्यात्मक रूप में एन्कोड हो चुके हैं। क्या आप अब pipelines और XGBoost पर बढ़ सकते हैं? अभी नहीं! इस डेटासेट के categorical कॉलम्स में प्रविष्टियों के बीच कोई नैचरल ऑर्डरिंग नहीं है। उदाहरण के लिए: LabelEncoder का उपयोग करके, Neighborhood में CollgCr को 5 के रूप में, Veenker को 24 और Crawfor को 6 के रूप में एन्कोड किया गया। क्या Veenker, Crawfor और CollgCr से "बड़ा" है? नहीं — और मॉडल को ऐसी नैचरल ऑर्डरिंग मानने देना परफॉर्मेंस को खराब कर सकता है.
इसीलिए एक और स्टेप ज़रूरी है: आपको one-hot encoding लागू करनी होगी ताकि binary या "dummy" वैरिएबल्स बनाए जा सकें। आप यह scikit-learn के OneHotEncoder का उपयोग करके कर सकते हैं।
यह अभ्यास पाठ्यक्रम का हिस्सा है
XGBoost के साथ Extreme Gradient Boosting
अभ्यास निर्देश
sklearn.preprocessingसेOneHotEncoderइम्पोर्ट करें.oheनाम का एकOneHotEncoderऑब्जेक्ट बनाएँ। कीवर्ड आर्गुमेंटsparse=Falseसेट करें.- इसकी
.fit_transform()मेथड का उपयोग करकेOneHotEncoderकोdfपर लागू करें और आउटपुट कोdf_encodedके रूप में सेव करें। आउटपुट एक NumPy array होगा. df_encodedकी पहली 5 पंक्तियाँ प्रिंट करें, और फिर अंतर की तुलना के लिएdfतथाdf_encodedका shape प्रिंट करें.
इंटरैक्टिव व्यावहारिक अभ्यास
इस अभ्यास को इस नमूना कोड को पूरा करके आज़माएँ।
# Import OneHotEncoder
____
# Create OneHotEncoder: ohe
ohe = ____
# Apply OneHotEncoder to categorical columns - output is no longer a dataframe: df_encoded
df_encoded = ____
# Print first 5 rows of the resulting dataset - again, this will no longer be a pandas dataframe
print(df_encoded[:5, :])
# Print the shape of the original DataFrame
print(df.shape)
# Print the shape of the transformed array
print(df_encoded.shape)