当前位置: 首页>>代码示例>>Python>>正文


Python GaussianHMM.fit方法代码示例

本文整理汇总了Python中hmmlearn.hmm.GaussianHMM.fit方法的典型用法代码示例。如果您正苦于以下问题:Python GaussianHMM.fit方法的具体用法?Python GaussianHMM.fit怎么用?Python GaussianHMM.fit使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在hmmlearn.hmm.GaussianHMM的用法示例。


在下文中一共展示了GaussianHMM.fit方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: fit_batch

# 需要导入模块: from hmmlearn.hmm import GaussianHMM [as 别名]
# 或者: from hmmlearn.hmm.GaussianHMM import fit [as 别名]
def fit_batch(traj_data, n_components=2, subsample_factor=1,
              features=['speed', 'rotation'], **kwargs):
    '''
    Fits model to concatenated traj_data
    Args:
        traj_data - list of paths of training dataset (trajectory csv)
        n_components - number of hidden states
        subsample_factor - subsample factor to apply to all files
        features - columns to fit model to
        **kwargs passed to GaussianHMM
    Returns:
        model - fitted model
    '''
    # Concatenate data
    feature_list = []
    lengths_list = []
    for path in traj_data:
        X, l = features_from_csv(path, features=features,
                                 subsample_factor=subsample_factor)
        feature_list.append(X)
        lengths_list.append(l)
    print 'Concatenating features...'
    X = np.vstack(feature_list)
    l = np.hstack(lengths_list)

    # Fit HMM
    print 'Fitting model...'
    model = GaussianHMM(n_components, **kwargs)
    model.fit(X, lengths=l)

    return model
开发者ID:J-Wall,项目名称:bee-tracking,代码行数:33,代码来源:traj_hmm.py

示例2: main

# 需要导入模块: from hmmlearn.hmm import GaussianHMM [as 别名]
# 或者: from hmmlearn.hmm.GaussianHMM import fit [as 别名]
def main(args):
    x, X = loadDiffRows(args.diffFile)
    model = GaussianHMM(n_components=3,
                        covariance_type="diag",
                        n_iter=100000000000)
    model.transmat_ = numpy.array([[0.5, 0.5, 0.0],
                                   [0.0, 0.5, 0.5],
                                   [0.0, 0.0, 1.0]])
    model.fit(X)
    print(model.transmat_)
    model.transmat_[0][2] = 0.
    model.transmat_[1][0] = 0.
    model.transmat_[2][0] = 0.
    model.transmat_[2][1] = 0.
    
    exp = args.outFile.split('/')[-1].split('_')[0]
    with open(args.outFile, 'w') as fout:
        print('exp\tbin\treads\tstate', file=fout)
        for seq in X:
            hiddenStates = model.predict(seq)
            for idx,v in enumerate(zip(x,hiddenStates)):
                r,h = v
                print(exp + '\t' + str(idx) + '\t'
                      + str(r) + '\t' + str(h),
                      file=fout)
开发者ID:samesense,项目名称:pol2_states,代码行数:27,代码来源:hmm.py

示例3: addModel

# 需要导入模块: from hmmlearn.hmm import GaussianHMM [as 别名]
# 或者: from hmmlearn.hmm.GaussianHMM import fit [as 别名]
 def addModel(self, nom, data, nbEtats, n_iter, startprob_prior=None, transmat_prior=None):
     '''
     ajoute un model à tabModels
     
     paramètres :
     nom = nom du modèle
     data = tableau à trois dimension représentant un cluster possèdant des mouvements possèdant lui même des positions        
     nbEtats = nombre d'états cachés pour chaque modèle
     n_iter = nombre d'itérations pour l'algorithme de Baum-Welch
     startprob_prior = la matrice initiale à priori
     transmat_prior = la matrice de transition à priori des états
     '''
     model = GaussianHMM(nbEtats, covariance_type="diag", n_iter=n_iter, startprob_prior=startprob_prior, transmat_prior=transmat_prior)      
     model.fit(data)
     verif_set_transMat(model)
     taille = len(self.tabModels)
     if(taille == 0):
         self.tabModels.append([nom])
         self.tabModels[0].append(model)
         return
     for i in range(taille):        
         if(self.tabModels[i][0] == nom):
             self.tabModels[i].append(model)
             return
     self.tabModels.append([nom])
     self.tabModels[-1].append(model)
开发者ID:MaxenceQueyrel,项目名称:kinectApp,代码行数:28,代码来源:classSkeleton.py

示例4: fit

# 需要导入模块: from hmmlearn.hmm import GaussianHMM [as 别名]
# 或者: from hmmlearn.hmm.GaussianHMM import fit [as 别名]
	def fit(self):

		if self.verbose:
			print "[Clustering] Clearing old model and segmentation"
		
		self.segmentation = []
		self.model = []


		new_segments = []
		new_model = []

		g = GaussianHMM(n_components=self.n_components)

		all_demos = self._demonstrations[0]
		lens = [np.shape(self._demonstrations[0])[0]]
		for i in range(1, len(self._demonstrations)):
			all_demos = np.concatenate([all_demos,self._demonstrations[i]])
			lens.append(np.shape(self._demonstrations[i])[0])

		g.fit(all_demos,lens) 
			
		for d in self._demonstrations:
			new_segments.append(self.findTransitions(g.predict(d)))
			#print g.predict(d)
			new_model.append(g)

		self.segmentation = new_segments
		self.model = new_model
开发者ID:BerkeleyAutomation,项目名称:tsc,代码行数:31,代码来源:clustering.py

示例5: fit_HMM

# 需要导入模块: from hmmlearn.hmm import GaussianHMM [as 别名]
# 或者: from hmmlearn.hmm.GaussianHMM import fit [as 别名]
 def fit_HMM(self,error_metric):
     print "Looking for optimal number of states and fitting HMM"
     for i in xrange(2,5):
         candidate = GaussianHMM(n_components=i, covariance_type="full", n_iter=1000)
         candidate.fit(self.X_train)
         if error_metric == HMM_MAD:
             error = HMM_MAD(candidate,self.X_test)
             if i == 2:
                 best_guess = error
                 best_model = candidate
                 opt_n_states = i
             else:
                 if error < best_guess:
                     opt_n_states = i
                     best_model = candidate
                     best_guess = error
         else:
             error = error_metric(candidate,self.X_test)
             if i == 2:
                 best_guess = error
                 best_model = candidate
                 opt_n_states = i
             else:
                 if error > best_guess:
                     opt_n_states = i
                     best_model = candidate
                     best_guess = error
     self.model = best_model
     self.n_states = opt_n_states
     print "Done. Lowest error of {} achieved with {} states".format(best_guess, opt_n_states)
开发者ID:pipette,项目名称:Electricity-load-disaggregation,代码行数:32,代码来源:HMM.py

示例6: fit_hmm

# 需要导入模块: from hmmlearn.hmm import GaussianHMM [as 别名]
# 或者: from hmmlearn.hmm.GaussianHMM import fit [as 别名]
def fit_hmm(df, n_components, features=['speed', 'rotation'],
            **kwargs):
    '''
    Fits a Gaussian HMM to the velocity data
    Args:
        df - dataframe containing positional data to be processed
        n_components - number of hidden states
        features - features to use in model fitting
        **kwargs passed to GaussianHMM
    Returns:
        model
    '''
    X, lengths = get_features(df, features=features)
    model = GaussianHMM(n_components, **kwargs)
    model.fit(X, lengths=lengths)

    return model
开发者ID:J-Wall,项目名称:bee-tracking,代码行数:19,代码来源:traj_hmm.py

示例7: test_backward_with_hmmlearn

# 需要导入模块: from hmmlearn.hmm import GaussianHMM [as 别名]
# 或者: from hmmlearn.hmm.GaussianHMM import fit [as 别名]
    def test_backward_with_hmmlearn(self):
        r = np.random.randn
        obs = [np.array([[-600 + r(), 100 + r()], [-300 + r(), 200 + r()], [0 + r(), 300 + r()]]) for _ in xrange(10)]
        hmm = GaussianHMM(n_components=3)
        hmm.fit(obs)

        # Calculcate bwdlattice using hmmlearn algorithm
        framelogprob = hmm._compute_log_likelihood(obs[0])
        start = timeit.default_timer()
        bwdlattice1 = hmm._do_backward_pass(framelogprob)
        print('hmmlearn took %fs' % (timeit.default_timer() - start))

        # Calculate bwdlattice using fhmm algorithm with #chains = 1. This should yield the exact same results
        start = timeit.default_timer()
        bwdlattice2 = np.zeros(bwdlattice1.shape)
        fhmmc._backward(obs[0].shape[0], 1, hmm.n_components, [(x,) for x in xrange(hmm.n_components)],
                        hmm._log_startprob.reshape(1, 3), hmm._log_transmat.reshape(1, 3, 3), framelogprob, bwdlattice2)
        print('fhmm took %fs' % (timeit.default_timer() - start))
        self.assertTrue(np.allclose(bwdlattice1, bwdlattice2))
开发者ID:caomw,项目名称:motion-classification,代码行数:21,代码来源:test_fhmm.py

示例8: HmmClassifier

# 需要导入模块: from hmmlearn.hmm import GaussianHMM [as 别名]
# 或者: from hmmlearn.hmm.GaussianHMM import fit [as 别名]
class HmmClassifier():
    def __init__(self, referenceSeqs, inputSeq):
        self.referenceSeqs = referenceSeqs
        self.inputSeq = inputSeq

        # feel free to change this model
        self.model = GaussianHMM(n_components=2, covariance_type="full", n_iter=2000)

    def predict(self):
        probs = []
        for referenceSeq in self.referenceSeqs:
            #print "reference: {}".format(referenceSeq)
            self.model.fit(referenceSeq)
            hidden_states = self.model.predict(referenceSeq)
            prob = self.model.score(self.inputSeq)
            probs.append(prob)

        # return the index of the max prob
        return probs.index(max(probs))
开发者ID:lujunzju,项目名称:AirTicketPredicting,代码行数:21,代码来源:HmmClassifier.py

示例9: __init__

# 需要导入模块: from hmmlearn.hmm import GaussianHMM [as 别名]
# 或者: from hmmlearn.hmm.GaussianHMM import fit [as 别名]
class HMM:
    __slots__ = [
        "model"
    ]

    def __init__(self):
        pass


    def draw(self, data):
        figure()
        plot(range(len(data)),data,alpha=0.8,color='red')
        show()


    def train(self, data, n_components):
        print("Training Data: %s" % data)
        self.data = data
        self.model = GaussianHMM(n_components, algorithm='viterbi', covariance_type='diag')
        X = np.reshape(data, (len(data),1))
        self.model = self.model.fit([X])

        self.hidden_states = self.model.predict(X)
        print("Sequence of States: " % self.hidden_states)


    def eval(self, obs):
        print("Testing Data: %s" % obs)
        X = np.reshape(obs, (len(obs),1))
        print("Eval: %s" % str(self.model.score(X)))


    def plot(self):
        fig = figure(facecolor="white")
        ax = fig.add_subplot(111)

        for i in range(self.model.n_components):
            # use fancy indexing to plot data in each state
            idx = (self.hidden_states == i)
            ax.plot(np.array(range(len(self.data)))[idx], np.array(self.data)[idx], '.', label="State %d" % (i+1))

        ax.legend()
        show()
开发者ID:mkdmkk,项目名称:infaas,代码行数:45,代码来源:hmm.py

示例10: print

# 需要导入模块: from hmmlearn.hmm import GaussianHMM [as 别名]
# 或者: from hmmlearn.hmm.GaussianHMM import fit [as 别名]
import numpy as np
import matplotlib.pyplot as plt
from hmmlearn.hmm import GaussianHMM

# 从输入文件中加载数据
input_file = 'CNY.csv'
data = np.loadtxt(input_file, delimiter=',')

# 提取需要的值
closing_values = np.array(data[:, 6])
volume_of_shares = np.array(data[:, 8])[:-1]

# 计算每天收盘价变化率
diff_percentage = 100.0 * np.diff(closing_values) / closing_values[:-1]

# 将变化率与交易量组合起来
X = np.column_stack((diff_percentage, volume_of_shares))

# 创建并训练高斯隐马尔科夫模型
print(u"训练高斯隐马尔科夫模型中......")
model = GaussianHMM(n_components=5, covariance_type='diag', n_iter=1000)
model.fit(X)

# 用模型生成数据
num_samples = 500
samples, _ = model.sample(num_samples)
plt.plot(np.arange(num_samples), samples[:, 0], c='black')
plt.figure()
plt.plot(np.arange(num_samples), samples[:, 1], c='red')
plt.show()
开发者ID:Tian-Yu,项目名称:Python-box,代码行数:32,代码来源:hmm_stock.py

示例11: CasmlApproximator

# 需要导入模块: from hmmlearn.hmm import GaussianHMM [as 别名]
# 或者: from hmmlearn.hmm.GaussianHMM import fit [as 别名]

#.........这里部分代码省略.........
            # # use HMM to calculate probability for observing sequence <current_state, next_state>
            # # noinspection PyTypeChecker
            # weights = np.exp(self._approximator._hmm.score(sequences))
            # for (_, succ), w in zip(self._neighbors, weights):
            #     self._weights[MDPState.create(succ)] = w
            #
            # sum_ = weights.sum()
            # for (_, succ), w in zip(self._neighbors, weights):
            #     if len(weights) <= 1:
            #         w *= 0.9
            #     self._weights[MDPState.create(succ)] = w / sum_

    # -----------------------------
    # CasmlApproximator
    # -----------------------------
    def __init__(self, feature_metadata, minfraction, scale, kernelfn, tau=None, sigma=None, ncomponents=1, n_iter=1):
        super(CasmlApproximator, self).__init__()

        self._minfraction = minfraction
        self._scale = scale
        self._kernelfn = kernelfn
        self._new_sequence = True

        #: Contains all the existing CasmlAppoximations created by
        #: this CasmlApproximator. The keys serve as both queries and
        #: bases (queries are a superset of bases), so a datum may be
        #: None if the associated key is just a basis, not a query.
        self._queries = weakref.WeakValueDictionary()
        """:type: dict[tuple[MDPState, MDPAction], Approximation]"""
        #: The subset of keys of queries that are also bases.
        #: The order in which the bases have been received is preserved
        self._bases = set()
        """:type: set[tuple[MDPState, Hashable]"""
        self._fit_X = []
        """:type: list[ndarray]"""

        #: The case base maintaining the observations in the form
        #:     c = <s, a, ds>, where ds = s_{i+1} - s_i
        #: to identify possible successor states.
        self._basiscb = CaseBase(feature_metadata,
                                 retention_method=self._RetentionMethod,
                                 retention_method_params=(tau, sigma), name='basiscb')
        """:type: CaseBase"""
        del feature_metadata['delta_state']
        #: Invariant: contains all the keys in queries
        self._querycb = CaseBase(feature_metadata, name='querycb')
        """:type: CaseBase"""
        #: The hidden Markov model maintaining the observations in the form
        #:     seq = <s_{i}, s_{i+1}>
        #: to reason on the transition probabilities of successor states.
        self._hmm = GaussianHMM(ncomponents, n_iter=n_iter)  # , covariance_type='full'
        # self._hmm = GaussianHMM(ncomponents)
        """:type: GaussianHMM"""

        self._not_add_bases = 0
        self._not_add_count = 0

    def initialize(self):
        """Prepare for a new episode."""
        self._new_sequence = True

    def add_basis(self, state, act, succ=None):
        """Adds a state to the set of bases used to approximate query
        states.

        Parameters
开发者ID:evenmarbles,项目名称:rlpy,代码行数:70,代码来源:casml.py

示例12: predict_states

# 需要导入模块: from hmmlearn.hmm import GaussianHMM [as 别名]
# 或者: from hmmlearn.hmm.GaussianHMM import fit [as 别名]
def predict_states(X,group_id,empirical_states):
	#print("fitting to HMM and decoding ...")
	max_state_number = (group_id+1)*10
	n_components = 2
	
	# make an HMM instance and execute fit
	model = GaussianHMM(n_components, covariance_type="diag", n_iter=1000)
	
	# Train n number of HMM to avoid loacl minimal 
	max_score = 0
	max_proba_states = []
	transmat = [[]]
	n = 2
	for i in range(1,n):
		model.fit([X])
		score = model.decode(X)[0]
		if i==1 or max_score < score:
			max_score = score
			max_proba_states = model.predict(X)
			transmat = model.transmat_
		
		'''	
		print "score", score
		# predict the optimal sequence of internal hidden state
		hidden_states = model.predict(X)
		print hidden_states
		'''
	# end multiple training
	
	#print max_score, max_proba_states, transmat
	
	# Compare the state with empirical states
	max_proba_states = max_proba_states.tolist()
	max_proba_states_inver = []
	for s in max_proba_states:
		max_proba_states_inver.append(0 if s == 1 else 1)
	
	#print empirical_states, max_proba_states, max_proba_states_inver
	
	difference_state = np.subtract(np.array(max_proba_states),np.array(empirical_states)).tolist()
	difference_state_inver = np.subtract(np.array(max_proba_states_inver),np.array(empirical_states)).tolist()
	
	difference = np.sum(np.power(difference_state,2))
	difference_inver = np.sum(np.power(difference_state_inver,2))
	
	#print difference, difference_inver
	
	if(difference_inver < difference):
		max_proba_states = max_proba_states_inver
	# end switch bits
	
	# Predict future state
	future_states_proba = np.dot([0,1],transmat)
	future_state = 0
	if future_states_proba[1] > future_states_proba[0]:
		future_state = 1	
	# End
	
	result_states = max_proba_states+[future_state for i in range(0,max_state_number-len(max_proba_states))];
	return result_states		
	print("done\n")
开发者ID:xwtt8,项目名称:Hospital-Readmission-,代码行数:63,代码来源:multiFeaturesHmm.py

示例13: range

# 需要导入模块: from hmmlearn.hmm import GaussianHMM [as 别名]
# 或者: from hmmlearn.hmm.GaussianHMM import fit [as 别名]
std_devs = []

for i in range(len(spoken)):
	#print "fitting to HMM and decoding ..."

	n_components = 3
	arr = []

	# make an HMM instance and execute fit
	model = GaussianHMM(n_components, covariance_type="diag", n_iter=1000)

	for j in range(n_samples):
		(rate,sig) = wav.read(fpaths[i][j])
		features = get_features(sig)
		arr.append(len(features))
		model.fit([features])

	models.append(model)
	means.append(np.mean(arr))
	std_devs.append(np.std(arr))
	#print("done\n")

correct_answers = []
with open('Test/'+test_folder+'/answer.txt') as answers:
    for entry in answers:
        correct_answers.append(entry.split())

tot_words = len(correct_answers)
right = 0.0
threshold = 1.5
开发者ID:jigneshjain25,项目名称:Isolated-Word-Hindi-Speech-Recognition,代码行数:32,代码来源:training.py

示例14: print

# 需要导入模块: from hmmlearn.hmm import GaussianHMM [as 别名]
# 或者: from hmmlearn.hmm.GaussianHMM import fit [as 别名]
diff = close_v[1:] - close_v[:-1]
dates = dates[1:]
close_v = close_v[1:]

# pack diff and volume for training
X = np.column_stack([diff, volume])

###############################################################################
# Run Gaussian HMM
print("fitting to HMM and decoding ...", end="")
n_components = 5

# make an HMM instance and execute fit
model = GaussianHMM(n_components, covariance_type="diag", n_iter=1000)

model.fit([X])

# predict the optimal sequence of internal hidden state
hidden_states = model.predict(X)

print("done\n")

###############################################################################
# print trained parameters and plot
print("Transition matrix")
print(model.transmat_)
print()

print("means and vars of each hidden state")
for i in range(n_components):
    print("%dth hidden state" % i)
开发者ID:pierre-haessig,项目名称:hmmlearn,代码行数:33,代码来源:plot_hmm_stock_analysis.py

示例15: scale

# 需要导入模块: from hmmlearn.hmm import GaussianHMM [as 别名]
# 或者: from hmmlearn.hmm.GaussianHMM import fit [as 别名]
            obs = obs[1:]
            obs = obs.T
            obs = scale(obs)

            model = GaussianHMM(algorithm='viterbi', covariance_type='diag', covars_prior=0.01,
                  covars_weight=1, init_params='mc', means_prior=0, means_weight=0,
                  min_covar=0.001, n_components=3, n_iter=1000, params='mc',
                  random_state=None, startprob_prior=1.0, tol=0.01, transmat_prior=1.0,
                  verbose=False)

            model.startprob_ = numpy.array([1., 0, 0])
            model.startprob_prior = model.startprob_
            model.transmat_ = numpy.array([[0.9, 0.1, 0], [0, 0.9, 0.1], [0, 0, 1]])
            model.transmat_prior = model.transmat_

            model.fit(obs)

            pi = model.startprob_
            A = model.transmat_
            w = numpy.ones((n, m), dtype=numpy.double)
            hmm_means = numpy.ones((n, m, d), dtype=numpy.double)
            hmm_means[0][0] = model.means_[0]
            hmm_means[1][0] = model.means_[1]
            hmm_means[2][0] = model.means_[2]
            hmm_covars = numpy.array([[ numpy.matrix(numpy.eye(d,d)) for j in xrange(m)] for i in xrange(n)])
            hmm_covars[0][0] = model.covars_[0]
            hmm_covars[1][0] = model.covars_[1]
            hmm_covars[2][0] = model.covars_[2]
            gmmhmm = GMHMM(n,m,d,A,hmm_means,hmm_covars,w,pi,init_type='user',verbose=False)

            # hidden_state = model.predict(obs)
开发者ID:xavierfav,项目名称:freesound-python,代码行数:33,代码来源:exWind.py


注:本文中的hmmlearn.hmm.GaussianHMM.fit方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。