Daru Ruby Gem - 如何将分类变量转换为二进制变量

问题描述 投票:0回答:1

我有以下Daru数据框,其中包含一个名为search_term的分类变量:

home,search_term,bought
0,php,1
0,java,1
1,php,1
...

我想将它转换为带有二进制列的Daru数据框,例如:

home,php,java,bought
0,1,0,1
0,0,1,1
1,1,0,1
...

我找不到实现它的方法。我知道它可以在Python Panda中使用,但我想将Ruby与Darus gem一起使用。

谢谢。

ruby dataframe rubygems data-analysis
1个回答
0
投票

根据blog post机器学习库的作者Yoshoku编写的Rumale,您可以这样做:

train_df['IsFemale'] = train_df['Sex'].map { |v| v == 'female' ? 1 : 0 }

Rumale的标签编码器对分类变量也很有用。

require 'rumale'
encoder = Rumale::Preprocessing::LabelEncoder.new
labels = Numo::Int32[1, 8, 8, 15, 0]
encoded_labels = encoder.fit_transform(labels)
# Numo::Int32#shape=[5]
# [1, 2, 2, 3, 0]

Rumale ::预处理:: OneHotEncoder

encoder = Rumale::Preprocessing::OneHotEncoder.new
labels = Numo::Int32[0, 0, 2, 3, 2, 1]
one_hot_vectors = encoder.fit_transform(labels)
# > pp one_hot_vectors
# Numo::DFloat#shape[6, 4]
# [[1, 0, 0, 0],
#  [1, 0, 0, 0],
#  [0, 0, 1, 0],
#  [0, 0, 0, 1],
#  [0, 0, 1, 0],
#  [0, 1, 0, 0]]

但是,Daru :: Vector和Numo :: NArray的转换需要使用to_a

encoder = Rumale::Preprocessing::LabelEncoder.new
train_df['Embarked'] = encoder.fit_transform(train_df['Embarked'].to_a).to_a
© www.soinside.com 2019 - 2024. All rights reserved.