【问题标题】:spark.read.format('libsvm') not working with pythonspark.read.format('libsvm')不适用于python
【发布时间】:2019-12-09 07:38:48
【问题描述】:

我在学习PYSPARK,遇到了一个我无法解决的问题。我跟着这个视频从PYSPARK 文档中复制代码来加载线性回归的数据。我从文档中得到的代码是 spark.read.format('libsvm').load('file.txt')。我在此 btw 之前创建了一个 spark 数据框。当我在 Jupyter 笔记本中运行此代码时,它不断给我一些 java 错误,并且此视频中的人做了与我完全相同的事情,但他没有收到此错误。有人可以帮我解决这个问题吗?
非常感谢!

【问题讨论】:

  • 您遇到了什么样的 java 错误?只能在问题中复制和粘贴确切的堆栈跟踪。
  • 我在调用 o65 时出现错误。加载。 java.lang.UnsupportedOperationExeption:空集合。我认为这是因为格式。在视频中,格式是一个以绿色显示的关键字,但在我的文件中却是黑色。

标签: pyspark jupyter pyspark-dataframes


【解决方案1】:

我想我通过在选项方法中设置“numFeatures”解决了这个问题:

 training = spark.read.format('libsvm').option("numFeatures","10").load('sample_linear_regression_data.txt', header=True)

【讨论】:

    【解决方案2】:

    您可以使用此自定义函数来读取 libsvm 文件。

    from pyspark.sql import Row
    from pyspark.ml.linalg import SparseVector
    
    def read_libsvm(filepath, spark_session):
        '''
        A utility function that takes in a libsvm file and turn it to a pyspark dataframe.
    
        Args:
            filepath (str): The file path to the data file.
            spark_session (object): The SparkSession object to create dataframe.
    
        Returns:
            A pyspark dataframe that contains the data loaded.
        '''
    
        with open(filepath, 'r') as f:
            raw_data = [x.split() for x in f.readlines()]
    
        outcome = [int(x[0]) for x in raw_data]
    
        index_value_dict = list()
        for row in raw_data:
            index_value_dict.append(dict([(int(x.split(':')[0]), float(x.split(':')[1]))
                                           for x in row[1:]]))
    
        max_idx = max([max(x.keys()) for x in index_value_dict])
        rows = [
            Row(
                label=outcome[i],
                feat_vector=SparseVector(max_idx + 1, index_value_dict[i])
            )
            for i in range(len(index_value_dict))
        ]
        df = spark_session.createDataFrame(rows)
        return df
    

    用法:

    my_data = read_libsvm(filepath="sample_libsvm_data.txt", spark_session=spark)
    

    【讨论】:

      猜你喜欢
      • 2012-08-08
      • 2014-06-23
      • 2016-04-26
      • 2022-11-26
      • 1970-01-01
      • 2018-12-05
      • 2015-05-28
      • 2017-05-25
      • 2016-07-11
      相关资源
      最近更新 更多