• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python label.LabelEncoder类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中sklearn.preprocessing.label.LabelEncoder的典型用法代码示例。如果您正苦于以下问题:Python LabelEncoder类的具体用法?Python LabelEncoder怎么用?Python LabelEncoder使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了LabelEncoder类的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: __call__

 def __call__(self, labels):
     labels = LabelEncoder().fit_transform(labels)
     labels = labels.reshape((len(labels), 1))
     labels = OneHotEncoder(sparse=False).fit_transform(labels)
     if labels.shape[1] == 2:
         return labels[:, 0].reshape((len(labels), 1))
     else:
         return labels
开发者ID:etamponi,项目名称:emetrics,代码行数:8,代码来源:onehot_label_encoder.py


示例2: test_label_encoder

def test_label_encoder():
    """Test LabelEncoder's transform and inverse_transform methods"""
    le = LabelEncoder()
    le.fit([1, 1, 4, 5, -1, 0])
    assert_array_equal(le.classes_, [-1, 0, 1, 4, 5])
    assert_array_equal(le.transform([0, 1, 4, 4, 5, -1, -1]), [1, 2, 3, 3, 4, 0, 0])
    assert_array_equal(le.inverse_transform([1, 2, 3, 3, 4, 0, 0]), [0, 1, 4, 4, 5, -1, -1])
    assert_raises(ValueError, le.transform, [0, 6])
开发者ID:huyng,项目名称:scikit-learn,代码行数:8,代码来源:test_label.py


示例3: test_label_encoder_empty_array

def test_label_encoder_empty_array(values):
    le = LabelEncoder()
    le.fit(values)
    # test empty transform
    transformed = le.transform([])
    assert_array_equal(np.array([]), transformed)
    # test empty inverse transform
    inverse_transformed = le.inverse_transform([])
    assert_array_equal(np.array([]), inverse_transformed)
开发者ID:manhhomienbienthuy,项目名称:scikit-learn,代码行数:9,代码来源:test_label.py


示例4: test_label_encoder_negative_ints

def test_label_encoder_negative_ints():
    le = LabelEncoder()
    le.fit([1, 1, 4, 5, -1, 0])
    assert_array_equal(le.classes_, [-1, 0, 1, 4, 5])
    assert_array_equal(le.transform([0, 1, 4, 4, 5, -1, -1]),
                       [1, 2, 3, 3, 4, 0, 0])
    assert_array_equal(le.inverse_transform([1, 2, 3, 3, 4, 0, 0]),
                       [0, 1, 4, 4, 5, -1, -1])
    assert_raises(ValueError, le.transform, [0, 6])
开发者ID:manhhomienbienthuy,项目名称:scikit-learn,代码行数:9,代码来源:test_label.py


示例5: test_label_encoder_fit_transform

def test_label_encoder_fit_transform():
    # Test fit_transform
    le = LabelEncoder()
    ret = le.fit_transform([1, 1, 4, 5, -1, 0])
    assert_array_equal(ret, [2, 2, 3, 4, 0, 1])

    le = LabelEncoder()
    ret = le.fit_transform(["paris", "paris", "tokyo", "amsterdam"])
    assert_array_equal(ret, [1, 1, 2, 0])
开发者ID:tguillemot,项目名称:scikit-learn,代码行数:9,代码来源:test_label.py


示例6: test_label_encoder_errors

def test_label_encoder_errors():
    # Check that invalid arguments yield ValueError
    le = LabelEncoder()
    assert_raises(ValueError, le.transform, [])
    assert_raises(ValueError, le.inverse_transform, [])

    # Fail on unseen labels
    le = LabelEncoder()
    le.fit([1, 2, 3, 1, -1])
    assert_raises(ValueError, le.inverse_transform, [-1])
开发者ID:tguillemot,项目名称:scikit-learn,代码行数:10,代码来源:test_label.py


示例7: load_dataset

    def load_dataset(self):
        with open(self.file_name) as f:
            dataset = arff.load(f)

            if self.label_attribute is None:
                self.label_attribute = dataset["attributes"][-1][0]

            data = list(numpy.asarray(dataset["data"]).transpose())
            labels = None

            row = 0
            for attribute_name, attribute_type in dataset["attributes"]:
                if attribute_name == self.label_attribute:
                    # Labels found!
                    labels = data.pop(row)
                    continue
                # Nominal attribute
                if isinstance(attribute_type, list):
                    # Convert None in '?' for next check and to make label_binarize work
                    for j in range(len(data[row])):
                        if data[row][j] is None:
                            data[row][j] = "?"
                    if numpy.all(data[row] == "?"):
                        # If no data is present, just remove the row
                        data.pop(row)
                        continue
                    if self.binarize:
                        data[row] = numpy.asarray(label_binarize(data[row], attribute_type), dtype=numpy.float64)
                    else:
                        encoder = LabelEncoder()
                        encoder.classes_ = attribute_type
                        if "?" not in encoder.classes_:
                            encoder.classes_.insert(0, "?")
                        data[row] = encoder.transform(data[row]).reshape((len(data[row]), 1)).astype(numpy.float64)
                else:
                    # Numeric attributes: check for nan values
                    data[row] = data[row].astype(numpy.float64)
                    nans = numpy.isnan(data[row])
                    if numpy.all(nans):
                        # If everything is nan, remove the feature
                        data.pop(row)
                        continue
                    if numpy.any(nans):
                        mean = data[row][numpy.invert(nans)].sum() / numpy.invert(nans).sum()
                        data[row][nans] = mean
                    # Reshape to do hstack later
                    data[row] = data[row].reshape((len(data[row]), 1))
                # Go to next row only if we have NOT removed the current one
                row += 1

            instances = numpy.hstack(tuple(data))
            useless_indices = numpy.where(instances.var(axis=0) == 0)
            instances = numpy.delete(instances, useless_indices, axis=1)

            return instances, labels
开发者ID:etamponi,项目名称:eole,代码行数:55,代码来源:dataset_utils.py


示例8: test_label_encoder_string_labels

def test_label_encoder_string_labels():
    """Test LabelEncoder's transform and inverse_transform methods with
    non-numeric labels"""
    le = LabelEncoder()
    le.fit(["paris", "paris", "tokyo", "amsterdam"])
    assert_array_equal(le.classes_, ["amsterdam", "paris", "tokyo"])
    assert_array_equal(le.transform(["tokyo", "tokyo", "paris"]),
                       [2, 2, 1])
    assert_array_equal(le.inverse_transform([2, 2, 1]),
                       ["tokyo", "tokyo", "paris"])
    assert_raises(ValueError, le.transform, ["london"])
开发者ID:andywangpku,项目名称:scikit-learn,代码行数:11,代码来源:test_label.py


示例9: test_label_encoder_errors

def test_label_encoder_errors():
    # Check that invalid arguments yield ValueError
    le = LabelEncoder()
    assert_raises(ValueError, le.transform, [])
    assert_raises(ValueError, le.inverse_transform, [])

    # Fail on unseen labels
    le = LabelEncoder()
    le.fit([1, 2, 3, -1, 1])
    msg = "contains previously unseen labels"
    assert_raise_message(ValueError, msg, le.inverse_transform, [-2])
    assert_raise_message(ValueError, msg, le.inverse_transform, [-2, -3, -4])
开发者ID:NelleV,项目名称:scikit-learn,代码行数:12,代码来源:test_label.py


示例10: normalize_data

def normalize_data(data, target):
    data.replace({'None': np.nan}, inplace=True)
    types = pd.read_csv('data/datatypes.csv')
    for i, row in types.iterrows():
        data[row['feature']] = data[row['feature']].astype(row['type'])
    data['memFreq'].fillna(0, inplace=True)
    data['memtRFC'].fillna(0, inplace=True)

    os_le = LabelEncoder()
    cpu_full_le = LabelEncoder()
    cpu_arch_le = LabelEncoder()
    mem_type_le = LabelEncoder()
    data['cpuFull'] = cpu_full_le.fit_transform(data['cpuFull'])
    data['os'] = os_le.fit_transform(data['os'])
    data['cpuArch'] = cpu_arch_le.fit_transform(data['cpuArch'])
    data['memType'] = mem_type_le.fit_transform(data['memType'])
    # drop single value columns
    data = data.drop(['cacheL3IsShared', 'BMI', 'CLF_._Cache_Line_Flush', 'CMOV_._Conditionnal_Move_Inst.',
                      'CX8_._CMPXCHG8B', 'FXSR.FXSAVE.FXRSTOR', 'IA.64_Technology',
                      'MMX_Technology', 'SSE', 'SSE2', 'SSE4a', 'SSE5', 'TBM', 'X3DNow_Pro_Technology'], axis=1)

    data['C0'] = np.log(data['n'] * data['m'] * data['k'])
    data = data.drop(['m', 'n', 'k'], axis=1)
    return data, target, {
        'os': os_le,
        'cpuFull': cpu_full_le,
        'cpuArch': cpu_arch_le,
        'memType': mem_type_le,
    }
开发者ID:blvp,项目名称:ml_tasks,代码行数:29,代码来源:data.py


示例11: test_label_encoder

def test_label_encoder(values, classes, unknown):
    # Test LabelEncoder's transform, fit_transform and
    # inverse_transform methods
    le = LabelEncoder()
    le.fit(values)
    assert_array_equal(le.classes_, classes)
    assert_array_equal(le.transform(values), [1, 0, 2, 0, 2])
    assert_array_equal(le.inverse_transform([1, 0, 2, 0, 2]), values)
    le = LabelEncoder()
    ret = le.fit_transform(values)
    assert_array_equal(ret, [1, 0, 2, 0, 2])

    with pytest.raises(ValueError, match="unseen labels"):
        le.transform(unknown)
开发者ID:manhhomienbienthuy,项目名称:scikit-learn,代码行数:14,代码来源:test_label.py


示例12: test_label_encoder

def test_label_encoder():
    # Test LabelEncoder's transform and inverse_transform methods
    le = LabelEncoder()
    le.fit([1, 1, 4, 5, -1, 0])
    assert_array_equal(le.classes_, [-1, 0, 1, 4, 5])
    assert_array_equal(le.transform([0, 1, 4, 4, 5, -1, -1]), [1, 2, 3, 3, 4, 0, 0])
    assert_array_equal(le.inverse_transform([1, 2, 3, 3, 4, 0, 0]), [0, 1, 4, 4, 5, -1, -1])
    assert_raises(ValueError, le.transform, [0, 6])

    le.fit(["apple", "orange"])
    msg = "bad input shape"
    assert_raise_message(ValueError, msg, le.transform, "apple")
开发者ID:tguillemot,项目名称:scikit-learn,代码行数:12,代码来源:test_label.py


示例13: test_label_encoder_str_bad_shape

def test_label_encoder_str_bad_shape(dtype):
    le = LabelEncoder()
    le.fit(np.array(["apple", "orange"], dtype=dtype))
    msg = "bad input shape"
    assert_raise_message(ValueError, msg, le.transform, "apple")
开发者ID:manhhomienbienthuy,项目名称:scikit-learn,代码行数:5,代码来源:test_label.py


示例14: design_matrix

def design_matrix(sample_labels, interaction_indices=None):
    """
    Parameters
    ---------
    sample_labels: 
        a numpy matrix, for each sample a vector with the conditions
        which we would like to model.
        cols represent the type of conditions we want to model,
        row represent a combination of conditions that are represented by the row-variable.
        if we have a 2x3 design we build this matrix:
        [[0,0],
         [0,1],
         [0,2],
         [1,0],
         [1,1],
         [1,2]]
        
        
    
    Returns
    -------
    X: the design matrix.
    factor_labels: the labels of the design-matrix columns
    factor_num : number of factors for each condition
    
    """
        
    factor_num = []
    n_factors = 0
    
    for i in range(sample_labels.shape[1]):
        unique_labels = np.unique(sample_labels[:,i])
        if len(unique_labels) == 1:
            label_factors = 0
        else:
            label_factors = len(unique_labels)
        
        n_factors+=label_factors
        factor_num.append(label_factors)
    
    n_interactions = 0
    if interaction_indices != None:
        interaction_factors = np.array(factor_num)[[interaction_indices]]
        n_interactions = np.prod(interaction_factors)
        Xint = np.zeros((sample_labels.shape[0], n_interactions))
    
    
    X = np.zeros((sample_labels.shape[0], n_factors))
    
    lb = LabelEncoder()
    factor_labels = []
    offset = 0
    for i, factor in enumerate(factor_num):
        if factor == 0:
            continue
        index = lb.fit_transform(sample_labels.T[i])
        for j in range(sample_labels.shape[0]):
            X[j,index[j]+offset] = 1
        
        factor_labels.append(lb.classes_)
        
        offset += factor
    
    if interaction_indices != None:
        interaction_product = [np.arange(v).tolist() for v in interaction_factors]
        interaction_gen = cartesian(interaction_product)
        
        # This is buggy!!
        Xint = np.zeros((sample_labels.shape[0], n_interactions))
        offset = interaction_indices[0] * np.sum(factor_num[:interaction_indices[0]])
        offset = np.int(offset)
        for i, int_indices in enumerate(interaction_gen):
            
            index1 = offset + int_indices[0]
            index2 = offset + int_indices[1] + factor_num[interaction_indices[0]]
            
            Xint[:,i] = X[:,index1] * X[:,index2]
            
            factor1 = interaction_indices[0]
            factor2 = interaction_indices[1]

            new_label = factor_labels[factor1][int_indices[0]] + "_" + \
                        factor_labels[factor2][int_indices[1]]
                        
            factor_labels.append(new_label)
        
        X = np.hstack((X, Xint))
        
    return X, np.hstack(factor_labels), factor_num
开发者ID:robbisg,项目名称:mvpa_itab_wu,代码行数:89,代码来源:anova.py



注:本文中的sklearn.preprocessing.label.LabelEncoder类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python label.MultiLabelBinarizer类代码示例发布时间:2022-05-27
下一篇:
Python label.LabelBinarizer类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap