@@ -23,24 +23,29 @@ ctypedef np.float64_t DOUBLE
23
23
24
24
def csr_row_norms (X ):
25
25
""" L2 norm of each row in CSR matrix X."""
26
+ if X.dtype != np.float32:
27
+ X = X.astype(np.float64)
28
+ return _csr_row_norms(X.data, X.shape, X.indices, X.indptr)
29
+
30
+
31
+ def _csr_row_norms (np.ndarray[floating , ndim = 1 , mode = " c" ] X_data,
32
+ shape ,
33
+ np.ndarray[int , ndim = 1 , mode = " c" ] X_indices,
34
+ np.ndarray[int , ndim = 1 , mode = " c" ] X_indptr):
26
35
cdef:
27
- unsigned int n_samples = X. shape[0 ]
28
- unsigned int n_features = X. shape[1 ]
36
+ unsigned int n_samples = shape[0 ]
37
+ unsigned int n_features = shape[1 ]
29
38
np.ndarray[DOUBLE, ndim= 1 , mode= " c" ] norms
30
- np.ndarray[DOUBLE, ndim= 1 , mode= " c" ] data
31
- np.ndarray[int , ndim= 1 , mode= " c" ] indices = X.indices
32
- np.ndarray[int , ndim= 1 , mode= " c" ] indptr = X.indptr
33
39
34
40
np.npy_intp i, j
35
41
double sum_
36
42
37
43
norms = np.zeros(n_samples, dtype = np.float64)
38
- data = np.asarray(X.data, dtype = np.float64) # might copy!
39
44
40
45
for i in range (n_samples):
41
46
sum_ = 0.0
42
- for j in range (indptr [i], indptr [i + 1 ]):
43
- sum_ += data [j] * data [j]
47
+ for j in range (X_indptr [i], X_indptr [i + 1 ]):
48
+ sum_ += X_data [j] * X_data [j]
44
49
norms[i] = sum_
45
50
46
51
return norms
0 commit comments