Python Sklearn LabelEncoder inverse transform

Click For Summary
To inverse a label transformation using sklearn's LabelEncoder and obtain an array with the shape (10, 7), the 'reshape' function can be applied after using 'inverse_transform'. The process involves first transforming the original array into a label-encoded format and then using 'inverse_transform' to revert it back. The final step is to reshape the resulting array to the desired dimensions. This method effectively restores the original array structure while maintaining the integrity of the data.
BRN
Messages
107
Reaction score
10
Hi everyone!

I need to inverse an label transform with sklearn. I found this example on web:

[CODE lang="python" title="example"]
from sklearn.preprocessing import LabelEncoder

np.random.seed(1)
y = np.random.randint(0, 2, (10, 7))
y = y[np.where(y.sum(axis=1) != 0)[0]]
[/CODE]
[CODE title="output:"]
array([[1, 1, 0, 0, 1, 1, 1],
[1, 1, 0, 0, 1, 0, 1],
[1, 0, 0, 1, 0, 0, 0],
[1, 0, 0, 1, 0, 0, 0],
[1, 0, 0, 0, 1, 1, 1],
[1, 1, 0, 0, 0, 1, 1],
[1, 1, 1, 1, 0, 1, 1],
[0, 0, 1, 0, 0, 1, 1],
[1, 0, 1, 0, 0, 1, 1],
[0, 1, 1, 1, 1, 0, 0]])
[/CODE]

[CODE lang="python" title="example"]
le = LabelEncoder()
y_new = le.fit_transform([''.join(str(l)) for l in y])
[/CODE]
[CODE title="output:"]
array([7, 6, 3, 3, 2, 5, 8, 0, 4, 1])
[/CODE]

[CODE lang="python" title="example"]
y_old = le.inverse_transform(y_new)
[/CODE]
[CODE title="output:"]
array(['[1 1 0 0 1 1 1]', '[1 1 0 0 1 0 1]', '[1 0 0 1 0 0 0]',
'[1 0 0 1 0 0 0]', '[1 0 0 0 1 1 1]', '[1 1 0 0 0 1 1]',
'[1 1 1 1 0 1 1]', '[0 0 1 0 0 1 1]', '[1 0 1 0 0 1 1]',
'[0 1 1 1 1 0 0]'], dtype='<U15')
[/CODE]

With 'inverse_transform' How can I obtain an array with shape (10, 7)?

Thaks!
 
Technology news on Phys.org


Hi there!

To obtain an array with shape (10, 7), you can use the 'reshape' function after applying the 'inverse_transform' method. Here's an example:

y_old = le.inverse_transform(y_new).reshape(10,7)

This will reshape the array to have 10 rows and 7 columns. Hope this helps!
 

Similar threads

  • · Replies 2 ·
Replies
2
Views
1K
  • · Replies 34 ·
2
Replies
34
Views
3K
  • · Replies 18 ·
Replies
18
Views
1K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 17 ·
Replies
17
Views
3K
  • · Replies 7 ·
Replies
7
Views
3K
  • · Replies 6 ·
Replies
6
Views
2K
  • · Replies 1 ·
Replies
1
Views
4K
Replies
3
Views
4K
  • · Replies 5 ·
Replies
5
Views
3K