Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Truncated-Normal Operation #1015

Merged
merged 4 commits into from
Jun 12, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion api/src/main/java/ai/djl/ndarray/BaseNDManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
import ai.djl.ndarray.types.DataType;
import ai.djl.ndarray.types.Shape;
import ai.djl.util.PairList;
import ai.djl.util.RandomUtils;
import java.nio.Buffer;
import java.nio.file.Path;
import java.util.UUID;
Expand Down Expand Up @@ -156,7 +157,19 @@ public NDArray randomNormal(float loc, float scale, Shape shape, DataType dataTy
/** {@inheritDoc} */
@Override
public NDArray truncatedNormal(float loc, float scale, Shape shape, DataType dataType) {
throw new UnsupportedOperationException("Not supported!");
int sampleSize = (int) shape.size();
double[] dist = new double[sampleSize];

for (int i = 0; i < sampleSize; i++) {
double sample = RandomUtils.nextGaussian();
while (sample < -2 || sample > 2) {
sample = RandomUtils.nextGaussian();
}

dist[i] = sample;
}

return create(dist).addi(loc).muli(scale).reshape(shape).toType(dataType, false);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@AzizZayed I think you need to multiply before you add. Otherwise, it will scale the addition too.

}

/** {@inheritDoc} */
Expand Down