Skip to content
Merged
Show file tree
Hide file tree
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
19 changes: 19 additions & 0 deletions tfjs-layers/src/activations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,25 @@ export class LogSoftmax extends Activation {
}
serialization.registerClass(LogSoftmax);

/**
* Swish activation function
*/
export class Swish extends Activation {
/** @nocollapse */
static readonly className = 'swish';
/**
* Calculate the activation function.
*
* @param x Tensor.
* @param alpha Scaling factor for the sigmoid function.
* @returns a Tensor of the same shape as x
*/
apply(x: Tensor, alpha = 1): Tensor {
return tidy(() => tfc.sigmoid(x.mul(alpha)).mul(x));
}
}
serialization.registerClass(Swish);

export function serializeActivation(activation: Activation): string {
return activation.getClassName();
}
Expand Down
35 changes: 34 additions & 1 deletion tfjs-layers/src/activations_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
*/
import {scalar, tensor1d, tensor2d, tensor3d} from '@tensorflow/tfjs-core';

import {Elu, HardSigmoid, Linear, LogSoftmax, Relu, Relu6, Selu, Sigmoid, Softmax, Softplus, Softsign, Tanh} from './activations';
import {Elu, HardSigmoid, Linear, LogSoftmax, Relu, Relu6, Selu, Sigmoid, Softmax, Softplus, Softsign, Tanh, Swish} from './activations';
import {describeMathCPUAndGPU, expectNoLeakedTensors, expectTensorsClose} from './utils/test_utils';

describeMathCPUAndGPU('linear activation', () => {
Expand Down Expand Up @@ -300,3 +300,36 @@ describeMathCPUAndGPU('logsoftmax activation', () => {
expectNoLeakedTensors(() => logsoftmax(initX), 1);
});
});

describeMathCPUAndGPU('swish activation', () => {
const swish = new Swish().apply;
// Setup: Array with initial values.
// Execute: Swish on the last dimension.
// Expect: Output array matches size and approximate expected values.
it('1D', () => {
const initX = tensor1d([0, 1, 3, 9]);
const expectedVals = tensor1d([0, .731, 2.857, 8.998]);
expectTensorsClose(swish(initX), expectedVals);
});
it('1D all equal', () => {
const initX = tensor1d([-1, -1, -1, -1]);
const expectedVals = tensor1d([-.268, -.268, -.268, -.268]);
expectTensorsClose(swish(initX), expectedVals);
});
it('2D', () => {
const initX = tensor2d([[0, 1, 3, 9], [0, 1, 3, 9]]);
const expectedVals = tensor2d(
[[0, .731, 2.857, 8.998], [0, .731, 2.857, 8.998]]);
expectTensorsClose(swish(initX), expectedVals);
});
it('3D', () => {
const initX = tensor3d([[[0, 1, 3, 9], [0, 1, 3, 9]]]);
const expectedVals = tensor3d(
[[[0, .731, 2.857, 8.998], [0, .731, 2.857, 8.998]]]);
expectTensorsClose(swish(initX), expectedVals);
});
it('Does not leak', () => {
const initX = tensor1d([0, 1, 3, 9]);
expectNoLeakedTensors(() => swish(initX), 1);
});
});