【问题标题】:Modular Symbolic (and indexed) Matrix Creation with Sympy使用 Sympy 创建模块化符号(和索引)矩阵
【发布时间】:2020-03-11 22:08:30
【问题描述】:

我正在尝试使用 sympy 创建一个符号和模块化的 Python 函数,该函数采用维度 j(行)和 k(列)并返回一个索引矩阵。这是函数:

import sympy
from sympy import *
from sympy import init_printing,Matrix
from sympy.physics.vector import dynamicsymbols
import numpy as np
init_printing()    
def weights_func_L(j,k):
    #
    # jth nuerons in the k ( or L - 1 ) layer   
    # j rows
    # k columns

    #in other words, this is the weight (in a specific layer j) for the jth nueron and the kth neuron in the 
    #previous (L-1 layer) i.e wjk

    #this will return a weight matrix for j rows (i.e corresponds to the # of layers) 
    #and k (corresponds to the # of nuerons)

    #
    matrix_bin = ones(j,k)
    matrix_bin = flatten(matrix_bin)
    basic_w_string  = 'w'

    for a in np.arange(len(matrix_bin)):
        #symbols(basic_w_string+str(countj)+str(countk))
        if j == k:
            matrix_bin[a] = symbols(basic_w_string+str(a // k)+str( a % j))
        else:
            matrix_bin[a] = symbols(basic_w_string+str(a // k)+str( a % j))
        #print matrix_bin[a]

#         for aa in np.arange(j):
#             matrix_bin[countj,countk] = symbols(basic_w_string+str(countj)+str(countk))
#         countj += 1
#         countk += 1


    matrix_bin2 = np.reshape(matrix_bin,(j,k))
    return Matrix(matrix_bin2)

这适用于方阵:

weights_func_L(3,3)

产生:

但是对于非方阵,j!=k:

weights_func_L(5,3) 产量

类似地调用weights_func_L(3,5) 会产生:

任何指导将不胜感激!

【问题讨论】:

    标签: python-2.7 sympy


    【解决方案1】:

    a % j 应该是a % k,像这样:

    def weights_func_L(j,k):
        matrix_bin = ones(j,k)
        matrix_bin = flatten(matrix_bin)
        basic_w_string  = 'w'
    
        for a in np.arange(len(matrix_bin)):
            matrix_bin[a] = symbols(basic_w_string+str(a // k)+str(a % k))
    
        matrix_bin2 = np.reshape(matrix_bin,(j,k))
        return Matrix(matrix_bin2)
    
    >>> weights_func_L(5, 3)
    ⎡w₀₀  w₀₁  w₀₂⎤
    ⎢             ⎥
    ⎢w₁₀  w₁₁  w₁₂⎥
    ⎢             ⎥
    ⎢w₂₀  w₂₁  w₂₂⎥
    ⎢             ⎥
    ⎢w₃₀  w₃₁  w₃₂⎥
    ⎢             ⎥
    ⎣w₄₀  w₄₁  w₄₂⎦
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-18
      • 1970-01-01
      • 2016-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多