Skip to content

Commit 6c4d9a8

Browse files
dataangelEsther2013
authored andcommitted
更新Mse
1 parent 0ff31a3 commit 6c4d9a8

4 files changed

Lines changed: 33 additions & 3 deletions

File tree

‎src/TensorFlowNET.Keras/Losses/ILossFunc.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,6 @@
33
public interface ILossFunc
44
{
55
string Reduction { get; }
6-
Tensor Call(Tensor y_true, Tensor y_pred);
6+
Tensor Call(Tensor y_true, Tensor y_pred, Tensor sample_weight = null);
77
}
88
}

‎src/TensorFlowNET.Keras/Losses/Loss.cs‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,10 +31,11 @@ public virtual Tensor Apply(Tensor y_true, Tensor y_pred, bool from_logits = fal
3131
throw new NotImplementedException("");
3232
}
3333

34-
public Tensor Call(Tensor y_true, Tensor y_pred)
34+
public Tensor Call(Tensor y_true, Tensor y_pred, Tensor sample_weight = null)
3535
{
3636
var losses = Apply(y_true, y_pred, from_logits: from_logits);
37-
return losses_utils.compute_weighted_loss(losses, reduction: ReductionV2.SUM_OVER_BATCH_SIZE);
37+
38+
return losses_utils.compute_weighted_loss(losses, reduction: this.reduction == null?ReductionV2.SUM_OVER_BATCH_SIZE : this.reduction, sample_weight: sample_weight);
3839
}
3940

4041
void _set_name_scope()

‎src/TensorFlowNET.Keras/Losses/LossesApi.cs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,5 +7,8 @@ public ILossFunc SparseCategoricalCrossentropy(bool from_logits = false)
77

88
public ILossFunc CategoricalCrossentropy(bool from_logits = false)
99
=> new CategoricalCrossentropy(from_logits: from_logits);
10+
11+
public ILossFunc MeanSquaredError(string reduction = null)
12+
=> new MeanSquaredError(reduction: reduction);
1013
}
1114
}
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Text;
4+
using static Tensorflow.Binding;
5+
using static Tensorflow.KerasApi;
6+
7+
namespace Tensorflow.Keras.Losses
8+
{
9+
public class MeanSquaredError : LossFunctionWrapper, ILossFunc
10+
{
11+
public MeanSquaredError(
12+
string reduction = ReductionV2.AUTO,
13+
string name = "mean_squared_error") :
14+
base(reduction: reduction,
15+
name: name)
16+
{
17+
}
18+
19+
public override Tensor Apply(Tensor y_true = null, Tensor y_pred =null, bool from_logits = false, int axis = -1)
20+
{
21+
Tensor y_pred_dispatch = ops.convert_to_tensor(y_pred);
22+
Tensor y_true_cast = gen_math_ops.cast(y_true, y_pred_dispatch.dtype);
23+
return gen_math_ops.mean(gen_math_ops.squared_difference(y_pred_dispatch, y_true_cast), axis: -1);
24+
}
25+
}
26+
}

0 commit comments

Comments
 (0)