【问题标题】:ValueError: setting an array element with a sequence while fitting data to svmValueError:在将数据拟合到 svm 时设置具有序列的数组元素
【发布时间】:2019-11-28 14:32:10
【问题描述】:

我的数据集如下:

 text  size   bold   label
 xxxx    5     1      0.0
 yyyy   15     0      1.0
  .      .     .       . 
  .      .     .       .

其中标签是目标变量,文本列是字符串,粗体和大小是int,标签是float。

现在我已经使用 tf-idf 矢量化器将文本列转换为数组。

data['tf_idf_q1'] = tfidf_vect.fit_transform(data["text"])

现在我分别使用 3 列和 1 列进行训练和测试:

X = data[['tf_idf_q1', 'size', 'bold']].as_matrix()
y = data['label'].as_matrix()

现在当我尝试将数据拟合到 svm 模型时:

clf = svm.LinearSVC().fit(X, y)

它显示错误:

ValueError: setting an array element with a sequence.

我试图将我的 X 和 y 转换为 dtype=float 但它不起作用。

我是 nlp 的新手,请大家帮帮我。

【问题讨论】:

    标签: python pandas machine-learning nlp tf-idf


    【解决方案1】:

    创建虚拟数据帧

    import pandas as pd
    import pandas as pd
    
    from sklearn.feature_extraction.text  import TfidfVectorizer
    tfidf = TfidfVectorizer()
    
    df = pd.DataFrame([['hi how are you',5],['hope this help you',4],['gd mrng',3]], columns=['sent','size'])
    df['tf_idf_q1'] = tfidf.fit_transform(df["sent"])
    
    df['tf_idf_q1'].as_matrix()
    
    #o/p , which is not a number and you are getting error
    
    array([<3x9 sparse matrix of type '<class 'numpy.float64'>'
    with 10 stored elements in Compressed Sparse Row format>,
       <3x9 sparse matrix of type '<class 'numpy.float64'>'
    with 10 stored elements in Compressed Sparse Row format>,
       <3x9 sparse matrix of type '<class 'numpy.float64'>'
    with 10 stored elements in Compressed Sparse Row format>], dtype=object)
    

    将上面的稀疏矩阵转换为密集表示..

    text_feature_df = pd.DataFrame(tfidf.fit_transform(df["sent"]).todense(), columns = tfidf.get_feature_names()) 
    
    df_size_text = pd.concat([text_feature_df,df],axis = 1)
    

    现在将 df_size_text 的数据传递到您的模型中,并删除列 df['tf_idf_q1']

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-21
      • 2015-11-18
      • 2019-05-02
      • 2017-10-20
      • 2023-03-16
      • 2014-10-18
      • 2018-04-25
      • 2013-03-12
      相关资源
      最近更新 更多