Refactor matrix permutations in numpy's style












1















I wrote the following code to do multiplication of matrix permutations and I was wondering if it can be written in a numpy style, such that I can get rid of the two for loops:



Z = np.empty([new_d, X.shape[1]])
Z = np.ndarray(shape=(new_d, X.shape[1]))
Z = np.concatenate((X, X**2))
res =
for i in range(0, d):
for j in range(i+1, d):
res.append(np.array(X.T[:,i]* X.T[:,j]))

Z = np.concatenate((Z, res))


while: X shape is (7, 1000), d = 7, new_d=35



any suggestion ?










share|improve this question





























    1















    I wrote the following code to do multiplication of matrix permutations and I was wondering if it can be written in a numpy style, such that I can get rid of the two for loops:



    Z = np.empty([new_d, X.shape[1]])
    Z = np.ndarray(shape=(new_d, X.shape[1]))
    Z = np.concatenate((X, X**2))
    res =
    for i in range(0, d):
    for j in range(i+1, d):
    res.append(np.array(X.T[:,i]* X.T[:,j]))

    Z = np.concatenate((Z, res))


    while: X shape is (7, 1000), d = 7, new_d=35



    any suggestion ?










    share|improve this question



























      1












      1








      1








      I wrote the following code to do multiplication of matrix permutations and I was wondering if it can be written in a numpy style, such that I can get rid of the two for loops:



      Z = np.empty([new_d, X.shape[1]])
      Z = np.ndarray(shape=(new_d, X.shape[1]))
      Z = np.concatenate((X, X**2))
      res =
      for i in range(0, d):
      for j in range(i+1, d):
      res.append(np.array(X.T[:,i]* X.T[:,j]))

      Z = np.concatenate((Z, res))


      while: X shape is (7, 1000), d = 7, new_d=35



      any suggestion ?










      share|improve this question
















      I wrote the following code to do multiplication of matrix permutations and I was wondering if it can be written in a numpy style, such that I can get rid of the two for loops:



      Z = np.empty([new_d, X.shape[1]])
      Z = np.ndarray(shape=(new_d, X.shape[1]))
      Z = np.concatenate((X, X**2))
      res =
      for i in range(0, d):
      for j in range(i+1, d):
      res.append(np.array(X.T[:,i]* X.T[:,j]))

      Z = np.concatenate((Z, res))


      while: X shape is (7, 1000), d = 7, new_d=35



      any suggestion ?







      python numpy machine-learning vectorization






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 24 '18 at 14:28









      Divakar

      157k1488179




      157k1488179










      asked Nov 24 '18 at 11:30









      user181452user181452

      11712




      11712
























          1 Answer
          1






          active

          oldest

          votes


















          1














          Approach #1



          We could use np.triu_indices to get those pair-wise permutation-indices and then simply perform elementwise multiplicatons of row-indexed arrays -



          r,c = np.triu_indices(d,1)
          res = X[r]*X[c]


          Approach #2



          For memory efficiency and hence performance especially on large arrays, we are better off slicing the input array and run a single loop with each iteration working on chunks of data, like so -



          n = d-1
          idx = np.concatenate(( [0], np.arange(n,0,-1).cumsum() ))
          start, stop = idx[:-1], idx[1:]
          L = n*(n+1)//2
          res_out = np.empty((L,X.shape[1]), dtype=X.dtype)
          for i,(s0,s1) in enumerate(zip(start,stop)):
          res_out[s0:s1] = X[i] * X[i+1:]


          To get Z directly and thus avoid all those concatenations, we could modify the earlier posted approach, like so -



          n = d-1
          N = len(X)
          idx = 2*N + np.concatenate(( [0], np.arange(n,0,-1).cumsum() ))
          start, stop = idx[:-1], idx[1:]
          L = n*(n+1)//2
          Z_out = np.empty((2*N + L,X.shape[1]), dtype=X.dtype)
          Z_out[:N] = X
          Z_out[N:2*N] = X**2
          for i,(s0,s1) in enumerate(zip(start,stop)):
          Z_out[s0:s1] = X[i] * X[i+1:]





          share|improve this answer


























          • Your first approach is so smart !! Whenever I write too much code in python (Matrices), I know it can be written in a shorter way but because I'm still beginner I'm not aware of all of those functions. Many thanks :))

            – user181452
            Nov 24 '18 at 14:19











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53457673%2frefactor-matrix-permutations-in-numpys-style%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1














          Approach #1



          We could use np.triu_indices to get those pair-wise permutation-indices and then simply perform elementwise multiplicatons of row-indexed arrays -



          r,c = np.triu_indices(d,1)
          res = X[r]*X[c]


          Approach #2



          For memory efficiency and hence performance especially on large arrays, we are better off slicing the input array and run a single loop with each iteration working on chunks of data, like so -



          n = d-1
          idx = np.concatenate(( [0], np.arange(n,0,-1).cumsum() ))
          start, stop = idx[:-1], idx[1:]
          L = n*(n+1)//2
          res_out = np.empty((L,X.shape[1]), dtype=X.dtype)
          for i,(s0,s1) in enumerate(zip(start,stop)):
          res_out[s0:s1] = X[i] * X[i+1:]


          To get Z directly and thus avoid all those concatenations, we could modify the earlier posted approach, like so -



          n = d-1
          N = len(X)
          idx = 2*N + np.concatenate(( [0], np.arange(n,0,-1).cumsum() ))
          start, stop = idx[:-1], idx[1:]
          L = n*(n+1)//2
          Z_out = np.empty((2*N + L,X.shape[1]), dtype=X.dtype)
          Z_out[:N] = X
          Z_out[N:2*N] = X**2
          for i,(s0,s1) in enumerate(zip(start,stop)):
          Z_out[s0:s1] = X[i] * X[i+1:]





          share|improve this answer


























          • Your first approach is so smart !! Whenever I write too much code in python (Matrices), I know it can be written in a shorter way but because I'm still beginner I'm not aware of all of those functions. Many thanks :))

            – user181452
            Nov 24 '18 at 14:19
















          1














          Approach #1



          We could use np.triu_indices to get those pair-wise permutation-indices and then simply perform elementwise multiplicatons of row-indexed arrays -



          r,c = np.triu_indices(d,1)
          res = X[r]*X[c]


          Approach #2



          For memory efficiency and hence performance especially on large arrays, we are better off slicing the input array and run a single loop with each iteration working on chunks of data, like so -



          n = d-1
          idx = np.concatenate(( [0], np.arange(n,0,-1).cumsum() ))
          start, stop = idx[:-1], idx[1:]
          L = n*(n+1)//2
          res_out = np.empty((L,X.shape[1]), dtype=X.dtype)
          for i,(s0,s1) in enumerate(zip(start,stop)):
          res_out[s0:s1] = X[i] * X[i+1:]


          To get Z directly and thus avoid all those concatenations, we could modify the earlier posted approach, like so -



          n = d-1
          N = len(X)
          idx = 2*N + np.concatenate(( [0], np.arange(n,0,-1).cumsum() ))
          start, stop = idx[:-1], idx[1:]
          L = n*(n+1)//2
          Z_out = np.empty((2*N + L,X.shape[1]), dtype=X.dtype)
          Z_out[:N] = X
          Z_out[N:2*N] = X**2
          for i,(s0,s1) in enumerate(zip(start,stop)):
          Z_out[s0:s1] = X[i] * X[i+1:]





          share|improve this answer


























          • Your first approach is so smart !! Whenever I write too much code in python (Matrices), I know it can be written in a shorter way but because I'm still beginner I'm not aware of all of those functions. Many thanks :))

            – user181452
            Nov 24 '18 at 14:19














          1












          1








          1







          Approach #1



          We could use np.triu_indices to get those pair-wise permutation-indices and then simply perform elementwise multiplicatons of row-indexed arrays -



          r,c = np.triu_indices(d,1)
          res = X[r]*X[c]


          Approach #2



          For memory efficiency and hence performance especially on large arrays, we are better off slicing the input array and run a single loop with each iteration working on chunks of data, like so -



          n = d-1
          idx = np.concatenate(( [0], np.arange(n,0,-1).cumsum() ))
          start, stop = idx[:-1], idx[1:]
          L = n*(n+1)//2
          res_out = np.empty((L,X.shape[1]), dtype=X.dtype)
          for i,(s0,s1) in enumerate(zip(start,stop)):
          res_out[s0:s1] = X[i] * X[i+1:]


          To get Z directly and thus avoid all those concatenations, we could modify the earlier posted approach, like so -



          n = d-1
          N = len(X)
          idx = 2*N + np.concatenate(( [0], np.arange(n,0,-1).cumsum() ))
          start, stop = idx[:-1], idx[1:]
          L = n*(n+1)//2
          Z_out = np.empty((2*N + L,X.shape[1]), dtype=X.dtype)
          Z_out[:N] = X
          Z_out[N:2*N] = X**2
          for i,(s0,s1) in enumerate(zip(start,stop)):
          Z_out[s0:s1] = X[i] * X[i+1:]





          share|improve this answer















          Approach #1



          We could use np.triu_indices to get those pair-wise permutation-indices and then simply perform elementwise multiplicatons of row-indexed arrays -



          r,c = np.triu_indices(d,1)
          res = X[r]*X[c]


          Approach #2



          For memory efficiency and hence performance especially on large arrays, we are better off slicing the input array and run a single loop with each iteration working on chunks of data, like so -



          n = d-1
          idx = np.concatenate(( [0], np.arange(n,0,-1).cumsum() ))
          start, stop = idx[:-1], idx[1:]
          L = n*(n+1)//2
          res_out = np.empty((L,X.shape[1]), dtype=X.dtype)
          for i,(s0,s1) in enumerate(zip(start,stop)):
          res_out[s0:s1] = X[i] * X[i+1:]


          To get Z directly and thus avoid all those concatenations, we could modify the earlier posted approach, like so -



          n = d-1
          N = len(X)
          idx = 2*N + np.concatenate(( [0], np.arange(n,0,-1).cumsum() ))
          start, stop = idx[:-1], idx[1:]
          L = n*(n+1)//2
          Z_out = np.empty((2*N + L,X.shape[1]), dtype=X.dtype)
          Z_out[:N] = X
          Z_out[N:2*N] = X**2
          for i,(s0,s1) in enumerate(zip(start,stop)):
          Z_out[s0:s1] = X[i] * X[i+1:]






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 24 '18 at 12:08

























          answered Nov 24 '18 at 11:34









          DivakarDivakar

          157k1488179




          157k1488179













          • Your first approach is so smart !! Whenever I write too much code in python (Matrices), I know it can be written in a shorter way but because I'm still beginner I'm not aware of all of those functions. Many thanks :))

            – user181452
            Nov 24 '18 at 14:19



















          • Your first approach is so smart !! Whenever I write too much code in python (Matrices), I know it can be written in a shorter way but because I'm still beginner I'm not aware of all of those functions. Many thanks :))

            – user181452
            Nov 24 '18 at 14:19

















          Your first approach is so smart !! Whenever I write too much code in python (Matrices), I know it can be written in a shorter way but because I'm still beginner I'm not aware of all of those functions. Many thanks :))

          – user181452
          Nov 24 '18 at 14:19





          Your first approach is so smart !! Whenever I write too much code in python (Matrices), I know it can be written in a shorter way but because I'm still beginner I'm not aware of all of those functions. Many thanks :))

          – user181452
          Nov 24 '18 at 14:19




















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53457673%2frefactor-matrix-permutations-in-numpys-style%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Wiesbaden

          Marschland

          Dieringhausen