Python numpy.matrix() Examples

The following are 30 code examples for showing how to use numpy.matrix(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module numpy , or try the search function .

Example 1
Project: indras_net   Author: gcallah   File: fashion_markov_model.py    License: GNU General Public License v3.0 6 votes vote down vote up
def set_state(self, new_state):
        '''
        Set Hipster's new type.
        This comes from evaling the env.
        Args:
            new_state: the agent's new state
        Returns:
            None
        '''
        old_type = self.ntype
        self.state = new_state
        self.ntype = STATE_MAP[new_state]
        self.env.change_agent_type(self, old_type, self.ntype)
        # Unlike the forest fire model, we don't here update environment's cell's
        # transition matrices. This is because the cell's transition matrix depends
        # on all the agents near it, not just one. 
Example 2
Project: indras_net   Author: gcallah   File: zombie.py    License: GNU General Public License v3.0 6 votes vote down vote up
def get_pre(self, agent, n_census):

        trans_str = ""

        d, total = self.dir_info(agent)

        if type(agent) == Zombie:
            trans_str += self.zombie_trans(d, total)
        else:
            trans_str += self.human_trans(d, total)

        trans_matrix = markov.from_matrix(np.matrix(trans_str))
        return trans_matrix
       
    # Finds out which direction (NORTH, SOUTH, EAST, WEST) as more of the 
    # opposite agent type depending on what agent we are dealing with
    # CAN'T GET RID OF OLD METHOD OF MOVEMENT DUE TO ERRORS
    # IN OTHER SCRIPTS 
Example 3
Project: deep-learning-note   Author: wdxtub   File: 4_multi_classification.py    License: MIT License 6 votes vote down vote up
def predict_all(X, all_theta):
    rows = X.shape[0]
    params = X.shape[1]
    num_labels = all_theta.shape[0]
    
    # same as before, insert ones to match the shape
    X = np.insert(X, 0, values=np.ones(rows), axis=1)
    
    # convert to matrices
    X = np.matrix(X)
    all_theta = np.matrix(all_theta)
    
    # compute the class probability for each class on each training instance
    h = sigmoid(X * all_theta.T)
    
    # create array of the index with the maximum probability
    h_argmax = np.argmax(h, axis=1)
    
    # because our array was zero-indexed we need to add one for the true label prediction
    h_argmax = h_argmax + 1
    
    return h_argmax 
Example 4
Project: deep-learning-note   Author: wdxtub   File: 5_nueral_network.py    License: MIT License 6 votes vote down vote up
def cost0(params, input_size, hidden_size, num_labels, X, y, learning_rate):
    m = X.shape[0]
    X = np.matrix(X)
    y = np.matrix(y)
    
    # reshape the parameter array into parameter matrices for each layer
    theta1 = np.matrix(np.reshape(params[:hidden_size * (input_size + 1)], (hidden_size, (input_size + 1))))
    theta2 = np.matrix(np.reshape(params[hidden_size * (input_size + 1):], (num_labels, (hidden_size + 1))))
    
    # run the feed-forward pass
    a1, z2, a2, z3, h = forward_propagate(X, theta1, theta2)
    
    # compute the cost
    J = 0
    for i in range(m):
        first_term = np.multiply(-y[i,:], np.log(h[i,:]))
        second_term = np.multiply((1 - y[i,:]), np.log(1 - h[i,:]))
        J += np.sum(first_term - second_term)
    
    J = J / m
    
    return J 
Example 5
Project: deep-learning-note   Author: wdxtub   File: 9_anomaly_and_rec.py    License: MIT License 6 votes vote down vote up
def cost(params, Y, R, num_features):
    Y = np.matrix(Y)  # (1682, 943)
    R = np.matrix(R)  # (1682, 943)
    num_movies = Y.shape[0]
    num_users = Y.shape[1]
    
    # reshape the parameter array into parameter matrices
    X = np.matrix(np.reshape(params[:num_movies * num_features], (num_movies, num_features)))  # (1682, 10)
    Theta = np.matrix(np.reshape(params[num_movies * num_features:], (num_users, num_features)))  # (943, 10)
    
    # initializations
    J = 0
    
    # compute the cost
    error = np.multiply((X * Theta.T) - Y, R)  # (1682, 943)
    squared_error = np.power(error, 2)  # (1682, 943)
    J = (1. / 2) * np.sum(squared_error)
    
    return J 
Example 6
Project: deep-learning-note   Author: wdxtub   File: 3_logistic_regression.py    License: MIT License 6 votes vote down vote up
def gradientReg(theta, X, y, learningRate):
    theta = np.matrix(theta)
    X = np.matrix(X)
    y = np.matrix(y)
    
    parameters = int(theta.ravel().shape[1])
    grad = np.zeros(parameters)
    
    error = sigmoid(X * theta.T) - y
    
    for i in range(parameters):
        term = np.multiply(error, X[:,i])
        
        if (i == 0):
            grad[i] = np.sum(term) / len(X)
        else:
            grad[i] = (np.sum(term) / len(X)) + ((learningRate / len(X)) * theta[:,i])
    
    return grad 
Example 7
Project: pointnet-registration-framework   Author: vinits5   File: icp.py    License: MIT License 6 votes vote down vote up
def _icp_find_rigid_transform(p_from, p_target):
	######### flag = 1 for SVD 
	######### flag = 2 for Gaussian
	A, B = np.copy(p_from), np.copy(p_target)

	centroid_A = np.mean(A, axis=0)
	centroid_B = np.mean(B, axis=0)

	A -= centroid_A						# 500x3
	B -= centroid_B						# 500x3

	H = np.dot(A.T, B)					# 3x3
	# print(H)
	U, S, Vt = np.linalg.svd(H)
	# H_new = U*np.matrix(np.diag(S))*Vt
	# print(H_new)
	R = np.dot(Vt.T, U.T)

	# special reflection case
	if np.linalg.det(R) < 0:
		Vt[2,:] *= -1
		R = np.dot(Vt.T, U.T)
	t = np.dot(-R, centroid_A) + centroid_B
	return R, t 
Example 8
Project: controlpy   Author: markwmuller   File: synthesis.py    License: GNU General Public License v3.0 6 votes vote down vote up
def controller_lqr_discrete_from_continuous_time(A, B, Q, R, dt):
    """Solve the discrete time LQR controller for a continuous time system.
    
    A and B are system matrices, describing the systems dynamics:
     dx/dt = A x + B u
    
    The controller minimizes the infinite horizon quadratic cost function:
     cost = integral (x.T*Q*x + u.T*R*u) dt
    where Q is a positive semidefinite matrix, and R is positive definite matrix.
    
    The controller is implemented to run at discrete times, at a rate given by
     onboard_dt, 
    i.e. u[k] = -K*x(k*t)
    Discretization is done by zero order hold.
    
    Returns K, X, eigVals:
    Returns gain the optimal gain K, the solution matrix X, and the closed loop system eigenvalues.
    The optimal input is then computed as:
     input: u = -K*x
    """
    #ref Bertsekas, p.151
    
    Ad, Bd = analysis.discretise_time(A, B, dt)

    return controller_lqr_discrete_time(Ad, Bd, Q, R) 
Example 9
Project: tensortrade   Author: tensortrade-org   File: heston.py    License: Apache License 2.0 6 votes vote down vote up
def heston_construct_correlated_path(params: ModelParameters,
                                     brownian_motion_one: np.array):
    """
    This method is a simplified version of the Cholesky decomposition method
    for just two assets. It does not make use of matrix algebra and is therefore
    quite easy to implement.

    Arguments:
        params : ModelParameters
            The parameters for the stochastic model.
        brownian_motion_one : np.array
            (Not filled)

    Returns:
        A correlated brownian motion path.
    """
    # We do not multiply by sigma here, we do that in the Heston model
    sqrt_delta = np.sqrt(params.all_delta)
    # Construct a path correlated to the first path
    brownian_motion_two = []
    for i in range(params.all_time - 1):
        term_one = params.cir_rho * brownian_motion_one[i]
        term_two = np.sqrt(1 - pow(params.cir_rho, 2)) * random.normalvariate(0, sqrt_delta)
        brownian_motion_two.append(term_one + term_two)
    return np.array(brownian_motion_one), np.array(brownian_motion_two) 
Example 10
Project: DualFisheye   Author: ooterness   File: fisheye.py    License: MIT License 6 votes vote down vote up
def add_pixels(self, uv_px, img1d, weight=None):
        # Lookup row & column for each in-bounds coordinate.
        mask = self.get_mask(uv_px)
        xx = uv_px[0,mask]
        yy = uv_px[1,mask]
        # Update matrix according to assigned weight.
        if weight is None:
            img1d[mask] = self.img[yy,xx]
        elif np.isscalar(weight):
            img1d[mask] += self.img[yy,xx] * weight
        else:
            w1 = np.asmatrix(weight, dtype='float32')
            w3 = w1.transpose() * np.ones((1,3))
            img1d[mask] += np.multiply(self.img[yy,xx], w3[mask])


# A panorama image made from several FisheyeImage sources.
# TODO: Add support for supersampled anti-aliasing filters. 
Example 11
Project: DualFisheye   Author: ooterness   File: fisheye.py    License: MIT License 6 votes vote down vote up
def render_cubemap(self, out_size, mode='blend'):
        # Create coordinate arrays.
        cvec = np.arange(out_size, dtype='float32') - out_size/2        # Coordinate range [-S/2, S/2)
        vec0 = np.ones(out_size*out_size, dtype='float32') * out_size/2 # Constant vector +S/2
        vec1 = np.repeat(cvec, out_size)                                # Increment every N steps
        vec2 = np.tile(cvec, out_size)                                  # Sweep N times
        # Create XYZ coordinate vectors and render each cubemap face.
        render = lambda(xyz): self._render(xyz, out_size, out_size, mode)
        xm = render(np.matrix([-vec0, vec1, vec2]))     # -X face
        xp = render(np.matrix([vec0, vec1, -vec2]))     # +X face
        ym = render(np.matrix([-vec1, -vec0, vec2]))    # -Y face
        yp = render(np.matrix([vec1, vec0, vec2]))      # +Y face
        zm = render(np.matrix([-vec2, vec1, -vec0]))    # -Z face
        zp = render(np.matrix([vec2, vec1, vec0]))      # +Z face
        # Concatenate the individual faces in canonical order:
        # https://en.wikipedia.org/wiki/Cube_mapping#Memory_Addressing
        img_mat = np.concatenate([zp, zm, ym, yp, xm, xp], axis=0)
        return Image.fromarray(img_mat)

    # Get XYZ vectors for an equirectangular render, in raster order.
    # (Each row left to right, with rows concatenates from top to bottom.) 
Example 12
Project: DualFisheye   Author: ooterness   File: fisheye.py    License: MIT License 6 votes vote down vote up
def _get_equirectangular_raster(self, out_size):
        # Set image size (2x1 aspect ratio)
        rows = out_size
        cols = 2*out_size
        # Calculate longitude of each column.
        theta_x = np.linspace(-pi, pi, cols, endpoint=False, dtype='float32')
        cos_x = np.cos(theta_x).reshape(1,cols)
        sin_x = np.sin(theta_x).reshape(1,cols)
        # Calculate lattitude of each row.
        ystep = pi / rows
        theta_y = np.linspace(-pi/2 + ystep/2, pi/2 - ystep/2, rows, dtype='float32')
        cos_y = np.cos(theta_y).reshape(rows,1)
        sin_y = np.sin(theta_y).reshape(rows,1)
        # Calculate X, Y, and Z coordinates for each output pixel.
        x = cos_y * cos_x
        y = sin_y * np.ones((1,cols), dtype='float32')
        z = cos_y * sin_x
        # Vectorize the coordinates in raster order.
        xyz = np.matrix([x.ravel(), y.ravel(), z.ravel()])
        return [xyz, rows, cols]

    # Convert all lens parameters to a state vector. See also: optimize() 
Example 13
Project: indras_net   Author: gcallah   File: markov.py    License: GNU General Public License v3.0 5 votes vote down vote up
def create_iden_matrix(n):
    """
    Create a dim1 * dim2 identity matrix.

    Returns: the new matrix.
    """
    matrix_init = [[] for i in range(n)]
    for i in range(0, n): 
        for j in range(0, n): 
            if i == j:
                matrix_init[i].append(1)
            else:
                matrix_init[i].append(0)

    return np.matrix(matrix_init) 
Example 14
Project: indras_net   Author: gcallah   File: markov.py    License: GNU General Public License v3.0 5 votes vote down vote up
def state_vector(vlen, init_state):
    vals = ""
    for i in range(vlen):
        if i == init_state:
            vals = vals + "1 "
        else:
            vals = vals + "0 "
    return np.matrix(vals) 
Example 15
Project: indras_net   Author: gcallah   File: markov.py    License: GNU General Public License v3.0 5 votes vote down vote up
def from_matrix(m):
    """
    Takes an numpy matrix and returns a prehension.
    """
    pre = MarkovPre("")
    pre.matrix = m
    return pre 
Example 16
Project: indras_net   Author: gcallah   File: markov.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, str_matrix):
        """
        str_matrix is the matrix represented as a string in numpy fashion.
        """
        super().__init__()
        self.matrix = np.matrix(str_matrix) 
Example 17
Project: indras_net   Author: gcallah   File: markov.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __str__(self):
        return str(self.matrix) 
Example 18
Project: indras_net   Author: gcallah   File: markov.py    License: GNU General Public License v3.0 5 votes vote down vote up
def to_json(self):
        safe_fields = {}
        safe_fields["matrix"] = [str(self.matrix.dtype), base64.b64encode(self.matrix.A).decode('utf-8'), self.matrix.shape]
        
        return safe_fields 
Example 19
Project: indras_net   Author: gcallah   File: markov.py    License: GNU General Public License v3.0 5 votes vote down vote up
def from_json(self, json_input):
        # get the encoded json dump
        enc = json_input["matrix"]
        
        # build the numpy data type
        dataType = np.dtype(enc[0])
        
        # decode the base64 encoded numpy array data and create a new numpy array with this data & type
        dataArray = np.frombuffer(base64.decodestring(enc[1].encode('utf-8')), dataType)
        
        # if the array had more than one data set it has to be reshaped
        if len(enc) > 2:
             dataArray = dataArray.reshape(enc[2]) # return the reshaped numpy array containing several data sets
             
        self.matrix = np.matrix(dataArray) 
Example 20
Project: indras_net   Author: gcallah   File: fashion_markov_model.py    License: GNU General Public License v3.0 5 votes vote down vote up
def get_pre(self, agent, n_census):
        numRH = 0
        numBH = 0
        numRF = 0
        numBF = 0

        if(REDHIPSTER in n_census):
            numRH = n_census[REDHIPSTER]
        if(BLUEHIPSTER in n_census):
            numBH = n_census[BLUEHIPSTER]
        if(REDFOLLOWER in n_census):
            numRF = n_census[REDFOLLOWER]
        if(BLUEFOLLOWER in n_census):
            numBF = n_census[BLUEFOLLOWER]

        rh = self.influence(numRH, 5)
        bh = self.influence(numBH, 5)

        rf = self.influence(numRF, 5)
        bf = self.influence(numBF, 5)

        str_trans = ""
            # THE TRANSITION MATRIX
            # See documentation.
        str_trans += str(1 - rf) + " " + str(rf) + " 0 0;"
        str_trans += str(bf) + " " + str(1 - bf) + " 0 0;" 
        str_trans += "0 0 " + str(1 - bh) + " " + str(bh) + ";"
        str_trans += "0 0 " + str(rh) + " " + str(1 - rh)

        trans_matrix = markov.from_matrix(np.matrix(str_trans))
        return trans_matrix 
Example 21
Project: StructEngPy   Author: zhuoju36   File: __init__.py    License: MIT License 5 votes vote down vote up
def add_beam(self,node0,node1,E, mu, A, I2, I3, J, rho,check_dup=False):
        """
        add beam to model
        
        params: 
            node0,node1: hid of nodes.
            check_dup: boolean, if True and beam already exits, it will not be added.
        return: 
            beam hidden id
        """
        node0=self.nodes[node0]
        node1=self.nodes[node1]
        beam=Beam(node0,node1,E, mu, A, I2, I3, J, rho)
        if check_dup: #should use a matrix to check, to be revised.
            res=[a.hid for a in self.__beams.values() 
                if (a.nodes[0]==beam.nodes[0] and a.nodes[1]==beam.nodes[1]) 
                or (a.nodes[0]==beam.nodes[1] and a.nodes[1]==beam.nodes[0])]
        else:
            res=[]
        if res==[]:
            res=len(self.__beams)
            beam.hid=res
            self.__beams[res]=beam
        else:
            res=res[0]
        return res 
Example 22
Project: deep-learning-note   Author: wdxtub   File: 4_multi_classification.py    License: MIT License 5 votes vote down vote up
def cost(theta, X, y, learningRate):
    theta = np.matrix(theta)
    X = np.matrix(X)
    y = np.matrix(y)
    first = np.multiply(-y, np.log(sigmoid(X * theta.T)))
    second = np.multiply((1 - y), np.log(1 - sigmoid(X * theta.T)))
    reg = (learningRate / (2 * len(X))) * np.sum(np.power(theta[:,1:theta.shape[1]], 2))
    return np.sum(first - second) / len(X) + reg 
Example 23
Project: deep-learning-note   Author: wdxtub   File: 4_multi_classification.py    License: MIT License 5 votes vote down vote up
def gradient(theta, X, y, learningRate):
    theta = np.matrix(theta)
    X = np.matrix(X)
    y = np.matrix(y)
    
    parameters = int(theta.ravel().shape[1])
    error = sigmoid(X * theta.T) - y
    
    grad = ((X.T * error) / len(X)).T + ((learningRate / len(X)) * theta)
    
    # intercept gradient is not regularized
    grad[0, 0] = np.sum(np.multiply(error, X[:,0])) / len(X)
    
    return np.array(grad).ravel() 
Example 24
Project: deep-learning-note   Author: wdxtub   File: 8_kmeans_pca.py    License: MIT License 5 votes vote down vote up
def pca(X):
    # normalize the features
    X = (X - X.mean()) / X.std()
    
    # compute the covariance matrix
    X = np.matrix(X)
    cov = (X.T * X) / X.shape[0]
    
    # perform SVD
    U, S, V = np.linalg.svd(cov)
    
    return U, S, V 
Example 25
Project: deep-learning-note   Author: wdxtub   File: 2_linear_regression.py    License: MIT License 5 votes vote down vote up
def gradientDescent(X, y, theta, alpha, iters):
    temp = np.matrix(np.zeros(theta.shape))
    parameters = int(theta.ravel().shape[1])
    cost = np.zeros(iters)

    for i in range(iters):
        error = (X * theta.T) - y

        for j in range(parameters):
            term = np.multiply(error, X[:, j])
            temp[0,j] = theta[0,j] - ((alpha / len(X)) * np.sum(term))
        
        theta = temp
        cost[i] = computeCost(X, y, theta)
    return theta, cost 
Example 26
Project: deep-learning-note   Author: wdxtub   File: 9_anomaly_and_rec.py    License: MIT License 5 votes vote down vote up
def cost0(params, Y, R, num_features):
    Y = np.matrix(Y)  # (1682, 943)
    R = np.matrix(R)  # (1682, 943)
    num_movies = Y.shape[0]
    num_users = Y.shape[1]
    
    # reshape the parameter array into parameter matrices
    X = np.matrix(np.reshape(params[:num_movies * num_features], (num_movies, num_features)))  # (1682, 10)
    Theta = np.matrix(np.reshape(params[num_movies * num_features:], (num_users, num_features)))  # (943, 10)
    
    # initializations
    J = 0
    X_grad = np.zeros(X.shape)  # (1682, 10)
    Theta_grad = np.zeros(Theta.shape)  # (943, 10)
    
    # compute the cost
    error = np.multiply((X * Theta.T) - Y, R)  # (1682, 943)
    squared_error = np.power(error, 2)  # (1682, 943)
    J = (1. / 2) * np.sum(squared_error)
    
    # calculate the gradients
    X_grad = error * Theta
    Theta_grad = error.T * X
    
    # unravel the gradient matrices into a single array
    grad = np.concatenate((np.ravel(X_grad), np.ravel(Theta_grad)))
    
    return J, grad 
Example 27
Project: deep-learning-note   Author: wdxtub   File: 9_anomaly_and_rec.py    License: MIT License 5 votes vote down vote up
def cost1(params, Y, R, num_features, learning_rate):
    Y = np.matrix(Y)  # (1682, 943)
    R = np.matrix(R)  # (1682, 943)
    num_movies = Y.shape[0]
    num_users = Y.shape[1]
    
    # reshape the parameter array into parameter matrices
    X = np.matrix(np.reshape(params[:num_movies * num_features], (num_movies, num_features)))  # (1682, 10)
    Theta = np.matrix(np.reshape(params[num_movies * num_features:], (num_users, num_features)))  # (943, 10)
    
    # initializations
    J = 0
    X_grad = np.zeros(X.shape)  # (1682, 10)
    Theta_grad = np.zeros(Theta.shape)  # (943, 10)
    
    # compute the cost
    error = np.multiply((X * Theta.T) - Y, R)  # (1682, 943)
    squared_error = np.power(error, 2)  # (1682, 943)
    J = (1. / 2) * np.sum(squared_error)
    
    # add the cost regularization
    J = J + ((learning_rate / 2) * np.sum(np.power(Theta, 2)))
    J = J + ((learning_rate / 2) * np.sum(np.power(X, 2)))
    
    # calculate the gradients with regularization
    X_grad = (error * Theta) + (learning_rate * X)
    Theta_grad = (error.T * X) + (learning_rate * Theta)
    
    # unravel the gradient matrices into a single array
    grad = np.concatenate((np.ravel(X_grad), np.ravel(Theta_grad)))
    
    return J, grad 
Example 28
Project: deep-learning-note   Author: wdxtub   File: 3_logistic_regression.py    License: MIT License 5 votes vote down vote up
def gradient(theta, X, y):
    theta = np.matrix(theta)
    X = np.matrix(X)
    y = np.matrix(y)
    
    parameters = int(theta.ravel().shape[1])
    grad = np.zeros(parameters)
    
    error = sigmoid(X * theta.T) - y
    
    for i in range(parameters):
        term = np.multiply(error, X[:,i])
        grad[i] = np.sum(term) / len(X)
    
    return grad 
Example 29
Project: deep-learning-note   Author: wdxtub   File: 3_logistic_regression.py    License: MIT License 5 votes vote down vote up
def costReg(theta, X, y, learningRate):
    theta = np.matrix(theta)
    X = np.matrix(X)
    y = np.matrix(y)
    first = np.multiply(-y, np.log(sigmoid(X * theta.T)))
    second = np.multiply((1 - y), np.log(1 - sigmoid(X * theta.T)))
    reg = (learningRate / (2 * len(X))) * np.sum(np.power(theta[:,1:theta.shape[1]], 2))
    return np.sum(first - second) / len(X) + reg 
Example 30
Project: DOTA_models   Author: ringringyi   File: vecs.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, vocab_filename, rows_filename, cols_filename=None):
    """Initializes the vectors from a text vocabulary and binary data."""
    with open(vocab_filename, 'r') as lines:
      self.vocab = [line.split()[0] for line in lines]
      self.word_to_idx = {word: idx for idx, word in enumerate(self.vocab)}

    n = len(self.vocab)

    with open(rows_filename, 'r') as rows_fh:
      rows_fh.seek(0, os.SEEK_END)
      size = rows_fh.tell()

      # Make sure that the file size seems reasonable.
      if size % (4 * n) != 0:
        raise IOError(
            'unexpected file size for binary vector file %s' % rows_filename)

      # Memory map the rows.
      dim = size / (4 * n)
      rows_mm = mmap.mmap(rows_fh.fileno(), 0, prot=mmap.PROT_READ)
      rows = np.matrix(
          np.frombuffer(rows_mm, dtype=np.float32).reshape(n, dim))

      # If column vectors were specified, then open them and add them to the row
      # vectors.
      if cols_filename:
        with open(cols_filename, 'r') as cols_fh:
          cols_mm = mmap.mmap(cols_fh.fileno(), 0, prot=mmap.PROT_READ)
          cols_fh.seek(0, os.SEEK_END)
          if cols_fh.tell() != size:
            raise IOError('row and column vector files have different sizes')

          cols = np.matrix(
              np.frombuffer(cols_mm, dtype=np.float32).reshape(n, dim))

          rows += cols
          cols_mm.close()

      # Normalize so that dot products are just cosine similarity.
      self.vecs = rows / np.linalg.norm(rows, axis=1).reshape(n, 1)
      rows_mm.close()