我了解如何使用多種技術中的任何一種將標記資料編碼為數字資料,包括單熱編碼、標簽編碼、序數編碼等。我想知道如何將數字資料轉換回標記資料。這是一個簡單的例子。
import pandas as pd
import numpy as np
# Load Library
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_moons
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier,AdaBoostClassifier,GradientBoostingClassifier# Step1: Create data set
# Define the headers since the data does not have any
headers = ["symboling", "normalized_losses", "make", "fuel_type", "aspiration",
"num_doors", "body_style", "drive_wheels", "engine_location",
"wheel_base", "length", "width", "height", "curb_weight",
"engine_type", "num_cylinders", "engine_size", "fuel_system",
"bore", "stroke", "compression_ratio", "horsepower", "peak_rpm",
"city_mpg", "highway_mpg", "price"]
# Read in the CSV file and convert "?" to NaN
df = pd.read_csv("https://archive.ics.uci.edu/ml/machine-learning-databases/autos/imports-85.data",
header=None, names=headers, na_values="?" )
df.head()
df.columns
df_fin = pd.DataFrame({col: df[col].astype('category').cat.codes for col in df}, index=df.index)
df_fin
X = df_fin[['symboling', 'normalized_losses', 'make', 'fuel_type', 'aspiration',
'num_doors', 'body_style', 'drive_wheels', 'engine_location',
'wheel_base', 'length', 'width', 'height', 'curb_weight', 'engine_type',
'num_cylinders', 'engine_size', 'fuel_system', 'bore', 'stroke',
'compression_ratio', 'horsepower', 'peak_rpm']]
y = df_fin['city_mpg']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Fit a Decision Tree model
clf = DecisionTreeClassifier()
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
accuracy_score(y_test, y_pred)
現在,如何根據自變數對目標變數(因變數)進行預測???
像這樣的東西應該可以作業,我認為,但它沒有......
clf.predict([[2,164,'audi','gas','std','four','sedan','fwd','front',99.8,176.6,66.2,54.3,2337,'ohc','four',109,'mpfi',3.19,3.4,10,102,5500,24,30,13950,]])
如果我們將數字保留為數字,并在標簽周圍加上引號,我想預測因變數,但我不能,因為標簽資料。如果資料都是數字,這是一個回歸問題,它會作業!!我的問題是,我們如何將分類代碼轉換回數字標記資料,并做出預測?
uj5u.com熱心網友回復:
您要用于預測目標變數的輸入資料需要與用于訓練模型的資料具有相同的格式。
我建議使用 eg 編碼分類資料sklearn OneHotEncoder(對于一種熱編碼,但也有 iaOrdinalEncoder和LabelEncoder)。這允許您首先fit()對分類資料進行預處理,然后您可以將transform()其用于您希望預測的資料。
使用一種熱編碼的示例:
import pandas as pd
from sklearn.preprocessing import OneHotEncoder
df = pd.DataFrame({"car_make": ["audi", "bmw", "bmw", "renault"],
"car_country": ["DE", "DE", "DE", "FR"], "car_age": [1, 3, 1, 5]})
categorical_cols = ["car_make", "car_country"]
enc = OneHotEncoder()
enc.fit(df[categorical_cols]) # fitting the transformer on our categorical data
X_enc = enc.transform(df[categorical_cols]).toarray() # this returns a numpy array with the encoded values
您可以get_feature_names_out()在適合的編碼器上使用該方法來獲取列名陣列。基于上述構建的示例:
df_encoded = pd.DataFrame(X_enc, columns=enc.get_feature_names_out())
print(df_encoded)
car_make_audi car_make_bmw car_make_renault car_country_DE car_country_FR
0 1.0 0.0 0.0 1.0 0.0
1 0.0 1.0 0.0 1.0 0.0
2 0.0 1.0 0.0 1.0 0.0
3 0.0 0.0 1.0 0.0 1.0
# getting our original values:
df_orig = enc.inverse_transform(X_enc)
print(df_orig)
[['audi' 'DE']
['bmw' 'DE']
['bmw' 'DE']
['renault' 'FR']]
如果您想將這些值轉換回它們的原始值,您可以inverse_transform在編碼資料上使用它們來回傳它們。
我建議查看檔案以獲取更多詳細資訊和用例:https ://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.OneHotEncoder.html#sklearn.preprocessing.OneHotEncoder
使用 sklearn 前處理器將為您省去很多麻煩!
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/508443.html
標籤:Python python-3.x 机器学习 数据科学 人工智能
