我有一个Tensorflow模型,其输出对应于多个多项式的系数。请注意,我的模型实际上还有另一组输出(多输出),但我在下面的示例中仅通过返回输入和多项式系数来模拟了这一点。
在模型训练过程中,我遇到了与张量形状相关的大量问题。我已经验证了模型能够对样本输入进行预测,并且损失函数在样本输出上也能正常工作。但在训练过程中,它立即抛出了错误(见下文)。
对于每个输入,模型接受一个固定大小的嵌入输入,并输出2
个二次多项式的系数。例如,单个输入的输出可能看起来像这样:
[array([[[1, 2, 3], [ 4, 5, 6]]]),[...]]
对应于多项式[1*x^2+2*x+3, 4*x^2+5*x+6]
。请注意,我隐藏了第二个输出。
我注意到tf.math.polyval
需要一个系数列表,这与AutoGrad不兼容。所以,我用纯张量实现了霍纳算法的版本。
import numpy as npimport tensorflow as tfimport loggingimport tensorflow.keras as K@tf.functiondef tensor_polyval(coeffs, x): """ 从多项式系数的张量中计算多项式标量 Tensorflow tf.math.polyval 需要一个列表系数,这与自动微分不兼容 # 输入: - coeffs (NxD Tensor): 每行coeffs对应于r[0]*x^(D-1)+r[1]*x^(D-2)...+r[D] - x: 标量! # 输出: - 对于coeffs中的每一行,r[0]*x^(D-1)+r[1]*x^(D-2)...+r[D] """ p = coeffs[:, 0] for i in range(1,coeffs.shape[1]): tf.autograph.experimental.set_loop_options( shape_invariants=[(p, tf.TensorShape([None]))]) c = coeffs[:, i] p = tf.add(c, tf.multiply(x, p)) return p@tf.functiondef coeffs_to_poly(coeffs, n): # 将NxM的系数数组转换为在x=n处评估的N个多项式 return tensor_polyval(coeffs, tf.convert_to_tensor(n))
现在,这里有一个我模型、损失函数和训练例程的超简化示例:
def model_init(embedDim=8, polyDim=2,terms=2): input = K.Input(shape=(embedDim,)) x = K.layers.Reshape((embedDim,))(input) aCoeffs = K.layers.Dense((polyDim+1)*terms, activation='tanh')(x) aCoeffs = K.layers.Reshape((terms, polyDim+1))(aCoeffs) model = K.Model(inputs=input, outputs=[aCoeffs, input]) return modeldef get_random_batch(batch, embedDim, dtype='float64'): x = np.random.randn(batch, embedDim).astype(dtype) y = np.array([1. for i in range(batch)]).astype(dtype) return [x, y]@tf.functiondef test_loss(y_true, y_pred, dtype=dataType): an = tf.vectorized_map(lambda y_p: coeffs_to_poly(y_p[0], tf.constant(5,dtype=dataType)), y_pred) return tf.reduce_mean(tf.reduce_mean(an,axis=-1))embedDim=8polyDim=2terms=2dataType = 'float64'tf.keras.backend.set_floatx(dataType)model = model_init(embedDim, polyDim, terms)XTrain, yTrain = get_random_batch(batch=128, embedDim=embedDim)# 初始化模型LR = 0.001loss = test_lossepochs = 5model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=LR), loss=loss)hist = model.fit(XTrain, yTrain, batch_size=4, epochs=epochs, max_queue_size=10, workers=2, use_multiprocessing=True)
我得到的错误与tensor_polyval
函数有关:
<ipython-input-15-f96bd099fe08>:3 test_loss * an = tf.vectorized_map(lambda y_p: coeffs_to_poly(y_p[0], <ipython-input-5-7205207d12fd>:23 coeffs_to_poly * return tensor_polyval(coeffs, tf.convert_to_tensor(n)) <ipython-input-5-7205207d12fd>:13 tensor_polyval * p = coeffs[:, 0] ... ValueError: Index out of range using input dim 1; input has only 1 dims for '{{node strided_slice}} = StridedSlice[Index=DT_INT32, T=DT_DOUBLE, begin_mask=1, ellipsis_mask=0, end_mask=1, new_axis_mask=0, shrink_axis_mask=2](coeffs, strided_slice/stack, strided_slice/stack_1, strided_slice/stack_2)' with input shapes: [3], [2], [2], [2] and with computed input tensors: input[3] = <1 1>.
令人沮丧的是,我完全能够用样本输入预测模型的输出,并且还可以计算样本损失:
test_loss(yTrain[0:5], model.predict(XTrain[0:5]), dtype=dataType)
这可以正常运行。
在test_loss
函数中,具体来说,我只是通过y_p[0]
引用第一个输出。它尝试在n=5
处计算多项式的值,然后输出所有内容的平均值(再次强调,这只是模拟代码)。据我所知,y_p[1]
将引用第二个输出(在这种情况下,是输入的副本)。我认为tf.vectorized_map
应该在模型批次的所有输出上操作,但它似乎多切了一个维度?
我注意到,如果我在模型中移除输出,input
(使其成为单输出),并在test_loss
中将y_p[0]
更改为y_p
,代码确实可以训练。我不知道为什么添加额外输出时会出错,因为我对tf.vectorized_map
的理解是,它对y_pred
列表的每个元素分别作用
回答:
如果我们需要单一损失函数接收所有多个输出,或许我们可以将它们连接在一起形成一个输出。
在这种情况下:
- 对模型结构进行更改,这里我们打包输出:
def model_init(embedDim=8, polyDim=2, terms=2): input = K.Input(shape=(embedDim, )) x = K.layers.Reshape((embedDim, ))(input) aCoeffs = K.layers.Dense((polyDim + 1) * terms, activation='tanh')(x) # 打包两个输出,如果它们的形状不是批量*K,则添加扁平层 outputs = K.layers.Concatenate()([aCoeffs, input]) model = K.Model(inputs=input, outputs=outputs) model.summary() return model
- 对损失函数进行更改,这里我们解包输出:
# 损失函数需要知道这些polyDim = 2terms = 2@tf.functiondef test_loss(y_true, y_pred, dtype=dataType): """针对扁平输出的损失函数。""" # 解包多个输出 offset = (polyDim + 1) * terms aCoeffs = tf.reshape(y_pred[:, :offset], [-1, terms, polyDim + 1]) inputs = y_pred[:, offset:] print(aCoeffs, inputs) # 对两个解包的输出做一些处理,如下所示 an = tf.vectorized_map( lambda y_p: coeffs_to_poly(y_p, tf.constant(5, dtype=dataType)), aCoeffs) return tf.reduce_mean(tf.reduce_mean(an, axis=-1))
请注意,损失函数依赖于对输出原始形状的了解,以便恢复它们。考虑子类化tf.keras.losses.Loss
。
P.S. 对于任何简单地需要多个损失的不同损失的人:
- 为两个输出定义损失函数。
@tf.functiondef test_loss(y_true, y_pred, dtype=dataType): """针对输出1的损失函数 (仅将y_p[0]更改为y_p)""" an = tf.vectorized_map( lambda y_p: coeffs_to_poly(y_p, tf.constant(5, dtype=dataType)), y_pred) return tf.reduce_mean(tf.reduce_mean(an, axis=-1))@tf.functiondef dummy_loss(y_true, y_pred, dtype=dataType): """针对输出2的损失函数,即输入,用于调试 最好使用0而不是1.2345""" return tf.constant(1.2345, dataType)
- 更改
model.compile
:
model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=LR), loss=[test_loss, dummy_loss])