Helping function of `_parse_feature_names` that parses a dictionary of feature names.
15026
def _parse_names_dict(feature_names):
        """"""
        feature_collection = OrderedDict()
        for feature_name, new_feature_name in feature_names.items():
            if isinstance(feature_name, str) and (isinstance(new_feature_name, str) or
                                                  new_feature_name is ...):
                feature_collection[feature_name] = new_feature_name
            else:
                if not isinstance(feature_name, str):
                    raise ValueError('Failed to parse {}, expected string'.format(feature_name))
                else:
                    raise ValueError('Failed to parse {}, expected string or Ellipsis'.format(new_feature_name))
        return feature_collection
1096609
def _generate_feature_labels(self, X):
        '''
        
        '''
        Xt, Xc = get_ts_data_parts(X)

        ftr_sizes = self._check_features(self.features, Xt[0:3])
        f_labels = []

        # calculated features
        for key in ftr_sizes:
            for i in range(ftr_sizes[key]):
                f_labels += [key + '_' + str(i)]

        # contextual features
        if Xc is not None:
            Ns = len(np.atleast_1d(Xc[0]))
            s_labels = ["context_" + str(i) for i in range(Ns)]
            f_labels += s_labels

        return f_labels
956548
def _to_dict(self):
        """"""
        _dict = {}
        if hasattr(self, 'classifiers') and self.classifiers is not None:
            _dict['classifiers'] = [x._to_dict() for x in self.classifiers]
        return _dict
7930
def _get_features_string(self, features=None):
    
    string = ""
    if features is None:
        features = []
    elif features == []:
        features = self.features

    for pr in features:
        if hasattr(self, pr):
            raw = getattr(self, pr)
            if type(raw) in ITERABLE_TYPES:
                raw = '|'.join([str(i) for i in raw])
            elif type(raw) == dict:
                raw = '|'.join(
                    map(lambda x,y: "%s-%s" %(x, y), six.iteritems(raw)))
            elif type(raw) == str:
                pass
            else:
                raw = str(raw)

            value = re.sub("["+_ILEGAL_NEWICK_CHARS+"]", "_", \
                             raw)
            if string != "":
                string +=":"
            string +="%s=%s"  %(pr, str(value))
    if string != "":
        string = "[&&NHX:"+string+"]"

    return string
1173166
def _from_dict(cls, _dict):
        """"""
        args = {}
        if 'count' in _dict:
            args['count'] = _dict.get('count')
        if 'relevance' in _dict:
            args['relevance'] = _dict.get('relevance')
        if 'text' in _dict:
            args['text'] = _dict.get('text')
        if 'emotion' in _dict:
            args['emotion'] = EmotionScores._from_dict(_dict.get('emotion'))
        if 'sentiment' in _dict:
            args['sentiment'] = FeatureSentimentResults._from_dict(
                _dict.get('sentiment'))
        return cls(**args)
1006774
def feature_names(self, names):
        ""

        if len(names) != self.num_features:
            raise ValueError("Number of names do not match the number of features!")
        if not isinstance(names, (Sequence, np.ndarray, np.generic)):
            raise ValueError("Input is not a sequence. "
                             "Ensure names are in the same order "
                             "and length as features.")

        self.__feature_names = np.array(names)
17404
def dict_to_example(dictionary):
  """"""
  features = {}
  for k, v in six.iteritems(dictionary):
    features[k] = tf.train.Feature(int64_list=tf.train.Int64List(value=v))
  return tf.train.Example(features=tf.train.Features(feature=features))
1001322
def parse_file_to_dict(self, fname):
        
        print('TODO - parse_file_to_dict' + fname)
        for m in self.maps:
            if m.tpe == 'file':
                if m.key[0:3] == 'col':
                    print('reading column..')
109625
def feature_names(self, feature_names):
        
        if not feature_names is None:
            # validate feature name
            if not isinstance(feature_names, list):
                feature_names = list(feature_names)
            if len(feature_names) != len(set(feature_names)):
                raise ValueError('feature_names must be unique')
            if len(feature_names) != self.num_col():
                msg = 'feature_names must have the same length as data'
                raise ValueError(msg)
            # prohibit to use symbols may affect to parse. e.g. ``[]=.``
            if not all(isinstance(f, STRING_TYPES) and f.isalnum()
                       for f in feature_names):
                raise ValueError('all feature_names must be alphanumerics')
        else:
            # reset feature_types also
            self.feature_types = None
        self._feature_names = feature_names
195622
def parse_nhx(NHX_string):
    
    # store features
    ndict = {}

    # parse NHX or MB features
    if "[&&NHX:" in NHX_string:
        NHX_string = NHX_string.replace("[&&NHX:", "")
        NHX_string = NHX_string.replace("]", "")
        
        for field in NHX_string.split(":"):
            try:
                pname, pvalue = field.split("=")
                ndict[pname] = pvalue
            except ValueError as e:
                raise NewickError('Invalid NHX format %s' % field)
    return ndict
530077
def _maybe_from_pandas(data, feature_names, feature_types):
    
    try:
        import pandas as pd
    except ImportError:
        return data, feature_names, feature_types

    if not isinstance(data, pd.DataFrame):
        return data, feature_names, feature_types

    dtypes = data.dtypes
    if not all(dtype.name in ('int64', 'float64', 'bool') for dtype in dtypes):
        raise ValueError('DataFrame.dtypes must be int, float or bool')

    if feature_names is None:
        feature_names = data.columns.format()
    if feature_types is None:
        mapper = {'int64': 'int', 'float64': 'q', 'bool': 'i'}
        feature_types = [mapper[dtype.name] for dtype in dtypes]
    data = data.values.astype('float')
    return data, feature_names, feature_types
1063424
def _ParseDocstring(function):
  """"""
  if not function.__doc__:
    return {}

  type_check_dict = {}
  for match in param_regexp.finditer(function.__doc__):
    param_str = match.group(1).strip()
    param_splitted = param_str.split(" ")
    if len(param_splitted) >= 2:
      type_str = " ".join(param_splitted[:-1])
      name = param_splitted[-1]
      type_check_dict[name] = type_str

  for match in returns_regexp.finditer(function.__doc__):
    type_check_dict["returns"] = match.group(1)

  for match in type_regexp.finditer(function.__doc__):
    name = match.group(1)
    type_str = match.group(2)
    type_check_dict[name] = type_str
  for match in rtype_regexp.finditer(function.__doc__):
    type_check_dict["returns"] = match.group(1)
  return type_check_dict
299290
def _parse_list(features, new_names):
        """"""
        feature_collection = OrderedDict()
        for feature in features:
            if isinstance(feature, FeatureType):
                feature_collection[feature] = ...

            elif isinstance(feature, (tuple, list)):
                for feature_type, feature_dict in FeatureParser._parse_tuple(feature, new_names).items():
                    feature_collection[feature_type] = feature_collection.get(feature_type, OrderedDict())

                    if feature_dict is ...:
                        feature_collection[feature_type] = ...

                    if feature_collection[feature_type] is not ...:
                        feature_collection[feature_type].update(feature_dict)
            else:
                raise ValueError('Failed to parse {}, expected a tuple'.format(feature))
        return feature_collection
664792
def convert_feature_layers_to_dict(feature_layers):
    """"""
    features_by_layer = {}
    for feature_layer in feature_layers:
        layer_name = feature_layer['name']
        features = feature_layer['features']
        features_by_layer[layer_name] = features
    return features_by_layer
650833
def pass_feature(*feature_names):
    
    def decorator(f):
        @functools.wraps(f)
        def wrapper(*args, **kwargs):
            for name in feature_names:
                kwargs[name] = feature_proxy(name)
            return f(*args, **kwargs)
        return wrapper
    return decorator
245036
def get_feature_names(clf, vec=None, bias_name='<BIAS>', feature_names=None,
                      num_features=None, estimator_feature_names=None):
    # type: (Any, Any, Optional[str], Any, int, Any) -> FeatureNames
    
    if not has_intercept(clf):
        bias_name = None

    if feature_names is None:
        if vec and hasattr(vec, 'get_feature_names'):
            return FeatureNames(vec.get_feature_names(), bias_name=bias_name)
        else:
            if estimator_feature_names is None:
                num_features = num_features or get_num_features(clf)
                return FeatureNames(
                    n_features=num_features,
                    unkn_template='x%d',
                    bias_name=bias_name
                )
            return FeatureNames(estimator_feature_names, bias_name=bias_name)

    num_features = num_features or get_num_features(clf)
    if isinstance(feature_names, FeatureNames):
        if feature_names.n_features != num_features:
            raise ValueError("feature_names has a wrong n_features: "
                             "expected=%d, got=%d" % (num_features,
                                                      feature_names.n_features))
        # Make a shallow copy setting proper bias_name
        return FeatureNames(
            feature_names.feature_names,
            n_features=num_features,
            bias_name=bias_name,
            unkn_template=feature_names.unkn_template)
    else:
        if len(feature_names) != num_features:
            raise ValueError("feature_names has a wrong length: "
                             "expected=%d, got=%d" % (num_features,
                                                      len(feature_names)))
        return FeatureNames(feature_names, bias_name=bias_name)
496896
def _dict_of_funcs(self, funcs: list) -> pd.Series:
        """"""
        return {func.__name__: func for func in funcs}