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. 【错误】Publishing to Tomcat'has encountered a problem

    tomcat 启动工程时候出现 Publishing to Tomcat'has encountered a problem错误 解决方案 之后重启tomcat 就可以正常启动了

  2. tf.reshape

    tf.reshape(tensor, shape, name=None) 其中,tensor是向量,或者说矩阵 shape是转换后的向量,或者转换后的矩阵形状 [2,1]转换成二行一列 [2,-1]转 ...

  3. Ansible笔记(1)---基本概念

    一.ansible的作用以及工作结构 1.1.ansible简介: ansible是新出现的自动化运维工具,基于Python开发,集合了众多运维工具(puppet.cfengine.chef.func ...

  4. [python 学习] IO操作之读写文件

    一.读取全部文件: # -*- coding: utf-8 -*- f = open('qq_url.txt','r'); print f.read(); f.close(); 二.读取规定长度文件 ...

  5. $_POST 和 php://input 的区别

    手册中摘取的几句话: 当 HTTP POST 请求的 Content-Type 是 application/x-www-form-urlencoded 或 multipart/form-data 时, ...

  6. 理解Promise (1)

    new Promise 需要传递一个执行器 (函数) 函数有两个参数 resolve reject promise 承诺 默认的状态是pengding 调用 resolve 表示成功 reject 表 ...

  7. 2019届校招前端面试题整理——HTML、CSS篇

    前言 2019届校招陆陆续续开始了,整理了一些高频的面试题. HTML部分 1. 什么是<!DOCTYPE>? DOCTYPE是html5标准网页声明,且必须声明在HTML文档的第一行.来 ...

  8. JUC并发工具类

    原创转载请注明出处:https://www.cnblogs.com/agilestyle/p/11449367.html java.util.concurrent及其子包,集中了Java并发的各种基础 ...

  9. python 生成多维数组

    在刷题时用到了数组,因为不提供三方库所以不能使用Numpy.想如何通过python列表模拟数组. 第一种方法 """ 生成n*m的初始值为0的矩阵 "" ...

  10. elasticsearch6.8.1 x-pack插件破解

    一.为什么要破解x-pack?       因为涉及到了ES服务的安全性.ES服务如果被劫持,数据直接会被删除.ES登录账号和密码的设置是通过x-pack来实现的,官方只给了免费的30天的使用权,而且 ...