【问题标题】:Creating a brand-new Scikit-Learn Dataset out of a CSV with string variables使用字符串变量从 CSV 创建全新的 Scikit-Learn 数据集
【发布时间】:2022-01-25 05:27:18
【问题描述】:

查找此内容后,我找到了解决问题的可能方法:How to transform my csv file into this scikit learn dataset

但是,同事的问题从未暗示过分类变量,因此每当我尝试实现此代码时,都会发现此错误:

ValueError: could not convert string to float: 'Adzuki beans, uncooked'
 

到目前为止我的代码:

def load_my_dataset():
    with open('data/Composition3_remastered') as csv_file:
        data_file = csv.reader(csv_file)
        temp = next(data_file)
        n_samples = 1878 #number of data rows, don't count header
        n_features = 14 #number of columns for features, don't count target column
        feature_names = ['Food Item','f2','f3','f4'] #adjust accordingly
        target_names = ['t1','t2','t3'] #adjust accordingly
        data = np.empty((n_samples, n_features))
        target = np.empty((n_samples,), dtype=np.int)

        for i, sample in enumerate(data_file):
            data[i] = np.asarray(sample[:-1])
            target[i] = np.asarray(sample[-1])

    return Bunch(data=data, target=target, feature_names = feature_names, target_names = target_names)

data6 = load_my_dataset()

请注意,我实际上有 2 个分类变量:食品项目和食品类别。

我该如何解决这个问题?

【问题讨论】:

  • 请在问题中提供完整的错误回溯。 (肯定有比逐行填充数组更好的方法吗?)

标签: python scikit-learn dataset opencsv


【解决方案1】:

您必须透露更多关于您计划如何处理数据的信息。对于回归任务,您必须对分类变量进行编码,就像添加这个一样简单

from sklearn.preprocessing import OneHotEncoder

oh = OneHotEncoder(handle_unknown='ignore')
oh.fit(data)

当您将列名输入特征名称时,它们将被保留。但是,由于您使用 sklearn 方法来预处理数据,因此最好考虑使用 Pipelines,这将使您能够适应在将数据推送到 ML 引擎之前通常需要的插补、数据转换、缩放和其他任务。

【讨论】:

  • 我需要做两个组件的 PCA!
猜你喜欢
  • 1970-01-01
  • 2012-06-12
  • 2016-07-13
  • 2017-07-14
  • 1970-01-01
  • 2015-06-17
  • 2019-03-25
  • 2017-02-24
  • 2015-08-16
相关资源
最近更新 更多