Skip to content

Commit

Permalink
Fix clamp bug when min = max (#6825)
Browse files Browse the repository at this point in the history
Co-authored-by: Ping Yu <[email protected]>
  • Loading branch information
ahmedsabie and pyu10055 authored Sep 12, 2022
1 parent 0b40a7d commit f8165e2
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 0 deletions.
5 changes: 5 additions & 0 deletions tfjs-core/src/ops/clip_by_value.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import {NamedTensorMap} from '../tensor_types';
import {convertToTensor} from '../tensor_util_env';
import {TensorLike} from '../types';
import * as util from '../util';
import {fill} from './fill';

import {op} from './operation';

Expand All @@ -47,6 +48,10 @@ function clipByValue_<T extends Tensor>(
() => `Error in clip: min (${clipValueMin}) must be ` +
`less than or equal to max (${clipValueMax}).`);

if (clipValueMin === clipValueMax) {
return fill($x.shape, clipValueMin, $x.dtype) as T;
}

const inputs: ClipByValueInputs = {x: $x};
const attrs: ClipByValueAttrs = {clipValueMin, clipValueMax};

Expand Down
8 changes: 8 additions & 0 deletions tfjs-core/src/ops/clip_by_value_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,14 @@ describeWithFlags('clipByValue', ALL_ENVS, () => {
expect(res[1]).toBeCloseTo(max);
});

it('clip min = max', async () => {
const min = 2;
const max = 2;
const tensor = tf.tensor([1, 2, 3, 4, 5], [5], 'float32');
const result = tf.clipByValue(tensor, min, max);
expectArraysClose(await result.data(), [2, 2, 2, 2, 2]);
});

it('throws for string tensor', () => {
expect(() => tf.clipByValue('q', 0, 1))
.toThrowError(/Argument 'x' passed to 'clipByValue' must be numeric/);
Expand Down

0 comments on commit f8165e2

Please sign in to comment.