我正在尝试使用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) 我目前尝试在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
我想用以下形式训练一个具有共享层的模型:
x --> F(x)
==> G(F(x),F(y))
y --> F(y)
Run Code Online (Sandbox Code Playgroud)
x和y是两个独立的输入层,F是一个共享层。G是连接F(x)and后的最后一层F(y)。
是否可以在 Keras 中对此进行建模?如何?
在我的理解中,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
我正在尝试编写按组件应用的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) 我想构建一个具有两个输入的神经网络:用于图像数据和数字数据。所以我为此编写了自定义数据生成器。在train和validationdataframes包含11列:
image_name — 图像路径;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) 我正在使用 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) 我正在尝试在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为。也许有人遇到了这个问题并想出了解决方案?
我是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) 我正在尝试编写 Elastic-Net 代码。它看起来像:

我想在 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 …
keras ×10
python ×10
tensorflow ×6
keras-layer ×2
generative-adversarial-network ×1
max-pooling ×1
rnn ×1
scikit-learn ×1
tf.keras ×1