KeyError:“未找到元组类型的键且不是 MultiIndex”SVM
Posted
技术标签:
【中文标题】KeyError:“未找到元组类型的键且不是 MultiIndex”SVM【英文标题】:KeyError: 'key of type tuple not found and not a MultiIndex' SVM 【发布时间】:2022-01-01 16:00:54 【问题描述】:我正在尝试为我的 SVM 模型绘制和创建视觉决策边界。关于数据集和任务的一些背景知识。这是一个二元分类任务,我将新闻文章分类为假的或真实的。我想直观地看到这个决策边界。图代码 sn-p 来自这里:https://medium.com/geekculture/svm-classification-with-sklearn-svm-svc-how-to-plot-a-decision-boundary-with-margins-in-2d-space-7232cb3962c0
我尝试使用 'test_x_vectorize' 作为 x 和 y,但我会得到错误:TypeError: unhashable type: 'csr_matrix'
然后我尝试按照这个线程进行展平,但它给了我同样的问题。 TypeError: unhashable type: 'matrix'
这是我的代码:
# test/train split for X and Y
X_train, X_test, Y_train, Y_test = train_test_split(data['News'], data['Label'], test_size=0.2, random_state=21, shuffle=True)
# Creating the vectorizer using TfidfVectorizer
vectorize = TfidfVectorizer(max_features=5)
vectorize.fit(data['News'])
train_x_vectorize = vectorize.transform(X_train)
test_x_vectorize = vectorize.transform(X_test)
# Creating the SVM model
SVM = svm.SVC(C=1, kernel='linear', degree=3, gamma='auto')
SVM.fit(train_x_vectorize, Y_train)
# Predicting the accuracy on testing data
pred = SVM.predict(test_x_vectorize)
plt.figure(figsize=(10, 8))
# Plotting our two-features-space
sns.scatterplot(x=X_train[:, 0],
y=X_train[:, 1],
hue=Y_train,
s=8);
# Constructing a hyperplane using a formula.
w = SVM.coef_[0] # w consists of 2 elements
b = SVM.intercept_[0] # b consists of 1 element
x_points = np.linspace(-1, 1) # generating x-points from -1 to 1
y_points = -(w[0] / w[1]) * x_points - b / w[1] # getting corresponding y-points
# Plotting a red hyperplane
plt.plot(x_points, y_points, c='r');
我的回溯错误在这里:
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-8-0535339c273a> in <module>()
30 plt.figure(figsize=(10, 8))
31 # Plotting our two-features-space
---> 32 sns.scatterplot(x=X_train[:, 0],
33 y=X_train[:, 1],
34 hue=Y_train,
2 frames
/usr/local/lib/python3.7/dist-packages/pandas/core/series.py in _get_values_tuple(self, key)
954
955 if not isinstance(self.index, MultiIndex):
--> 956 raise KeyError("key of type tuple not found and not a MultiIndex")
957
958 # If key is contained, would have returned by now
KeyError: 'key of type tuple not found and not a MultiIndex'
【问题讨论】:
错误指向哪一行?也许编辑并添加完整的错误消息 我添加了回溯错误信息。谢谢。 这里的X_train
到底是什么?
X_train 是一个包含新闻文本样本的对象类型
【参考方案1】:
尝试使用
sns.scatterplot(x=X_train.iloc[:, 0],
y=X_train.iloc[:, 1],
hue=Y_train,
s=8);
这将指定您尝试按索引访问
【讨论】:
以上是关于KeyError:“未找到元组类型的键且不是 MultiIndex”SVM的主要内容,如果未能解决你的问题,请参考以下文章
python3 日志检索异常抛出异常 raise KeyError(key),KeyError: 'formatters'