我正在训练带有两个输出的CovNet。我的训练样本如下所示:
[0, value_a1], [0, value_a2], ...
Run Code Online (Sandbox Code Playgroud)
和
[value_b1, 0], [value_b2, 0], ....
Run Code Online (Sandbox Code Playgroud)
我想生成自己的损失函数和包含的掩码对mask_value = 0。我具有此功能,尽管不确定是否确实可以实现我想要的功能。所以,我想写一些测试。
from tensorflow.python.keras import backend as K
from tensorflow.python.keras import losses
def masked_loss_function(y_true, y_pred, mask_value=0):
'''
This model has two target values which are independent of each other.
We mask the output so that only the value that is used for training
contributes to the loss.
mask_value : is the value that is not used for training
'''
mask = K.cast(K.not_equal(y_true, mask_value), K.floatx())
return …Run Code Online (Sandbox Code Playgroud) 假设您有Keras NN模型,如何在特定层之后的反向传播中停止梯度?
即,如果我们有一个带有两个输出的模型:
input_layer = Input(shape=(10,10,3))
x = Convolution2D(...)(input_layer)
x = Activation('relu')(x)
x = Flatten()(x)
x_1 = Dense(64)(x)
x_1 = Dense(32)(x_1)
x_1 = Dense(2)(x_1)
x_2 = Dense(64)(x)
x_2 = Dense(32)(x_2)
x_2 = Dense(2)(x_2)
model = Model(inputs=input_layer, outputs=[x_1, x_2])
Run Code Online (Sandbox Code Playgroud)
如何x_1在x_1 = Dense(64)(x)层之后停止输出的梯度,以免在卷积层的权重更新中不计入它?
根据在keras的特定层中停止渐变反向道具的答案,我会在x_1致密层之前添加一个lambda 层,但我不确定:
x_1 = Dense(64)(x)
x_1_stop_grad = Lambda(lambda x: K.stop_gradient(x))(x_1)
x_1 = Dense(32)(x_1)
x_1 = Dense(2)(x_1)
Run Code Online (Sandbox Code Playgroud)
我是否必须在第一个致密层之前或之后添加lambda x_1层?
当使用类似的东西时:
callbacks = [
EarlyStopping(patience=15, monitor='val_loss', min_delta=0, mode='min'),
ModelCheckpoint('best-weights.h5', monitor='val_loss', save_best_only=True, save_weights_only=True)
]
model.fit(..., callbacks=callbacks)
y_pred = model.predict(x_test)
Run Code Online (Sandbox Code Playgroud)
我model是使用训练过程中计算出的最佳权重进行预测还是使用最后的权重(可能不是最佳权重)?
因此,以上是安全的方法,还是best-weights.h5即使在训练后立即进行预测,也应该将其加载到模型中吗?
这是我的测试代码:
from keras import layers
input1 = layers.Input((2,3))
output = layers.Dense(4)(input1)
print(output)
Run Code Online (Sandbox Code Playgroud)
输出是:
<tf.Tensor 'dense_2/add:0' shape=(?, 2, 4) dtype=float32>
Run Code Online (Sandbox Code Playgroud)
但是什么是重要的?
文件说:
注意:如果图层的输入的排名大于2,则在使用内核的初始点积之前将其展平.
输出重塑了吗?
我正在建立一个具有多个顺序模型的模型,在训练数据集之前我需要将这些模型合并。keras.engine.topology.MergeKeras 2.0 似乎不再支持它。我尝试了keras.layers.Add,keras.layers.Concatenate但效果不佳。
这是我的代码:
model = Sequential()
model1 = Sequential()
model1.add(Embedding(len(word_index) + 1, 300, weights = [embedding_matrix], input_length = 40, trainable = False))
model1.add(TimeDistributed(Dense(300, activation = 'relu')))
model1.add(Lambda(lambda x: K.sum(x, axis = 1), output_shape = (300, )))
model2 = Sequential()
###Same as model1###
model3 = Sequential()
model3.add(Embedding(len(word_index) + 1, 300, weights = [embedding_matrix], input_length = 40, trainable = False))
model3.add(Convolution1D(nb_filter = nb_filter, filter_length = filter_length, border_mode = 'valid', activation = 'relu', subsample_length = 1)) …Run Code Online (Sandbox Code Playgroud) 我有一个自动编码器,我需要在输出后添加一个高斯噪声层。我需要一个自定义层来执行此操作,但我真的不知道如何生成它,我需要使用张量生成它。

如果我想在下面代码的调用部分实现上面的等式,我该怎么做?
class SaltAndPepper(Layer):
def __init__(self, ratio, **kwargs):
super(SaltAndPepper, self).__init__(**kwargs)
self.supports_masking = True
self.ratio = ratio
# the definition of the call method of custom layer
def call(self, inputs, training=None):
def noised():
shp = K.shape(inputs)[1:]
**what should I put here????**
return out
return K.in_train_phase(noised(), inputs, training=training)
def get_config(self):
config = {'ratio': self.ratio}
base_config = super(SaltAndPepper, self).get_config()
return dict(list(base_config.items()) + list(config.items()))
Run Code Online (Sandbox Code Playgroud)
我也尝试使用 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) 我的输入数组是image_array,包含 10000 张大小为 512x512、4 个通道的图像的数据。IE image_array.shape = (10000, 512, 512, 4)。每张图像都有一个相关的指标,我想训练 CNN 来为我进行预测。因此metric_array.shape = (10000)。由于我不希望网络偏向更频繁出现的指标值,因此我有一个加权数组,其中包含指标的每个值的权重。因此weightArray.shape = (10000)。
我正在使用 Keras。这是我的顺序模型:
model = Sequential()
model.add(Conv2D(32, use_bias=True, kernel_size=(3,3), strides=(1, 1), activation='relu', input_shape=(512,512,4))
model.add(BatchNormalization())
model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))
model.add(Conv2D(64, use_bias=True, kernel_size=(3,3), strides=(1, 1), activation='relu'))
model.add(BatchNormalization())
model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2)))
model.add(Conv2D(128, use_bias=True, kernel_size=(3,3), strides=(1, 1), activation='relu'))
model.add(BatchNormalization())
model.add(Flatten())
model.add(Dense(32))
model.add(Activation('relu'))
model.add(BatchNormalization())
model.add(Dense(1, activation=relu_max))
Run Code Online (Sandbox Code Playgroud)
我想使用均方误差损失函数和随机梯度下降优化器。我编译我的模型:
model.compile(loss='mean_squared_error', optimizer=optimizers.SGD(lr=0.01))
Run Code Online (Sandbox Code Playgroud)
我将数据集分为训练和验证:
X_train, X_validate, Y_train, Y_validate, W_train, W_validate \
= train_test_split(image_array, metric_array, weightArray, …Run Code Online (Sandbox Code Playgroud) python deep-learning conv-neural-network keras loss-function
我想可视化我的神经网络。因此,我from tensorflow.keras.utils import plot_model像这样使用和使用它:
model = Sequential()
model.add(Dense(8, activation="relu"))
model.add(Dense(1))
plot_model(model, to_file="model.png", show_shapes=True)
Run Code Online (Sandbox Code Playgroud)
但是,当我打开图形时,它看起来像这样:
我的代码有什么问题?我没有看到任何错误。
x是(64, 1)使用 随机创建的维度向量tf.random.uniform((BATCH_SIZE, 1)),其中BATCH_SIZE = 64.
随机初始化如下所示:
tf.Tensor(
[[0.76922464]
[0.7928164 ]
[0.91224647]
[0.41210544]
[0.33040464]
[0.20977008]
[0.96211743]
[0.59516513]
[0.67317 ]
[0.7600033 ]
[0.93105805]
[0.55348516]
[0.50683343]
[0.7563635 ]
[0.06255531]
[0.93398154]
[0.5622641 ]
[0.9913852 ]
[0.3019762 ]
[0.519048 ]
[0.57998526]
[0.21162748]
[0.9783536 ]
[0.38307965]
[0.6527189 ]
[0.8094288 ]
[0.97980523]
[0.5955998 ]
[0.7002481 ]
[0.6879872 ]
[0.50365186]
[0.57166266]
[0.97805905]
[0.458856 ]
[0.3485204 ]
[0.29394794]
[0.19313121]
[0.29782188]
[0.45194447]
[0.49442303]
[0.04192603]
[0.26818407]
[0.822567 ]
[0.8573874 ]
[0.15510845]
[0.76052403]
[0.4066763 …Run Code Online (Sandbox Code Playgroud) keras ×10
python ×8
keras-layer ×5
tensorflow ×5
gaussianblur ×1
keras-2 ×1
plot ×1
testing ×1
tf.keras ×1