tensor

TensorFlow、把数字标签转化成onehot标签

我怕爱的太早我们不能终老 提交于 2019-11-30 06:28:33
在MNIST手写字数据集中,我们导入的数据和标签都是预先处理好的,但是在实际的训练中,数据和标签往往需要自己进行处理。 以手写数字识别为例,我们需要将0-9共十个数字标签转化成onehot标签。例如:数字标签“6”转化为onehot标签就是[0,0,0,0,0,0,1,0,0,0]. 首先获取需要处理的标签的个数: batch_size = tf.size(labels) 1 假设输入了6张手写字图片,那么对应的标签数为6,batch_size=6. tf.size(input) 函数为获取输入tensor的元素数量。 例:设 t = [[1,2],[3,4]],则 tf.size(t) 的结果为4。 然后我们知道onehot标签的shape为[batch_size,10],采用稀疏编码的方法,在onehot标签中选择能够代表标签的位置,将其置为1,其余位置置为0。因此要选择onehot中需要置为1的位置的坐标。 labels = tf.expand_dims(labels, 1) indices = tf.expand_dims(tf.range(0, batch_size, 1), 1) concated = tf.concat([indices, labels],1)    这里得到的concated就是所要置为1 的位置的坐标了。 tf.expand_dims(input,

How to convert Pytorch autograd.Variable to Numpy?

两盒软妹~` 提交于 2019-11-30 05:08:06
The title says it all. I want to convert a PyTorch autograd.Variable to its equivalent numpy array. In their official documentation they advocated using a.numpy() to get the equivalent numpy array (for PyTorch tensor ). But this gives me the following error: Traceback (most recent call last): File "stdin", line 1, in module File "/home/bishwajit/anaconda3/lib/python3.6/site-packages/torch/autograd/variable.py", line 63, in getattr raise AttributeError(name) AttributeError: numpy Is there any way I can circumvent this? Two possible case Using GPU: If you try to convert a cuda float-tensor

tensorflow2.0 创建张量

老子叫甜甜 提交于 2019-11-30 00:40:42
2 创建张量 Tensorflow中可以通过多种方式创建张量,如从python list对象创建,从numpy数组创建,创建采样自某种已知分布的张量。 2.1 从numpy,python List对象创建 Numpy Array数组和Python List是python程序中间非常重要的数据载体容器,很多数据都是通过Python语言将数据加载至Array或者List容器,再转换到Tensor类型,通过Tensorflow运算处理后导出到Array或者List容器,方便其他模块调用。 通过tf.convert_to_tensor可以创建新Tensor,并将保存在Python List对象或者Numpy Array对象中的数据导入到新的Tensor中: tf.convert_to_tensor([1, 2.]) tf.convert_to_tensor(np.array([[1,2 ], [3, 4]])) tf.constant()和tf.convert_to_tensor()都能够自动的把Numpy数组或者Python List数据类型转换为Tensor类型,使用其一即可。 2.2 创建全0,全1张量(tf.zeros(), tf.ones()) 将张量创建为全0或者全1数据是非常常见的张量初始化手段。 考虑线性变换 ,将权值矩阵W初始化为全1矩阵,偏置b初始化为全0向量

tensorflow2.0 张量操作

假如想象 提交于 2019-11-30 00:25:04
3 张量操作 3.1 索引 Tensorflow中,支持基本的[i][j]…的标准索引方式,也支持通过逗号分隔索引号的索引方式[i, j, k]。假设如下为图片数据 In [3]: x = tf.random.normal([4, 32, 32, 3]) 取第一张图片数据 In [4]: x[0] Out[4]: <tf.Tensor: id=15, shape=(32, 32, 3), dtype=float32, numpy= 取第一张图片的第二行 In [5]: x[0][1] Out[5]: <tf.Tensor: id=23, shape=(32, 3), dtype=float32, numpy= 取第1张图片,第2行,第3列的像素 In [6]: x[0][1][2] Out[6]: <tf.Tensor: id=35, shape=(3,), dtype=float32, numpy=array([-0.11009463, 0.0398486 , 1.8434385 ], dtype=float32)> 取第三张图片,第2行,第1列元素,第2个通道的颜色强度值 In [7]: x[2][1][0][1] Out[7]: <tf.Tensor: id=51, shape=(), dtype=float32, numpy=0.96755> 取第2张图片,第10行,第3列

Data Loading and Processing Tutorial

倖福魔咒の 提交于 2019-11-30 00:23:17
1 import os   #路径组合 2 import torch # is_tensor 3 import pandas as pd   #读取csv 4 import numpy as np     #ndarray , reshape, 5 from torch.utils.data import Dataset, DataLoader   #实现数据集和数据集的分组 6 from skimage import io            #for image io 7 import matplotlib.pyplot as plt           #for plotting 8 from torchvision import transforms, utils        #transforms.compose ,utils.make_grid() 9 from skimage import io, transform            #读取图片, transform.resize 10 import warnings panda: 用于解析csv文件 scikit-iamge:读取图像和图像转换 os.path.join():把不同路径部分拼接在一起,并用 / 隔开,如果最后一个组分是“”,会在最后的路径名后加上 / 自己的数据集类继承与dataset

How does the “view” method work in PyTorch?

心不动则不痛 提交于 2019-11-29 18:42:20
I am confused about the method view() in the following code snippet. class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(3, 6, 5) self.pool = nn.MaxPool2d(2,2) self.conv2 = nn.Conv2d(6, 16, 5) self.fc1 = nn.Linear(16*5*5, 120) self.fc2 = nn.Linear(120, 84) self.fc3 = nn.Linear(84, 10) def forward(self, x): x = self.pool(F.relu(self.conv1(x))) x = self.pool(F.relu(self.conv2(x))) x = x.view(-1, 16*5*5) x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = self.fc3(x) return x net = Net() My confusion is regarding the following line. x = x.view(-1, 16*5*5)

python常用代码

烈酒焚心 提交于 2019-11-29 18:19:41
目录 常用代码片段及技巧 自动选择GPU和CPU 切换当前目录 打印模型参数 将tensor的列表转换为tensor 内存不够 debug tensor memory 常用代码片段及技巧 自动选择GPU和CPU device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') # model and tensor to device vgg = models.vgg16().to(device) 切换当前目录 import os try: os.chdir(os.path.join(os.getcwd(), '..')) print(os.getcwd()) except: pass 打印模型参数 from torchsummary import summary # 1 means in_channels summary(model, (1, 28, 28)) 将tensor的列表转换为tensor x = torch.stack(tensor_list) 内存不够 Smaller batch size torch.cuda.empty_cache() every few minibatches debug tensor memory resource` module is a Unix specific

TensorFlow01: 二进制文件读取

泪湿孤枕 提交于 2019-11-29 16:19:01
实现代码: # 读取文件列表 file_name = os.listdir("../data/cifar/") file_list = [os.path.join("../data/ficar/",file) for file in file_name] # 构造文件名度列 file_queue = tf.train.string_input_producer(file_list) # 读取 reader = tf.FixedLengthRecordReader(32*32*3+1) key, value = reader.read(file_queue) print(value) # 解码 decoded = tf.decode_raw(value, tf.uint8) print(decoded) # 将目标值和特征值切开 label = tf.slice(decoded, [0], [1]) image = tf.slice(decoded, [1], [32*32*3]) print("label:", label) print("image:", image) # 调整图片的形状 image_reshape = tf.reshape(image, shape=[3, 32, 32]) print("image_reshape:", image_reshape) # 转置

TensorFlow01:张量

对着背影说爱祢 提交于 2019-11-29 15:31:38
张量的形状: 标量---1个数字---0阶张量 向量---1维数组---1阶张量 矩阵---2维数组---2阶张量 张量---n维数组---n阶张量 张量操作: tf.zeros(shape,dype=tf.float,name=None) #全零张量 tf.ones()是全1张量 tf.zeros_like(tensor,dtype=None,name=None) #创建相同类型,相同形状的张量 tf.fill(shape,value,name=None) #填充指定标量的张量 tf.constant(value,dtype=None,shape=None,name=None) #创建一个常数张量 tf.truncated_normal(shape,mean=0.0,stddev=1.0,dtype=tf.float32,seed=None,name=None)#所有数字不超过两个标准差 tf.random_normal(shape,mean=0.0,stddv=1.0,dtype=tf.float32,seed,name=None)#随机正态分布的数字组成的矩阵 tf.cast(tensor,dtype) #不会改变原始的tensor,返回新的改变类型后的tensor tensor.get_shape() # 获取tensor形状 tensor.set_shape(shape)

TensorFlow01:增加变量显示+tensorboard可视化

走远了吗. 提交于 2019-11-29 15:30:53
#加名空间: with.tf.variable_scope(“name”): a = tf.Variable(initial_value=50) # 初始化变量 tf.global_variables_initializer().run() #收集变量: tf.summary.scalar(name=“”,tensor) #收集loss和accuray等单值变量,name是变量的名字,tensor为值 tf.summary.histogram(name=””,tensor) #收集高维度的变量参数 tf.summary.image(name,tensor) #收集输入的图片张量能显示图片 #合并变量写入事件 marged=tf.summary.merge_all() summary=sess.run(merged) # 每次迭代都需要运行 FileWriter.add_summary(summary,i) #i表示第几次的值 启动Tensorboard命令:tensorboard –logdir=”./tmp/summary/” 注意等于后面没有空格 来源: https://www.cnblogs.com/jumpkin1122/p/11521025.html