Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

from_dataset ignore null instance #454

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 4 additions & 0 deletions fastNLP/core/vocabulary.py
Original file line number Diff line number Diff line change
Expand Up @@ -396,6 +396,10 @@ def from_dataset(self, *datasets, field_name:Union[str,List[str]], no_create_ent
def construct_vocab(ins, no_create_entry=False):
for fn in field_name:
field = ins[fn]
# 如果 field 为空或者 None, 那么直接跳过即可。
if field is None or len(field) == 0:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这个地方有风险,假设field是数字就G了,数字无法len。可能需要先判断 hasattr(bar, 'len')

logger.warning(f"instance: {ins} has null field. Skip now!")
continue
if isinstance(field, str) or not _is_iterable(field):
self.add_word(field, no_create_entry=no_create_entry)
else:
Expand Down
15 changes: 15 additions & 0 deletions tests/core/test_vocabulary.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import pytest
from collections import Counter

from fastNLP.core.dataset import DataSet
from fastNLP.core.vocabulary import Vocabulary
from fastNLP import logger


class TestVocabulary:

def test_from_dataset(self):
ds = DataSet({"x": [[1, 2], [3, 4]], "y": ["apple", ""]})
vocab = Vocabulary()
vocab.from_dataset(ds, field_name="y")
assert vocab.word_count == Counter({'apple': 1})