tensor

pytorch中的Tensor和ndarray

霸气de小男生 提交于 2019-12-09 17:17:29
Tensor和ndarray是深度学习中经常遇到的两个概念: 针对于pytorch (1)所在的位置: cpu gpu一般Tensor是可以在cpu中也可以在gpu中的 空间位置转换: 把Tensor从cpu中移动到gpu中: Tensor.cuda() 把Tensor从gpu中移动到cpu中: Tensor.cpu() (2)tensor和ndarray之间的转换: tensor 到 ndarray: Tensor.numpy() ndarray到Tensor : torch.from_numpy(ndarray类型的数据) 来源: CSDN 作者: nbxuwentao 链接: https://blog.csdn.net/nbxuwentao/article/details/103460444

01-TensorFlow2.0基础

社会主义新天地 提交于 2019-12-08 23:10:42
01-TensorFlow基础 Tensorflow是什么 Google的开源软件库 采取数据流图,用于数值计算 支持多种平台 - GPU、CPU、 移动设备 最初用于深度学习,变得越来越通用 Tensorflow数据结构 #数据流图 线:节点之间的输入输出关系,线上运输张量. tensor:张量 - 指代数据 节点:operation (op): 专门运算的操作节点,所有的操作都是一个op,处理数据 只要使用tensorflow的API定义的函数都是OP 节点被分配到各种计算设备上运行 graph: 图 整个的程序结构 本质上是一个分配的内存位置,默认有一个图,所有的tensor 和 op 的内存地址都是一样的。 不同的图内存地址不一样,计算的过程中互不干扰 session: 会话: 运算程序的图 (只能运行一张图,可以在会话中指定图去运行 graph = g) 运行图的结构 分配资源计算 掌握资源(变量、队列、线程) Tensorflow的特性 高度的灵活性,便于调用函数,也可以写自己的封装 真正的可移植性,在不同的设备上都可以简单运行 产品和科研结合 自动求微分,主要用于反向传播计算 多语言支持,C++, Java , JS, R 性能最优化 Tensorflow的前后端系统 前端系统:定义程序的图的机构 后端系统: 运算图结构 Tensorflow版本变迁

动手学PyTorch | (18) GPU计算

只愿长相守 提交于 2019-12-08 14:47:31
到⽬前为止,我们⼀直在使⽤CPU计算。对复杂的神经网络和⼤规模的数据来说,使用CPU来计算可能不够⾼效。在本节中,我们将介绍如何使用单块NVIDIA GPU来计算。所以需要确保已经安装好了PyTorch GPU版本(又可用的GPU资源)。 可以在命令行使用nvidia-smi查看显卡信息: nvidia-smi #Linux/Mac OS 目录 1. 计算设备 2. Tensor的GPU计算 3. 模型的GPU计算 4. 小结 1. 计算设备 PyTorch可以指定⽤来存储和计算的设备,如使⽤内存的CPU或者使用显存的GPU。默认情况下,PyTorch会将数据创建在内存,然后利用CPU来计算。 用torch.cuda.is_available()查看GPU是否可用: import torch from torch import nn torch.cuda.is_available() # cuda是否可用 查看GPU数量: torch.cuda.device_count() # gpu数量 查看当前GPU索引号,索引号从0开始: torch.cuda.current_device() # 当前设备索引, 从0开始 根据索引号查看GPU的名字: torch.cuda.get_device_name(0) # 返回gpu名字 2. Tensor的GPU计算 默认情况下

Applying tf.nn.softmax() only to positive elements of a tensor

落花浮王杯 提交于 2019-12-08 07:07:04
问题 I tried far to long to solve this problem and did not find anything useful on the Internet so I have to ask: Given a tensor T , let's say T = tf.random_normal([100]) , I want to apply softmax() only to the positive elements of the tensor. Something like T = tf.nn.softmax(T[T>0]) which of course does not work in Tensorflow. In short: I want to compute softmax and applied only on elements T > 0 . How can I do that in Tensorflow? 回答1: If you want softmax computed + applied only to elements T > 0

学习tf.sparse_to_dense函数(代码实现)

我与影子孤独终老i 提交于 2019-12-07 17:10:20
#当tf.sparse_to_dense的第一个参数是2阶的tensor时 import tensorflow as tf BATCH_SIZE=5 label=tf.expand_dims(tf.constant([1,3,5,7,9]),1)#真实标签 shape==>[5,1] index=tf.expand_dims(tf.range(0, BATCH_SIZE),1)#真实标签的索引 shape==>[5,1] concated = tf.concat([index, label],1) #将标签和索引tensor在第二个维度上连接起来,新的concated的shape==>[5,2] onehot_labels = tf.sparse_to_dense(concated, [BATCH_SIZE,10], 1.0, 0.0) # onehot_labels的shape==>[5,10] with tf.Session() as sess: onehot1=sess.run(onehot_labels) print (onehot1) [[ 0. 1. 0. 0. 0. 0. 0. 0. 0. 0.] [ 0. 0. 0. 1. 0. 0. 0. 0. 0. 0.] [ 0. 0. 0. 0. 0. 1. 0. 0. 0. 0.] [ 0. 0. 0. 0. 0. 0.

tensorflow中embedding_lookup, tf.gather以及tf.nn.embedding_lookup_sparse的理解

霸气de小男生 提交于 2019-12-07 17:07:32
s###1. tf.nn.embedding_lookup() 函数签名如下: embedding_lookup( params , ids, partition_strategy = 'mod' , name = None , validate_indices = True , max_norm = None ) 参数说明:params参数是一些tensor组成的列表或者单个的tensor。ids一个整型的tensor,每个元素将代表要在params中取的每个元素的第0维的逻辑index,这个逻辑index是由partition_strategy来指定的。 paratition_strategy用来设定ids的切分方式。目前有两种方式分别是div和mod。其中mod的切分方式是如果对[1,2,3,4,5,6,7]进行切分则结果为[1,4,7],[2,5],[3,6]。如果是div的切分方式则是[1,2,3]、[4,5]、[6,7]。这两种切分方式在无法均匀切分的情况下都是将前(max_id+1)%len(params)个切分多分配一个元素。即在上面的例子中要求第一个切分是3个元素,其他的都是两个元素。params中有多少个tensor就进行多少切分。每个切分中的数字即是该元素的在ids中对应的index值,即对于mod切分来说,如果ids中的一个值为1

How to cast a 1-d IntTensor to int in Pytorch

旧巷老猫 提交于 2019-12-07 01:43:39
问题 I get a 1-D IntTensor,but i want to convert it to a integer. I try it by this method: print(dictionary[IntTensor.int()]) but got an error: KeyError: Variable containing: 423 [torch.IntTensor of size 1] Thanks~ 回答1: You can use: print(dictionary[IntTensor.data[0]]) The key you're using is an object of type autograd.Variable . .data gives the tensor and the index 0 can be used to access the element. 回答2: The simplest and cleanest method I know: IntTensor.item() From PyTorch docs: "Returns the

torch 中各种图像格式转换

妖精的绣舞 提交于 2019-12-06 23:44:42
PIL:使用python自带图像处理库读取出来的图片格式 numpy:使用python-opencv库读取出来的图片格式 tensor:pytorch中训练时所采取的向量格式(当然也可以说图片) PIL与Tensor相互转换 import torch from PIL import Image import matplotlib.pyplot as plt # loader使用torchvision中自带的transforms函数 loader = transforms.Compose([ transforms.ToTensor()]) unloader = transforms.ToPILImage() # 输入图片地址 # 返回tensor变量 def image_loader(image_name): image = Image.open(image_name).convert('RGB') image = loader(image).unsqueeze(0) return image.to(device, torch.float) # 输入PIL格式图片 # 返回tensor变量 def PIL_to_tensor(image): image = loader(image).unsqueeze(0) return image.to(device, torch.float)

Broadcasting np.dot vs tf.matmul for tensor-matrix multiplication (Shape must be rank 2 but is rank 3 error)

依然范特西╮ 提交于 2019-12-06 16:34:02
Let's say I have the following tensors: X = np.zeros((3,201, 340)) Y = np.zeros((340, 28)) Making a dot product of X, Y is successful with numpy, and yields a tensor of shape (3, 201, 28). However with tensorflow I get the following error: Shape must be rank 2 but is rank 3 error ... minimal code example: X = np.zeros((3,201, 340)) Y = np.zeros((340, 28)) print(np.dot(X,Y).shape) # successful (3, 201, 28) tf.matmul(X, Y) # errornous Any idea how to achieve the same result with tensorflow? Since, you are working with tensors , it would be better (for performance) to use tensordot there than np

How to load image files dataset to TensorFlow Jupyter Notebook

徘徊边缘 提交于 2019-12-06 14:23:35
问题 I'm trying to create a model to classify some plants, just so I can learn how to use TensorFlow. The problem is that every good example that I can use as reference is loading a .csv dataset and I want to load a .jpeg dataset (could be .png or .jpg as well). Those examples even use a built in dataset like: from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) My dataset is organized in folders containing the label of the