libtorch学习笔记(1)- 开发环境搭建

15 篇文章 0 订阅
14 篇文章 11 订阅

安装

首先下载libtorch安装包,我选在了debug版本的用于学习:
https://pytorch.org/get-started/locally/在这里插入图片描述
解压到某一目录,比如:I:\pytorch\1.5.1\debug

配置VS2017

创建一个VS2017 console project, 选择Debug|x64,然后配置include, libpath和link libraries:
include path
libpath
link libraries比如在我的Windows 10:c10.lib;torch.lib;caffe2_module_test_dynamic.lib;torch_cpu.lib;fbgemm.lib;cpuinfo.lib;clog.lib;libprotocd.lib;libprotobufd.lib;mkldnn.lib

测试代码

#include <stdio.h>
#include <ATen/ATen.h>
#include <ATen/Tensor.h>
#include <torch/torch.h>
#include <iostream>
#include <tuple>

struct Net : torch::nn::Module
{
	Net(int64_t N, int64_t M)
		:linear(register_module("linear", torch::nn::Linear(N, M))) {
		another_bias = register_parameter("b", torch::randn(M));
	}

	torch::Tensor forward(torch::Tensor input) {
		return linear(input) + another_bias;
	}

	torch::nn::Linear linear;
	torch::Tensor another_bias;
};

int main()
{
	// vector -> tensor
	{
		std::vector<float> scales = { 1, 1, 1, 1, 1, 1 };
		auto tscales = torch::tensor(scales);
		std::cout << tscales << std::endl;

		std::cout << tscales.sizes().size() << ":" <<  tscales.sizes()[0] << std::endl;

		std::cout << tscales.squeeze() << std::endl;
	}

	// select
	{
		auto a = torch::randn({ 2, 3 });
		std::cout << a << std::endl;
		auto b = a.select(1, 2);
		std::cout << b << std::endl;
	}

	// index select and max
	{
		auto indices = torch::tensor({ 0, 3, 1, 2 });
		std::cout << indices << std::endl;
		auto a = torch::randint(100, { 6, 4 });
		std::cout << a << std::endl;
		auto b = torch::index_select(a, 0, indices);
		std::cout << b << std::endl;

		auto max_classes = torch::max(a, 1);
		std::cout << std::get<0>(max_classes) << std::endl;
		std::cout << std::get<1>(max_classes) << std::endl;
	}

	// compare
	{
		auto a = torch::randn({ 2, 3 });
		auto b = a * 100;

		std::cout << "a:\n" << a << "b:\n" << b << std::endl;

		std::cout << (b < 10) << std::endl;
	}

	// stack
	{
		auto a = torch::randn(10);
		auto b = torch::randn(10);

		std::cout << "a:\n" << a << "b:\n" << b << std::endl;

		auto c = torch::stack({ a, b }, 0);
		std::cout << c << std::endl;
	}
	// nn test
	{
		Net net(4, 5);
		for (auto const& p : net.named_parameters())
		{
			std::cout << p.key() << ":\n" << p.value() << std::endl;
		}
	}

	{
		Net net(4, 5);
		std::cout << net.forward(torch::ones({ 2, 4 })) << std::endl;
	}

	return 0;
}

运行结果

在这里插入图片描述

  • 3
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值