Вызов функции Scipy Optimize SLSQP с пользовательской архитектурой TF 2 - PullRequest
0 голосов
/ 27 апреля 2020

В настоящее время я пытаюсь преобразовать код theano в TensorFlow 2 Код в theano только что создал фиктивный граф, выполнив действия с переменными theano.shared ().

В настоящее время я использую Tensorflow, где я сдвинул создание графика в @ tf.function

@tf.function
        def calculate_cost(tsLi):
            Li_subset = tsLi
            Li_subset_glob3D = (tf.reshape(Li_subset, (self.numJoints, 3)) * tsScale) + tsOff3D
            Li_subset_glob3D_hom = tf.concat([Li_subset_glob3D, tf.ones((self.numJoints, 1), dtype='float32')], axis=1)
            Li_subset_glob2D_hom = tf.matmul(Li_subset_glob3D_hom, tf.transpose(tsCam))
            x = Li_subset_glob2D_hom[:, 0] / Li_subset_glob2D_hom[:, 3]
            x = tf.reshape(x, (x.shape[0], 1))
            y = Li_subset_glob2D_hom[:, 1] / Li_subset_glob2D_hom[:, 3]
            y = tf.reshape(y, (y.shape[0], 1))
            temp = Li_subset_glob2D_hom[:, 2] / Li_subset_glob2D_hom[:, 3]
            temp = tf.reshape(temp, (temp.shape[0], 1))
            Li_subset_glob2D_hom = tf.concat(
                [x, y, temp, tf.reshape(Li_subset_glob2D_hom[:, 3], (Li_subset_glob2D_hom[:, 3].shape[0], 1))], axis=1)
            Li_subset_glob2D = Li_subset_glob2D_hom
            Li_subset_glob2D = tf.reshape(Li_subset_glob2D[:, 0:3], (self.numJoints, 3))
            Li_subset_img2D_hom = tf.matmul(Li_subset_glob2D, tsTrans2D)
            x = Li_subset_img2D_hom[:, 0] / Li_subset_img2D_hom[:, 2]
            x = tf.reshape(x, (x.shape[0], 1))
            y = Li_subset_img2D_hom[:, 1] / Li_subset_img2D_hom[:, 2]
            y = tf.reshape(y, (y.shape[0], 1))
            temp = Li_subset_img2D_hom[:, 2] / Li_subset_img2D_hom[:, 2]
            temp = tf.reshape(temp, (temp.shape[0], 1))
            Li_subset_img2D_hom = tf.concat([x, y, temp], axis=1)
            Li_subset_img2D = Li_subset_img2D_hom
            Li_subset_img2D = tf.reshape(Li_subset_img2D[:, 0:2], (self.numJoints * 2,))
            Li_subset_img2Dcrop = (Li_subset_img2D - (self.Di.shape[3] / 2.)) / (self.Di.shape[3] / 2.)
            costP = (self.ref_lambdaP / self.numJoints) * tf.math.reduce_sum(
                (Li_subset_img2Dcrop - tsli) ** 2)  # 3D to 2D projection
            # constraint with known joint length
            if len(self.lenghtConstraintIdx) > 0:
                di = tf.matmul((tf.matmul(tf.reshape(Li_subset, (1, -1)), self.lenghtConstraint)) ** 2
                               , self.lenghtConstraintS)
                eq = tf.reshape(di - tf.math.square(tsJL), (-1,))
            else:
                eq = tf.Variable(numpy.cast['float32'](0.), name='dummy', borrow=True)

            costP += (tsMuLagr / len(self.lenghtConstraintIdx)) * tf.math.reduce_sum(tf.math.square(eq))
            return eq, costP

Эти функции вызываются из функции обратного вызова из SLSQP

        def train_fn(x, ref_tsLi):
        ref_tsLi = tf.Variable(x.reshape(li3D[0].shape).astype('float32'))
        _, cost = calculate_cost(ref_tsLi)
        return numpy.asarray(cost).flatten().astype(float)

    # creates a function that computes the gradient
    def train_fn_grad(x, ref_tsLi):
        with tf.GradientTape(persistent=True) as tape:
            ref_tsLi = tf.Variable(x.reshape(li3D[0].shape).astype('float32'))
            _,cost = calculate_cost(ref_tsLi)
            return numpy.asarray(tape.gradient(cost, sources = ref_tsLi)).flatten().astype(float)

best_rval = scipy.optimize.fmin_slsqp(
                            func=train_fn,
                            x0=best_rval[0],
                            fprime=train_fn_grad,
                            # f_eqcons=eq_constr_fn,
                            # fprime_eqcons=eq_constr_fn_grad,
                            f_ieqcons=ieq_constr_fn,
                            fprime_ieqcons=ieq_constr_fn_grad,
                            bounds=bnds,
                            disp=0,
                            full_output=True,
                            iter=1,
                            acc=1e-5,
                            args=(tsLi,)

В настоящее время я получаю сообщение об ошибке, в котором говорится, что

tensorflow.python.framework.errors_impl.FailedPreconditionError:  Error while reading resource variable _AnonymousVar10 from Container: localhost. This could mean that the variable was uninitialized. Not found: Resource localhost/_AnonymousVar10/N10tensorflow3VarE does not exist.
     [[node ReadVariableOp (defined at home/giffy/PycharmProjects/Handpose/semiautoanno.py:1523) ]] [Op:__inference_calculate_cost_261]

Если я удаляю функцию @ tf.f, код работает нормально, но он чрезвычайно медленный, так как он с энтузиазмом выполняет каждую операцию каждый раз, когда я его вызываю.

Каков наилучший подход к решению этого типа проблемы?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...