AttributeError: объект 'Example' не имеет атрибута 'Insult' при сборке вокаба с использованием build_vocab () из torchtext - PullRequest
0 голосов
/ 07 апреля 2020

Я пытался построить словарь, используя .build_vocab () из torchtext в colab. Он возвращает сообщение об ошибке: AttributeError: у объекта «Пример» нет атрибута «Оскорбление»

Мой вопрос похож на @ szymix12 s вопрос . Его ответ заключается в том, чтобы убедиться, что порядок передаваемых полей такой же, как и у заголовков csv. Я подтверждаю, что заказ, который я назначил, правильный. Данные CSV получили два столбца: «Оскорбление» (LABEL) и «Комментарий» (TEXT). «Оскорбление» - это двоичный индикатор метки (0 или 1).

Код такой, как показано ниже, я также сделал ноутбук colab . Не стесняйтесь бежать.

import os
import torch
from torchtext import data, datasets
from torchtext.utils import download_from_url

CSV_FILENAME = 'data.csv'
CSV_GDRIVE_URL = 'https://drive.google.com/open?id=1ctPKO-_sJbmc8RodpBZ5-3EyYBWlUy5Pbtjio5pyq00'
download_from_url(CSV_GDRIVE_URL, CSV_FILENAME)

TEXT = data.Field(tokenize = 'spacy', batch_first = True, lower=True)  #from torchtext import data
LABEL = data.LabelField(sequential=False, dtype = torch.float)

train = data.TabularDataset(path=os.path.join('/content', CSV_FILENAME),
                            format='csv',
                            fields = [('Insult', LABEL), ('Comment', TEXT)],
                            skip_header=True)


print(vars(train[0]),vars(train[1]),vars(train[2]))

TEXT.build_vocab(train)

Ответы [ 2 ]

1 голос
/ 08 апреля 2020

Ваш скрипт извлек файл HTML вместо фактического набора данных. Это потому, что URL-адрес, который вы использовали 'https://drive.google.com/open?id=1ctPKO-_sJbmc8RodpBZ5-3EyYBWlUy5Pbtjio5pyq00', не является прямым URL-адресом файла CSV. Это скорее в формате HTML, потому что предоставленный URL-адрес Google Sheets. Чтобы решить эту проблему, вы можете загрузить набор данных на свой компьютер и загрузить его в Colab.


Это содержимое загруженного вами data.csv.

Contents of data.csv

0 голосов
/ 08 апреля 2020

Вам не нужно вручную загружать и загружать файл, как предложено @ kn oop. Как я указал в своем предыдущем ответе на ваш вопрос, вы не должны использовать ссылку с open. Вместо этого вы должны изменить на uc?export=download. Таким образом, правильный CSV_GDRIVE_URL должен быть:

CSV_GDRIVE_URL = 'https://drive.google.com/uc?export=download&id=1eWMjusU3H34m0uml5SdJvYX6gQuB8zta'

Тогда, если вы cat это, вы получите:

,Insult,Date,Comment
11,0,20120530044519Z,"""Be careful,Jimbo.OG has a fork with your name on it."""
1478,0,,"""@dale0987654321 @\\'Micah Carter So you\\'re saying those claims are all false...?  I don\\'t know... just from my understanding these are in his book.... but I can be wrong... I\\'m just saying if they are true....should I just assume he\\'s racist?\\n\\nFrom \\'Dreams of My Father\\',""I CEASED TO ADVERISE MY MOTHER\\'S RACE AT THE AGE OF12 OR 13, when I began to suspect that by doing so I was ingratiating myself to whites""From Dreams of My Father, "" I FOUND A SOLACE IN NURSING A PERVASIVE SENSE OF GRIEVANCE AND ANIMOSITY AGAINST MY MOTHER\\'S RACE"".From \\'Dreams of my Father\\', ""The emotion between the races could never be pure..... the THE OTHER RACE (WHITE) WOULD ALWAYS REMAIN JUST THAT: MENACING, ALIEN AND APART""From Dreams Of My Father, ""never emulate white men and brown men whose fates didn\\'t speak to my own. IT WAS INTO MY FATHER\\'S IMAGE , THE BLACK MAN, THE SON OF AFRICA, THAT I\\'D PACKED ALL THE ATTRIBUTES I SOUGHT IN MYSELF.From Dreams Of My Father:""THAT HATE HADN\\'T GONE AWAY,"" he wrote, BLAMING WHITE PEOPLE,- SOME CRUEL, SOME IGNORANT, sometimes a single face, sometimes just a faceless image of a system claiming power over our lives."""""
1983,0,20120610152024Z,"""Only fucking with number 2... that's prolly the only pair i can pull off \xa0out these."""
3201,1,,"""S T F U and pay your dues"""
3549,0,20120530024115Z,"""Worry about your current opponent...."""
3402,1,20120618222736Z,"""And while you're at it, please prove how your ""point"" related to past draconian laws that banned inter-racial marriage?\xa0 That intent was to ""ban"" mixed races.\xa0 Just stop it please! You are insulting intelligence."""
2233,0,20120620034735Z,"""I'd rather have an old, straight white guy than the stupid fcking zebra we have now....everything he touches turns toshit............"""
3219,1,20120619020631Z,"""Only a black racists idiot would claim that the NAACP is not racist in todays world, especially since you're a member.\n\nAnd I don't give a 'bo' whether you take that personally or not."""
3148,0,,"""Fight for money !!! go ahead ,kill yourselfs, all for greed,common, take decision that is not in accordance with what the supreme court says, find some connection by the INEC ,and say to yourself ,HO IS MY TURN TO LOOT NOT YOURS,OR I KILL U.bounch of shameless idiots."""
386,0,,"""The cleverest comment that I have seen for a long time, I think that it was in the Mail\\n\\n \\n\\n\\'Arshavin is the worst Russian Sub since the Kursk"""""

И TEXT.build_vocab(train) будет работать успешно.

...