1

I have this code for concatenate two arrays.

import numpy as np
from hmmlearn import hmm
model = hmm.MultinomialHMM(n_components=3, n_iter=10,algorithm='map',tol=0.00001)
sequence3 = np.array([[2, 1, 0, 1]]).T
sequence4 = np.array([[2, 1, 0, 1, 1]]).T
sample = np.concatenate([sequence3, sequence4])
lengths = [len(sequence3), len(sequence4)]
model.fit(sample,lengths)

and it is working correctly. but now if I have more than two array. let us to say I have 10 arrays. how I can make the same process?

import numpy as np
from hmmlearn import hmm
model = hmm.MultinomialHMM(n_components=3, n_iter=10,algorithm='map',tol=0.00001)
sample = np.array([])
lengths = []
for i in range(1:10)
    ?????????????
model.fit(sample,lengths)
2
  • So, you'd probably need the new array sample and the lengths of them in list lengths? Commented Mar 26, 2017 at 8:24
  • You can concatenate many arrays at once. Just put them all in the argument list. But the dimensions have to match. Commented Mar 26, 2017 at 8:59

2 Answers 2

2

In order to concatenate more than one array, you simply concatenate the array with the concatenation of all the previous arrays.

# Create arrays
arrays=[
    np.array([1,2,3]),
    np.array([4,5,6]),
    np.array([7,8,9])
]

# Create an array to return to
sample = np.array([])

for array in arrays:
    sample = np.concatenate([sample, array])

# Print results
print('sample', sample)
print('length', len(sample))
Sign up to request clarification or add additional context in comments.

5 Comments

it still give me this error "ValueError: expected a sample from a Multinomial distribution." at this line model.fit(sample,lengths)
Just use concatenate(arrays)
now I have this error "ValueError: more than 1 samples in lengths array [3, 3, 3]" in this line model.fit(np.concatenate(arrays),lengths)
it is working with me now. The problem was arrays should be. arrays=[ np.array([[1,2,3]]), np.array([[4,5,6]]), np.array([[7,8,9]]) ]
and I used np.concatenate(arrays) direct without for
1

You can use vstack

That is,

Equivalent to np.concatenate(tup, axis=0) if tup contains arrays that are at least 2-dimensional.

store your arrays as a list,say array_list

print np.vstack(array_list) 

Sample:

import numpy as np
sequence3 = np.array([[2, 1]]).T
sequence4 = np.array([[2, 5]]).T
sequence5 = np.array([[4, 5]]).T
sequence6 = np.array([[6, 7]]).T
array_list=[sequence3,sequence4,sequence5,sequence6]
sample = np.concatenate([sequence3, sequence4])
lengths = [len(sequence3), len(sequence4)]
print np.vstack(array_list)

[[2]
 [1]
 [2]
 [5]
 [4]
 [5]
 [6]
 [7]]

Hope it helps!

1 Comment

Since the arrays are already 2d, I'd suggest concatenate with axis=0.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.