[英]How to use dummy variable to represent categorical data in python scikit-learn random forest
[英]How to create dummy variable and then aggregate using scikit-learn?
我知道使用pandas包很容易實現,但是因為它太稀疏太大(170,000 x 5000),最后我需要再次使用sklearn來處理數據,我想知道是否有用 sklearn 做的方法。 我嘗試了一個熱編碼器,但被困在將假人與“id”關聯起來。
df = pd.DataFrame({'id': [1, 1, 2, 2, 3, 3], 'item': ['a', 'a', 'c', 'b', 'a', 'b']})
id item
0 1 a
1 1 a
2 2 c
3 2 b
4 3 a
5 3 b
dummy = pd.get_dummies(df, prefix='item', columns=['item'])
dummy.groupby('id').sum().reset_index()
id item_a item_b item_c
0 1 2 0 0
1 2 0 1 1
2 3 1 1 0
更新:
現在我來了,'id' 丟失了,那怎么做聚合呢?
lab = sklearn.preprocessing.LabelEncoder()
labels = lab.fit_transform(np.array(df.item))
enc = sklearn.preprocessing.OneHotEncoder()
dummy = enc.fit_transform(labels.reshape(-1,1))
dummy.todense()
matrix([[ 1., 0., 0.],
[ 1., 0., 0.],
[ 0., 0., 1.],
[ 0., 1., 0.],
[ 1., 0., 0.],
[ 0., 1., 0.]])
如果將來有人需要參考,我將我的解決方案放在這里。 我使用了 scipy 稀疏矩陣。
首先,進行分組並計算記錄數。
df = df.groupby(['id','item']).size().reset_index().rename(columns={0:'count'})
這需要一些時間,但不需要幾天。
然后使用數據透視表,我在這里找到了解決方案。
from scipy.sparse import csr_matrix
def to_sparse_pivot(df, id, item, count):
id_u = list(df[id].unique())
item_u = list(np.sort(df[item].unique()))
data = df[count].tolist()
row = df[id].astype('category', categories=id_u).cat.codes
col = df[item].astype('category', categories=item_u).cat.codes
return csr_matrix((data, (row, col)), shape=(len(id_u), len(item_u)))
然后調用函數
result = to_sparse_pivot(df, 'id', 'item', 'count')
OneHotEncoder 需要整數,所以這里是一種將您的項目映射到唯一整數的方法。 因為映射是一對一的,我們也可以逆向這個字典。
import pandas as pd
from sklearn.preprocessing import OneHotEncoder
df = pd.DataFrame({'ID': [1, 1, 2, 2, 3, 3],
'Item': ['a', 'a', 'c', 'b', 'a', 'b']})
mapping = {letter: integer for integer, letter in enumerate(df.Item.unique())}
reverse_mapping = {integer: letter for letter, integer in mapping.iteritems()}
>>> mapping
{'a': 0, 'b': 2, 'c': 1}
>>> reverse_mapping
{0: 'a', 1: 'c', 2: 'b'}
現在創建一個 OneHotEncoder 並映射您的值。
hot = OneHotEncoder()
h = hot.fit_transform(df.Item.map(mapping).values.reshape(len(df), 1))
>>> h
<6x3 sparse matrix of type '<type 'numpy.float64'>'
with 6 stored elements in Compressed Sparse Row format>
>>> h.toarray()
array([[ 1., 0., 0.],
[ 1., 0., 0.],
[ 0., 1., 0.],
[ 0., 0., 1.],
[ 1., 0., 0.],
[ 0., 0., 1.]])
作為參考,這些將是適當的列:
>>> [reverse_mapping[n] for n in reverse_mapping.keys()]
['a', 'c', 'b']
從您的數據中,您可以看到數據框中的值c
位於第三行(索引值為 2)。 這已映射到c
,您可以從反向映射中看到中間列。 它也是矩陣中間列中唯一包含值 1 的值,這證實了結果。
除此之外,我不確定你會被困在哪里。 如果您仍然有問題,請澄清。
連接 ID 值:
>>> np.concatenate((df.ID.values.reshape(len(df), 1), h.toarray()), axis=1)
array([[ 1., 1., 0., 0.],
[ 1., 1., 0., 0.],
[ 2., 0., 1., 0.],
[ 2., 0., 0., 1.],
[ 3., 1., 0., 0.],
[ 3., 0., 0., 1.]])
保持數組稀疏:
from scipy.sparse import hstack, lil_matrix
id_vals = lil_matrix(df.ID.values.reshape(len(df), 1))
h_dense = hstack([id_vals, h.tolil()])
>>> type(h_dense)
scipy.sparse.coo.coo_matrix
>>> h_dense.toarray()
array([[ 1., 1., 0., 0.],
[ 1., 1., 0., 0.],
[ 2., 0., 1., 0.],
[ 2., 0., 0., 1.],
[ 3., 1., 0., 0.],
[ 3., 0., 0., 1.]])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.