-
Notifications
You must be signed in to change notification settings - Fork 87
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
Improvement of automatic text detection #903
Open
andreygetmanov
wants to merge
10
commits into
master
Choose a base branch
from
multimodal_text_detection
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
1357d3a
- rebase on master
andreygetmanov 404e888
- now tfidf tries to fit on every potential text col
andreygetmanov 75341b1
- added autodetection of columns with links
andreygetmanov 2cdb32c
- fixed bug with crash on tuning
andreygetmanov f6e9828
- added ngram_range=(1,4) to search space
andreygetmanov 57bfc86
- minor changes
andreygetmanov 507d136
- max_features of tfidf is set to 10e5 to reduce memory consumption
andreygetmanov edffc87
- word2vec trained outline
andreygetmanov c0ed0d7
Fixed R2 calculation
andreygetmanov 86ae96f
Fixed bug with regression test
andreygetmanov File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,10 +1,14 @@ | ||
from abc import abstractmethod | ||
from typing import List | ||
|
||
import re | ||
import numpy as np | ||
import pandas as pd | ||
from sklearn.feature_extraction.text import TfidfVectorizer | ||
|
||
from fedot.core.constants import FRACTION_OF_UNIQUE_VALUES | ||
from fedot.core.constants import FRACTION_OF_UNIQUE_VALUES_IN_TEXT, MIN_VOCABULARY_SIZE | ||
from fedot.core.log import default_log | ||
from fedot.core.repository.default_params_repository import DefaultOperationParamsRepository | ||
|
||
ALLOWED_NAN_PERCENT = 0.9 | ||
|
||
|
@@ -26,24 +30,39 @@ class TextDataDetector(DataDetector): | |
""" | ||
Class for detecting text data during its import. | ||
""" | ||
def __init__(self): | ||
self.logger = default_log(prefix='FEDOT logger') | ||
super().__init__() | ||
|
||
def define_text_columns(self, data_frame: pd.DataFrame) -> List[str]: | ||
def find_text_columns(self, data_frame: pd.DataFrame) -> List[str]: | ||
""" | ||
:param data_frame: pandas dataframe with data | ||
:return: list of text columns' names | ||
""" | ||
text_columns = [] | ||
for column_name in data_frame.columns: | ||
if self._column_contains_text(data_frame[column_name]): | ||
text_columns.append(column_name) | ||
text_columns = [column_name for column_name in data_frame.columns | ||
if self._column_contains_text(data_frame[column_name])] | ||
return text_columns | ||
|
||
def find_link_columns(self, data_frame: pd.DataFrame) -> List[str]: | ||
""" | ||
:param data_frame: pandas dataframe with data | ||
:return: list of link columns' names | ||
""" | ||
link_columns = [column_name for column_name in data_frame.columns if self.is_link(data_frame[column_name])] | ||
return link_columns | ||
|
||
@staticmethod | ||
def is_full_of_nans(text_data: np.array) -> bool: | ||
if np.sum(pd.isna(text_data)) / len(text_data) > ALLOWED_NAN_PERCENT: | ||
return True | ||
return False | ||
|
||
@staticmethod | ||
def is_link(text_data: np.array) -> bool: | ||
link_pattern = \ | ||
'[(http(s)?):\\/\\/(www\\.)?a-zA-Z0-9@:%._\\+~#=]{2,256}\\.[a-z]{2,6}\\b([-a-zA-Z0-9@:%_\\+.~#?&//=]*)' | ||
return re.search(link_pattern, str(next(el for el in text_data if el is not None))) is not None | ||
|
||
@staticmethod | ||
def prepare_multimodal_data(dataframe: pd.DataFrame, columns: List[str]) -> dict: | ||
""" Prepares MultiModal text data in a form of dictionary | ||
|
@@ -70,16 +89,26 @@ def _column_contains_text(self, column: pd.Series) -> bool: | |
Column contains text if: | ||
1. it's not float or float compatible | ||
(e.g. ['1.2', '2.3', '3.4', ...] is float too) | ||
2. fraction of unique values (except nans) is more than 0.95 | ||
2. fraction of unique values (except nans) is more than 0.6 | ||
3. size of tfidf vocabulary is more than 20 | ||
|
||
If size of tfidf vocabulary is less than 20, then it is probably | ||
text column too, but it cannot be vectorized and used in model | ||
|
||
:param column: pandas series with data | ||
:return: True if column contains text | ||
:return: True if column contains text, False otherwise or if column contains links | ||
""" | ||
if column.dtype == object and not self._is_float_compatible(column): | ||
unique_num = len(column.unique()) | ||
nan_num = pd.isna(column).sum() | ||
return unique_num / len(column) > FRACTION_OF_UNIQUE_VALUES if nan_num == 0 \ | ||
else (unique_num - 1) / (len(column) - nan_num) > FRACTION_OF_UNIQUE_VALUES | ||
if self.is_link(column): | ||
return False | ||
elif column.dtype == object and not self._is_float_compatible(column) and self._has_unique_values(column): | ||
params = DefaultOperationParamsRepository().get_default_params_for_operation('tfidf') | ||
tfidf_vectorizer = TfidfVectorizer(**params) | ||
try: | ||
# TODO now grey zone columns (not text, not numerical) are not processed. Need to drop them | ||
tfidf_vectorizer.fit(np.where(pd.isna(column), '', column)) | ||
return len(tfidf_vectorizer.vocabulary_) > MIN_VOCABULARY_SIZE | ||
except ValueError: | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Можем ли вынести из-под
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Вот так, например? |
||
self.logger.warning(f"Column {column.name} possibly contains text, but it's impossible to vectorize it") | ||
return False | ||
|
||
@staticmethod | ||
|
@@ -96,6 +125,22 @@ def _is_float_compatible(column: pd.Series) -> bool: | |
failed_ratio = failed_objects_number / non_nan_all_objects_number | ||
return failed_ratio < 0.5 | ||
|
||
@staticmethod | ||
def _has_unique_values(column: pd.Series) -> bool: | ||
""" | ||
:param column: pandas series with data | ||
:return: True if number of unique column values > threshold | ||
""" | ||
unique_num = len(column.unique()) | ||
nan_num = pd.isna(column).sum() | ||
# fraction of unique values in column if there is no nans | ||
frac_unique_is_bigger_than_threshold = unique_num / (len(column) - nan_num) > FRACTION_OF_UNIQUE_VALUES_IN_TEXT | ||
# fraction of unique values in column if there are nans | ||
frac_unique_is_bigger_than_threshold_with_nans = \ | ||
(unique_num - 1) / (len(column) - nan_num) > FRACTION_OF_UNIQUE_VALUES_IN_TEXT | ||
return frac_unique_is_bigger_than_threshold if nan_num == 0 \ | ||
else frac_unique_is_bigger_than_threshold_with_nans | ||
|
||
|
||
class TimeSeriesDataDetector(DataDetector): | ||
""" | ||
|
@@ -114,10 +159,13 @@ def prepare_multimodal_data(dataframe: pd.DataFrame, columns: List[str]) -> dict | |
multi_modal_ts_data = {} | ||
for column_name in columns: | ||
feature_ts = np.array(dataframe[column_name]) | ||
idx = list(dataframe['datetime']) | ||
|
||
# Will be the same | ||
multi_modal_ts_data.update({column_name: feature_ts}) | ||
|
||
multi_modal_ts_data['idx'] = np.asarray(idx) | ||
|
||
return multi_modal_ts_data | ||
|
||
@staticmethod | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Во первых, стоит написать тесты, покрывающие эту функциональность, но как я понял из описания PR - они и так в процессе
Во вторых, в описании к PR сказано, что "Columns with links (they don't contain useful information and sometimes lead to a FEDOT fail) are removed automatically". Отсюда возникает вопрос, а стоит ли привязываться именно к ссылкам и заносить их все в категорию "столбцов для удаления" (кстати, а не сбивается ли индексация столбцов после их удаления в supplementary data?)? То есть вполне себе могу представить кейс, когда количество уникальных значений в текстовом столбце будет равно двум и оба варианта будут ссылками например. Тогда после One Hot Encoding'а информация из этого столбца вполне может пригодиться. Поэтому имеет смысл выделить свойства столбца с гиперссылками, которые мешают ML алгоритмам и избавляться от всех столбцов с такими свойствами.
Например, если проблема в том, что ссылка всегда одинаковая, то тогда стоит просто удалять все столбцы с неизменным набором символов в ячейках безотносительно их содержания. Если же ссылки для кажого объекта уникальные, то может имеет смысл удалять все столбцы, в которых текст уникален и при этом не представляет собой сырье для NLP алгоритмов (например, нет осмысленных фраз в ячейках или пробелов). Или проблема именно с тем, что встречается набор символов
http
в ячейке?С уже оставленными к этому PR комментариями согласен