我正在与Pytorch进行CNN任务,但它不会学习并不能提高准确性。我与MNIST一起制作了一个版本,因此可以在此处发布。我只是在寻找为什么它不起作用的答案。该体系结构很好,我在Keras中实现了它,经过3个星期,我的准确率超过了92%。注意:我将MNIST重塑为60x60图片,因为这是我的“真实”问题中的图片。
import numpy as np
from PIL import Image
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.utils.data import DataLoader
from torch.autograd import Variable
from keras.datasets import mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
def resize(pics):
pictures = []
for image in pics:
image = Image.fromarray(image).resize((dim, dim))
image = np.array(image)
pictures.append(image)
return np.array(pictures)
dim = 60
x_train, x_test = resize(x_train), resize(x_test) # because my real problem is in 60x60
x_train = x_train.reshape(-1, 1, …
Run Code Online (Sandbox Code Playgroud) 我有一堆从 pdf 中提取的质量较差的照片。我认识的某个人在她的电脑 (Mac) 上某处有高质量的照片,但我的理解是很难找到它们。
我想要
示例伪代码
for each image in poorQualityImages:
search ./macComputer for a higherQualityImage of image
copy higherQualityImage to ./higherQualityImages
Run Code Online (Sandbox Code Playgroud)
我需要执行一次此操作。我正在寻找一种工具、github 存储库或库,它可以执行此功能,而不是对基于内容的图像检索的深入理解。
imgdupes是一个程序,它似乎几乎实现了这一点,但我不想删除重复项,我想将最高质量的副本复制到目标文件夹
更新
给我以前的图像处理教授发了电子邮件,他给我发了这个
在我的头顶上,没有什么开箱即用的。
这里没有保证的解决方案,但您可以缩小搜索空间。您需要一个小程序来输出两个图像之间的 MSE 或 SSIM 相似度索引,然后编写另一个程序或 shell 脚本来扫描硬盘驱动器并计算硬盘驱动器上的每个图像与每个查询图像之间的 MSE,然后检查具有最高 X 百分比相似度得分的图像。
类似的东西。仍然不能保证找到你想要的一切。如果低质量图像与高质量图像的像素尺寸不同,则必须进行一些图像缩放才能获得相似度指数。如果质量差的图像具有不同的纵横比,那就更糟了。
所以我认为这并不难,但也不是微不足道的。难度部分取决于低质量图像中损坏的性质。
更新
我正在尝试使用 nn.Transformer 类训练 Transformer Seq2Seq 模型。我相信我的实现是错误的,因为当我训练它时,它似乎适应得太快了,并且在推理过程中它经常重复。这似乎是解码器中的掩码问题,当我移除目标掩码时,训练性能是相同的。这让我相信我做的目标屏蔽是错误的。这是我的模型代码:
class TransformerModel(nn.Module):
def __init__(self,
vocab_size, input_dim, heads, feedforward_dim, encoder_layers, decoder_layers,
sos_token, eos_token, pad_token, max_len=200, dropout=0.5,
device=(torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu"))):
super(TransformerModel, self).__init__()
self.target_mask = None
self.embedding = nn.Embedding(vocab_size, input_dim, padding_idx=pad_token)
self.pos_embedding = nn.Embedding(max_len, input_dim, padding_idx=pad_token)
self.transformer = nn.Transformer(
d_model=input_dim, nhead=heads, num_encoder_layers=encoder_layers,
num_decoder_layers=decoder_layers, dim_feedforward=feedforward_dim,
dropout=dropout)
self.out = nn.Sequential(
nn.Linear(input_dim, feedforward_dim),
nn.ReLU(),
nn.Linear(feedforward_dim, vocab_size))
self.device = device
self.max_len = max_len
self.sos_token = sos_token
self.eos_token = eos_token
# Initialize all weights to be uniformly distributed between -initrange …
Run Code Online (Sandbox Code Playgroud) 我正在尝试使用 pyinstaller 将脚本转换为 exe 脚本使用的是 tim esler 在此处找到的来自 facenet_pytorch 的 inception resnet v1 模型
运行转换后的脚本 exe 后出现以下错误:
回溯(最近一次调用最后一次):
文件“site-packages\torch_utils_internal.py”,第 46 行,在 get_source_lines_and_file 中
getsourcelines 中的文件“inspect.py”,第 955 行
findsource 中的文件“inspect.py”,第 786 行
OSError:无法获取源代码
在处理上述异常的过程中,又发生了一个异常:
回溯(最近一次调用最后一次):
文件“Fcenet-Pytorch\Test Rec2.py”,第 1 行,在
文件“”,第 983 行,在 _find_and_load 中
文件“”,第 967 行,在 _find_and_load_unlocked
文件“”,第 677 行,在 _load_unlocked 中
文件“c:\users\jorda\appdata\local\programs\python\python37\lib\site-packages\PyInstaller\loader\pyimod03_importers.py”,第 623 行,在 exec_module exec(bytecode, module. dict )
文件“site-packages\facenet_pytorch__init__.py”,第 1 行,在
Run Code Online (Sandbox Code Playgroud)# -*- coding: utf-8 -*-
文件“”,第 983 行,在 _find_and_load 中
文件“”,第 967 行,在 …
我正在尝试部署使用机器学习模型的 Django 应用程序。而机器学习模型需要pytorch来执行。当我尝试部署时,它给了我这个错误
ERROR: Could not find a version that satisfies the requirement torch==1.5.0+cpu (from -r /tmp/build_4518392d43f43bc52f067241a9661c92/requirements.txt (line 23)) (from versions: 0.1.2, 0.1.2.post1, 0.1.2.post2, 0.4.1, 0.4.1.post2, 1.0.0, 1.0.1, 1.0.1.post2, 1.1.0, 1.2.0, 1.3.0, 1.3.1, 1.4.0, 1.5.0)
ERROR: No matching distribution found for torch==1.5.0+cpu (from -r /tmp/build_4518392d43f43bc52f067241a9661c92/requirements.txt (line 23))
! Push rejected, failed to compile Python app.
! Push failed
Run Code Online (Sandbox Code Playgroud)
我的requirements.txt是
asgiref==3.2.7
certifi==2020.4.5.1
chardet==3.0.4
cycler==0.10.0
dj-database-url==0.5.0
Django==3.0.6
django-heroku==0.3.1
future==0.18.2
gunicorn==20.0.4
idna==2.9
imageio==2.8.0
kiwisolver==1.2.0
matplotlib==3.2.1
numpy==1.18.4
Pillow==7.1.2
psycopg2==2.8.5
pyparsing==2.4.7
python-dateutil==2.8.1
pytz==2020.1
requests==2.23.0
six==1.14.0 …
Run Code Online (Sandbox Code Playgroud) 我pytorch-1.5
用来做一些gan
测试。我的代码是非常简单的 gan 代码,只适合 sin(x) 函数:
import torch
import torch.nn as nn
import numpy as np
import matplotlib.pyplot as plt
# Hyper Parameters
BATCH_SIZE = 64
LR_G = 0.0001
LR_D = 0.0001
N_IDEAS = 5
ART_COMPONENTS = 15
PAINT_POINTS = np.vstack([np.linspace(-1, 1, ART_COMPONENTS) for _ in range(BATCH_SIZE)])
def artist_works(): # painting from the famous artist (real target)
r = 0.02 * np.random.randn(1, ART_COMPONENTS)
paintings = np.sin(PAINT_POINTS * np.pi) + r
paintings = torch.from_numpy(paintings).float()
return paintings
G = …
Run Code Online (Sandbox Code Playgroud) python computer-vision deep-learning pytorch generative-adversarial-network
我使用这个数据库建模
http://archive.ics.uci.edu/ml/datasets/Car+Evaluation
预处理后
X_train = df.drop('class', axis=1).to_numpy()
y_train = df['class'].to_numpy()
X_train, X_test, y_train, y_test = train_test_split(X_train, y_train, test_size=0.2)
Run Code Online (Sandbox Code Playgroud)
班级
class network(nn.Module):
def __init__(self, input_size, hidden1_size, hidden2_size, num_classes):
super(network, self).__init__()
self.fc1 = nn.Linear(input_size, hidden1_size)
self.relu1 = nn.ReLU()
self.fc2 = nn.Linear(hidden1_size, hidden2_size)
self.relu2 = nn.ReLU()
self.fc3 = nn.Linear(hidden2_size, num_classes)
def forward(self, x):
out = self.fc1(x)
out = self.relu1(out)
out = self.fc2(out)
out = self.relu2(out)
out = self.fc3(out)
return out
net = network(input_size=6, hidden1_size=5, hidden2_size=4, num_classes=4)
optimizer = torch.optim.SGD(net.parameters(), lr=0.2)
loss_func = torch.nn.MSELoss() …
Run Code Online (Sandbox Code Playgroud) 例如,如果我想解决 MNIST 分类问题,我们有 10 个输出类。对于 PyTorch,我想使用该torch.nn.CrossEntropyLoss
功能。我是否必须格式化目标以便它们是单热编码的,还是我可以简单地使用数据集附带的类标签?
python computer-vision multilabel-classification deep-learning pytorch
我想用 a 的validation_epoch_end
方法创建一个新的张量LightningModule
。从官方文档(第 48 页)中可以看出,我们应该避免直接.cuda()
或.to(device)
调用:
没有 .cuda() 或 .to() 调用。. . 闪电为你做这些。
我们鼓励使用type_as
方法转移到正确的设备。
new_x = new_x.type_as(x.type())
但是,在一个步骤中,validation_epoch_end
我没有任何张量可以type_as
以干净的方式从(通过方法)复制设备。
我的问题是,如果我想在这种方法中创建一个新的张量并将其传输到模型所在的设备,我该怎么办?
我唯一能想到的就是在outputs
字典中找到一个张量,但感觉有点乱:
avg_loss = torch.stack([x['val_loss'] for x in outputs]).mean()
output = self(self.__test_input.type_as(avg_loss))
Run Code Online (Sandbox Code Playgroud)
有没有干净的方法来实现这一目标?
我正在尝试使用 Trainer 训练模型,根据文档(https://huggingface.co/transformers/master/main_classes/trainer.html#transformers.Trainer)我可以指定一个标记器:
tokenizer (PreTrainedTokenizerBase, optional) – 用于预处理数据的 tokenizer。如果提供,将用于在批处理输入时自动填充输入的最大长度,并将沿模型保存,以便更轻松地重新运行中断的训练或重用微调的模型。
因此应该自动处理填充,但是在尝试运行它时出现此错误:
ValueError:无法创建张量,您可能应该使用 'padding=True' 'truncation=True' 激活截断和/或填充以具有相同长度的批处理张量。
分词器是这样创建的:
tokenizer = BertTokenizerFast.from_pretrained(pretrained_model)
Run Code Online (Sandbox Code Playgroud)
和这样的训练师:
trainer = Trainer(
tokenizer=tokenizer,
model=model,
args=training_args,
train_dataset=train,
eval_dataset=dev,
compute_metrics=compute_metrics
)
Run Code Online (Sandbox Code Playgroud)
我试过将padding
和truncation
参数放在分词器、训练器和training_args 中。什么都不做。任何的想法?
pytorch ×10
python ×8
torch ×2
cbir ×1
django ×1
generative-adversarial-network ×1
heroku ×1
keras ×1
numpy ×1
pyinstaller ×1
tensorflow ×1
torchvision ×1