转换csv与分类数据libsvm



我正在使用spark MLlib构建机器学习模型。我需要给libsvm格式文件作为输入,如果在数据中有分类变量。

我尝试转换csv文件到libsvm使用1. Convert.clibsvm网站建议的2. Csvtolibsvm.py in phraug github

但是这两个脚本似乎都没有转换分类数据。我还安装了weka并尝试保存为libsvm格式。但在weka explorer中找不到这个选项。

请建议将csv与分类数据转换为libsvm格式的任何其他方法,或者让我知道我是否在这里缺少任何东西。

提前感谢您的帮助

我猜你想训练一个支持向量机。它需要输入一个rdd [LabeledPoint]。

https://spark.apache.org/docs/1.4.1/api/scala/org.apache.spark.mllib.classification.SVMWithSGD

我建议你对待你的分类列类似于这里的第二个答案:

如何将Spark中的分类变量转换为一组编码为{0,1}的列?

,其中LogisticRegression的情况与SVM的情况非常相似。

您可以尝试散列技巧将分类特征转换为数字,然后将数据框转换为rdd,如果顺序将函数映射到每一行。下面的假示例是使用pyspark解决的。

例如,用于转换的数据框架是df:
>> df.show(5)
+------+----------------+-------+-------+
|gender|            city|country|     os|
+------+----------------+-------+-------+
|     M|         chennai|     IN|ANDROID|
|     F|       hyderabad|     IN|ANDROID|
|     M|leighton buzzard|     GB|ANDROID|
|     M|          kanpur|     IN|ANDROID|
|     F|       lafayette|     US|    IOS|
+------+----------------+-------+-------+

我想用特征:工作,城市,国家来预测性别。

import hashlib
from pyspark.sql import Row
from pyspark.ml.linalg import SparseVector
spark = SparkSession 
    .builder 
    .appName("Spark-app")
     .config("spark.some.config.option", "some-value")
    .getOrCreate() # create the spark session
NR_BINS = 100000 # the total number of categories, it should be a big number if you have many different categories in each feature and a lot of categorical features. in the meantime do consider the memory.
def hashnum(input):
    return int(hashlib.md5(input).hexdigest(), 16)%NR_BINS + 1
def libsvm_converter(row):
    target = "gender"
    features = ['city', 'country', 'os']
    if row[target] == "M":
        lab = 1
    elif row[target] == "F":
        lab = 0
    else:
        return
    sparse_vector = []
    for f in features:
        v = '{}-{}'.format(f, row[f].encode('utf-8'))
        hashv = hashnum(v) # the index in libsvm
        sparse_vector.append((hashv, 1)) # the value is always 1 because of categorical feature
    sparse_vector = list(set(sparse_vector)) # in case there are clashes (BR_BINS not big enough)
    return Row(label = lab, features=SparseVector(NR_BINS, sparse_vector))

libsvm = df.rdd.map(libsvm_converter_2)
data = spark.createDataFrame(libsvm)

如果你检查数据,它看起来像这样;

>> data.show()
+--------------------+-----+
|            features|label|
+--------------------+-----+
|(100000,[12626,68...|    1|
|(100000,[59866,68...|    0|
|(100000,[66386,68...|    1|
|(100000,[53746,68...|    1|
|(100000,[6966,373...|    0|
+--------------------+-----+

最新更新