def mc_sample(prior, trans, len, numex=1): ''' % SAMPLE_MC Generate random sequences from a Markov chain. % STATE = SAMPLE_MC(PRIOR, TRANS, LEN) generates a sequence of length LEN. % % STATE = SAMPLE_MC(PRIOR, TRANS, LEN, N) generates N rows each of length LEN. ''' trans = np.asarray(trans) S = np.zeros((numex,len), dtype=int); for i in range(0,numex): S[i, 0] = sample_discrete(prior) for t in range(1, len): S[i, t] = sample_discrete(trans[S[i,t-1],:]) return S
def testDistSmall(self): n = 10000 M = np.zeros((n, 2)) for i in range(n): M[i, :] = sample_discrete(np.array([0.8, 0.1, 0.1]), 1, 2) dist = np.bincount(M.ravel().astype(int)) / (n * 2.) assert np.all(np.abs(dist - [0.8, 0.1, 0.1]) < 1e-2)
def testDistSmall(self): n = 10000 M = np.zeros((n,2)) for i in range(n): M[i,:] = sample_discrete(np.array([0.8, 0.1, 0.1]), 1, 2) dist = np.bincount(M.ravel().astype(int)) / (n*2.) assert np.all(np.abs(dist-[0.8, 0.1, 0.1]) < 1e-2)
def mhmm_sample(T, numex, initial_prob, transmat, mu, Sigma, mixmat=None): ''' % SAMPLE_MHMM Generate random sequences from an HMM with (mixtures of) Gaussian output. % [obs, hidden] = sample_mhmm(T, numex, initial_prob, transmat, mu, Sigma, mixmat) % % INPUTS: % T - length of each sequence % numex - num. sequences % init_state_prob(i) = Pr(Q(1) = i) % transmat(i,j) = Pr(Q(t+1)=j | Q(t)=i) % mu(:,j,k) = mean of Y(t) given Q(t)=j, M(t)=k % Sigma(:,:,j,k) = cov. of Y(t) given Q(t)=j, M(t)=k % mixmat(j,k) = Pr(M(t)=k | Q(t)=j) : set to ones(Q,1) or omit if single mixture % % OUTPUT: % obs(:,t,l) = observation vector at time t for sequence l % hidden(t,l) = the hidden state at time t for sequence l ''' assert initial_prob.ndim == 1 Q = len(initial_prob); if mixmat==None: mixmat = np.ones((Q,1)) O = mu.shape[0] hidden = np.zeros((T, numex)) obs = np.zeros((O, T, numex)) hidden = mc_sample(initial_prob, transmat, T, numex).T for i in range(0,numex): for t in range(0,T): q = hidden[t,i] m = np.asscalar(sample_discrete(mixmat[q,:], 1, 1)) obs[:,t,i] = gaussian_sample(mu[:,q,m], Sigma[:,:,q,m], 1) return obs, hidden
def testDistLarge(self): n = 10000 M = sample_discrete(np.array([0.8, 0.2]), n, 10) dist = np.bincount(M.ravel().astype(int)) / (n * 10.) assert np.all(np.abs(dist - [0.8, 0.2]) < 1e-2)
def testRow(self): assert sample_discrete(np.array([0.8, 0.2]), 1, 10).shape == (1, 10)
def testDistLarge(self): n = 10000 M = sample_discrete(np.array([0.8, 0.2]), n, 10) dist = np.bincount(M.ravel().astype(int)) / (n*10.) assert np.all(np.abs(dist-[0.8, 0.2]) < 1e-2)
def testRow(self): assert sample_discrete(np.array([0.8, 0.2]), 1, 10).shape == (1,10)