标签: keras-2

在喀拉拉邦进行对抗训练

我想用一个分类器实现一个对抗网络,该分类器的输出连接到一个对手,该对手必须根据分类器的输出(该分类器的详细说明)来猜测分类器输入的具体特征(讨厌的参数)。对抗网络可以在本文中找到:学习如何对抗网络

然后将对模型进行如下训练:

  1. 批量训练对手(分类器将被固定)
  2. 冻结对手
  3. 在对手冻结的情况下训练整个模型
  4. 解冻对手
  5. 对其他批次重复
  6. 随机播放并重复其他时期

在训练对手时,我希望损失函数是分类交叉熵,而在训练整个模型时,我希望它是分类器的损失函数(二进制交叉熵损失)减去对手的损失乘以参数:L_c() - b * L_a()

我见过的大多数对抗性训练代码都是使用train_on_batch在Keras中训练的。但是,由于我已经使用另一个顺序模型进行了大量代码设置,并且想重用它,因此我想知道是否存在一种实现此模型并在Keras中使用model.fit对其进行训练的方法。

我当时想做的是使用Keras功能API设置模型,其中将分类器输入作为输入,将分类器和对手输出作为输出。我还将模型编译为仅具有单个输出的对手模型。例如:

classifier_input = Input(shape=(10,))
x = Dense(50, activation='tanh')(classifier_input)
x = Dense(25, activation='tanh')(x)
x = Dense(5, activation='tanh')(x)
classifier_output = Dense(1, activation='sigmoid')(x)

x = Dense(30, activation='tanh')(classifier_output)
x = Dense(15, activation='tanh')(x)
x = Dense(5, activation='tanh')(x)
adversary_output = Dense(3, activation='sgimoid')(x)

adversary = Model(inputs=classifier_input , outputs=adversary_output)
adversary.compile(optimizer='Adamax', loss='categorical_crossentropy', metrics=['accuracy'])

final_model = Model(inputs=classifier_input,outputs=[classifier_output,adversary_output])
final_model.compile(optimizer='Adamax', 
              loss=['binary_crossentropy', 'categorical_crossentropy'], 
              loss_weights=[1.0, -0.1], metrics=['accuracy'])
Run Code Online (Sandbox Code Playgroud)

然后我想在on_batch_begin中设置一个回调来训练对手(冻结分类器中的层之后),然后使用model.fit代码完成final_model的训练(我将冻结对手并解冻分类器层。 on_batch_begin即将在final_model的训练开始之前)。

但是然后我不知道是否有可能将当前批处理作为参数传递给on_batch_begin。我必须在Callback中设置自己的批次,还是可以通过model.fit传递批次?

在仍然使用model.fit的同时,有没有更好的方式进行对抗训练?

python neural-network deep-learning keras keras-2

6
推荐指数
0
解决办法
940
查看次数

Keras ModelCheckpoint 监控多个值

我想使用 Keras ModelCheckpoint 回调来监视多个参数(我有一个多任务网络)。只需要一个回调就可以吗?或者我需要在许多回调中这样做吗?

ckechpoint的创建:

checkpointer = ModelCheckpoint(filepath='checkpoints/weights-{epoch:02d}.hdf5', monitor='val_O1_categorical_accuracy' , verbose=1, save_best_only=True, mode='max')
Run Code Online (Sandbox Code Playgroud)

我要监控的第二个参数:val_O2_categorical_accuracy

在列表中这样做是行不通的。IE

checkpointer = ModelCheckpoint(filepath='checkpoints/weights-{epoch:02d}.hdf5', monitor=['val_O1_categorical_accuracy','val_O2_categorical_accuracy'] , verbose=1, save_best_only=True, mode='max')
Run Code Online (Sandbox Code Playgroud)

类型错误:不可散列的类型:“列表”

python conv-neural-network keras tensorflow keras-2

6
推荐指数
1
解决办法
7485
查看次数

3D 张量上的 Keras 点/点层行为

点/点层Keras 文档指出:

“计算两个张量样本之间的点积的层。

例如,如果应用于形状为 (batch_size, n) 的两个张量 a 和 b 的列表,则输出将是形状为 (batch_size, 1) 的张量,其中每个条目 i 将是 a[i] 和 b[ 之间的点积一世]。

参数

轴:整数或整数元组,轴或轴,沿其取点积。”

我没有得到这个,这是一个快速、可重复的示例来演示:

from keras.layers import Input, dot
input_a = Input(batch_shape=(99,45000,300))
input_b = Input(batch_shape=(99,45000,300))
element_wise_dot_product = dot([input_a,input_b], axes = -1)
print(input_a.get_shape(),input_b.get_shape(),element_wise_dot_product.get_shape()) 
Run Code Online (Sandbox Code Playgroud)

输出:(99, 45000, 300) (99, 45000, 300) (99, 45000, 45000)

为什么元素智能点积形状不是 (99,45000,1) ?我做错了什么,我该如何解决?

python python-3.x keras keras-layer keras-2

6
推荐指数
1
解决办法
3202
查看次数

在keras中将输入与常量向量连接起来

我试图将我的输入与 keras-2 函数 API 中的常量张量连接起来。在我的实际问题中,常量取决于设置中的某些参数,但我认为下面的示例显示了我得到的错误。

from keras.layers import*
from keras.models import *
from keras import backend as K
import numpy as np

a = Input(shape=(10, 5))
a1 = Input(tensor=K.variable(np.ones((10, 5))))
x = [a, a1]  # x = [a, a] works fine
b = concatenate(x, 1)
x += [b]  # This changes b._keras_history[0].input
b = concatenate(x, 1)
model = Model(a, b)
Run Code Online (Sandbox Code Playgroud)

我得到的错误是:

ValueError                                Traceback (most recent call last)
~/miniconda3/envs/ds_tools/lib/python3.6/site-packages/keras/engine/topology.py in assert_input_compatibility(self, inputs)
    418             try:
--> 419                 K.is_keras_tensor(x)
    420             except ValueError:

~/miniconda3/envs/ds_tools/lib/python3.6/site-packages/keras/backend/theano_backend.py …
Run Code Online (Sandbox Code Playgroud)

python keras keras-2

5
推荐指数
1
解决办法
4096
查看次数

在 Keras 中使用 Masking-layer 和 ConvLSTM2D-layer

我正在尝试使用 Keras (2.0.6) 和 TensorFlow 后端 (1.2.1) 来掩盖卷积 LSTM 层中的缺失数据:

import keras
from keras.models import Sequential
from keras.layers import Masking, ConvLSTM2D

n_timesteps = 10
n_width = 64
n_height = 64
n_channels = 1

model = Sequential()
model.add(Masking(mask_value = 0., input_shape = (n_timesteps, n_width, n_height, n_channels)))
model.add(ConvLSTM2D(filters = 64, kernel_size = (3, 3)))
Run Code Online (Sandbox Code Playgroud)

但是我收到以下 ValueError:

ValueError: Shape must be rank 4 but is rank 2 for 'conv_lst_m2d_1/while/Tile' (op: 'Tile') with input shapes: [?,64,64,1], [2].
Run Code Online (Sandbox Code Playgroud)

如何将 Masking 与 ConvLSTM2D 层一起使用?

keras tensorflow keras-2

5
推荐指数
1
解决办法
1432
查看次数

如何在 Keras 2.0 中使用 InceptionV3 瓶颈作为输入

我想在 Keras 中使用 InceptionV3 使用瓶颈进行迁移学习。我使用了来自https://blog.keras.io/building-powerful-image-classification-models-using-very-little-data.html 的一些创建、加载和使用瓶颈的技巧

我的问题是我不知道如何使用瓶颈(numpy 数组)作为具有新顶层的 InceptionV3 的输入。

我收到以下错误:

ValueError:检查输入时出错:预期 input_3 具有形状(无、无、无、3)但得到的数组具有形状(248、8、8、2048)

在这种情况下,248 指的是图像总数。

我知道这一行是错误的,但我不知道如何更正:

模型=模型(输入=base_model.input,输出=预测)

将瓶颈输入 InceptionV3 的正确方法是什么?

创建 InceptionV3 瓶颈:

def create_bottlenecks():
datagen = ImageDataGenerator(rescale=1. / 255)

model = InceptionV3(include_top=False, weights='imagenet')

# Generate bottlenecks for all training images
generator = datagen.flow_from_directory(
    train_data_dir,
    target_size=(img_width, img_height),
    batch_size=batch_size,
    class_mode=None,
    shuffle=False)

nb_train_samples = len(generator.filenames)
bottlenecks_train = model.predict_generator(generator, int(math.ceil(nb_train_samples / float(batch_size))), verbose=1)
np.save(open(train_bottlenecks_file, 'w'), bottlenecks_train)

# Generate bottlenecks for all validation images
generator = datagen.flow_from_directory(
    validation_data_dir,
    target_size=(img_width, img_height),
    batch_size=batch_size, …
Run Code Online (Sandbox Code Playgroud)

python deep-learning keras keras-2

5
推荐指数
1
解决办法
1095
查看次数

Keras以外的Keras初始化者

我想使用以下代码在Keras中使用glorot uniform初始化一个4*11矩阵:

import keras
keras.initializers.glorot_uniform((4,11))
Run Code Online (Sandbox Code Playgroud)

我得到这个输出:

<keras.initializers.VarianceScaling at 0x7f9666fc48d0>
Run Code Online (Sandbox Code Playgroud)

如何可视化输出?我试过c [1]并得到输出'VarianceScaling' object does not support indexing.

keras keras-layer keras-2

5
推荐指数
1
解决办法
387
查看次数

在 keras 回调中监控 F1 分数(或一般的自定义指标)

Keras 2.0 删除了 F1 分数,但我想监控它的值。我正在使用顺序模型来训练神经网络。

我定义了一个函数,正如这里的建议如何在 Keras 中计算 F1 宏?.

只有在model.compile 中使用该函数才能正常工作。通过这种方式,我在每一步都看到了它的价值。问题是我不想只看到它的价值,但我希望我的训练根据它的价值表现不同,使用 Keras 的回调。

如果我尝试在回调中插入自定义指标,则会收到此错误:

'函数对象不可迭代'

你知道如何定义一个函数,以便它可以在回调中用作参数吗?

machine-learning neural-network python-3.x deep-learning keras-2

5
推荐指数
1
解决办法
1043
查看次数

Keras 2:在“合并”层中使用 lambda 函数

我正在尝试实现这个合并层:

policy = merge([out1, out2], mode = lambda x: x[0]-K.mean(x[0])+x[1], output_shape = (out_node,))
Run Code Online (Sandbox Code Playgroud)

但是,Keras 2 中不再存在“合并”。您只能访问公共标准化的“合并”层,例如 Add、Multiply、Dot。

如何在 Keras 2 中实现此功能?我想制作两个合并层,但我不知道如何实现,尤其是因为“K.mean”部分。

作为参考,这里是进口:

from keras.layers import merge
from keras import backend as K
Run Code Online (Sandbox Code Playgroud)

python keras keras-layer keras-2

5
推荐指数
1
解决办法
735
查看次数

CancelledError: [_Derived_]RecvAsync 被取消

我有问题。我使用 CPU 和 Tensorflow 1.14.0 在我的本地机器上运行相同的代码。它工作正常。但是,当我使用 Tensorflow 2.0 在 GPU 上运行它时,我得到

CancelledError:  [_Derived_]RecvAsync is cancelled.      [[{{node Adam/Adam/update/AssignSubVariableOp/_65}}]]   [[Reshape_13/_62]] [Op:__inference_distributed_function_3722]

Function call stack: distributed_function
Run Code Online (Sandbox Code Playgroud)

可重现的代码在这里:

import numpy as np
import pandas as pd
import tensorflow as tf
from tensorflow import keras
print(tf.__version__)

import matplotlib.pyplot as plt
%matplotlib inline

batch_size = 32
num_obs = 100
num_cats = 1 # number of categorical features
n_steps = 10 # number of timesteps in each sample
n_numerical_feats = 18 # number of numerical features in …
Run Code Online (Sandbox Code Playgroud)

tensorflow keras-2 tf.keras tensorflow2.0

5
推荐指数
1
解决办法
3726
查看次数