小编tod*_*day的帖子

Keras中间层输出

我正在尝试使用Keras的功能API时获得中间层输出.我可以在使用标准的Sequential API时获得输出,但不能使用功能API.

我正在研究这个有用的玩具示例:

from keras.models import Sequential
from keras.layers import Input, Dense,TimeDistributed
from keras.models import Model
from keras.layers import Dense, LSTM, Bidirectional,Masking

inputs = [[[0,0,0],[0,0,0],[0,0,0],[0,0,0]],[[1,2,3],[4,5,6],[7,8,9],[10,11,12]],[[10,20,30],[40,50,60],[70,80,90],[100,110,120]]]

model = Sequential()
model.add(Masking(mask_value=0., input_shape = (4,3)))
model.add(Bidirectional(LSTM(3,return_sequences = True),merge_mode='concat'))
model.add(TimeDistributed(Dense(3,activation = 'softmax')))


print "First layer:"
intermediate_layer_model = Model(input=model.input,output=model.layers[0].output)
print intermediate_layer_model.predict(inputs)
print ""
print "Second layer:"
intermediate_layer_model = Model(input=model.input,output=model.layers[1].output)
print intermediate_layer_model.predict(inputs)
print ""
print "Third layer:"
intermediate_layer_model = Model(input=model.input,output=model.layers[2].output)
print intermediate_layer_model.predict(inputs)
Run Code Online (Sandbox Code Playgroud)

但是如果我使用功能API,它就不起作用.输出不正确.例如,它在第二层输出初始输入:

inputs_ = Input(shape=(4,3))
x = Masking(mask_value=0., input_shape = (4,3))(inputs_)
x = Bidirectional(LSTM(3,return_sequences = …
Run Code Online (Sandbox Code Playgroud)

python neural-network deep-learning keras keras-layer

7
推荐指数
1
解决办法
1920
查看次数

具有Maxpooling1D和channel_first的Keras模型

我目前尝试在Keras中为时间序列分类构建顺序模型时遇到问题.我想处理channels_first数据,因为从处理的角度来看它更方便(不过我只使用一个通道).这工作得很好了Convolution1D我使用的图层,我可以指定data_sample='channels_first',但不知何故,这不会对工作Maxpooling1D,因为它似乎不具有此选项.

我想要构建的模型结构如下:

model = Sequential()
model.add(Convolution1D(filters=16, kernel_size=35, activation='relu', input_shape=(1, window_length), data_format='channels_first'))
model.add(MaxPooling1D(pool_size=5)
model.add(Convolution1D(filters=16, kernel_size=10, activation='relu', data_format='channels_first'))
[...] #several other layers here
Run Code Online (Sandbox Code Playgroud)

window_length = 5000添加所有三个图层后,我得到以下摘要:

_________________________________________________________________
Layer (type)                 Output Shape              Param #  
=================================================================
conv1d_1 (Conv1D)           (None, 32, 4966)          1152     
_________________________________________________________________
max_pooling1d_1 (MaxPooling1 (None, 4, 4966)           0        
_________________________________________________________________
conv1d_2 (Conv1D)           (None, 16, 4957)          656      
=================================================================
Total params: 1,808
Trainable params: 1,808
Non-trainable params: 0
Run Code Online (Sandbox Code Playgroud)

现在,我想知道这是否正确,因为我期望第三维(即特征图中的神经元数)而不是第二维(即过滤器的数量)被汇集层减少?在我看来,MaxPooling1D不承认channels_first订购和而Keras文档说存在一个关键词data_format …

python machine-learning conv-neural-network keras max-pooling

7
推荐指数
1
解决办法
773
查看次数

如何在 keras 中建模共享层?

我想用以下形式训练一个具有共享层的模型:

x --> F(x)
          ==> G(F(x),F(y))
y --> F(y) 
Run Code Online (Sandbox Code Playgroud)

xy是两个独立的输入层,F是一个共享层。G是连接F(x)and后的最后一层F(y)

是否可以在 Keras 中对此进行建模?如何?

python machine-learning keras keras-layer

7
推荐指数
1
解决办法
4274
查看次数

我如何在每个时期而不是每个批次中获得损失?

在我的理解中,epoch 是在整个数据集上任意频繁地重复运行,然后分部分处理,即所谓的批处理。每次train_on_batch计算损失后,权重都会更新,下一批将获得更好的结果。这些损失是我对神经网络质量和学习状态的指标。

在几个来源中,每个时期都会计算(并打印)损失。因此,我不确定我这样做是否正确。

目前我的 GAN 看起来像这样:

for epoch:
  for batch:

    fakes = generator.predict_on_batch(batch)

    dlc = discriminator.train_on_batch(batch, ..)
    dlf = discriminator.train_on_batch(fakes, ..)
    dis_loss_total = 0.5 *  np.add(dlc, dlf)

    g_loss = gan.train_on_batch(batch,..)

    # save losses to array to work with later
Run Code Online (Sandbox Code Playgroud)

这些损失是针对每个批次的。我如何在一个时代获得它们?顺便说一句:我需要一个时代的损失,为了什么?

python machine-learning keras generative-adversarial-network

7
推荐指数
1
解决办法
8418
查看次数

在 Keras/Tensorflow 中实现可训练的广义 Bump 函数层

我正在尝试编写按组件应用的Bump 函数的以下变体:

广义凹凸函数方程,

在哪里 ?可训练;但它不起作用(下面报告了错误)。


我的尝试:

这是我到目前为止编码的内容(如果有帮助的话)。假设我有两个函数(例如):

  def f_True(x):
    # Compute Bump Function
    bump_value = 1-tf.math.pow(x,2)
    bump_value = -tf.math.pow(bump_value,-1)
    bump_value = tf.math.exp(bump_value)
    return(bump_value)

  def f_False(x):
    # Compute Bump Function
    x_out = 0*x
    return(x_out)

class trainable_bump_layer(tf.keras.layers.Layer):

    def __init__(self, *args, **kwargs):
        super(trainable_bump_layer, self).__init__(*args, **kwargs)

    def build(self, input_shape):
        self.threshold_level = self.add_weight(name='threshlevel',
                                    shape=[1],
                                    initializer='GlorotUniform',
                                    trainable=True)

    def call(self, input):
        # Determine Thresholding Logic
        The_Logic = tf.math.less(input,self.threshold_level)
        # Apply Logic
        output_step_3 = tf.cond(The_Logic, 
                                lambda: f_True(input),
                                lambda: f_False(input))
        return output_step_3
Run Code Online (Sandbox Code Playgroud)

错误报告:

    Train on 100 samples …
Run Code Online (Sandbox Code Playgroud)

python machine-learning keras tensorflow tf.keras

7
推荐指数
0
解决办法
486
查看次数

AttributeError: 在使用自定义生成器的 Keras 模型上调用 fit 时,'tuple' 对象没有属性 'rank'

我想构建一个具有两个输入的神经网络:用于图像数据和数字数据。所以我为此编写了自定义数据生成器。在trainvalidationdataframes包含11列:

  1. image_name — 图像路径;
  2. 9个数字特征;
  3. target — 项目的类(最后一列)。

自定义生成器的代码(基于此答案):

target_size = (224, 224)
batch_size = 1

train_datagen = ImageDataGenerator(
    rescale=1./255,
    rotation_range=20,
    width_shift_range=0.2,
    height_shift_range=0.2,
    horizontal_flip=True)

val_datagen = ImageDataGenerator(rescale=1./255)

train_generator = train_datagen.flow_from_dataframe(
    train,
    x_col='image_name',
    y_col=train.columns[1:],
    target_size=target_size,
    batch_size=batch_size,
    shuffle=True,
    class_mode='raw')

validation_generator = val_datagen.flow_from_dataframe(
    validation,
    x_col='image_name',
    y_col=validation.columns[1:],
    target_size=target_size,
    shuffle=False,
    batch_size=batch_size,
    class_mode='raw')

def train_generator_func():
    count = 0
    while True:
        if count == len(train.index):
            train_generator.reset()
            break
        count += 1
        data = train_generator.next()
        
        imgs = []
        cols = []
        targets = …
Run Code Online (Sandbox Code Playgroud)

python neural-network deep-learning keras tensorflow

7
推荐指数
1
解决办法
5032
查看次数

如何使用 sklearn 管道缩放 Keras 自动编码器模型的目标值?

我正在使用 sklearn 管道来构建 Keras 自动编码器模型并使用 gridsearch 来查找最佳超参数。如果我使用多层感知器模型进行分类,这很好用;但是,在自动编码器中,我需要输出值与输入相同。换句话说,我正在使用StandardScalar在管道中实例来缩放输入值,因此这引出了我的问题:如何使StandardScalar管道内的实例同时处理输入数据和目标数据,以便它们最终会一样吗?

我提供了一个代码片段作为示例。

from sklearn.datasets import make_classification
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
from sklearn.model_selection import GridSearchCV, KFold
from keras.models import Sequential
from keras.layers import Dense, Dropout
from keras.optimizers import RMSprop, Adam
from tensorflow.keras.wrappers.scikit_learn import KerasRegressor

X, y = make_classification (n_features = 50, n_redundant = 0, random_state = 0,
                            scale = 100, n_clusters_per_class = 1)

# Define wrapper
def create_model (learn_rate = 0.01, input_shape, metrics = ['mse']):
  model = …
Run Code Online (Sandbox Code Playgroud)

python machine-learning scikit-learn keras tensorflow

7
推荐指数
1
解决办法
719
查看次数

具有预先训练的卷积基数的keras模型中损失函数的奇异行为

我正在尝试在Keras中创建模型,以便根据图片进行数值预测。我的模型具有densitynet121卷积基础,顶部还有几个附加层。除最后两个图层外的所有图层均设置为layer.trainable = False。我的损失是均方误差,因为这是一项回归任务。在训练期间,我得到loss: ~3,而对同一批数据的评估给出loss: ~30

model.fit(x=dat[0],y=dat[1],batch_size=32)
Run Code Online (Sandbox Code Playgroud)

时代1/1 32/32 [==============================]-0s 11ms / step-损耗:2.5571

model.evaluate(x=dat[0],y=dat[1])
Run Code Online (Sandbox Code Playgroud)

32/32 [==============================]-2s 59ms / step 29.276123046875

在训练和评估期间,我提供了完全相同的32张图片。我还使用的预测值计算了损失y_pred=model.predict(dat[0]),然后使用numpy构造了均方误差。结果与我从评估中得到的结果相同(即29.276123 ...)。

有人建议这种行为可能是由于BatchNormalization卷积基础中的层(有关github的讨论)。当然,BatchNormalization我模型中的所有图层也都已设置layer.trainable=False为。也许有人遇到了这个问题并想出了解决方案?

python deep-learning keras tensorflow transfer-learning

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

Keras报告TypeError:+不支持的操作数类型:'NoneType'和'int'

我是Keras的初学者,只写一个玩具示例。它报告一个TypeError。代码和错误如下:

码:

inputs = keras.Input(shape=(3, ))

cell = keras.layers.SimpleRNNCell(units=5, activation='softmax')
label = keras.layers.RNN(cell)(inputs)

model = keras.models.Model(inputs=inputs, outputs=label)
model.compile(optimizer='rmsprop',
              loss='mae',
              metrics=['acc'])

data = np.array([[1, 2, 3], [3, 4, 5]])
labels = np.array([1, 2])
model.fit(x=data, y=labels)
Run Code Online (Sandbox Code Playgroud)

错误:

Traceback (most recent call last):
    File "/Users/david/Documents/code/python/Tensorflow/test.py", line 27, in <module>
        run()
    File "/Users/david/Documents/code/python/Tensorflow/test.py", line 21, in run
        label = keras.layers.RNN(cell)(inputs)
    File "/Users/david/anaconda3/lib/python3.6/site-packages/tensorflow/python/keras/layers/recurrent.py", line 619, in __call__
...
    File "/Users/david/anaconda3/lib/python3.6/site-packages/tensorflow/python/ops/init_ops.py", line 473, in __call__
        scale /= max(1., (fan_in + fan_out) / 2.)
TypeError: …
Run Code Online (Sandbox Code Playgroud)

python machine-learning keras tensorflow rnn

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

Keras 自定义损失函数(弹性网)

我正在尝试编写 Elastic-Net 代码。它看起来像:

elticnet公式

我想在 Keras 中使用这个损失函数:

def nn_weather_model():
    ip_weather = Input(shape = (30, 38, 5))
    x_weather = BatchNormalization(name='weather1')(ip_weather)
    x_weather = Flatten()(x_weather)
    Dense100_1 = Dense(100, activation='relu', name='weather2')(x_weather)
    Dense100_2 = Dense(100, activation='relu', name='weather3')(Dense100_1)
    Dense18 = Dense(18, activation='linear', name='weather5')(Dense100_2)
    model_weather = Model(inputs=[ip_weather], outputs=[Dense18])
    model = model_weather
    ip = ip_weather
    op = Dense18
    return model, ip, op
Run Code Online (Sandbox Code Playgroud)

我的损失函数是:

def cost_function(y_true, y_pred):
        return ((K.mean(K.square(y_pred - y_true)))+L1+L2)
   return cost_function
Run Code Online (Sandbox Code Playgroud)

它是 mse+L1+L2

L1 和 L2 是

weight1=model.layers[3].get_weights()[0]
weight2=model.layers[4].get_weights()[0]
weight3=model.layers[5].get_weights()[0]
L1 = Calculate_L1(weight1,weight2,weight3)
L2 = Calculate_L2(weight1,weight2,weight3)
Run Code Online (Sandbox Code Playgroud)

我使用Calculate_L1 函数来计算dense1、dense2 …

python machine-learning keras tensorflow loss-function

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