SEO:

libtorch 如何 OneHot ?

torch OneHot 源代码 ?

https://www.tensorflow.org/api_docs/python/tf/one_hot

最新的 1.3 版本中已经添加了该函数

#include <torch/torch.h>
#include <c10/util/StringUtil.h>
torch::Tensor one_hot(const torch::Tensor &self, int64_t num_classes) {
AT_CHECK(self.dtype() == torch::kLong, "one_hot is only applicable to index tensor.");
auto shape = self.sizes().vec(); // empty tensor could be converted to one hot representation,
// but shape inference is not possible.
if (self.numel() == 0) {
if (num_classes <= 0) {
AT_ERROR("Can not infer total number of classes from empty tensor.");
}
else {
shape.push_back(num_classes);
return at::empty(shape, self.options());
}
} // non-empty tensor
AT_CHECK(self.min().item().toLong() >= 0, "Class values must be non-negative.");
if (num_classes == -1) {
num_classes = self.max().item().toLong() + 1;
}
else {
AT_CHECK(num_classes > self.max().item().toLong(), "Class values must be smaller than num_classes.");
} shape.push_back(num_classes);
torch::Tensor ret = at::zeros(shape, self.options());
ret.scatter_(-1, self.unsqueeze(-1), 1);
return ret;
}

使用示例

	torch::TensorOptions options(torch::kLong);
auto tensor = torch::tensor({ 0,1,2 }, options);
std::cout << tensor << std::endl; try
{
auto one_hot = torch::one_hot(tensor,4);
std::cout << one_hot << std::endl;
}
catch (const c10::Error& watch)
{
std::cout << watch.msg() << std::endl;
}

随机推荐

  1. linux使用v 2ray

    一.安装配置服务端程序 是时候使用 了,因为相对安全,使用方法很简单,使用root权限执行以下命令即可 $ sudo -i 一顿安装后如图 输入 命令可以查看链接,然后在客户端使用这个链接就能配置好了 ...

  2. opencv windows源码编译

    WITH_QT//H:\software\programming\qt\5.12.3\mingw73_32\lib\cmake  5.6的路径要改这样 WITH_OPENGL 编译器mingw32-m ...

  3. C++中的const_cast

    开发环境 Qt Creator 4.8.2 编译器版本 MinGw 32-bit const_cast 用法: const_cast<type_id> (expression) 说明: 该 ...

  4. window环境下mysql导入sql文件时报错:ERROR: ASCII '\0' appeared in the statement

    错误信息: ERROR: ASCII '\0' appeared in the statement, but this is not allowed unless option --binary-mo ...

  5. [python 学习] 使用 xml.etree.ElementTree 模块处理 XML

    ---恢复内容开始--- 导入数据(读文件和读字符串) 本地文件 country_data.xml <?xml version="1.0"?> <data> ...

  6. Mybatis学习笔记大纲

    Mybatis学习笔记大纲: 一.MyBatis简介 二.MyBatis-HelloWorld 三.MyBatis-全局配置文件 四.MyBatis-映射文件 五.MyBatis-动态SQL 六.My ...

  7. 股票交易 (单调队列优化DP)

    股票交易 $ solution: $ 这道题以前就写了,题目很好,但自己没有发题解,来补一篇: 首先,题目出得很有迷惑性,但我们不难想到状态要设天数,和自己手上的股票数目(因为这两个就是充要信息).而 ...

  8. HashMap测试程序1

    package com.iotek.map; import java.util.Collection;import java.util.HashMap;import java.util.Map;imp ...

  9. Python3解leetcode Min Cost Climbing Stairs

    问题描述: On a staircase, the i-th step has some non-negative cost cost[i]assigned (0 indexed). Once you ...

  10. php prev()函数 语法

    php prev()函数 语法 作用:将内部指针指向数组中的上一个元素,并输出.直线电机选型 语法:prev(array) 参数: 参数 描述 array 必需.指定需要操作的数组. 说明:如果数组包 ...