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. vue.js 笔记

    <!-- 多层for循环 --> <ul> <li v-for="(ite,key) in list2"> {{key}}-------{{it ...

  2. How to Add Memory, vCPU, Hard Disk to Linux KVM Virtual Machine

    ref: https://www.thegeekstuff.com/2015/02/add-memory-cpu-disk-to-kvm-vm/ In our previous article of ...

  3. python常用函数 V

    vars(object) 返回对象object的属性和属性值的字典对象.不输入参数,就打印当前调用位置的属性和属性值,相当于locals()的功能. 例子:

  4. JVM加载class文件原理

    装载的概念 所谓装载就是寻找一个类或是一个接口的二进制形式并用该二进制形式来构造代表这个类或是这个接口的class对象的过程. Java中类装载器装载类到虚拟机 在Java中,类装载器把一个类装入Ja ...

  5. 手工实现Array List和Linked List

    Array List样例: /** * 增加泛型 * 自动增加数组容量 * 增加set.get方法:增加数组边界的检查 * 增加remove方法 */package cn.study.lu.four; ...

  6. 检测代理IP匿名程度的方法,很实用

    做网络的基本都知道代理,这个是肯定的,不管是用花刺还是猎手的网页代理,还是直接VPN的通道代理,代理有着不用说大家也知道的重要性.不管是做CPA还是做点击亦或者投票,代理都能帮我们一下,虽然帮的忙不大 ...

  7. 解决在vue_cli上使用mui或引入mui.js各种报错及问题

    原文:https://blog.csdn.net/u012815877/article/details/81187826 在main.js里添加 import mui from './assets/j ...

  8. spring boot中注册拦截器

    拦截器是动态拦截Action调用的对象.它提供了一种机制可以使开发者可以定义在一个action执行的前后执行的代码,也可以在一个action执行前阻止其执行,同时也提供了一种可以提取action中可重 ...

  9. Js获取屏幕宽度、高度

    document.body.clientWidth ==> BODY对象宽度 document.body.clientHeight ==> BODY对象高度 document.docume ...

  10. ARP(Address Resolution Protocol)地址解析协议初识

    ARP址解析协议是根据IP地址获取物理地址的一个TCP/IP协议.它工作在OSI七层模型的中第二层——数据链路层. 使用ARP地址解析协议,可根据网络层IP数据包包头中的IP地址信息解析出目标硬件地址 ...