如何在sklearn中使用pandas DataFrames



我的项目的目标是预测一些文本描述的准确性水平。

我用FASTTEXT制作了矢量。

TSV输出:

0  1:0.0033524514 2:-0.021896651 3:0.05087798 4:0.0072637126 ...
1  1:0.003118149 2:-0.015105667 3:0.040879637 4:0.000539902 ...

资源被标记为好(1(或坏(0(。

为了检查准确性,我使用了scikit学习和SVM。

根据这个教程,我制作了这个脚本:


import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn import svm
from sklearn import metrics
import numpy as np
import matplotlib.pyplot as plt
r_filenameTSV = 'TSV/A19784.tsv'
tsv_read = pd.read_csv(r_filenameTSV, sep='t',names=["vector"])
df = pd.DataFrame(tsv_read)
df = pd.DataFrame(df.vector.str.split(' ',1).tolist(),
columns = ['label','vector'])

print ("Features:" , df.vector)
print ("Labels:" , df.label)
X_train, X_test, y_train, y_test = train_test_split(df.vector, df.label, test_size=0.2,random_state=0)
#Create a svm Classifier
clf = svm.SVC(kernel='linear') 
#Train the model using the training sets
clf.fit (str((X_train, y_train)))
#Predict the response for test dataset
y_pred = clf.predict(X_test)
print("Accuracy:",metrics.accuracy_score(y_test, y_pred))

我第一次尝试运行脚本时,在第28行遇到了这个错误:

ValueError: could not convert string to float:

所以我换了

clf.fit (X_train, y_train)


clf.fit (str((X_train, y_train)))

然后,在同一条线上,我得到了这个错误

TypeError: fit() missing 1 required positional argument: 'y'

建议如何解决这个问题?

谢谢你抽出时间。

就像你的问题下面的评论中提到的那样,你的功能和标签是持久的字符串。然而,sklearn要求它们是数字的(sklearn通常与numpy数组一起使用(。如果是这种情况,您必须将数据帧的元素从字符串转换为数值。

查看您的代码,我假设feature列的每个元素都是字符串列表,label列的每个元件都是单个字符串。下面是一个如何将这样的数据帧转换为包含数值的示例。

import numpy as np
import pandas as pd
df = pd.DataFrame({'features': [['5', '4.2'], ['3', '7.9'], ['2', '9']],
'label': ['1', '0', '0']})
print(type(df.features[0][0]))
print(type(df.label[0]))

def convert_to_float(collection):
floats = [float(el) for el in collection]
return np.array(floats)

df_numeric = pd.concat([df["features"].apply(convert_to_float),
pd.to_numeric(df["label"])],
axis=1)
print(type(df_numeric.features[0][0]))
print(type(df_numeric.label[0]))

但是,所描述的数据帧格式不是sklearn模型期望panda数据帧具有的格式。据我所知,sklearn模型希望每个功能都存储在一个单独的列中,就像这里的情况一样:

from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
feature_df = pd.DataFrame(np.arange(6).reshape(3, 2), columns=["feature_1", "feature_2"])
label_df = pd.DataFrame(np.array([[1], [0], [0]]), columns=["label"])
df = pd.concat([feature_df, label_df], axis=1)
X_train, X_test, y_train, y_test = train_test_split(df.drop(["label"], axis=1), df["label"], test_size=1 / 3)
clf = SVC(kernel='linear')
clf.fit(X_train, y_train)
clf.predict(X_test)

也就是说,在转换数据帧使其仅包含数值之后,您必须为特性列列表中的每个元素创建一个自己的列。你可以这样做:

arr = np.concatenate(df_numeric.features.to_numpy()).reshape(df_numeric.shape)
df_sklearn_compatible = pd.concat([pd.DataFrame(arr, columns=["feature_1", "feature_2"]),
df["label"]],
axis=1)

相关内容

最新更新