'convert tf.tensor to numpy
I've built a custom loss function to train my model
def JSD_Tensor_loss(P,Q):
P=tf.make_ndarray(P)
Q=tf.make_ndarray(Q)
M=np.divide((np.sum(P,Q)),2)
D1=np.multiply(P,(np.log(P,M)))
D2=np.multiply(Q,(np.log(Q,M)))
JSD=np.divide((np.sum(D1,D2)),2)
JSD=np.sum(JSD)
return JSD
model.compile(optimizer='adam', loss=JSD_Tensor_loss, metrics=['accuracy'])
model.fit(x_train, x_test, epochs=EPOCHS)
Although I've converted the tensor params to numpy but I've having the following error and cant solve it AttributeError: 'Tensor' object has no attribute 'tensor_shape'
Solution 1:[1]
Your error stems from your conversion to numpy.array (first two lines).
If you have to convert a tensor (which in my opinion you shouldn't in this case), I would go with:
P, Q = P.numpy(), Q.numpy()
However, this is really not necessary here. Just replace the numpy function with the respective tf.math function (docs) and you should be good:
def JSD_Tensor_loss(P,Q):
M=tf.math.divide((tf.math.add(P,Q)),2)
D1=tf.math.multiply(P,(tf.math.log(P)))
D2=tf.math.multiply(Q,(tf.math.log(Q)))
JSD=tf.math.divide((tf.add(D1,D2)),2)
JSD=tf.math.reduce_sum(JSD)
return JSD
(I did not understand your call to np.log. Do you maybe use an outdated version of the function (docs))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | PlzBePython |
