DickNixon
DickNixon

Reputation: 151

How do I scale a Tensor column by a constant value?

I need to scale certain columns of a tensor by a constant value, but I've got no idea how to approach this with Keras/Tensorflow. I've got a (BatchSize, 6) matrix, and I need to multiply column 2 by one constant and column 5 by another constant.

I tried making a Lambda that multiplied the columns using sliced indexes, but TF returned an error about not being able to assign values to the result.

e.g.

x[:,2] *= constant

Any suggestions?

Upvotes: 0

Views: 698

Answers (1)

Vlad
Vlad

Reputation: 8595

Just multiply it by a tensor of ones and constants at the desired column locations. For example:

import tensorflow as tf
import numpy as np

x = tf.placeholder(tf.float32, (None, 6))

const1 = 5.
const2 = 3.
scaler = tf.constant([1, 1, const1, 1, 1, const2], dtype=tf.float32)
res = x*scaler

x_data = np.ones((3, 6))
with tf.Session() as sess:
    print(res.eval({x:x_data}))
# [[1. 1. 5. 1. 1. 3.]
#  [1. 1. 5. 1. 1. 3.]
#  [1. 1. 5. 1. 1. 3.]]

Upvotes: 1

Related Questions