我正在Keras中创建一个模型,并想计算自己的指标(困惑度)。这需要使用非标准化的概率/对数。但是,keras模型仅返回softmax概率:
model = Sequential()
model.add(embedding_layer)
model.add(LSTM(n_hidden, return_sequences=False))
model.add(Dropout(dropout_keep_prob))
model.add(Dense(vocab_size))
model.add(Activation('softmax'))
optimizer = RMSprop(lr=self.lr)
model.compile(optimizer=optimizer,
loss='sparse_categorical_crossentropy')
Run Code Online (Sandbox Code Playgroud)
Keras常见问题解答提供了一种在此处获取中间层输出的解决方案。这里给出了另一个解决方案。但是,这些答案将中间输出存储在其他模型中,这不是我所需要的。我想将logits用于我的自定义指标。自定义指标应包含在model.compile()函数中,以便在训练过程中对其进行评估和显示。因此,我不需要Dense在不同模型中分隔层的输出,而将其作为原始模型的一部分。
简而言之,我的问题是:
当定义所概述自定义指标在这里使用def custom_metric(y_true, y_pred),并在y_pred含有logits或标准化的概率?
如果它包含归一化的概率,如何获得未归一化的概率,即该层输出的logits Dense?
我正在使用带有tensorflow后端的keras编写两个类别的图像分类代码。我的图像存储在计算机的文件夹中,我想将这些图像作为我的keras模型的输入。load_img我只需要一个输入图像,所以我必须使用flow(x,y)或flow_from_directory(directory),但是flow(x,y)我们还需要提供标签,这是长度任务,所以我正在使用flow_from_directory(directory)。我的图像大小可变,例如20 * 40、55 * 43 .....,但是这里提到需要固定的target_size。在该解决方案中,我们可以使用以下方法将可变大小的图像作为卷积层的输入input_shape=(1, None, None)或input_shape =(None,None,3)(最后一个通道和彩色图像),但fchollet提到它对平坦层没有用,我的模型同时包括卷积层和平坦层。在那篇文章中,只有moi90建议尝试不同的批次,但是每个批次都应具有相同大小的图像,但是由于我的数据非常分散,因此无法对相同尺寸的图像进行分组。所以我决定去batch size=1写下面的代码:
from __future__ import print_function
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D
from keras import backend as K
import numpy as np
from keras.preprocessing.image import ImageDataGenerator
input_shape = (None,None,3)
model = Sequential()
model.add(Conv2D(8, kernel_size=(3, 3),
activation='relu',
input_shape=input_shape))
model.get_weights()
model.add(Conv2D(16, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(32, activation='relu')) …Run Code Online (Sandbox Code Playgroud) machine-learning image-processing neural-network deep-learning keras
我想重塑一个张量,它的形状是 (?,12,12,5,512) 到 (?,12,12,2560) 张量的形状。有没有人可以帮助我?我的代码如下。
conv5_1 = Conv3D(512, (3, 3, 3), activation='relu', padding='same')(drop4_1) # conv5_1: Tensor("conv3d_10/Relu:0", shape=(", 12, 12, 5, 512), dtype=float32)
conv5_1 = Conv3D(512, (3, 3, 3), activation='relu', padding='same')(conv5_1)
drop5_1 = Dropout(0.2)(conv5_1) # drop5_1: Tensor("dropout_8/cond/Merge:0", shape=(", 12, 12, 5, 512), dtype=float32)
Run Code Online (Sandbox Code Playgroud)
我想在 drop5_1 之后制作 (?, 12, 12, 2560) 张量的形状。谢谢
我在官方 pytorch 教程中得到了这个 nn 结构:
输入 -> conv2d -> relu -> maxpool2d -> conv2d -> relu -> maxpool2d -> 视图 -> 线性 -> relu -> 线性 -> relu -> 线性 -> MSELoss -> 损失
然后是如何使用变量中的内置 .grad_fn 向后跟踪 grad 的示例。
# Eg:
print(loss.grad_fn) # MSELoss
print(loss.grad_fn.next_functions[0][0]) # Linear
print(loss.grad_fn.next_functions[0][0].next_functions[0][0]) # ReLU
Run Code Online (Sandbox Code Playgroud)
所以我想我可以通过粘贴 next_function[0][0] 9 次来达到 Conv2d 的 grad 对象,因为给定的例子但我得到了索引之外的错误元组。那么如何正确索引这些反向传播对象呢?
我使用 keras(tensorflow backend) 来构建我的 lstm 网络,这是我的代码:
from keras.models import Sequential,Model
from keras.layers import LSTM,Conv1D,Dense,MaxPooling1D,GlobalMaxPooling1D,Input,Concatenate
from keras.optimizers import Adam
x_input = Input(shape=(None,x_train.shape[-1]),name='input')
x_mid = Conv1D(32,4, activation='relu')(x_input)
x_mid = MaxPooling1D(3)(x_mid)
x_mid = Conv1D(32,4,activation = 'relu')(x_mid)
x_mid = LSTM(32,dropout=0.1, recurrent_dropout=0.2,activation='relu')(x_mid)
x_mid = Dense(1,activation='sigmoid')(x_mid)
other_input = Input(shape=(x_blend_train.shape[-1],),name='clfs_input')
merge_x = concatenate(inputs= [x_mid,other_input],axis = -1)
output = Dense(32,activation='relu')(merge_x)
output = Dense(1,activation='sigmoid')(output)
model = Model(inputs=[x_input,other_input],outputs=output)
model.compile(optimizer='adam',loss=['binary_crossentropy'],metrics=['acc'])
model.summary()
Run Code Online (Sandbox Code Playgroud)
这就是我的网络的样子
Layer (type) Output Shape Param # Connected to
==================================================================================================
input (InputLayer) (None, None, 49) 0
__________________________________________________________________________________________________
conv1d_56 (Conv1D) (None, …Run Code Online (Sandbox Code Playgroud) 我想做的是在自定义RNN类中使用DataParallel。
似乎我以错误的方式初始化了hidden_0。
class RNN(nn.Module):
def __init__(self, input_size, hidden_size, output_size, n_layers=1):
super(RNN, self).__init__()
self.input_size = input_size
self.hidden_size = hidden_size
self.output_size = output_size
self.n_layers = n_layers
self.encoder = nn.Embedding(input_size, hidden_size)
self.gru = nn.GRU(hidden_size, hidden_size, n_layers,batch_first = True)
self.decoder = nn.Linear(hidden_size, output_size)
self.init_hidden(batch_size)
def forward(self, input):
input = self.encoder(input)
output, self.hidden = self.gru(input,self.hidden)
output = self.decoder(output.contiguous().view(-1,self.hidden_size))
output = output.contiguous().view(batch_size,num_steps,N_CHARACTERS)
#print (output.size())10,50,67
return output
def init_hidden(self,batch_size):
self.hidden = Variable(T.zeros(self.n_layers, batch_size, self.hidden_size).cuda())
Run Code Online (Sandbox Code Playgroud)
我以这种方式称呼网络:
decoder = T.nn.DataParallel(RNN(N_CHARACTERS, HIDDEN_SIZE, N_CHARACTERS), dim=1).cuda()
Run Code Online (Sandbox Code Playgroud)
然后开始训练:
for epoch in range(EPOCH_):
hidden …Run Code Online (Sandbox Code Playgroud) 操作系统平台和发行版:Linux Ubuntu16.04;TensorFlow版本:'1.4.0'
我可以使用以下代码正常运行:
import tensorflow as tf
from tensorflow.python.keras.layers import Dense
from tensorflow.python.keras.backend import categorical_crossentropy
from tensorflow.examples.tutorials.mnist import input_data
from tensorflow.python.keras.models import Model
from tensorflow.python.keras.layers import Input
mnist_data = input_data.read_data_sets('MNIST_data', one_hot=True)
img_size_flat = 28*28
batch_size = 64
def gen(batch_size=32):
while True:
batch_data, batch_label = mnist_data.train.next_batch(batch_size)
yield batch_data, batch_label
inputs = Input(shape=(img_size_flat,))
x = Dense(128, activation='relu')(inputs) # fully-connected layer with 128 units and ReLU activation
x = Dense(128, activation='relu')(x)
preds = Dense(10, activation='softmax')(x) # output layer with 10 units and a …Run Code Online (Sandbox Code Playgroud) 我正在将VGG16与keras一起用于迁移学习(我的新模型中有7个类),因此我想使用内置的encode_predictions方法输出模型的预测。但是,使用以下代码:
preds = model.predict(img)
decode_predictions(preds, top=3)[0]
Run Code Online (Sandbox Code Playgroud)
我收到以下错误消息:
ValueError:
decode_predictions需要进行一系列预测(例如,二维形状数组(样本,1000个))。找到形状为(1,7)的数组
现在,我想知道为什么在重新训练的模型中只有7个班级时会期望1000。
我在stackoverflow上发现的一个类似问题(Keras:ValueError:decode_predictions期望进行一系列预测 )建议在模型定义中包括“ inlcude_top = True”以解决此问题:
model = VGG16(weights='imagenet', include_top=True)
Run Code Online (Sandbox Code Playgroud)
我已经尝试过了,但是仍然无法正常工作-给我和以前一样的错误。非常感谢您对如何解决此问题的任何提示或建议。
python machine-learning conv-neural-network keras pre-trained-model
我有以下问题:
我在 Keras 中有一个自动编码器,并对其进行了几个时期的训练。训练概览显示验证 MAE 为 0.0422,MSE 为 0.0024。但是,如果我随后调用 network.predict 并手动计算验证错误,我会得到 0.035 和 0.0024。
人们会认为我对 MAE 的手动计算完全不正确,但奇怪的是,如果我使用恒等模型(仅输出您输入的内容)并使用它来评估预测值,则会返回与我的手工计算。代码如下:
input = Input(shape=(X_train.shape[1], ))
encoded = Dense(50, activation='relu', activity_regularizer=regularizers.l1(10e-5))(input)
encoded = Dense(50, activation='relu', activity_regularizer=regularizers.l1(10e-5))(encoded)
encoded = Dense(50, activation='relu', activity_regularizer=regularizers.l1(10e-5))(encoded)
decoded = Dense(50, activation='relu', activity_regularizer=regularizers.l1(10e-5))(encoded)
decoded = Dense(50, activation='relu', activity_regularizer=regularizers.l1(10e-5))(decoded)
decoded = Dense(X_train.shape[1], activation='sigmoid')(decoded)
network = Model(input, decoded)
# sgd = SGD(lr=8, decay=1e-6)
# network.compile(loss='mean_squared_error', optimizer='adam')
network.compile(loss='mean_absolute_error', optimizer='adam', metrics=['mse'])
# Fitting the data
network.fit(X_train, X_train, epochs=2, batch_size=1, shuffle=True, validation_data=(X_valid, X_valid),
callbacks=[EarlyStopping(monitor='val_loss', min_delta=0.00001, patience=20, verbose=0, …Run Code Online (Sandbox Code Playgroud) 我正在尝试将大型数据集提供给keras模型。数据集不适合内存。当前存储为一系列hd5f文件
我想使用训练我的模型
model.fit_generator(my_gen, steps_per_epoch=30, epochs=10, verbose=1)
Run Code Online (Sandbox Code Playgroud)
但是,在我可以在线找到的所有示例中,这些示例my_gen仅用于对已加载的数据集执行数据扩充。例如
def generator(features, labels, batch_size):
# Create empty arrays to contain batch of features and labels#
batch_features = np.zeros((batch_size, 64, 64, 3))
batch_labels = np.zeros((batch_size,1))
while True:
for i in range(batch_size):
# choose random index in features
index= random.choice(len(features),1)
batch_features[i] = some_processing(features[index])
batch_labels[i] = labels[index]
yield batch_features, batch_labels
Run Code Online (Sandbox Code Playgroud)
就我而言,它必须像
def generator(features, labels, batch_size):
while True:
for i in range(batch_size):
# choose random index in features
index= # SELECT THE NEXT FILE
batch_features[i] …Run Code Online (Sandbox Code Playgroud)