给定3维Keras张量,如何将尺寸1和2的对角线设置为1?

时间:2018-02-09 05:02:01

标签: keras

考虑到Keras张量,我想用数字1替换对角线。这类似于numpy函数fill_diagonal

1 个答案:

答案 0 :(得分:1)

inputTensor成为您想要更改的张量,size是维度1和2的大小:

#create a diagonal matrix
diag = K.eye(size)

#make it 3D by adding a dummy batch dimension
diag = K.expand_dims(diag,0)

#get a complement for wich complement + diag = ones    
complement = 1 - diag

#annulate the diagonal from the input
noDiagInput = complement * inputTensor    

#add diagonal 1
return noDiagInput + diag