1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363
| from __future__ import annotations from typing import Tuple import numpy as np
class CSRMatrix:
def __init__(self, indptr: np.ndarray, indices: np.ndarray, data: np.ndarray, shape: Tuple[int, int]) -> None:
self.indptr = indptr self.indices = indices self.data = data self.shape = shape
self.dtype = self.data.dtype
def toarray(self) -> np.ndarray: """Convert CSR matrix to Numpy array.
Returns: np.ndarray: Dense matrix. """
array = np.zeros(self.shape).astype(self.data.dtype) num_rows = self.shape[0] for i in range(num_rows): num_vals = self.indptr[i + 1] - self.indptr[i] for k in range(num_vals): val = self.data[self.indptr[i] + k] j = self.indices[self.indptr[i] + k] array[i][j] = val
return array
def transpose(self) -> CSRMatrix: """Transpose CSR matrix.
O(NlogN) where N is the number of non-zero values.
Returns: CSRMatrix: Transposed CSR matrix. """
col_2d_idx = self.indices
row_2d_idx = np.zeros_like(col_2d_idx) k = 0 num_rows = self.shape[0] for i in range(num_rows): num_vals = self.indptr[i + 1] - self.indptr[i] for j in range(num_vals): row_2d_idx[k + j] = i k += num_vals assert k == self.indptr[-1]
new_row_2d_idx = col_2d_idx new_col_2d_idx = row_2d_idx
ind = np.lexsort((new_col_2d_idx, new_row_2d_idx)) new_row_2d_idx = new_row_2d_idx[ind] new_col_2d_idx = new_col_2d_idx[ind]
indices = new_col_2d_idx data = self.data[ind] shape = (self.shape[1], self.shape[0]) num_rows = shape[0] indptr = np.zeros(num_rows + 1).astype(np.int32)
for i in new_row_2d_idx: indptr[i + 1] += 1
for i in range(num_rows): indptr[i + 1] += indptr[i]
indices = np.array(indices).astype(np.int32) data = np.array(data).astype(self.dtype)
csr_matrix = CSRMatrix(indptr=indptr, indices=indices, data=data, shape=shape) return csr_matrix
def append_csr_rows(self, row_mat: CSRMatrix) -> CSRMatrix: """Append an another CSR matrix.
Args: row_mat (CSRMatrix): Another CSR matrix that has the same width.
Returns: CSRMatrix: The resulted new CSR matrix. """
assert len(row_mat.shape) == 2 assert row_mat.shape[1] == self.shape[1] assert self.dtype == row_mat.dtype
data = np.append(self.data, row_mat.data) indices = np.append(self.indices, row_mat.indices) shape = (self.shape[0] + row_mat.shape[0], self.shape[1])
indptr = row_mat.indptr.copy() + self.indptr[-1] indptr = np.append(self.indptr[:-1], indptr)
csr_matrix = CSRMatrix(indptr=indptr, indices=indices, data=data, shape=shape) return csr_matrix
def get_csr_row(self, row: int) -> CSRMatrix: """Get one row as a CSR matrix.
Args: row (int): Row index.
Returns: CSRMatrix: Row CSR matrix. """
assert 0 <= row and row < self.shape[0]
data = self.data[self.indptr[row]:self.indptr[row + 1]] indices = self.indices[self.indptr[row]:self.indptr[row + 1]] indptr = self.indptr[row:row + 2] indptr = indptr - indptr[0] shape = (1, self.shape[1])
csr_matrix = CSRMatrix(indptr=indptr, indices=indices, data=data, shape=shape) return csr_matrix
def dot_vector_transposed(self, vec_transposed: CSRMatrix) -> CSRMatrix: """The dot product of the CSR matrix with another transposed vector CSR matrix.
Suppose the CSR matrix is of shape [A, B], the transposed vector CSR matrix should be of shape [1, B]. The resulted dot product transposed CSR matrix is of shape [1, B].
O(MN) where M is the non-zero values in the CSR matrix and N is the number of non-zero values in the vector CSR matrix.
Args: vec_transposed (CSRMatrix): The vector CSR matrix which has been transposed.
Returns: CSRMatrix: The resulted CSR matrix. """
assert len(vec_transposed.shape) == 2 assert vec_transposed.shape[1] == self.shape[1] assert vec_transposed.shape[0] == 1
num_vals_vec = vec_transposed.indptr[-1] - vec_transposed.indptr[0]
num_rows = self.shape[0] shape = (1, num_rows) indptr = np.zeros(2).astype(np.int32) indices = [] data = []
for i in range(num_rows): num_vals_matrix = self.indptr[i + 1] - self.indptr[i]
idx_1 = 0 idx_2 = 0
val = 0 while idx_1 < num_vals_matrix and idx_2 < num_vals_vec: if self.indices[self.indptr[i] + idx_1] == vec_transposed.indices[idx_2]: val += self.data[self.indptr[i] + idx_1] * vec_transposed.data[idx_2] idx_1 += 1 idx_2 += 1 elif self.indices[self.indptr[i] + idx_1] < vec_transposed.indices[idx_2]: idx_1 += 1 else: idx_2 += 1
if val != 0: data.append(val) indices.append(i)
indices = np.array(indices).astype(np.int32) data = np.array(data).astype( np.result_type(self.dtype, vec_transposed.dtype)) indptr[-1] = len(data)
csr_vec_transposed = CSRMatrix(indptr=indptr, indices=indices, data=data, shape=shape)
return csr_vec_transposed
def dot_matrix_transposed(self, mat_transposed: CSRMatrix) -> CSRMatrix: """The dot product of the CSR matrix with another transposed CSR matrix.
O(MN) where M is the non-zero values in the CSR matrix and N is the number of non-zero values in the another transposed CSR matrix.
Args: mat_transposed (CSRMatrix): Another transposed CSR matrix.
Returns: CSRMatrix: The resulted CSR matrix. """
assert len(mat_transposed.shape) == 2 assert mat_transposed.shape[1] == self.shape[1]
num_rows = self.shape[0] shape = (mat_transposed.shape[0], num_rows)
row_vec = mat_transposed.get_csr_row(row=0) csr_mat_transposed = self.dot_vector_transposed(vec_transposed=row_vec)
for i in range(1, shape[0]): row_vec = mat_transposed.get_csr_row(row=i) product_row_vec = self.dot_vector_transposed( vec_transposed=row_vec) csr_mat_transposed = csr_mat_transposed.append_csr_rows( row_mat=product_row_vec)
return csr_mat_transposed
def dot_vector(self, vec: CSRMatrix) -> CSRMatrix: """The dot product of the CSR matrix with another vector CSR matrix.
Args: vec (CSRMatrix): Another vector CSR matrix.
Returns: CSRMatrix: The resulted CSR matrix. """
assert len(vec.shape) == 2 assert vec.shape[0] == self.shape[1] assert vec.shape[1] == 1
vec_transposed = vec.transpose()
csr_vector_transposed = self.dot_vector_transposed( vec_transposed=vec_transposed)
csr_vector = csr_vector_transposed.transpose()
return csr_vector
def dot_matrix(self, mat: CSRMatrix) -> CSRMatrix: """The dot product of the CSR matrix with another CSR matrix.
O(MN) where M is the non-zero values in the CSR matrix and N is the number of non-zero values in the another SR matrix.
Args: mat (CSRMatrix): Another CSR matrix.
Returns: CSRMatrix: The resulted CSR matrix. """
assert len(mat.shape) == 2 assert mat.shape[0] == self.shape[1]
mat_transposed = mat.transpose()
csr_mat_transposed = self.dot_matrix_transposed( mat_transposed=mat_transposed)
csr_mat = csr_mat_transposed.transpose()
return csr_mat
def create_csr_matrix_from_dense_matrix(dense_matrix: np.ndarray) -> CSRMatrix: """Create a CSR matrix from a dense matrix.
Args: dense_matrix (np.ndarray): Dense matrix.
Returns: CSRMatrix: The resulted CSR matrix. """
shape = dense_matrix.shape assert len(shape) == 2 num_rows = shape[0] num_cols = shape[1] indptr = np.zeros(num_rows + 1).astype(np.int32) indices = [] data = [] for i in range(num_rows): for j in range(num_cols): if dense_matrix[i][j] != 0: data.append(dense_matrix[i][j]) indices.append(j) indptr[i + 1] = len(indices) indices = np.array(indices).astype(np.int32) data = np.array(data).astype(dense_matrix.dtype) csr_matrix = CSRMatrix(indptr=indptr, indices=indices, data=data, shape=shape) return csr_matrix
def create_random_matrix(shape: Tuple[int, int]) -> np.ndarray: """Create random matrix.
Args: shape (Tuple[int, int]): Matrix shape.
Returns: np.ndarray: Resulted random matrix. """
matrix = np.random.randint(low=1, high=100, size=shape)
return matrix
if __name__ == "__main__":
num_tests = 100 np.random.seed(0)
for _ in range(num_tests):
a = np.random.randint(low=1, high=20) b = np.random.randint(low=1, high=20) c = np.random.randint(low=1, high=20) mat_1 = create_random_matrix(shape=(a, b)) mat_2 = create_random_matrix(shape=(b, c)) mat_3 = mat_1.dot(mat_2)
csr_mat_1 = create_csr_matrix_from_dense_matrix(dense_matrix=mat_1) csr_mat_2 = create_csr_matrix_from_dense_matrix(dense_matrix=mat_2) csr_mat_3 = csr_mat_1.dot_matrix(csr_mat_2)
assert np.array_equal(mat_3, csr_mat_3.toarray())
|