当条件满足 Python 时,从列表中删除元素并从 numpy 数组中删除行

Deleting elements from list and rows from numpy array when condition holds in Python

我正在编写一个算法,以便将我的数据集中的推文分类为 positive/negative,我想测试它的准确性。为了做到这一点并找到最佳解决方案,我想要一个基线(使用经典的 ML 算法)。在对推文进行预处理后,受到相关工作的启发,我首先使用词袋模型进行了探索,并成功 运行 代码并计算了准确率和 Fscore。经过一些文本预处理并将数据集拆分为训练集和测试集:

from sklearn.cross_validation import train_test_split
X_train, X_test1, y_train, y_test1 = train_test_split(X, y, test_size = 0.11, random_state = 0)

我希望能够从测试集中消除所有标记为负面的推文(只保留正面的)并计算算法的精度、召回率和 Fscore(然后对标记为正面的推文)。我试过这样做:

finRow = len(X_test1) 
finCol = len(X_test1[0])

for o in range(0, finrow):
    if y_test1[o]== 1:
       del y_test1[o]
       X_test1 = np.delete(X_test1, o, axis=0)

但是我得到这个错误:

Traceback (most recent call last):

File "<ipython-input-4-5ed18876a8b5>", line 2, in <module>
if y_test1[o]== 1:

IndexError: list index out of range

X_test1 包含推文,大小为 1102 x 564,y_test1 包含零和一(推文是正面的还是负面的)并且大小为1102。错误出现在第774次迭代时,当y_test1的长度从1102减少到774时。

现在,我也尝试这样做:

a = 1
for o in range(0, finrow):
    if (y_test1[o] == 1 and o <= finrow - a):
       del y_test1[o]
       a = a + 1
       X_test1 = np.delete(X_test1, o, axis=0)

但我仍然遇到同样的错误,我不知道这是否是删除矩阵行和列表元素的最佳方法,因为当我检查 [=29= 的值时]y_test1 我还有一些(一些,不是全部 - 像开始时那样)应该删除的元素。

我是新手,我不知道我的错误在哪里。

您可能想看看 scikit-learn 中的函数 classification_report

http://scikit-learn.org/stable/modules/generated/sklearn.metrics.classification_report.html

这是为每个 class 计算 Precision/Recall 和 F1 的最简单方法。

您只需要传递两个数组,第一个是真实预测,第二个是 classifier 的预测,例如:

predictions = your_clf.predict(X_test1)
classification_report(y_test1, prediction)

y_test == 0 创建一个布尔值数组,可用于过滤掉 y_testx_test.

中的行
positive_indexes = y_test == 0
y_test_positive = y_test[positive_indexes]
x_test_positive = x_test[positive_indexes]
In [328]: alist = list(range(10))
In [329]: alist
Out[329]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

从列表中删除项目会更改后续项目的索引。

In [330]: del alist[7]          # removes the 7
In [331]: alist
Out[331]: [0, 1, 2, 3, 4, 5, 6, 8, 9]
In [332]: del alist[8]          # removes the 9, not the 8       
In [333]: alist
Out[333]: [0, 1, 2, 3, 4, 5, 6, 8]
In [334]: del alist[8]          # with only 8 items left, error
IndexError: list assignment index out of range

删除以 end 开头的项目会保留剩余项目的索引:

In [335]: alist = list(range(10))
In [336]: del alist[9]
In [337]: del alist[8]
In [338]: del alist[7]
In [339]: del alist[6]
In [340]: alist
Out[340]: [0, 1, 2, 3, 4, 5]