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. openstack stein部署手册 4. glance

    # 建立数据库用户及权限 create database glance; grant all privileges on glance.* to glance@'localhost' identifi ...

  2. tail 显示文件内容尾部

    1.命令功能 tail默认显示文件内容尾部10行. 2.语法格式 tail  option  file 参数说明 参数 参数说明 -n 显示指定行数 -f 实时输出文件变化后追加的数据 -s 监视文件 ...

  3. bzoj 3569 DZY Loves Chinese II 随机算法 树上倍增

    题意:给你一个n个点m条边的图,有若干组询问,每次询问会选择图中的一些边删除,删除之后问此图是否联通?询问之间相互独立.此题强制在线. 思路:首先对于这张图随便求一颗生成树,对于每一条非树边,随机一个 ...

  4. WiFi密码新攻击破解方法,黑客攻破只需10秒

    近日,中国知名黑客安全组织东方联盟研究人员透露了一种新的WiFi黑客技术,使黑客更容易破解大多数现代路由器的WiFi密码,并且攻破只需要10秒,速度非常快. 方法是利用由流行的密码破解工具Hashca ...

  5. ELK Stack

    原创转载请注明出处:https://www.cnblogs.com/agilestyle/p/11488404.html ELK workflow log -> filebeat -> l ...

  6. C#语句,console,C#//,/**/

    ].

  7. 基于ELK Stack7.1.0构建多用户安全认证日志系统

    ​ 配置tls加密通信及身份验证,主要目的是为了确保集群数据安全.在es早期版本,安全认证相关功能都属于商业付费服务,一般普通公司如果集群部署在内网,基本上就忽略了这些安全认证,当然也可以通过Ngin ...

  8. win7下redis开机自启动设置

    win7下安装完redis之后,每次开机都得用cmd命令行启动redis,所以就想办法实现开机自启动redis. 一.把启动命令写入bat: E:\redis\redis-server.exe E:\ ...

  9. Python_009(函数,命名空间)

    一.函数 1.函数格式: #定义函数: def function(): 函数体 return 返回值 #调用函数: function() ret = function() 这是得到返回值. 这里是用关 ...

  10. 屏幕分辨率测试工具(舍弃)---chrome开发者工具devTools(强烈建议系统学习)

    2019-01-25 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http:// ...