【问题标题】:stacking unequal matrices in python在python中堆叠不等矩阵
【发布时间】:2013-09-16 03:51:12
【问题描述】:

谁能告诉我如何加入两个不相等的 numpy 数组(一个稀疏和一个密集)。我尝试使用 hstack/vstack,但不断收到维度错误。

from scipy import sparse 
from scipy.sparse import coo_matrix 
m=(coo_matrix(X_new)) # is a(7395,50000) sparse array 
a=(other) # is a (7395,20) dense array 
new_tr=scipy.sparse.hstack((m,a))

【问题讨论】:

  • 你能出示你的代码吗?
  • from scipy import sparse from scipy.sparse import coo_matrix m=(coo_matrix(X_new)) # is a(7395,50000) sparse array a=(other) # is a (7395,20) dense数组 new_tr=scipy.sparse.hstack((m,a))
  • 请在您的问题中粘贴并格式化您的代码。

标签: python arrays numpy matrix scipy


【解决方案1】:

请发布更多上下文以使您的问题可重现。如发布的那样,您的代码对我有用:

X_new = np.zeros((10,5), int)
X_new[(np.random.randint(0,10,5),np.random.randint(0,5,5))] = np.random.randint(0,10,5)
X_new
#array([[ 0, 0, 7, 0, 0],
#       [ 0, 0, 0, 0, 0],
#       [ 0, 0, 8, 3, 0],
#       [ 0, 0, 0, 0, 0],
#       [ 0, 0, 0, 0, 0],
#       [ 0, 0, 0, 0, 0],
#       [ 0, 0, 8, 0, 0],
#       [ 1, 0, 0, 0, 0],
#       [ 0, 0, 0, 0, 0],
#       [ 0, 0, 0, 0, 0]])

m = coo_matrix(X_new)
m
#<10x5 sparse matrix of type '<type 'numpy.int64'>'
#    with 5 stored elements in COOrdinate format>


a = np.matrix(np.random.randint(0,10,(10,2)))
a
#matrix([[2, 1],
#        [5, 2],
#        [4, 1],
#        [1, 4],
#        [5, 2],
#        [7, 2],
#        [6, 3],
#        [8, 4],
#        [5, 5],
#        [7, 4]])

new_tr = sparse.hstack([m,a])
new_tr
#<10x7 sparse matrix of type '<type 'numpy.int64'>'
#   with 25 stored elements in COOrdinate format>

new_tr.todense()
#matrix([[ 0, 0, 7, 0, 0, 2, 1],
#        [ 0, 0, 0, 0, 0, 5, 2],
#        [ 0, 0, 8, 3, 0, 4, 1],
#        [ 0, 0, 0, 0, 0, 1, 4],
#        [ 0, 0, 0, 0, 0, 5, 2],
#        [ 0, 0, 0, 0, 0, 7, 2],
#        [ 0, 0, 8, 0, 0, 6, 3],
#        [ 1, 0, 0, 0, 0, 8, 4],
#        [ 0, 0, 0, 0, 0, 5, 5],
#        [ 0, 0, 0, 0, 0, 7, 4]])

【讨论】:

    猜你喜欢
    • 2016-12-21
    • 1970-01-01
    • 1970-01-01
    • 2020-09-25
    • 2020-04-13
    • 1970-01-01
    • 2019-08-05
    • 1970-01-01
    • 2017-09-18
    相关资源
    最近更新 更多