我是张量流新手,我想使用多个 if-else 条件创建一个张量。我只是不知道该怎么做。
在 python 中,如果张量类似于[3,3,3],我可以使用for循环,如下所示:
for i in range(3):
for j in range(3):
for k in range(3):
if tensor[i,j,k]>10:
tensor[i,j,k]=tensor[i,j,k]-10
elif tensor[i,j,k]<4:
tensor[i,j,k]=tensor[i,j,k]+60
Run Code Online (Sandbox Code Playgroud)
之后我仍然想使用张量计算loos函数,然后进入下一个循环进行训练。有谁知道如何做到这一点?我知道如何在会话中以单一方式执行此操作。但我不知道如何在训练循环中做到这一点。
for-loop vectorization multidimensional-array tensorflow tensor
如何在 Pytorch 中将字符串列表转换为字符串/字符张量?
numpy 的相关示例:
import numpy as np
mylist = ["this","is","my","list"]
np.array([mylist])
Run Code Online (Sandbox Code Playgroud)
返回:
array([['this', 'is', 'my', 'list']], dtype='<U4')
Run Code Online (Sandbox Code Playgroud)
然而,在pytorch中:
torch.tensor(mylist)
Run Code Online (Sandbox Code Playgroud)
返回:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-156-36722d81da09> in <module>
----> 1 torch.tensor(mylist)
ValueError: too many dimensions 'str'
Run Code Online (Sandbox Code Playgroud)
张量是一个多维数组,所以我假设这在 pytorch 中是可能的。
注意:这篇文章没有回答我的问题
对于PyTorch.randn()方法,文档说:
返回一个张量,该张量填充有来自具有均值
0和方差的正态分布1(也称为标准正态分布)的随机数。
这是一个张量示例:
x = torch.randn(4,3)
tensor([[-0.6569, -0.7337, -0.0028],
[-0.3938, 0.3223, 0.0497],
[ 0.0129, -2.7546, -2.2488],
[ 1.6754, -0.1497, 1.8202]])
Run Code Online (Sandbox Code Playgroud)
当我打印平均值时:
x.mean()
tensor(-0.2550)
Run Code Online (Sandbox Code Playgroud)
当我打印标准差时:
x.std()
tensor(1.3225)
Run Code Online (Sandbox Code Playgroud)
那么为什么均值不为 0,标准差不为 1呢?
额外问题:如何生成均值为 0 的随机张量?
我有一个大小为:的张量torch.Size([64, 2941]),它是 64 个批次,共 2941 个元素。
在所有 64 个批次中,我想计算张量第二维中 1 和 0 的总数,一直到第 2941 个,以便我将这些计数作为大小的张量torch.Size([2941])
我怎么做?
当尝试将旧 PyTorch 编写的代码转换为 1.9 时,我收到此错误:
(fashcomp) [jalal@goku fashion-compatibility]$ python main.py --name test_baseline --learned --l2_embed --datadir ../../../data/fashion/
/scratch3/venv/fashcomp/lib/python3.8/site-packages/torchvision/transforms/transforms.py:310: UserWarning: The use of the transforms.Scale transform is deprecated, please use transforms.Resize instead.
warnings.warn("The use of the transforms.Scale transform is deprecated, " +
+ Number of params: 3191808
<class 'torch.utils.data.dataloader.DataLoader'>
/scratch3/venv/fashcomp/lib/python3.8/site-packages/torch/nn/functional.py:718: UserWarning: Named tensors and all their associated APIs are an experimental feature and subject to change. Please do not use them for anything important until they are released as stable. (Triggered internally …Run Code Online (Sandbox Code Playgroud) 是否可以在 PyTorch 中按行对两个 2D 张量进行打乱,但保持两者的顺序相同?我知道您可以使用以下代码按行对 2D 张量进行洗牌:
a=a[torch.randperm(a.size()[0])]
Run Code Online (Sandbox Code Playgroud)
详细说明:如果我有 2 个张量
a = torch.tensor([[1, 1, 1, 1, 1],
[2, 2, 2, 2, 2],
[3, 3, 3, 3, 3]])
b = torch.tensor([[4, 4, 4, 4, 4],
[5, 5, 5, 5, 5],
[6, 6, 6, 6, 6]])
Run Code Online (Sandbox Code Playgroud)
并通过一些函数/代码块运行它们以随机洗牌但保持相关性并产生如下所示的内容
a = torch.tensor([[2, 2, 2, 2, 2],
[1, 1, 1, 1, 1],
[3, 3, 3, 3, 3]])
b = torch.tensor([[5, 5, 5, 5, 5],
[4, 4, 4, 4, 4],
[6, 6, 6, 6, 6]]) …Run Code Online (Sandbox Code Playgroud) 我想在这里运行CIFAR10图像分类PyTorch教程- http://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html#sphx-glr-beginner-blitz-cifar10-tutorial-py
我做了一个小的更改,并且我使用了另一个数据集。我有Wikiart数据集中要按艺术家分类的图像(标签=艺术家名称)。
这是网络的代码-
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
Run Code Online (Sandbox Code Playgroud)
然后在代码的这一部分中,我开始训练网络。
for epoch in range(2):
running_loss = 0.0
for i, data in enumerate(wiki_train_dataloader, 0):
inputs, labels = data['image'], data['class']
print(inputs.shape) …Run Code Online (Sandbox Code Playgroud) 我尝试将卷积层应用于形状[256,256,3]的图片 a当我直接使用图像的张量时出错
conv1 = conv2d(input,W_conv1) +b_conv1 #<=== error
Run Code Online (Sandbox Code Playgroud)
错误信息:
ValueError: Shape must be rank 4 but is rank 3 for 'Conv2D' (op: 'Conv2D')
with input shapes: [256,256,3], [3,3,3,1].
Run Code Online (Sandbox Code Playgroud)
但是当我重塑函数时,conv2d正常工作
x_image = tf.reshape(input,[-1,256,256,3])
conv1 = conv2d(x_image,W_conv1) +b_conv1
Run Code Online (Sandbox Code Playgroud)
如果我必须重塑张量,在我的情况下重塑的最佳价值是什么?为什么?
import tensorflow as tf
import numpy as np
from PIL import Image
def img_to_tensor(img) :
return tf.convert_to_tensor(img, np.float32)
def weight_generater(shape):
return tf.Variable(tf.truncated_normal(shape,stddev=0.1))
def bias_generater(shape):
return tf.Variable(tf.constant(.1,shape=shape))
def conv2d(x,W):
return tf.nn.conv2d(x,W,[1,1,1,1],'SAME')
def pool_max_2x2(x):
return tf.nn.max_pool(x,ksize=[1,2,2,1],strides=[1,1,1,1],padding='SAME')
#read image
img = Image.open("img.tif")
sess …Run Code Online (Sandbox Code Playgroud) 所以,我的代码就像
parsed_line = tf.decode_csv(line, [[0], [0], [""]])
print(parsed_line[0])
del parsed_line[0]
del parsed_line[0]
features = parsed_line
print(parsed_line[0])
Run Code Online (Sandbox Code Playgroud)
那么结果是
[<tf.Tensor 'DecodeCSV:0' shape=() dtype=int32>, <tf.Tensor 'DecodeCSV:1' shape=() dtype=int32>, <tf.Tensor 'DecodeCSV:2' shape=() dtype=string>]
Run Code Online (Sandbox Code Playgroud)
和
[<Tensor("DecodeCSV:2", shape=(), dtype=string)>]
Run Code Online (Sandbox Code Playgroud)
我会给这个解码函数的 csv 是
1, 0, 0101010010101010101010
Run Code Online (Sandbox Code Playgroud)
我想要这个“0101010010101010101010”
[0,1,0,1,0,.........]
Run Code Online (Sandbox Code Playgroud)
在张量流中
[<Tensor("DecodeCSV:2", shape=(), dtype=string)>]
Run Code Online (Sandbox Code Playgroud)
到
[<tf.Tensor 'DecodeCSV:0' shape=() dtype=int32>, <tf.Tensor 'DecodeCSV:1' shape=() dtype=int32>, ............]
Run Code Online (Sandbox Code Playgroud)
你有什么想法吗?
我最近一直在研究我的大学项目的机器学习模型,它接受用户的健康因素并将其提供给CNN,CNN告诉用户未来几年他们患有糖尿病.我已经写了一个keras模型并将其保存为hdf5格式.我已经检查过它在本地运行,保存的模型做了很好的预测.我想通过Web应用程序运行这个模型,因此我在过去的几天里一直在研究瓶子.我已经为flask app.py和index.html编写了代码
app.py
from flask import Flask, render_template, request
from flask import request
import numpy as np
from keras.models import load_model
from sklearn.preprocessing import MinMaxScaler
from flask import jsonify
import os
import re
import sys
# init model directory
MODEL_DIR = './models'
result=''
#init Flask
app = Flask(__name__)
#load the compiled model.
print("Loading model")
model = load_model(os.path.join(MODEL_DIR, 'classifier_model.hdf5'))
scaler= MinMaxScaler(feature_range=(0,1))
#routing for home page
@app.route('/', methods=['GET','POST'])
def index():
if request.method == 'GET':
return render_template('index.html')
if request.method == 'POST':
weight=float(request.form['weight'])
height=float(request.form['height']) …Run Code Online (Sandbox Code Playgroud)