sklearn .fit transformers , IndexError: tuple index out of range

sklearn .fit transformers , IndexError: tuple index out of range

我正在使用“ColumnTransformer”,尽管我只转换一个特征,因为我不知道如何才能只改变“clean_text”特征。我没有使用带有“make_column_selector”的“make_column_transformer”,因为我想稍后使用网格搜索,但我不明白为什么我找不到数据集的第 0 列

import pandas as pd

from sklearn.compose import ColumnTransformer
from sklearn.feature_extraction.text import CountVectorizer

from sklearn.model_selection import train_test_split

#dataset download: https://www.kaggle.com/saurabhshahane/twitter-sentiment-dataset 

df = pd.read_csv('Twitter_Data.csv')
y = df1['category']   #target
X = df1['clean_text'].values.astype('U') #feature, i transformed "X" into a string even if in theory it was because otherwise it would return an error

transformers = [
    ['text_vectorizer', CountVectorizer(), [0]];
]

ct = ColumnTransformer(transformers, remainder='passthrough')

ct.fit(X) #<---IndexError: tuple index out of range
X = ct.transform(X)

我想在此示例中有几点需要强调:

  • CountVectorizer 要求它的输入是一维的。在这种情况下,ColumnTransformer 的文档指出

columns: str, array-like of str, int, array-like of int, array-like of bool, slice or callable

Indexes the data on its second axis. Integers are interpreted as positional columns, while strings can reference DataFrame columns by name. A scalar string or int should be used where transformer expects X to be a 1d array-like (vector), otherwise a 2d array will be passed to the transformer.

因此,columns 参数应作为 int 传递,而不是作为 int 列表传递。我还建议 作为另一个参考。

  • 鉴于您使用的是列转换器,我会将整个数据帧传递给在 ColumnTransformer 实例上调用的方法 .fit(),而不是 X只有.

  • 数据框似乎有缺失值;以某种方式处理它们可能很方便。例如,通过删除它们并应用上面描述的内容,我能够使其工作,但您也可以决定以不同的方式进行。

     import pandas as pd
     import numpy as np
     from sklearn.compose import ColumnTransformer
     from sklearn.feature_extraction.text import CountVectorizer
     from sklearn.model_selection import train_test_split
    
     #dataset download: https://www.kaggle.com/saurabhshahane/twitter-sentiment-dataset 
     df = pd.read_csv('Twitter_Data.csv')
     y = df['category']  
     X = df['clean_text']
    
     df.info()
    
     df_n = df.dropna()
    
     transformers = [
         ('text_vectorizer', CountVectorizer(), 0)
     ]
    
     ct = ColumnTransformer(transformers, remainder='passthrough')
    
     ct.fit(df_n) 
     ct.transform(df_n)
    
  • 如评论中所述,transformers 应指定为 元组列表 (根据文档)而不是 列表列表。但是,运行 上面带有您的 transformers 规范的代码段似乎有效。我最终观察到,在其他地方(在我拥有的不相关的代码片段中)用列表替换元组似乎不会引起问题。但是,根据我的经验,发现它们作为 元组列表 .

    传递肯定更常见