我正在尝试从scikit-learn训练一个KNeighborsClassifier,但在从tarfile加载训练数据时遇到了一些问题。
下面是我写的代码:
#Part 1 ~ Q1
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score
import tarfile
tar = tarfile.open(r'C:\Users\Calum Nairn\Downloads\enron1.tar.gz')
tar.extractall()
tar.close()
data_x = tar['spam']
data_y = tar['target']
classes = tar['target_names']
x_train,x_test,y_train,y_test = train_test_split(data_x,data_y,test_size=0.30,random_state=42)
# Create the classifier
knnclassifier = KNeighborsClassifier()
# Fitting the model on the train dataset
knnclassifier.fit(x_train,y_train)
# Check the Performance on the training set
pred_train = knnclassifier.predict(x_train)
train_accu= accuracy_score(pred_train,y_train)
print(f'The Accuracy on the train set is: {round(train_accu*100,2)}%')
# Check the Performance on the test set
pred_test = knnclassifier.predict(x_test)
test_accu= accuracy_score(pred_test,y_test)
print(f'The Accuracy on the test set is: {round(test_accu*100,2)}%')我得到的错误是:
TypeError Traceback (most recent call last)
<ipython-input-45-fdb7523b73d9> in <module>
11 tar.close()
12
---> 13 data_x = tar['spam']
14 data_y = tar['target']
15 classes = tar['target_names']
TypeError: 'TarFile' object is not subscriptable发布于 2020-12-04 16:56:42
在提取tarfile和访问数据之间,您似乎遗漏了几个步骤,所以让我们对其进行分析。
tar是一个TarFile对象,它既不保存tar文件的内容,也不保存其中单个文件的内容。它基本上是文件系统上打开的文件的句柄(在Python世界中通常称为file-like objects )。
tar.extractall()将tarfile中包含的各个文件放入工作目录中。这不会以任何方式修改tar对象,它仍然没有保存任何实际的文件内容。
然后,您尝试将数据点加载为tar['spam']、tar['target']等。'TarFile' object is not subscriptable意味着类型为TarFile的对象tar不支持通过像'spam'这样的“名称”来访问其“项”,因为如上所述,它内部没有任何“项”。
您实际需要做的是读取之前提取的那些文件。
data_x_file = open('spam', 'r')
data_x_raw_text = data_x_file.read()
data_x_file.close()然后,您需要将data_x_raw_text转换为适合train_test_split的数据结构,如数据点列表。如何做到这一点将取决于源数据的格式。
此外,scikit-learn或numpy很可能有一些用于加载数据集的帮助器,因此您不必手动打开-加载-转换,您应该尝试搜索它们的文档。
https://stackoverflow.com/questions/65127989
复制相似问题