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 all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
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 (hasattr(field, "__len__") and len(field) == 0):
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
21 changes: 21 additions & 0 deletions tests/core/test_vocabulary.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
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})

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