日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

Python之sklearn:LabelEncoder函数简介(编码与编码还原)、使用方法、具体案例之详细攻略

發布時間:2025/3/21 python 47 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Python之sklearn:LabelEncoder函数简介(编码与编码还原)、使用方法、具体案例之详细攻略 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

Python之sklearn:LabelEncoder函數簡介(編碼與編碼還原)、使用方法、具體案例之詳細攻略

?

?

目錄

LabelEncoder函數的簡介(編碼與編碼還原)

Methods

LabelEncoder函數的使用方法

LabelEncoder函數的具體案例

1、基礎案例

2、在數據缺失和test數據內存在新值(train數據未出現過)環境下的數據LabelEncoder化


?

LabelEncoder函數的簡介(編碼與編碼還原)

class LabelEncoder Found at: sklearn.preprocessing._labelclass LabelEncoder(TransformerMixin, BaseEstimator):
? ? """Encode target labels with value between 0 and n_classes-1.
? ? This transformer should be used to encode target values, *i.e.* `y`, and not the input `X`.
? ? Read more in the :ref:`User Guide <preprocessing_targets>`.

?

""對目標標簽進行編碼,值在0到n_class -1之間

這個轉換器應該用于編碼目標值,*即' y ',而不是輸入' X '。

更多內容見:ref: ' User Guide '。

? ? .. versionadded:: 0.12
? ??
? ? Attributes
? ? ----------
? ? classes_ : array of shape (n_class,)
? ? Holds the label for each class.
? ??
? ? Examples
? ? --------
? ? `LabelEncoder` can be used to normalize labels.
? ??
? ? >>> from sklearn import preprocessing
? ? >>> le = preprocessing.LabelEncoder()
? ? >>> le.fit([1, 2, 2, 6])
? ? LabelEncoder()
? ? >>> le.classes_
? ? array([1, 2, 6])
? ? >>> le.transform([1, 1, 2, 6])
? ? array([0, 0, 1, 2]...)
? ? >>> le.inverse_transform([0, 0, 1, 2])
? ? array([1, 1, 2, 6])
? ??
? ? It can also be used to transform non-numerical labels (as long as they are hashable and comparable) to numerical labels.
? ??
? ? >>> le = preprocessing.LabelEncoder()
? ? >>> le.fit(["paris", "paris", "tokyo", "amsterdam"])
? ? LabelEncoder()
? ? >>> list(le.classes_)
? ? ['amsterdam', 'paris', 'tokyo']
? ? >>> le.transform(["tokyo", "tokyo", "paris"])
? ? array([2, 2, 1]...)
? ? >>> list(le.inverse_transform([2, 2, 1]))
? ? ['tokyo', 'tokyo', 'paris']
? ??
? ? See also
? ? --------
? ? sklearn.preprocessing.OrdinalEncoder : Encode categorical features using an ordinal encoding scheme.
? ? sklearn.preprocessing.OneHotEncoder : Encode categorical features as a one-hot numeric array.

. .versionadded:: 0.12

屬性
----------
classes_:形狀數組(n_class,)
保存每個類的標簽。

例子
--------
“LabelEncoder”可用于規范化標簽。

?

? ? >>> from sklearn import preprocessing
? ? >>> le = preprocessing.LabelEncoder()
? ? >>> le.fit([1, 2, 2, 6])
? ? LabelEncoder()
? ? >>> le.classes_
? ? array([1, 2, 6])
? ? >>> le.transform([1, 1, 2, 6])
? ? array([0, 0, 1, 2]...)
? ? >>> le.inverse_transform([0, 0, 1, 2])
? ? array([1, 1, 2, 6])


它還可以用于將非數字標簽(只要它們是可hashable和可比的)轉換為數字標簽

?

? ? >>> le = preprocessing.LabelEncoder()
? ? >>> le.fit(["paris", "paris", "tokyo", "amsterdam"])
? ? LabelEncoder()
? ? >>> list(le.classes_)
? ? ['amsterdam', 'paris', 'tokyo']
? ? >>> le.transform(["tokyo", "tokyo", "paris"])
? ? array([2, 2, 1]...)
? ? >>> list(le.inverse_transform([2, 2, 1]))
? ? ['tokyo', 'tokyo', 'paris']


另請參閱
--------
sklearn.preprocessing.OrdinalEncoder :序號編碼器:使用序號編碼方案編碼分類特征
sklearn.preprocessing.OneHotEncoder :??將分類特性編碼為一個熱的數字數組

? ? """
? ? def fit(self, y):
? ? ? ? """Fit label encoder

? ? ? ? Parameters
? ? ? ? ----------
? ? ? ? y : array-like of shape (n_samples,)
? ? ? ? ? ? Target values.

? ? ? ? Returns
? ? ? ? -------
? ? ? ? self : returns an instance of self.
? ? ? ? """
? ? ? ? y = column_or_1d(y, warn=True)
? ? ? ? self.classes_ = _encode(y)
? ? ? ? return self
? ??
? ? def fit_transform(self, y):
? ? ? ? """Fit label encoder and return encoded labels

? ? ? ? Parameters
? ? ? ? ----------
? ? ? ? y : array-like of shape [n_samples]
? ? ? ? ? ? Target values.

? ? ? ? Returns
? ? ? ? -------
? ? ? ? y : array-like of shape [n_samples]
? ? ? ? """
? ? ? ? y = column_or_1d(y, warn=True)
? ? ? ? self.classes_, y = _encode(y, encode=True)
? ? ? ? return y
? ??
? ? def transform(self, y):
? ? ? ? """Transform labels to normalized encoding.

? ? ? ? Parameters
? ? ? ? ----------
? ? ? ? y : array-like of shape [n_samples]
? ? ? ? ? ? Target values.

? ? ? ? Returns
? ? ? ? -------
? ? ? ? y : array-like of shape [n_samples]
? ? ? ? """
? ? ? ? check_is_fitted(self)
? ? ? ? y = column_or_1d(y, warn=True)
? ? ? ? # transform of empty array is empty array
? ? ? ? if _num_samples(y) == 0:
? ? ? ? ? ? return np.array([])
? ? ? ? _, y = _encode(y, uniques=self.classes_, encode=True)
? ? ? ? return y
? ??
? ? def inverse_transform(self, y):
? ? ? ? """Transform labels back to original encoding.

? ? ? ? Parameters
? ? ? ? ----------
? ? ? ? y : numpy array of shape [n_samples]
? ? ? ? ? ? Target values.

? ? ? ? Returns
? ? ? ? -------
? ? ? ? y : numpy array of shape [n_samples]
? ? ? ? """
? ? ? ? check_is_fitted(self)
? ? ? ? y = column_or_1d(y, warn=True)
? ? ? ? # inverse transform of empty array is empty array
? ? ? ? if _num_samples(y) == 0:
? ? ? ? ? ? return np.array([])
? ? ? ? diff = np.setdiff1d(y, np.arange(len(self.classes_)))
? ? ? ? if len(diff):
? ? ? ? ? ? raise ValueError(
? ? ? ? ? ? ? ? "y contains previously unseen labels: %s" % str(diff))
? ? ? ? y = np.asarray(y)
? ? ? ? return self.classes_[y]
? ??
? ? def _more_tags(self):
? ? ? ? return {'X_types':['1dlabels']}

?

?

Methods

fit(y)

Fit label encoder

fit_transform(y)

Fit label encoder and return encoded labels

get_params([deep])

Get parameters for this estimator.

inverse_transform(y)

Transform labels back to original encoding.

set_params(**params)

Set the parameters of this estimator.

transform(y)

Transform labels to normalized encoding.

?

?

LabelEncoder函數的使用方法

import pandas as pd from sklearn.preprocessing import LabelEncoder from DataScienceNYY.DataAnalysis import dataframe_fillAnyNull,Dataframe2LabelEncoder#構造數據 train_data_dict={'Name':['張三','李四','王五','趙六','張七','李八','王十','un'],'Age':[22,23,24,25,22,22,22,None],'District':['北京','上海','廣東','深圳','山東','河南','浙江',' '],'Job':['CEO','CTO','CFO','COO','CEO','CTO','CEO','']} test_data_dict={'Name':['張三','李四','王十一',None],'Age':[22,23,22,'un'],'District':['北京','上海','廣東',''],'Job':['CEO','CTO','UFO',' ']} train_data_df = pd.DataFrame(train_data_dict) test_data_df = pd.DataFrame(test_data_dict) print(train_data_df,'\n',test_data_df)#缺失數據填充 for col in train_data_df.columns:train_data_df[col]=dataframe_fillAnyNull(train_data_df,col)test_data_df[col]=dataframe_fillAnyNull(test_data_df,col) print(train_data_df,'\n',test_data_df)#數據LabelEncoder化 train_data,test_data=Dataframe2LabelEncoder(train_data_df,test_data_df) print(train_data,'\n',test_data)

?

?

?

?

LabelEncoder函數的具體案例

1、基礎案例

LabelEncoder can be used to normalize labels.>>> >>> from sklearn import preprocessing >>> le = preprocessing.LabelEncoder() >>> le.fit([1, 2, 2, 6]) LabelEncoder() >>> le.classes_ array([1, 2, 6]) >>> le.transform([1, 1, 2, 6]) array([0, 0, 1, 2]...) >>> le.inverse_transform([0, 0, 1, 2]) array([1, 1, 2, 6]) It can also be used to transform non-numerical labels (as long as they are hashable and comparable) to numerical labels.>>> >>> le = preprocessing.LabelEncoder() >>> le.fit(["paris", "paris", "tokyo", "amsterdam"]) LabelEncoder() >>> list(le.classes_) ['amsterdam', 'paris', 'tokyo'] >>> le.transform(["tokyo", "tokyo", "paris"]) array([2, 2, 1]...) >>> list(le.inverse_transform([2, 2, 1])) ['tokyo', 'tokyo', 'paris']

?

?

?

2、在數據缺失和test數據內存在新值(train數據未出現過)環境下的數據LabelEncoder化

參考文章:Python之sklearn:LabelEncoder函數的使用方法之使用LabelEncoder之前的必要操作

import numpy as np from sklearn.preprocessing import LabelEncoder#訓練train數據 LE= LabelEncoder() LE.fit(train_df[col])#test數據中的新值添加到LE.classes_ test_df[col] =test_df[col].map(lambda s:'Unknown' if s not in LE.classes_ else s) LE.classes_ = np.append(LE.classes_, 'Unknown') #分別轉化train、test數據 train_df[col] = LE.transform(train_df[col]) test_df[col] = LE.transform(test_df[col])

?

?

?

?

?

?

?

?

?

?

?

?

?

總結

以上是生活随笔為你收集整理的Python之sklearn:LabelEncoder函数简介(编码与编码还原)、使用方法、具体案例之详细攻略的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。