Class: Rumale::Preprocessing::LabelEncoder

Inherits:
Base::Estimator show all
Includes:
Base::Transformer
Defined in:
rumale-preprocessing/lib/rumale/preprocessing/label_encoder.rb

Overview

Encode labels to values between 0 and n_classes - 1.

Examples:

require 'rumale/preprocessing/label_encoder'

encoder = Rumale::Preprocessing::LabelEncoder.new
labels = Numo::Int32[1, 8, 8, 15, 0]
encoded_labels = encoder.fit_transform(labels)
# > pp encoded_labels
# Numo::Int32#shape=[5]
# [1, 2, 2, 3, 0]
decoded_labels = encoder.inverse_transform(encoded_labels)
# > pp decoded_labels
# [1, 8, 8, 15, 0]

Instance Attribute Summary collapse

Attributes inherited from Base::Estimator

#params

Instance Method Summary collapse

Constructor Details

#initializeLabelEncoder

Create a new encoder for encoding labels to values between 0 and n_classes - 1.



30
31
32
# File 'rumale-preprocessing/lib/rumale/preprocessing/label_encoder.rb', line 30

def initialize # rubocop:disable Lint/UselessMethodDefinition
  super()
end

Instance Attribute Details

#classesArray (readonly)

Return the class labels.

Returns:

  • (Array)

    (size: [n_classes])



27
28
29
# File 'rumale-preprocessing/lib/rumale/preprocessing/label_encoder.rb', line 27

def classes
  @classes
end

Instance Method Details

#fit(x) ⇒ LabelEncoder

Fit label-encoder to labels.

Parameters:

  • x (Array)

    (shape: [n_samples]) The labels to fit label-encoder.

Returns:



40
41
42
43
44
# File 'rumale-preprocessing/lib/rumale/preprocessing/label_encoder.rb', line 40

def fit(x, _y = nil)
  x = x.to_a if x.is_a?(Numo::NArray)
  @classes = x.sort.uniq
  self
end

#fit_transform(x) ⇒ Numo::Int32

Fit label-encoder to labels, then return encoded labels.

Parameters:

  • x (Array)

    (shape: [n_samples]) The labels to fit label-encoder.

Returns:

  • (Numo::Int32)

    The encoded labels.



52
53
54
55
# File 'rumale-preprocessing/lib/rumale/preprocessing/label_encoder.rb', line 52

def fit_transform(x, _y = nil)
  x = x.to_a if x.is_a?(Numo::NArray)
  fit(x).transform(x)
end

#inverse_transform(x) ⇒ Array

Decode encoded labels.

Parameters:

  • x (Numo::Int32)

    (shape: [n_samples]) The labels to be decoded.

Returns:

  • (Array)

    The decoded labels.



70
71
72
# File 'rumale-preprocessing/lib/rumale/preprocessing/label_encoder.rb', line 70

def inverse_transform(x)
  x.to_a.map { |n| @classes[n] }
end

#transform(x) ⇒ Numo::Int32

Encode labels.

Parameters:

  • x (Array)

    (shape: [n_samples]) The labels to be encoded.

Returns:

  • (Numo::Int32)

    The encoded labels.



61
62
63
64
# File 'rumale-preprocessing/lib/rumale/preprocessing/label_encoder.rb', line 61

def transform(x)
  x = x.to_a if x.is_a?(Numo::NArray)
  Numo::Int32[*(x.map { |v| @classes.index(v) })]
end