python实现one-hot 编码

在机器学习和深度学习模型中,独热编码是对类别标签常见的编码形式,对指定类别数目的标签进行编码时,chatgpt给出了解答,很多时候替我省下了很多试错成本。

import numpy as np
from sklearn.preprocessing import OneHotEncoder

def numerical_to_one_hot(labels, num_classes):
    """
    Convert numerical labels into one-hot encoded vectors with specified number of classes.

    Parameters:
    - labels: List or array of numerical labels.
    - num_classes: Number of unique classes.

    Returns:
    - one_hot_encoded: 2D numpy array of one-hot encoded vectors.
    """
    labels = np.array(labels).reshape(-1, 1)  # Reshape labels to a column vector
    encoder = OneHotEncoder(categories='auto', sparse_output=False, drop='if_binary')
    encoder.fit(np.arange(num_classes).reshape(-1, 1))  # Fit encoder on possible classes
    one_hot_encoded = encoder.transform(labels)
    return one_hot_encoded

# Example usage:
numerical_labels = [0, 2, 1, 0, 2]
num_classes = 4
one_hot_encoded = numerical_to_one_hot(numerical_labels, num_classes)
print("Original labels:", numerical_labels)
print("One-hot encoded labels:\n", one_hot_encoded)

  • 5
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值