我在Keras中的自定义损失函数出现错误

时间:2019-06-25 16:25:05

标签: keras deep-learning

我正在创建一个自定义损失函数,其中包含许多代码和方程式。当我尝试这样编译模型时:

model.compile(optimizer ='rmsprop',loss = custom_loss(pic),metrics = ['accuracy'])

我收到一个错误,试图了解如何解决。

除此之外,我还必须更改函数内部的某些内容才能使其运行,并且我也有兴趣将其更改回原来的位置,所以我共有两个问题。

问题1:

我遇到了一个错误,尽管我确保在自定义损失函数期间打印出一些东西,以告知在哪里接收到错误,并且看起来它能够在整个损失函数中运行,直到返回命令为止。但是,我得到的错误是

'numpy.float64' object has no attribute 'get_shape'

,更详细的错误是:

AttributeError                            Traceback (most recent call 
last)
<ipython-input-254-fe4381ab64e0> in <module>()
----> 1 model.compile(optimizer='rmsprop',loss=custom_loss(pic), metrics= 
['accuracy'])

2 frames
/usr/local/lib/python3.6/dist-packages/keras/engine/training.py in 
compile(self, optimizer, loss, metrics, loss_weights, sample_weight_mode, 
weighted_metrics, target_tensors, **kwargs)
    340                 with K.name_scope(self.output_names[i] + 
'_loss'):
    341                     output_loss = weighted_loss(y_true, y_pred,
--> 342                                                 sample_weight, 
mask)
343                 if len(self.outputs) > 1:
344                     self.metrics_tensors.append(output_loss)

/usr/local/lib/python3.6/dist-packages/keras/engine/training_utils.py in 
weighted(y_true, y_pred, weights, mask)
    415         if weights is not None:
    416             # reduce score_array to same ndim as weight array
--> 417             ndim = K.ndim(score_array)
    418             weight_ndim = K.ndim(weights)
    419             score_array = K.mean(score_array,

/usr/local/lib/python3.6/dist- 
ndim(x)中的

packages / keras / backend / tensorflow_backend.py         617```         618“”“     -> 619昏暗= x.get_shape()._ dims         620如果暗淡不是无:         621返回len(dims)

丢失功能很长,我在此版本中包含一些印刷材料,因为也许可以帮助您了解问题所在:

'''def dl_loss(x,pic):

print('orig shape(x): ',x.shape)
x=tf.reshape(x,[2501,1])
print('try shape(x): ',x.shape)


a=x[0]
print('tfshape(a): ',a.shape)
print('shape(a): ',np.shape(a))
ms=x[1:]
print('tfshape(ms): ',np.shape(ms))




frac=2 
ms_reshaped=tf.reshape(ms,[int(np.shape(pic)[0]/frac),int(np.shape(pic) 
[0]/frac)])
print('got here')
ms=upsample(ms_reshaped,2) #THIS IS MY OWN FUNCTION THAT I ALSO NEED HELP 
WITH
print('finished upsampling')


h=np.shape(pic)[0]
w=np.shape(pic)[1]
print('hot h and w')

cur_noisy=(a*np.ones(np.shape(pic)))*(np.ones(np.shape(pic))+ms)
print('got noisy pic')

cur_clean=pic/(1.000000000001+ms)
print('got clean pic')


avg_m=np.mean(ms)
std_m=np.std(ms)

l_4=0.6*shannon_entropy(np.around(cur_clean,3))
if std_m<0.1:
#   print('in')
    l_4=5*l_4  
print('got l_4')


F_new=im2freq(cur_clean)
F_noisy=im2freq(pic)
print('got fourriers')



l_1=abs(avg_m)
print('got l1')


l_2=-(np.sum(abs(F_noisy[int(np.round(0.5*h)):,int(np.round(0.5*w)):]))
        -np.sum(abs(F_new[int(np.round(0.5*h)):,int(np.round(0.5*w)):])))

l_2=l_2/10000
print('got l2')


m_max=np.max(ms)
m_min=np.min(ms)
std=(m_max-m_min)/3


perc_pix_in_1_std = len(np.where(np.logical_and(ms>(avg_m-std), 
ms<(avg_m+std)))[0])/(np.shape(pic)[0]*np.shape(pic)[1])



l_3=(0.95-perc_pix_in_1_std) #because we're expecting m to be normally 
distributed
print('got l3')
print('final shape: ',np.shape(l_1+l_2+l_4))

return (l_1+l_3+l_4)'''

我从中得到的是: 原始形状(x):( ?, 2501) 尝试shape(x):(2501,1) tfshape(a):(1,) 形状(a):( 1,) tfshape(毫秒):(2500,1) 去那里 r_size:50 c_size:50 完成升采样 H和W 嘈杂的图片 干净的照片 得到了l_4 有富勒 得到了l1 得了l2 得了l3 最终形状:()

这意味着它确实设法完成了整个功能。

我输入到编译器中的自定义损失是     '''def custom_loss(pic):

def my_loss(y_true, y_pred):
return dl_loss(y_pred,pic)

return my_loss'''

问题2:

'''ms=upsample(ms_reshaped,2) #THIS IS MY OWN FUNCTION THAT I ALSO NEED 
HELP WITH
print('finished upsampling')'''

实际的上采样定义:     '''def upsample(pic,frac):     frac = int(分数)     r_siz = np.shape(pic)[0]     打印('r_size:',r_siz)     c_siz = np.shape(pic)[1]     print('c_size:',c_siz)     new_pic = np.zeros((frac r_siz,frac c_siz))     对于我在范围内(r_siz):         对于范围(c_siz)中的j:

#new_pic [frac i:frac i + frac,frac j:frac j + frac] = pic [i,j] * np.ones((frac ,frac))

new_pic[frac*i:frac*i+frac,frac*j:frac*j+frac]=3*np.ones((frac,frac))
return new_pic'''

我必须将pic [i,j]更改为一些随机数3才能运行。我知道这里的图片是一个tensorflow对象,当编译器尝试运行时,它没有实际的矩阵,而只是一个占位符,也许这就是问题所在吗?我虽然先编译它,然后再改回来。无论如何,我也该如何解决?

非常感谢任何尝试了解此问题的人!

0 个答案:

没有答案
相关问题