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. 2019-5-28-VisualStudio-扩展开发

    title author date CreateTime categories VisualStudio 扩展开发 lindexi 2019-05-28 19:51:49 +0800 2018-2-1 ...

  2. VS #include 【bits/bstdc++.h】出错

    目录 1. 本文地址 2. 按 3. 操作步骤 1. 本文地址 博客园:https://www.cnblogs.com/coco56/p/11163142.html 简书:https://www.ji ...

  3. linux精简开机启动服务

    1.可以使用 setup-system services 里面调整,这样调整起来效率低 2.或者 ntsysv 调出来 3.使用脚本一件关闭 #LANG=en chkconfig --list #停止 ...

  4. Redis复制实现原理

    摘要 我的前一篇文章<Redis 复制原理及特性>已经介绍了Redis复制相关特性,这篇文章主要在理解Redis复制相关源码的基础之上介绍Redis复制的实现原理. Redis复制实现原理 ...

  5. RabbitMQ走过的坑,发送的消息是乱码

    发送的消息在可视化界面中是乱码,如图: 看见这个content_tpye没有,是不是很奇怪,就是这个坑,设置下就行,看代码: @Bean Jackson2JsonMessageConverter me ...

  6. 手写hashmap算法

    /** * 01.自定义一个hashmap * 02.实现put增加键值对,实现key重复时替换key的值 * 03.重写toString方法,方便查看map中的键值对信息 * 04.实现get方法, ...

  7. 在vue项目中,解决如何在element表格中循环出图片列!

    效果图: 1,vue项目环境 2,引入element-ui组件 3,制作表格 此处省去制作循环表格数据那步,想看的可以找回我的博客:element中的表格处理:循环出表格数据 今天想在表格出循环出一列 ...

  8. HTTP通信安全和Web攻击技术

    一.HTTPS,确保Web安全 在HTTP协议中可能存在信息窃听或身份伪装等安全问题,HTTP的不足: 通信使用明文(不加密),内容可能会被窃听  不验证通信方的身份,因此有可能遭遇伪装 无法证明报文 ...

  9. 实现粘贴WORD图片的在线编辑器

    我司需要做一个需求,就是使用富文本编辑器时,不要以上传附件的形式上传图片,而是以复制粘贴的形式上传图片. 在网上找了一下,有一个插件支持这个功能. WordPaster 安装方式如下: 直接使用Wor ...

  10. 20180821-Java封装

    java 封装 在面向对象程式设计方法中,封装(英语:Encapsulation)是指,一种将抽象性函式接口的实作细节部份包装.隐藏起来的方法. 封装可以被认为是一个保护屏障,防止该类的代码和数据被外 ...