本文整理汇总了Python中hmmlearn.hmm.GaussianHMM.score方法的典型用法代码示例。如果您正苦于以下问题:Python GaussianHMM.score方法的具体用法?Python GaussianHMM.score怎么用?Python GaussianHMM.score使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类hmmlearn.hmm.GaussianHMM
的用法示例。
在下文中一共展示了GaussianHMM.score方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: select
# 需要导入模块: from hmmlearn.hmm import GaussianHMM [as 别名]
# 或者: from hmmlearn.hmm.GaussianHMM import score [as 别名]
def select(self):
warnings.filterwarnings("ignore", category=DeprecationWarning)
# TODO implement model selection based on DIC scores
# raise NotImplementedError
record = float("-inf")
min_seq = min([len(seq) for seq in self.sequences])
self.max_n_components = min (self.max_n_components, min_seq)
hmm_model = self.base_model(self.n_constant)
for num in range(self.min_n_components,self.max_n_components+1,1):
#print(num)
try:
model = GaussianHMM(n_components= num, n_iter=1000).fit(self.X, self.lengths)
logL = model.score(self.X, self.lengths)
tmp = 0
for word in self.hwords:
X, lengths = self.hwords[word]
tmp += model.score(X,lengths)
DIC = logL - (tmp-logL) /(len(self.hwords)-1)
if DIC > record:
record = DIC
hmm_model = model
except:
continue
# print("failure on {} with {} states".format(self.this_word, num))
return hmm_model
示例2: select
# 需要导入模块: from hmmlearn.hmm import GaussianHMM [as 别名]
# 或者: from hmmlearn.hmm.GaussianHMM import score [as 别名]
def select(self):
warnings.filterwarnings("ignore", category=DeprecationWarning)
best_score = float("-inf")
best_model = None
for n in range(self.min_n_components, self.max_n_components+1):
try:
other_words_score = 0.0
quantity = 0.0
model = GaussianHMM(n_components=n, covariance_type="diag", n_iter=1000,
random_state=self.random_state, verbose=False).fit(self.X, self.lengths)
this_word_score = model.score(self.X, self.lengths)
for word in self.hwords:
if word != self.this_word:
quantity += 1
X, lengths = self.hwords[word]
other_words_score += model.score(X, lengths)
# equation from udacity forum: https://discussions.udacity.com/t/how-to-start-coding-the-selectors/476905/10
score = this_word_score - other_words_score / quantity
if score > best_score:
best_score = score
best_model = model
except:
continue
return best_model
示例3: select
# 需要导入模块: from hmmlearn.hmm import GaussianHMM [as 别名]
# 或者: from hmmlearn.hmm.GaussianHMM import score [as 别名]
def select(self):
warnings.filterwarnings("ignore", category=DeprecationWarning)
max_score = None
max_model = None
for n in range(self.min_n_components, self.max_n_components + 1):
try:
all_score = 0.0
qty = 0
final_model = None
if (len(self.sequences) >= 2):
# Generate K folds
folds = min(len(self.sequences),3)
split_method = KFold(shuffle=True, n_splits=folds)
parts = split_method.split(self.sequences)
for cv_train_idx, cv_test_idx in parts:
# Kfold information for train
X_train, lengths_train = np.asarray(combine_sequences(cv_train_idx, self.sequences))
# Kfold information for test
X_test, lengths_test = np.asarray(combine_sequences(cv_test_idx, self.sequences))
# Fit model with train data
model = GaussianHMM(n_components=n, covariance_type="diag", n_iter=1000,
random_state=self.random_state, verbose=False).fit(X_train, lengths_train)
# Get score using test data
all_score = all_score+model.score(X_test,lengths_test)
qty = qty+1
# Calculate score
score = all_score / qty
else:
# cant be fold
final_model = GaussianHMM(n_components=n, covariance_type="diag", n_iter=1000,
random_state=self.random_state, verbose=False).fit(self.X, self.lengths)
score = model.score(self.X, self.lengths)
# Keep model with best score
if max_score is None or max_score < score:
max_score = score
if final_model is None:
final_model = GaussianHMM(n_components=n, covariance_type="diag", n_iter=1000,
random_state=self.random_state, verbose=False).fit(self.X, self.lengths)
max_model = final_model
except:
pass
return max_model
示例4: HmmClassifier
# 需要导入模块: from hmmlearn.hmm import GaussianHMM [as 别名]
# 或者: from hmmlearn.hmm.GaussianHMM import score [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))
示例5: __init__
# 需要导入模块: from hmmlearn.hmm import GaussianHMM [as 别名]
# 或者: from hmmlearn.hmm.GaussianHMM import score [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()
示例6: len
# 需要导入模块: from hmmlearn.hmm import GaussianHMM [as 别名]
# 或者: from hmmlearn.hmm.GaussianHMM import score [as 别名]
tot_words = len(correct_answers)
right = 0.0
threshold = 1.5
for i in xrange(tot_words):
try:
(rate,sig) = wav.read('Test/'+test_folder+"/word" + str(i) + ".wav")
features = get_features(sig)
word_len = len(features)
ans = -1
j = -1
max_ans = -1e9
for model in models:
j = j+1
if math.fabs(word_len - means[j]) <= threshold * std_devs[j]:
temp = model.score(features)
if temp>max_ans:
max_ans = temp
ans = j
#print max_ans
print str(i+1)+". Detected word: "+spoken[ans]
if spoken[ans] == correct_answers[i][0]:
right = right + 1
except:
break
cur_accuracy = (right/tot_words)*100
print "Accuracy = "+str(cur_accuracy)+"%"
if cur_accuracy > accuracy:
示例7: GaussianHMM
# 需要导入模块: from hmmlearn.hmm import GaussianHMM [as 别名]
# 或者: from hmmlearn.hmm.GaussianHMM import score [as 别名]
for grp, files in filesorter.groupby('group'):
list_of_datasets = []
lengths = []
for fn in files.index:
try:
fbf = pd.read_pickle(files.ix[fn]['filepath'])
x_ = np.column_stack(fbf[ i +'_smoothed'] for i in parameters)
list_of_datasets.append(x_)
lengths.append(len(x_))
except:
print 'failed to complete: ', grp, fn
X = np.concatenate(list_of_datasets)
np.save(DATADIR + 'HMM_JAR/' + grp +'_X.npy', X)
np.save(DATADIR + 'HMM_JAR/' + grp +'_lengths.npy', lengths)
model = GaussianHMM(n_components=n_components, covariance_type="diag", n_iter=1000).fit(X, lengths)
likelihoods.append(model.score(X))
joblib.dump(model, DATADIR + 'HMM_JAR/' + grp +'_model.pkl')
groups.append(grp)
# MAKE ONE MODEL PER TREATMENT:
for grp in treatments:
list_of_datasets = []
for data in glob.glob( DATADIR + 'HMM_JAR/*'+ grp +'_X.npy'):
list_of_datasets.append(np.load(data))
X = np.concatenate(list_of_datasets)
lengths = []
for l in glob.glob( DATADIR + 'HMM_JAR/*'+ grp +'_lengths.npy'):
lengths.append(np.load(l))
lengths = np.concatenate(lengths)
示例8: HMM
# 需要导入模块: from hmmlearn.hmm import GaussianHMM [as 别名]
# 或者: from hmmlearn.hmm.GaussianHMM import score [as 别名]
class HMM(object):
def __init__(self):
def setup():
def load_patterns(file):
patterns = None
sizes = np.zeros(len(words))
counter = 0
f = open(file, 'rb')
data = f.readlines()
stack = []
for i in range(np.shape(data)[0]):
data2 = map(float, data[i].split())
data2 = np.reshape(data2, (1, -1))
if i == 0:
stack = data2
else:
stack = np.vstack((stack, data2))
f.close()
sizes[counter] = np.shape(stack)[0]
counter += 1
if patterns is None:
patterns = stack
else:
patterns = np.vstack((patterns, stack))
return patterns
hidden = 1
self.go_model = GaussianHMM(n_components=hidden, covariance_type="diag", n_iter=10000).fit(
load_patterns('go.bin'))
self.back_model = GaussianHMM(n_components=hidden, covariance_type="diag", n_iter=10000).fit(
load_patterns('back.bin'))
self.right_model = GaussianHMM(n_components=hidden, covariance_type="diag", n_iter=10000).fit(
load_patterns('right.bin'))
self.left_model = GaussianHMM(n_components=hidden, covariance_type="diag", n_iter=10000).fit(
load_patterns('left.bin'))
self.stop_model = GaussianHMM(n_components=hidden, covariance_type="diag", n_iter=10000).fit(
load_patterns('stop.bin'))
setup()
self.number_of_components = 5
def match(self, pattern):
probabilities = np.zeros(5)
probabilities[0] = self.go_model.score(np.reshape(pattern, (1, -1)))
probabilities[1] = self.back_model.score(np.reshape(pattern, (1, -1)))
probabilities[2] = self.right_model.score(np.reshape(pattern, (1, -1)))
probabilities[3] = self.left_model.score(np.reshape(pattern, (1, -1)))
probabilities[4] = self.stop_model.score(np.reshape(pattern, (1, -1)))
probabilities = abs(probabilities)
index, error = min(enumerate(probabilities), key=lambda x: x[1])
if error < 9500:
if index == 0:
return 0
elif index == 1:
return 1
elif index == 2:
return 2
elif index == 3:
return 3
else:
return 4
return -1
示例9: GaussianHMM
# 需要导入模块: from hmmlearn.hmm import GaussianHMM [as 别名]
# 或者: from hmmlearn.hmm.GaussianHMM import score [as 别名]
spx_price = spx_price['Close']
spx_price.name = 'SPX Index'
spx_ret = spx_price.shift(1)/ spx_price[1:] - 1
spx_ret.dropna(inplace=True)
#spx_ret = spx_ret * 1000.0
rets = np.column_stack([spx_ret])
# Create the Gaussian Hidden markov Model and fit it
# to the SPY returns data, outputting a score
hmm_model = GaussianHMM(
n_components=3, # number of states
covariance_type="full", # full covariance matrix vs diagonal
n_iter=1000 # number of iterations
).fit(rets)
print("Model Score:", hmm_model.score(rets))
# Plot the in sample hidden states closing values
# Predict the hidden states array
hidden_states = hmm_model.predict(rets)
print('Percentage of hidden state 1 = %f' % (sum(hidden_states)/len(hidden_states)))
print("Transition matrix")
print(hmm_model.transmat_)
print("Means and vars of each hidden state")
for i in range(hmm_model.n_components): # 0 is down, 1 is up
print("{0}th hidden state".format(i))
print("mean = ", hmm_model.means_[i])
print("var = ", np.diag(hmm_model.covars_[i]))