Python numpy.mat() Examples

The following are 30 code examples for showing how to use numpy.mat(). 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: python-control   Author: python-control   File: matlab_test.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def testDamp(self):
        A = np.mat('''-0.2  0.06 0    -1;
               0    0    1     0;
             -17    0   -3.8   1;
               9.4  0   -0.4  -0.6''')
        B = np.mat('''-0.01  0.06;
               0     0;
             -32     5.4;
               2.6  -7''')
        C = np.eye(4)
        D = np.zeros((4,2))
        sys = ss(A, B, C, D)
        wn, Z, p = damp(sys, False)
        # print (wn)
        np.testing.assert_array_almost_equal(
            wn, np.array([4.07381994,   3.28874827,   3.28874827,
                          1.08937685e-03]))
        np.testing.assert_array_almost_equal(
            Z, np.array([1.0, 0.07983139,  0.07983139, 1.0])) 
Example 2
Project: python-control   Author: python-control   File: matlab_test.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def testConnect2(self):
        sys = append(ss([[-5, -2.25], [4, 0]], [[2], [0]],
                          [[0, 1.125]], [[0]]),
                       ss([[-1.6667, 0], [1, 0]], [[2], [0]],
                          [[0, 3.3333]], [[0]]),
                       1)
        Q = [ [ 1, 3], [2, 1], [3, -2]]
        sysc = connect(sys, Q, [3], [3, 1, 2])
        np.testing.assert_array_almost_equal(
            sysc.A, np.mat([[-5, -2.25, 0, -6.6666],
                            [4, 0, 0, 0],
                            [0, 2.25, -1.6667, 0],
                            [0, 0, 1, 0]]))
        np.testing.assert_array_almost_equal(
            sysc.B, np.mat([[2], [0], [0], [0]]))
        np.testing.assert_array_almost_equal(
            sysc.C, np.mat([[0, 0, 0, -3.3333],
                            [0, 1.125, 0, 0],
                            [0, 0, 0, 3.3333]]))
        np.testing.assert_array_almost_equal(
            sysc.D, np.mat([[1], [0], [0]])) 
Example 3
Project: Jtyoui   Author: jtyoui   File: lr.py    License: MIT License 6 votes vote down vote up
def lr_train_bgd(feature: np.array, label: np.array, max_cycle: int, alpha: float) -> np.mat:
    """利用梯度下降法训练逻辑回归模型(LR)

    :param feature: 特征
    :param label: 标签
    :param max_cycle: 最大迭代次数
    :param alpha: 学习率
    :return: w的权重
    """
    n = np.shape(feature)[1]  # 特征个数
    w = np.random.rand(n).reshape((n, 1))  # 随机初始化权重
    i = 0
    while i <= max_cycle:
        i += 1
        h = sigmoid(np.dot(feature, w))  # 做点乘,计算sigmoid值
        err = label - h  # 误差
        if i % 100 == 0:
            print(f'error rate: {error_rate(h, label)}')
        w += alpha * np.dot(feature.T, err)  # wi+ 1= wi+ α·d 梯度下降进行权重修正

    return w 
Example 4
Project: twitchslam   Author: geohot   File: helpers.py    License: MIT License 6 votes vote down vote up
def fundamentalToRt(F):
  W = np.mat([[0,-1,0],[1,0,0],[0,0,1]],dtype=float)
  U,d,Vt = np.linalg.svd(F)
  if np.linalg.det(U) < 0:
    U *= -1.0
  if np.linalg.det(Vt) < 0:
    Vt *= -1.0
  R = np.dot(np.dot(U, W), Vt)
  if np.sum(R.diagonal()) < 0:
    R = np.dot(np.dot(U, W.T), Vt)
  t = U[:, 2]

  # TODO: Resolve ambiguities in better ways. This is wrong.
  if t[2] < 0:
    t *= -1
  
  # TODO: UGLY!
  if os.getenv("REVERSE") is not None:
    t *= -1
  return np.linalg.inv(poseRt(R, t)) 
Example 5
Project: calfem-python   Author: CALFEM   File: core.py    License: MIT License 6 votes vote down vote up
def bar2e(ex,ey,ep):
    """
    Compute the element stiffness matrix for two dimensional bar element.
    
    :param list ex: element x coordinates [x1, x2]
    :param list ey: element y coordinates [y1, y2]
    :param list ep: [E, A]: E - Young's modulus, A - Cross section area
    :return mat Ke: stiffness matrix, [4 x 4]
    """
    E=ep[0]
    A=ep[1]
    
    b = np.mat([[ex[1]-ex[0]],[ey[1]-ey[0]]])
    L = np.asscalar(np.sqrt(b.T*b))
    
    Kle = np.mat([[1.,-1.],[-1.,1.]])*E*A/L
    
    n = np.asarray(b.T/L).reshape(2,)
    
    G = np.mat([
        [n[0],n[1],0.,0.],
        [0.,0.,n[0],n[1]]
    ])
    
    return G.T*Kle*G 
Example 6
Project: nussl   Author: nussl   File: duet.py    License: MIT License 6 votes vote down vote up
def _compute_spectrogram(self, sample_rate):
        """ Creates the STFT matrices for channel 0 and 1, and computes the frequency matrix.
        Parameter:
            sample_rate (integer): sample rate

        Returns:
            stft_ch0 (np.matrix): a 2D Numpy matrix containing the stft of channel 0
            stft_ch1 (np.matrix): a 2D Numpy matrix containing the stft of channel 1
            wmat (np.matrix): a 2D Numpy matrix containing the frequencies of analysis of the Fourier transform
        """

        # Compute the stft of the two channel mixtures
        self.audio_signal.stft_params = self.stft_params
        self.audio_signal.stft()

        stft_ch0 = self.audio_signal.get_stft_channel(0)
        stft_ch1 = self.audio_signal.get_stft_channel(1)

        # Compute the freq. matrix for later use in phase calculations
        n_time_bins = len(self.audio_signal.time_bins_vector)
        wmat = np.array(np.tile(np.mat(
            self.audio_signal.freq_vector).T, (1, n_time_bins))) * (
            2 * np.pi / sample_rate)
        wmat += constants.EPSILON
        return stft_ch0, stft_ch1, wmat 
Example 7
Project: Broad-Learning-System   Author: LiangjunFeng   File: bls_enhence.py    License: MIT License 6 votes vote down vote up
def fit(self,oridata,orilabel):
        if self._batchsize == 'auto':
            self._batchsize = oridata.shape[1]
        data = self.normalscaler.fit_transform(oridata)
        label = self.onehotencoder.fit_transform(np.mat(orilabel).T)
        
        mappingdata = self.mapping_generator.generator_nodes(data,self._maptimes,self._batchsize,self._map_function)
        enhencedata = self.enhence_generator.generator_nodes(mappingdata,self._enhencetimes,self._batchsize,self._enhence_function)
        inputdata = np.column_stack((mappingdata,enhencedata))
        
        self.pesuedoinverse = self.pinv(inputdata)
        self.W =  self.pesuedoinverse.dot(label)
        
        Y = self.predict(oridata)
        accuracy, i = self.accuracy(Y,orilabel),0
        print("inital setting, number of mapping nodes {0}, number of enhence nodes {1}, accuracy {2}".format(mappingdata.shape[1],enhencedata.shape[1],round(accuracy,5)))
        
        while i < self._traintimes and accuracy < self._acc:
            Y = self.addingenhence_predict(data, label, self._step,self._batchsize)  
            accuracy = self.accuracy(Y,orilabel)
            i += 1
            print("enhencing {3}, number of mapping nodes {0}, number of enhence nodes {1}, accuracy {2}".format(len(self.mapping_generator.Wlist)*self._batchsize,len(self.enhence_generator.Wlist)*self._batchsize,round(accuracy,5),i)) 
Example 8
Project: Broad-Learning-System   Author: LiangjunFeng   File: bls_enhence.py    License: MIT License 6 votes vote down vote up
def addingenhence_nodes(self, data, label, step = 1, batchsize = 'auto'):
        if batchsize == 'auto':
            batchsize = data.shape[1]
            
        mappingdata = self.mapping_generator.transform(data)
        inputdata = self.transform(data)         
        localenhence_generator = node_generator()
        extraenhence_nodes = localenhence_generator.generator_nodes(mappingdata,step,batchsize,self._enhence_function)
            
        D = self.pesuedoinverse.dot(extraenhence_nodes)
        C = extraenhence_nodes - inputdata.dot(D)
        BT = self.pinv(C) if (C == 0).any() else  np.mat((D.T.dot(D)+np.eye(D.shape[1]))).I.dot(D.T).dot(self.pesuedoinverse)
        
        self.W = np.row_stack((self.W-D.dot(BT).dot(label),BT.dot(label))) 
        self.enhence_generator.update(localenhence_generator.Wlist,localenhence_generator.blist)
        self.pesuedoinverse =  np.row_stack((self.pesuedoinverse - D.dot(BT),BT)) 
Example 9
Project: Broad-Learning-System   Author: LiangjunFeng   File: bls_enhmap.py    License: MIT License 6 votes vote down vote up
def adding_nodes(self, data, label, mapstep = 1, enhencestep = 1, batchsize = 'auto'):
        if batchsize == 'auto':
            batchsize = data.shape[1]
        
        mappingdata = self.mapping_generator.transform(data)        
        inputdata = self.transform(data) 
        
        localmap_generator = node_generator()
        extramap_nodes = localmap_generator.generator_nodes(data,mapstep,batchsize,self._map_function)
        localenhence_generator = node_generator()
        extraenh_nodes = localenhence_generator.generator_nodes(mappingdata,enhencestep,batchsize,self._map_function)
        extra_nodes = np.column_stack((extramap_nodes,extraenh_nodes))
        
        D = self.pesuedoinverse.dot(extra_nodes)
        C = extra_nodes - inputdata.dot(D)
        BT = self.pinv(C) if (C == 0).any() else  np.mat((D.T.dot(D)+np.eye(D.shape[1]))).I.dot(D.T).dot(self.pesuedoinverse)
        
        self.W = np.row_stack((self.W-D.dot(BT).dot(label),BT.dot(label))) 
        self.pesuedoinverse =  np.row_stack((self.pesuedoinverse - D.dot(BT),BT)) 
        self.local_mapgeneratorlist.append(localmap_generator)
        self.local_enhgeneratorlist.append(localenhence_generator) 
Example 10
Project: Broad-Learning-System   Author: LiangjunFeng   File: bls_mapping.py    License: MIT License 6 votes vote down vote up
def fit(self,oridata,orilabel):
        if self._batchsize == 'auto':
            self._batchsize = oridata.shape[1]
        data = self.normalscaler.fit_transform(oridata)
        label = self.onehotencoder.fit_transform(np.mat(orilabel).T)
        
        mappingdata = self.mapping_generator.generator_nodes(data,self._maptimes,self._batchsize,self._map_function)
        enhencedata = self.enhence_generator.generator_nodes(mappingdata,self._enhencetimes,self._batchsize,self._enhence_function)
        inputdata = np.column_stack((mappingdata,enhencedata))
        
        self.pesuedoinverse = self.pinv(inputdata)
        self.W =  self.pesuedoinverse.dot(label)
        
        Y = self.predict(oridata)
        accuracy, i = self.accuracy(Y,orilabel),0
        print("inital setting, number of mapping nodes {0}, number of enhence nodes {1}, accuracy {2}".format(mappingdata.shape[1],enhencedata.shape[1],round(accuracy,5)))
        
        while i < self._traintimes and accuracy < self._acc:
            Y = self.addingmap_predict(data, label, self._step,self._batchsize)  
            accuracy = self.accuracy(Y,orilabel)
            i += 1
            print("mapping {3}, number of mapping nodes {0}, number of enhence nodes {1}, accuracy {2}".format((len(self.mapping_generator.Wlist)+len(self.local_mapgeneratorlist)*len(self.local_mapgeneratorlist[0].Wlist))*self._batchsize,len(self.enhence_generator.Wlist)*self._batchsize,round(accuracy,5),i)) 
Example 11
Project: Broad-Learning-System   Author: LiangjunFeng   File: bls.py    License: MIT License 6 votes vote down vote up
def fit(self,data,label):
        if self._batchsize == 'auto':
            self._batchsize = data.shape[1]
        data = self.normalscaler.fit_transform(data)
        label = self.onehotencoder.fit_transform(np.mat(label).T)
        
        mappingdata = self.mapping_generator.generator_nodes(data,self._maptimes,self._batchsize,self._map_function)
        enhencedata = self.enhence_generator.generator_nodes(mappingdata,self._enhencetimes,self._batchsize,self._enhence_function)
        
        print('number of mapping nodes {0}, number of enhence nodes {1}'.format(mappingdata.shape[1],enhencedata.shape[1]))
        print('mapping nodes maxvalue {0} minvalue {1} '.format(round(np.max(mappingdata),5),round(np.min(mappingdata),5)))
        print('enhence nodes maxvalue {0} minvalue {1} '.format(round(np.max(enhencedata),5),round(np.min(enhencedata),5)))
        
        inputdata = np.column_stack((mappingdata,enhencedata))
        pesuedoinverse = self.pinv(inputdata,self._reg)
        self.W =  pesuedoinverse.dot(label) 
Example 12
Project: Broad-Learning-System   Author: LiangjunFeng   File: bls_addinput.py    License: MIT License 6 votes vote down vote up
def fit(self,oridata,orilabel):
        if self._batchsize == 'auto':
            self._batchsize = oridata.shape[1]
        data = self.normalscaler.fit_transform(oridata)
        label = self.onehotencoder.fit_transform(np.mat(orilabel).T)
        
        mappingdata = self.mapping_generator.generator_nodes(data,self._maptimes,self._batchsize,self._map_function)
        enhencedata = self.enhence_generator.generator_nodes(mappingdata,self._enhencetimes,self._batchsize,self._enhence_function)
        inputdata = np.column_stack((mappingdata,enhencedata))
        
        self.pesuedoinverse = self.pinv(inputdata)
        self.W =  self.pesuedoinverse.dot(label)
        
        Y = self.predict(oridata)
        accuracy, i = self.accuracy(Y,orilabel),0
#        print("inital setting, number of mapping nodes {0}, number of enhence nodes {1}, accuracy {2}".format(mappingdata.shape[1],enhencedata.shape[1],round(accuracy,5)))
        
        while i < self._traintimes and accuracy < self._acc:
            Y = self.adding_predict(oridata, orilabel, self._mapstep, self._enhencestep, self._batchsize)  
            accuracy = self.accuracy(Y,orilabel)
            i += 1
#            print("adding {3}, number of mapping nodes {0}, number of enhence nodes {1}, accuracy {2}".format((len(self.mapping_generator.Wlist)+len(self.local_mapgeneratorlist)*len(self.local_mapgeneratorlist[0].Wlist))*self._batchsize,(len(self.enhence_generator.Wlist)+len(self.local_enhgeneratorlist)*len(self.local_enhgeneratorlist[0].Wlist))*self._batchsize,round(accuracy,5),i)) 
Example 13
Project: Broad-Learning-System   Author: LiangjunFeng   File: bls_addinput.py    License: MIT License 6 votes vote down vote up
def adding_nodes(self, data, label, mapstep = 1, enhencestep = 1, batchsize = 'auto'):
        if batchsize == 'auto':
            batchsize = data.shape[1]
        
        mappingdata = self.mapping_generator.transform(data)        
        inputdata = self.transform(data) 
        
        localmap_generator = node_generator()
        extramap_nodes = localmap_generator.generator_nodes(data,mapstep,batchsize,self._map_function)
        localenhence_generator = node_generator()
        extraenh_nodes = localenhence_generator.generator_nodes(mappingdata,enhencestep,batchsize,self._map_function)
        extra_nodes = np.column_stack((extramap_nodes,extraenh_nodes))
        
        D = self.pesuedoinverse.dot(extra_nodes)
        C = extra_nodes - inputdata.dot(D)
        BT = self.pinv(C) if (C == 0).any() else  np.mat((D.T.dot(D)+np.eye(D.shape[1]))).I.dot(D.T).dot(self.pesuedoinverse)
        
        self.W = np.row_stack((self.W-D.dot(BT).dot(label),BT.dot(label))) 
        self.pesuedoinverse =  np.row_stack((self.pesuedoinverse - D.dot(BT),BT)) 
        self.local_mapgeneratorlist.append(localmap_generator)
        self.local_enhgeneratorlist.append(localenhence_generator) 
Example 14
Project: cryptotrader   Author: naripok   File: risk.py    License: MIT License 6 votes vote down vote up
def polar_returns(ret, k):
    """
    Calculate polar return
    :param obs: pandas DataFrame
    :return: return radius, return angles
    """
    ret= np.mat(ret)
    # Find the radius and the angle decomposition on price relative vectors
    radius = np.linalg.norm(ret, ord=1, axis=1)
    angle = np.divide(ret, np.mat(radius).T)

    # Select the 'window' greater values on the observation
    index = np.argpartition(radius, -(int(ret.shape[0] * k) + 1))[-(int(ret.shape[0] * k) + 1):]
    index = index[np.argsort(radius[index])]

    # Return the radius and the angle for extreme found values
    return radius[index][::-1], angle[index][::-1]


# Pareto Extreme Risk Index 
Example 15
Project: HGNN   Author: iMoonLab   File: hypergraph_utils.py    License: MIT License 6 votes vote down vote up
def Eu_dis(x):
    """
    Calculate the distance among each raw of x
    :param x: N X D
                N: the object number
                D: Dimension of the feature
    :return: N X N distance matrix
    """
    x = np.mat(x)
    aa = np.sum(np.multiply(x, x), 1)
    ab = x * x.T
    dist_mat = aa + aa.T - 2 * ab
    dist_mat[dist_mat < 0] = 0
    dist_mat = np.sqrt(dist_mat)
    dist_mat = np.maximum(dist_mat, dist_mat.T)
    return dist_mat 
Example 16
Project: Pose2Seg   Author: liruilong940607   File: transforms.py    License: MIT License 6 votes vote down vote up
def get_affine_matrix(center, angle, translate, scale, shear=0):
    # Helper method to compute affine transformation

    # As it is explained in PIL.Image.rotate
    # We need compute affine transformation matrix: M = T * C * RSS * C^-1
    # where T is translation matrix: [1, 0, tx | 0, 1, ty | 0, 0, 1]
    #       C is translation matrix to keep center: [1, 0, cx | 0, 1, cy | 0, 0, 1]
    #       RSS is rotation with scale and shear matrix
    #       RSS(a, scale, shear) = [ cos(a)*sx    -sin(a + shear)*sy     0]
    #                              [ sin(a)*sx    cos(a + shear)*sy     0]
    #                              [     0                  0          1]

    angle = math.radians(angle)
    shear = math.radians(shear)

    T = np.array([[1, 0, translate[0]], [0, 1, translate[1]], [0, 0, 1]]).astype(np.float32)
    C = np.array([[1, 0, center[0]], [0, 1, center[1]], [0, 0, 1]]).astype(np.float32)
    RSS = np.array([[ math.cos(angle)*scale[0], -math.sin(angle + shear)*scale[1], 0],
                    [ math.sin(angle)*scale[0],  math.cos(angle + shear)*scale[1], 0],
                    [ 0, 0, 1]]).astype(np.float32)
    C_inv = np.linalg.inv(np.mat(C))
    M = T.dot(C).dot(RSS).dot(C_inv)
    return M

# ** tools ** 
Example 17
Project: AILearners   Author: aimi-cn   File: Logistic.py    License: Apache License 2.0 6 votes vote down vote up
def gradAscent(dataMatIn, classLabels):
    #用dataMatIn创建特征矩阵
    dataMatrix = np.mat(dataMatIn)     
    #调换矩阵的坐标顺序,对于二维矩阵来说,transpose()就是转置                                  
    labelMat = np.mat(classLabels).transpose()          
    #m是样本数,n是特征数                 
    m, n = np.shape(dataMatrix)   
    #梯度上升步长                                         
    alpha = 0.001   
    #最大迭代次数                                                     
    maxCycles = 500       
    #权重向量b,初始化为全1 这里面n为3                                                
    weights = np.ones((n,1))
    for k in range(maxCycles):
        #讲给定的值通过sigmoid函数输出为0-1之间的数值 #对w1*x1+w2*x2求对数几率回归
        h = sigmoid(dataMatrix * weights)      
        #计算真实值和预测值之间的误差                         
        error = labelMat - h
        #根据误差进行梯度更新
        weights = weights + alpha * dataMatrix.transpose() * error
    #.getA()将自身矩阵变量转化为ndarray类型的变量
    return weights.getA() 
Example 18
Project: AILearners   Author: aimi-cn   File: Logistic_demo01.py    License: Apache License 2.0 6 votes vote down vote up
def gradAscent(dataMatIn, classLabels):
    #用dataMatIn创建特征矩阵
    dataMatrix = np.mat(dataMatIn)
    #调换矩阵的坐标顺序,对于二维矩阵来说,transpose()就是转置 
    labelMat = np.mat(classLabels).transpose()
    #m是样本数,n是特征数
    m, n = np.shape(dataMatrix)
    #梯度上升步长
    alpha = 0.001   
    #最大迭代次数                                                     
    maxCycles = 500       
    #权重向量b,初始化为全1 这里面n为3                                                
    weights = np.ones((n,1))
    for k in range(maxCycles):
        #讲给定的值通过sigmoid函数输出为0-1之间的数值 #对w1*x1+w2*x2求对数几率回归
        h = sigmoid(dataMatrix * weights)      
        #计算真实值和预测值之间的误差                         
        error = labelMat - h
        #根据误差进行梯度更新
        weights = weights + alpha * dataMatrix.transpose() * error
    #.getA()将自身矩阵变量转化为ndarray类型的变量
    return weights 
Example 19
Project: AILearners   Author: aimi-cn   File: svm2.py    License: Apache License 2.0 6 votes vote down vote up
def kernelTrans(X, A, kTup):
    """
    通过核函数将数据转换更高维的空间
    Parameters:
        X - 数据矩阵
        A - 单个数据的向量
        kTup - 包含核函数信息的元组
    Returns:
        K - 计算的核K
    """
    m,n = np.shape(X)
    K = np.mat(np.zeros((m,1)))
    if kTup[0] == 'lin': K = X * A.T                       #线性核函数,只进行内积。
    elif kTup[0] == 'rbf':                                 #高斯核函数,根据高斯核函数公式进行计算
        for j in range(m):
            deltaRow = X[j,:] - A
            K[j] = deltaRow*deltaRow.T
        K = np.exp(K/(-1*kTup[1]**2))                     #计算高斯核K
    else: raise NameError('核函数无法识别')
    return K                                             #返回计算的核K 
Example 20
Project: AILearners   Author: aimi-cn   File: svm_demo02.py    License: Apache License 2.0 6 votes vote down vote up
def kernelTrans(X, A, kTup):
    """
    通过核函数将数据转换更高维的空间
    Parameters:
        X - 数据矩阵
        A - 单个数据的向量
        kTup - 包含核函数信息的元组
    Returns:
        K - 计算的核K
    """
    m,n = np.shape(X)
    K = np.mat(np.zeros((m,1)))
    if kTup[0] == 'lin': K = X * A.T                       #线性核函数,只进行内积。
    elif kTup[0] == 'rbf':                                 #高斯核函数,根据高斯核函数公式进行计算
        for j in range(m):
            deltaRow = X[j,:] - A
            K[j] = deltaRow*deltaRow.T
        K = np.exp(K/(-1*kTup[1]**2))                     #计算高斯核K
    else: raise NameError('核函数无法识别')
    return K                                             #返回计算的核K 
Example 21
Project: python-control   Author: python-control   File: timeresp_test.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_lsim_double_integrator(self):
        # Note: scipy.signal.lsim fails if A is not invertible
        A = np.mat("0. 1.;0. 0.")
        B = np.mat("0.; 1.")
        C = np.mat("1. 0.")
        D = 0.
        sys = StateSpace(A, B, C, D)

        def check(u, x0, xtrue):
            _t, yout, xout = forced_response(sys, t, u, x0)
            np.testing.assert_array_almost_equal(xout, xtrue, decimal=6)
            ytrue = np.squeeze(np.asarray(C.dot(xtrue)))
            np.testing.assert_array_almost_equal(yout, ytrue, decimal=6)

        # test with zero input
        npts = 10
        t = np.linspace(0, 1, npts)
        u = np.zeros_like(t)
        x0 = np.array([2., 3.])
        xtrue = np.zeros((2, npts))
        xtrue[0, :] = x0[0] + t * x0[1]
        xtrue[1, :] = x0[1]
        check(u, x0, xtrue)

        # test with step input
        u = np.ones_like(t)
        xtrue = np.array([0.5 * t**2, t])
        x0 = np.array([0., 0.])
        check(u, x0, xtrue)

        # test with linear input
        u = t
        xtrue = np.array([1./6. * t**3, 0.5 * t**2])
        check(u, x0, xtrue) 
Example 22
Project: python-control   Author: python-control   File: frd_test.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def testbdalg(self):
        # get two SISO transfer functions
        h1 = TransferFunction([1], [1, 2, 2])
        h2 = TransferFunction([1], [0.1, 1])
        omega = np.logspace(-1, 2, 10)
        f1 = FRD(h1, omega)
        f2 = FRD(h2, omega)

        np.testing.assert_array_almost_equal(
            (bdalg.series(f1, f2)).freqresp([0.1, 1.0, 10])[0],
            (bdalg.series(h1, h2)).freqresp([0.1, 1.0, 10])[0])

        np.testing.assert_array_almost_equal(
            (bdalg.parallel(f1, f2)).freqresp([0.1, 1.0, 10])[0],
            (bdalg.parallel(h1, h2)).freqresp([0.1, 1.0, 10])[0])

        np.testing.assert_array_almost_equal(
            (bdalg.feedback(f1, f2)).freqresp([0.1, 1.0, 10])[0],
            (bdalg.feedback(h1, h2)).freqresp([0.1, 1.0, 10])[0])

        np.testing.assert_array_almost_equal(
            (bdalg.negate(f1)).freqresp([0.1, 1.0, 10])[0],
            (bdalg.negate(h1)).freqresp([0.1, 1.0, 10])[0])

#       append() and connect() not implemented for FRD objects
#        np.testing.assert_array_almost_equal(
#            (bdalg.append(f1, f2)).freqresp([0.1, 1.0, 10])[0],
#            (bdalg.append(h1, h2)).freqresp([0.1, 1.0, 10])[0])
#
#        f3 = bdalg.append(f1, f2, f2)
#        h3 = bdalg.append(h1, h2, h2)
#        Q = np.mat([ [1, 2], [2, -1] ])
#        np.testing.assert_array_almost_equal(
#           (bdalg.connect(f3, Q, [2], [1])).freqresp([0.1, 1.0, 10])[0],
#            (bdalg.connect(h3, Q, [2], [1])).freqresp([0.1, 1.0, 10])[0]) 
Example 23
Project: python-control   Author: python-control   File: matlab_test.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def testConnect(self):
        sys1 = ss("1. -2; 3. -4", "5.; 7", "6, 8", "9.")
        sys2 = ss("-1.", "1.", "1.", "0.")
        sys = append(sys1, sys2)
        Q= np.mat([ [ 1, 2], [2, -1] ]) # basically feedback, output 2 in 1
        sysc = connect(sys, Q, [2], [1, 2])
        # print(sysc)
        np.testing.assert_array_almost_equal(
            sysc.A, np.mat('1 -2 5; 3 -4 7; -6 -8 -10'))
        np.testing.assert_array_almost_equal(
            sysc.B, np.mat('0; 0; 1'))
        np.testing.assert_array_almost_equal(
            sysc.C, np.mat('6 8 9; 0 0 1'))
        np.testing.assert_array_almost_equal(
            sysc.D, np.mat('0; 0')) 
Example 24
Project: Jtyoui   Author: jtyoui   File: fm.py    License: MIT License 5 votes vote down vote up
def initialize_v(n: int, k: int):
    """初始化交叉项

    :param n: 特征个数
    :param k: FM模型的度
    :return: 交叉项的系数权重
    """
    v = np.mat(np.zeros(shape=(n, k)))
    for i in range(n):
        for j in range(k):
            v[i, j] = normalvariate(0, 0.2)
    return v 
Example 25
Project: Jtyoui   Author: jtyoui   File: fm.py    License: MIT License 5 votes vote down vote up
def stop_grad_ascent(data: np.mat, label: np.mat, k: int, max_iter: int, alpha: float) -> (float, np.mat, np.mat):
    """利用随机梯度下降法训练FM模型

    :param data: 数据特征
    :param label: 标签
    :param k: v的维度
    :param max_iter: 最大迭代次数
    :param alpha: 学习率
    :return: w0,w,v权重
    """
    m, n = np.shape(data)
    w = np.random.randn(n).reshape((n, 1))
    w0 = 0
    v = initialize_v(n, k)
    for it in range(max_iter):
        for x in range(m):
            inter_1 = data[x] * v
            inter_2 = np.multiply(data[x], data[x]) * np.multiply(v, v)
            inter = np.sum(np.multiply(inter_1, inter_1) - inter_2) / 2.
            p = w0 + data[x] * w + inter
            loss = sigmoid(label[x] * p[0, 0]) - 1
            w0 -= alpha * loss * label[x]
            for i in range(n):
                if data[x, i] != 0:
                    w[i, 0] -= alpha * loss * label[x] * data[x, i]
                for j in range(k):
                    v[i, j] -= alpha * loss * label[x] * (
                            data[x, i] * inter_1[0, j] - v[i, j] * data[x, i] * data[x, i])
        if it % 100 == 0:
            pre = get_prediction(np.mat(data), w0, w, v)
            print(get_cost(np.mat(pre), label))
    return w0, w, v 
Example 26
Project: Jtyoui   Author: jtyoui   File: common.py    License: MIT License 5 votes vote down vote up
def get_cost(predict: np.mat, label: np.mat) -> float:
    """计算损失函数的值

    :param predict: 预测值
    :param label: 标签
    :return: 损失函数的值
    """
    m = len(predict)
    error = 0.0
    for i in range(m):
        error -= np.log(sigmoid(predict[i, 0] * label[i, 0]))
    return error 
Example 27
Project: recruit   Author: Frank-qlu   File: test_regression.py    License: Apache License 2.0 5 votes vote down vote up
def test_matrix_multiply_by_1d_vector(self):
        # Ticket #473
        def mul():
            np.mat(np.eye(2))*np.ones(2)

        assert_raises(ValueError, mul) 
Example 28
Project: westpa   Author: westpa   File: string_method.py    License: MIT License 5 votes vote down vote up
def finalize_init(self):
        # Set up A and kappan for each string
        uslen = np.unique(self._slen)

        for ulen in uslen:
            self._kappan[ulen] = self._kappa * self._dtau * ulen
            self._A[ulen] = None

            if self._SCIPY_FLAG:
                ud = np.zeros((ulen,))
                ld = np.zeros((ulen,))
                d = np.ones((ulen,))

                d[1:-1] = 2.0*self._kappan[ulen] + 1.0
                ud[2:] = -self._kappan[ulen]
                ld[:-2] = -self._kappan[ulen]

                self._A[ulen] = np.mat([ud,d,ld])

            else:
                self._A[ulen] = np.eye(ulen)
                di = np.diag_indices(ulen, ndim=2)
                ii = (di[0][1:-1],di[1][1:-1])

                self._A[ulen][ii] = 2.0*self._kappan[ulen] + 1.0

                dd = np.zeros((ulen-1,))
                dd[1:] = -self._kappan[ulen]
                self._A[ulen] += np.diag(dd,k=1)

                dd = np.zeros((ulen-1,))
                dd[:-1] = -self._kappan[ulen]
                self._A[ulen] += np.diag(dd,k=-1) 
Example 29
Project: lambda-packs   Author: ryfeus   File: test_regression.py    License: MIT License 5 votes vote down vote up
def test_matrix_multiply_by_1d_vector(self, level=rlevel):
        # Ticket #473
        def mul():
            np.mat(np.eye(2))*np.ones(2)

        self.assertRaises(ValueError, mul) 
Example 30
Project: auto-alt-text-lambda-api   Author: abhisuri97   File: test_regression.py    License: MIT License 5 votes vote down vote up
def test_matrix_multiply_by_1d_vector(self, level=rlevel):
        # Ticket #473
        def mul():
            np.mat(np.eye(2))*np.ones(2)

        self.assertRaises(ValueError, mul)