我正在使用一个 TFRecord 数据集,该数据集由 3D 对象横截面的多个灰度图像组成,最终形状为 [32, 256, 256]。32的尺寸代表横截面的数量,它明显小于其他尺寸。
因此,我想知道是否可以将数据视为具有 32 个通道的 2D 数据,而不是将数据视为具有 1 个通道的 3D 数据,尤其是在所需的计算资源方面有帮助。我现在正在 Google Colab 中使用 TensorFlow 和 TPU,并且使用 TensorFlow可以tf.layers.conv2d通过tf.layers.conv3d减少填充来节省大量内存。
这两种方法之间是否有任何显着差异,或者是否有我应该遵循的约定?使用会conv2d以任何方式损害我的准确性吗?
我正在研究 CNN 模型,我很好奇如何将 datagen.flow_from_directory() 给出的输出转换为凹凸数组。datagen.flow_from_directory() 的格式是目录迭代器。
除了 ImageDataGenerator 之外,还有其他方法可以从目录中获取数据。
img_width = 150
img_height = 150
datagen = ImageDataGenerator(rescale=1/255.0, validation_split=0.2)
train_data_gen = directory='/content/xray_dataset_covid19',
target_size = (img_width, img_height),
class_mode='binary',
batch_size=16,
subset='training')
vali_data_gen = datagen.flow_from_directory(directory='/content/xray_dataset_covid19',
target_size = (img_width, img_height),
class_mode='binary',
batch_size=16,
subset='validation')
Run Code Online (Sandbox Code Playgroud) 我们正在尝试在 pytorch 中使用 CNN 实现多标签分类。我们有 8 个标签和大约 260 张图像,使用 90/10 分割作为训练/验证集。
\n\n这些类别高度不平衡,最常见的类别出现在 140 多张图像中。另一方面,最不频繁的类别出现在少于 5 个图像中。
\n\n我们最初尝试了 BCEWithLogitsLoss 函数,该函数导致模型预测所有图像的相同标签。
\n\n然后,我们实施了焦点损失方法来处理类别不平衡,如下所示:
\n\n import\xc2\xa0torch.nn\xc2\xa0as\xc2\xa0nn\n import\xc2\xa0torch\n\n class\xc2\xa0FocalLoss(nn.Module):\n def\xc2\xa0__init__(self,\xc2\xa0alpha=1,\xc2\xa0gamma=2):\n super(FocalLoss,\xc2\xa0self).__init__()\n self.alpha\xc2\xa0=\xc2\xa0alpha\n self.gamma\xc2\xa0=\xc2\xa0gamma\n\n def\xc2\xa0forward(self,\xc2\xa0outputs,\xc2\xa0targets):\n bce_criterion\xc2\xa0=\xc2\xa0nn.BCEWithLogitsLoss()\n bce_loss\xc2\xa0=\xc2\xa0bce_criterion(outputs,\xc2\xa0targets)\n pt\xc2\xa0=\xc2\xa0torch.exp(-bce_loss)\n focal_loss\xc2\xa0=\xc2\xa0self.alpha\xc2\xa0*\xc2\xa0(1\xc2\xa0-\xc2\xa0pt)\xc2\xa0**\xc2\xa0self.gamma\xc2\xa0*\xc2\xa0bce_loss\n return\xc2\xa0focal_loss \nRun Code Online (Sandbox Code Playgroud)\n\n这导致模型为每个图像预测空集(无标签),因为它无法获得任何类别大于 0.5 的置信度。
\n\npytorch 有没有办法帮助解决这种情况?
\nmachine-learning multilabel-classification conv-neural-network pytorch
我用于tensorflow.keras在图像识别问题中训练 CNN,使用 Adam 最小化器来最小化自定义损失(一些代码位于问题的底部)。我正在试验我的训练集中需要使用多少数据,并认为我应该研究我的每个模型是否已正确收敛。然而,当绘制损失与不同训练集分数的训练时期数的关系时,我注意到损失函数中大约存在周期性尖峰,如下图所示。在这里,不同的线显示了不同的训练集大小作为我的总数据集的一部分。
当我减小训练集的大小(蓝色 -> 橙色 -> 绿色)时,这些尖峰的频率似乎减少,但幅度似乎增加。直觉上,我会将这种行为与跳出局部最小值的最小化器联系起来,但我对 TensorFlow/CNN 的经验还不够,不知道这是否是解释这种行为的正确方法。同样,我不太理解训练集大小的变化。
谁能帮助我理解这种行为?我应该关注这些功能吗?
from quasarnet.models import QuasarNET, custom_loss
from tensorflow.keras.optimizers import Adam
...
model = QuasarNET(
X[0,:,None].shape,
nlines=len(args.lines)+len(args.lines_bal)
)
loss = []
for i in args.lines:
loss.append(custom_loss)
for i in args.lines_bal:
loss.append(custom_loss)
adam = Adam(decay=0.)
model.compile(optimizer=adam, loss=loss, metrics=[])
box, sample_weight = io.objective(z,Y,bal,lines=args.lines,
lines_bal=args.lines_bal)
print( "starting fit")
history = model.fit(X[:,:,None], box,
epochs = args.epochs,
batch_size = 256,
sample_weight = sample_weight)
Run Code Online (Sandbox Code Playgroud) python machine-learning conv-neural-network keras tensorflow
我推测我在使用 PyTorch 框架训练 Conv 网络时遇到了 GPU 内存泄漏。下图
为了解决这个问题,我添加了 -
os.environ['CUDA_LAUNCH_BLOCKING'] = "1"
但由于我当时使用的是torch.nn.DataParallel,所以我希望我的代码能够利用所有 GPU,但现在它只利用GPU:1.
在使用之前os.environ['CUDA_LAUNCH_BLOCKING'] = "1",GPU 利用率低于(同样糟糕)-
经过进一步挖掘,我发现,当我们使用 时torch.nn.DataParallel,我们不应该使用CUDA_LAUNCH_BLOCKING',因为它会使网络陷入某种死锁机制。所以,现在我又回到了 GPU 内存问题,因为我认为我的代码没有利用它在没有设置的情况下显示的那么多内存CUDA_LAUNCH_BLOCKING=1。
我要使用的代码torch.nn.DataParallel-
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
if torch.cuda.device_count() > 1:
print("Let's use", torch.cuda.device_count(), "GPUs!")
# dim = 0 [30, xxx] -> [10, ...], [10, ...], [10, ...] on 3 GPUs
model_transfer = nn.DataParallel(model_transfer.cuda(),device_ids=range(torch.cuda.device_count()))
model_transfer.to(device)
Run Code Online (Sandbox Code Playgroud)
如何解决GPU内存问题?编辑:最少的代码 -
image_dataset = datasets.ImageFolder(train_dir_path,transform = …Run Code Online (Sandbox Code Playgroud) parallel-processing gpu deep-learning conv-neural-network pytorch
我正在创建一个网络网络,它将采用连续值矩阵以及一些表示为所有类向量的分类输入。
现在,我也在寻找通过卷积从矩阵中提取特征。但如果我将矩阵减少到 1 维并与类向量连接,这是不可能的。
有没有办法将其连接在一起作为单个输入?或者我是否必须创建两个单独的输入层,然后在卷积后以某种方式将它们连接起来?如果是后者,我要寻找什么功能?
这是与我的问题相关的完整代码。您应该能够运行此代码并查看创建的绘图 - 只需将其粘贴到 IDE 中并运行即可。
\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nnp.random.seed(1)\nx = np.random.randn(4, 3, 3, 2)\nx_pad = np.pad(x, ((0,0), (2, 2), (2, 2), (0,0))\\\n , mode=\'constant\', constant_values = (0,0))\nprint ("x.shape =\\n", x.shape)\nprint ("x_pad.shape =\\n", x_pad.shape)\nprint ("x[1,1] =\\n", x[1,1])\nprint ("x_pad[1,1] =\\n", x_pad[1,1])\nfig, axarr = plt.subplots(1, 2)\naxarr[0].set_title(\'x\')\naxarr[0].imshow(x[0,:,:,0])\naxarr[1].set_title(\'x_pad\')\naxarr[1].imshow(x_pad[0,:,:,0])\nRun Code Online (Sandbox Code Playgroud)\n\n具体来说,我的问题与这两行代码有关:
\n\nx = np.random.randn(4, 3, 3, 2)\nx_pad = np.pad(x, ((0,0), (2, 2), (2, 2), (0,0)), mode=\'constant\', constant_values = (0,0))\nRun Code Online (Sandbox Code Playgroud)\n\n我想在 中填充第二维和第三维x。所以,我想填充x[1]哪个值是3,x[2]哪个值也有3 …
如果我们查看 Keras 中的可用模型列表(如此处所示),我们会发现几乎所有模型都是用 实例化的weights='imagenet'。例如:
model = VGG16(weights='imagenet', include_top=False)
Run Code Online (Sandbox Code Playgroud)
为什么总是imagenet?是因为它是基线吗?如果没有,还有哪些其他选择?
谢谢
deep-learning conv-neural-network keras tensorflow pre-trained-model
我目前正在训练 CNN 来检测一个人是否戴口罩。不幸的是,我不明白为什么我的验证损失如此之高。正如我注意到的,我正在验证的数据是在类之后排序的(这是网络的输出)。这对我的验证准确性和损失有影响吗?我使用计算机视觉测试了该模型,效果非常好,但验证损失和准确性看起来仍然非常错误。其原因何在?
validation machine-learning deep-learning conv-neural-network tensorflow
我有一个像这样的训练数据集(主列表中的项目数为 211,每个数组中的数字数为 185):
[np.array([2, 3, 4, ... 5, 4, 6]) ... np.array([3, 4, 5, ... 3, 4, 5])]
Run Code Online (Sandbox Code Playgroud)
我使用此代码来训练模型:
def create_model():
model = keras.Sequential([
keras.layers.Flatten(input_shape=(211, 185), name="Input"),
keras.layers.Dense(211, activation='relu', name="Hidden_Layer_1"),
keras.layers.Dense(185, activation='relu', name="Hidden_Layer_2"),
keras.layers.Dense(1, activation='softmax', name="Output"),
])
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
return model
Run Code Online (Sandbox Code Playgroud)
但每当我这样安装时:
model.fit(x=training_data, y=training_labels, epochs=10, validation_data = [training_data,training_labels])
Run Code Online (Sandbox Code Playgroud)
它返回此错误:
ValueError: Layer sequential expects 1 inputs, but it received 211 input tensors.
Run Code Online (Sandbox Code Playgroud)
可能是什么问题?
tensorflow ×6
keras ×4
python ×3
pytorch ×3
numpy ×2
gpu ×1
padding ×1
python-3.x ×1
tpu ×1
validation ×1