addons/giou_loss.py at master · tensorflow/addons - GitHub

文章推薦指數: 80 %
投票人數:10人

model = tf.keras.Model(). >>> model.compile('sgd', loss=tfa.losses.GIoULoss()). Args: mode: one of ['giou', 'iou'], decided to calculate GIoU or IoU loss. Skiptocontent {{message}} tensorflow / addons Public Notifications Fork 589 Star 1.6k Code Issues 208 Pullrequests 39 Actions Projects 2 Security Insights More Code Issues Pullrequests Actions Projects Security Insights Permalink master Branches Tags Couldnotloadbranches Nothingtoshow {{refName}} default Couldnotloadtags Nothingtoshow {{refName}} default Atagalreadyexistswiththeprovidedbranchname.ManyGitcommandsacceptbothtagandbranchnames,socreatingthisbranchmaycauseunexpectedbehavior.Areyousureyouwanttocreatethisbranch? addons/tensorflow_addons/losses/giou_loss.py / Jumpto GIoULoss Class __init__ Function giou_loss Function _calculate_giou Function Gotofile Gotofile T Gotoline L Gotodefinition R Copypath Copypermalink Thiscommitdoesnotbelongtoanybranchonthisrepository,andmaybelongtoaforkoutsideoftherepository.     Cannotretrievecontributorsatthistime 138lines(114sloc) 5.22KB Raw Blame Editthisfile E OpeninGitHubDesktop OpenwithDesktop Viewraw Viewblame ThisfilecontainsbidirectionalUnicodetextthatmaybeinterpretedorcompileddifferentlythanwhatappearsbelow.Toreview,openthefileinaneditorthatrevealshiddenUnicodecharacters. LearnmoreaboutbidirectionalUnicodecharacters Showhiddencharacters #Copyright2019TheTensorFlowAuthors.AllRightsReserved. # #LicensedundertheApacheLicense,Version2.0(the"License"); #youmaynotusethisfileexceptincompliancewiththeLicense. #YoumayobtainacopyoftheLicenseat # #http://www.apache.org/licenses/LICENSE-2.0 # #Unlessrequiredbyapplicablelaworagreedtoinwriting,software #distributedundertheLicenseisdistributedonan"ASIS"BASIS, #WITHOUTWARRANTIESORCONDITIONSOFANYKIND,eitherexpressorimplied. #SeetheLicenseforthespecificlanguagegoverningpermissionsand #limitationsundertheLicense. #============================================================================== """ImplementsGIoUloss.""" fromtypingimportOptional importtensorflowastf fromtypeguardimporttypechecked fromtensorflow_addons.utils.keras_utilsimportLossFunctionWrapper fromtensorflow_addons.utils.typesimportTensorLike @tf.keras.utils.register_keras_serializable(package="Addons") classGIoULoss(LossFunctionWrapper): """ImplementstheGIoUlossfunction. GIoUlosswasfirstintroducedinthe [GeneralizedIntersectionoverUnion: AMetricandALossforBoundingBoxRegression] (https://giou.stanford.edu/GIoU.pdf). GIoUisanenhancementformodelswhichuseIoUinobjectdetection. Usage: >>>gl=tfa.losses.GIoULoss() >>>boxes1=tf.constant([[4.0,3.0,7.0,5.0],[5.0,6.0,10.0,7.0]]) >>>boxes2=tf.constant([[3.0,4.0,6.0,8.0],[14.0,14.0,15.0,15.0]]) >>>loss=gl(boxes1,boxes2) >>>loss Usagewith`tf.keras`API: >>>model=tf.keras.Model() >>>model.compile('sgd',loss=tfa.losses.GIoULoss()) Args: mode:oneof['giou','iou'],decidedtocalculateGIoUorIoUloss. """ @typechecked def__init__( self, mode:str="giou", reduction:str=tf.keras.losses.Reduction.AUTO, name:Optional[str]="giou_loss", ): super().__init__(giou_loss,name=name,reduction=reduction,mode=mode) @tf.keras.utils.register_keras_serializable(package="Addons") defgiou_loss(y_true:TensorLike,y_pred:TensorLike,mode:str="giou")->tf.Tensor: """ImplementstheGIoUlossfunction. GIoUlosswasfirstintroducedinthe [GeneralizedIntersectionoverUnion: AMetricandALossforBoundingBoxRegression] (https://giou.stanford.edu/GIoU.pdf). GIoUisanenhancementformodelswhichuseIoUinobjectdetection. Args: y_true:truetargetstensor.Thecoordinatesoftheeachbounding boxinboxesareencodedas[y_min,x_min,y_max,x_max]. y_pred:predictionstensor.Thecoordinatesoftheeachbounding boxinboxesareencodedas[y_min,x_min,y_max,x_max]. mode:oneof['giou','iou'],decidedtocalculateGIoUorIoUloss. Returns: GIoUlossfloat`Tensor`. """ ifmodenotin["giou","iou"]: raiseValueError("Valueofmodeshouldbe'iou'or'giou'") y_pred=tf.convert_to_tensor(y_pred) ifnoty_pred.dtype.is_floating: y_pred=tf.cast(y_pred,tf.float32) y_true=tf.cast(y_true,y_pred.dtype) giou=tf.squeeze(_calculate_giou(y_pred,y_true,mode)) return1-giou def_calculate_giou(b1:TensorLike,b2:TensorLike,mode:str="giou")->tf.Tensor: """ Args: b1:boundingbox.Thecoordinatesoftheeachboundingboxinboxesare encodedas[y_min,x_min,y_max,x_max]. b2:theotherboundingbox.Thecoordinatesoftheeachboundingbox inboxesareencodedas[y_min,x_min,y_max,x_max]. mode:oneof['giou','iou'],decidedtocalculateGIoUorIoUloss. Returns: GIoUlossfloat`Tensor`. """ zero=tf.convert_to_tensor(0.0,b1.dtype) b1_ymin,b1_xmin,b1_ymax,b1_xmax=tf.unstack(b1,4,axis=-1) b2_ymin,b2_xmin,b2_ymax,b2_xmax=tf.unstack(b2,4,axis=-1) b1_width=tf.maximum(zero,b1_xmax-b1_xmin) b1_height=tf.maximum(zero,b1_ymax-b1_ymin) b2_width=tf.maximum(zero,b2_xmax-b2_xmin) b2_height=tf.maximum(zero,b2_ymax-b2_ymin) b1_area=b1_width*b1_height b2_area=b2_width*b2_height intersect_ymin=tf.maximum(b1_ymin,b2_ymin) intersect_xmin=tf.maximum(b1_xmin,b2_xmin) intersect_ymax=tf.minimum(b1_ymax,b2_ymax) intersect_xmax=tf.minimum(b1_xmax,b2_xmax) intersect_width=tf.maximum(zero,intersect_xmax-intersect_xmin) intersect_height=tf.maximum(zero,intersect_ymax-intersect_ymin) intersect_area=intersect_width*intersect_height union_area=b1_area+b2_area-intersect_area iou=tf.math.divide_no_nan(intersect_area,union_area) ifmode=="iou": returniou enclose_ymin=tf.minimum(b1_ymin,b2_ymin) enclose_xmin=tf.minimum(b1_xmin,b2_xmin) enclose_ymax=tf.maximum(b1_ymax,b2_ymax) enclose_xmax=tf.maximum(b1_xmax,b2_xmax) enclose_width=tf.maximum(zero,enclose_xmax-enclose_xmin) enclose_height=tf.maximum(zero,enclose_ymax-enclose_ymin) enclose_area=enclose_width*enclose_height giou=iou-tf.math.divide_no_nan((enclose_area-union_area),enclose_area) returngiou Copylines Copypermalink Viewgitblame Referenceinnewissue Go Youcan’tperformthatactionatthistime. Yousignedinwithanothertaborwindow.Reloadtorefreshyoursession. Yousignedoutinanothertaborwindow.Reloadtorefreshyoursession.



請為這篇文章評分?