Skip to content
Projects
Groups
Snippets
Help
This project
Loading...
Sign in / Register
Toggle navigation
O
OvoTools
Project
Project
Details
Activity
Cycle Analytics
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Issues
0
Issues
0
List
Board
Labels
Milestones
Merge Requests
0
Merge Requests
0
CI / CD
CI / CD
Pipelines
Jobs
Schedules
Charts
Wiki
Wiki
Snippets
Snippets
Members
Members
Collapse sidebar
Close sidebar
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Open sidebar
林帅浩
OvoTools
Commits
21dc6361
Commit
21dc6361
authored
Apr 03, 2019
by
IlyaOvodov
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
FocalLoss
parent
68d5cadd
Show whitespace changes
Inline
Side-by-side
Showing
1 changed file
with
49 additions
and
0 deletions
+49
-0
pytorch_tools.py
ovotools/pytorch_tools.py
+49
-0
No files found.
ovotools/pytorch_tools.py
View file @
21dc6361
import
os
import
torch
import
torch.nn
as
nn
import
torch.nn.functional
as
F
import
numpy
as
np
class
DummyTimer
:
...
...
@@ -152,3 +154,50 @@ def save_model(model, params, rel_dir, filename):
dir_name
=
os
.
path
.
dirname
(
file_name
)
os
.
makedirs
(
dir_name
,
exist_ok
=
True
)
torch
.
save
(
model
.
state_dict
(),
file_name
)
class
FocalBceLoss
(
nn
.
Module
):
def
__init__
(
self
,
weight
=
1
,
gamma
=
2
,
logits
=
False
,
reduce
=
True
):
super
(
FocalBceLoss
,
self
)
.
__init__
()
self
.
weight
=
weight
self
.
gamma
=
gamma
self
.
logits
=
logits
self
.
reduce
=
reduce
def
forward
(
self
,
inputs
,
targets
):
if
self
.
logits
:
bce_loss
=
F
.
binary_cross_entropy_with_logits
(
inputs
,
targets
,
reduce
=
False
)
else
:
bce_loss
=
F
.
binary_cross_entropy
(
inputs
,
targets
,
reduce
=
False
)
pt
=
torch
.
exp
(
-
bce_loss
)
f_loss
=
self
.
weight
*
(
1
-
pt
)
**
self
.
gamma
*
bce_loss
if
self
.
reduce
:
return
torch
.
mean
(
f_loss
)
else
:
return
f_loss
class
FocalCeLoss
(
nn
.
Module
):
def
__init__
(
self
,
weight
=
None
,
gamma
=
2
,
logits
=
False
,
reduce
=
True
):
super
(
FocalCeLoss
,
self
)
.
__init__
()
self
.
weight
=
weight
self
.
gamma
=
gamma
self
.
logits
=
logits
self
.
reduce
=
reduce
def
forward
(
self
,
inputs
,
targets
):
if
self
.
logits
:
ce_loss
=
F
.
cross_entropy
(
inputs
,
targets
,
reduction
=
'none'
)
else
:
ce_loss
=
F
.
nll_loss
(
inputs
,
targets
,
reduction
=
'none'
)
pt
=
torch
.
exp
(
-
ce_loss
)
f_loss
=
(
1
-
pt
)
**
self
.
gamma
*
ce_loss
if
self
.
weight
is
not
None
:
weights
=
torch
.
index_select
(
self
.
weight
,
0
,
targets
.
view
(
-
1
))
.
view
(
targets
.
shape
)
f_loss
*=
weights
if
self
.
reduce
:
return
torch
.
mean
(
f_loss
)
else
:
return
f_loss
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment