0

The question seems dummy, but I cannot get it right. The output cm1 is expected to be floats, but I only get zeros and ones.

import numpy as np
import scipy.spatial.distance
sim  = scipy.spatial.distance.cosine
a = [2, 3, 1]
b = [3, 1, 2]
c = [1, 2, 6]
cm0 = np.array([a,b,c])
ca, cb, cc = 0.9, 0.7, 0.4 
cr = np.array([ca, cb, cc])
cm1 = np.empty_like(cm0)
for i in range(3):
    for j in range(3):
        cm1[i,j] = cm0[i,j] * cr[i] * cr[j]
print(cm1)

And I get:

[[1 1 0]
 [1 0 0]
 [0 0 0]]
user3015347
  • 503
  • 3
  • 12

2 Answers2

1

As @hpaulj said in the comments section, the problem is using empty_like which will keep the cm0 dtype, to solve it try:

cm1 = np.empty_like(cm0, dtype=float)
Pablo C
  • 4,661
  • 2
  • 8
  • 24
1

empty_like() matches the type of the given numpy array by default, as hpaulj suggested in the comments. In your case cm0 is of type integer.

The empty_like function accepts multiple arguments though, one of wich is dtype. Setting dtype to float should solve the problem:

cm1 = np.empty_like(cm0, dtype=float)

And also Python truncates floating point numbers at the decimal point when converting to integers. In your case, every multiplication done results in a number between 1.89 and 0.36, so flooring the results will result in 0s and 1s respectively.

Andy Sukowski-Bang
  • 1,402
  • 7
  • 20