本文整理汇总了Python中pystruct.learners.LatentSSVM类的典型用法代码示例。如果您正苦于以下问题:Python LatentSSVM类的具体用法?Python LatentSSVM怎么用?Python LatentSSVM使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了LatentSSVM类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_switch_to_ad3
def test_switch_to_ad3():
# smoketest only
# test if switching between qpbo and ad3 works inside latent svm
# use less perfect initialization
if not get_installed(['qpbo']) or not get_installed(['ad3']):
return
X, Y = generate_crosses(n_samples=20, noise=5, n_crosses=1, total_size=8)
X_test, Y_test = X[10:], Y[10:]
X, Y = X[:10], Y[:10]
crf = LatentGridCRF(n_states_per_label=2,
inference_method='qpbo')
crf.initialize(X, Y)
H_init = crf.init_latent(X, Y)
np.random.seed(0)
mask = np.random.uniform(size=H_init.shape) > .7
H_init[mask] = 2 * (H_init[mask] / 2)
base_ssvm = OneSlackSSVM(crf, inactive_threshold=1e-8, cache_tol=.0001,
inference_cache=50, max_iter=10000,
switch_to=('ad3', {'branch_and_bound': True}),
C=10. ** 3)
clf = LatentSSVM(base_ssvm)
clf.fit(X, Y, H_init=H_init)
assert_equal(clf.model.inference_method[0], 'ad3')
Y_pred = clf.predict(X)
assert_array_equal(np.array(Y_pred), Y)
# test that score is not always 1
assert_true(.98 < clf.score(X_test, Y_test) < 1)
示例2: test_with_crosses_bad_init
def test_with_crosses_bad_init():
# use less perfect initialization
X, Y = toy.generate_crosses(n_samples=10, noise=5, n_crosses=1,
total_size=8)
n_labels = 2
crf = LatentGridCRF(n_labels=n_labels, n_states_per_label=2,
inference_method='lp')
H_init = crf.init_latent(X, Y)
mask = np.random.uniform(size=H_init.shape) > .7
H_init[mask] = 2 * (H_init[mask] / 2)
one_slack = OneSlackSSVM(crf, inactive_threshold=1e-8, cache_tol=.0001,
inference_cache=50, max_iter=10000)
n_slack = StructuredSVM(crf)
subgradient = SubgradientSSVM(crf, max_iter=150, learning_rate=5)
for base_ssvm in [one_slack, n_slack, subgradient]:
base_ssvm.C = 10. ** 3
base_ssvm.n_jobs = -1
clf = LatentSSVM(base_ssvm)
clf.fit(X, Y, H_init=H_init)
Y_pred = clf.predict(X)
assert_array_equal(np.array(Y_pred), Y)
示例3: test_with_crosses_bad_init
def test_with_crosses_bad_init():
# use less perfect initialization
rnd = np.random.RandomState(0)
X, Y = toy.generate_crosses(n_samples=20, noise=5, n_crosses=1,
total_size=8)
X_test, Y_test = X[10:], Y[10:]
X, Y = X[:10], Y[:10]
n_labels = 2
crf = LatentGridCRF(n_labels=n_labels, n_states_per_label=2)
H_init = crf.init_latent(X, Y)
mask = rnd.uniform(size=H_init.shape) > .7
H_init[mask] = 2 * (H_init[mask] / 2)
one_slack = OneSlackSSVM(crf, inactive_threshold=1e-8, cache_tol=.0001,
inference_cache=50, max_iter=10000)
n_slack = NSlackSSVM(crf)
subgradient = SubgradientSSVM(crf, max_iter=150, learning_rate=.01,
momentum=0)
for base_ssvm in [one_slack, n_slack, subgradient]:
base_ssvm.C = 10. ** 2
clf = LatentSSVM(base_ssvm)
clf.fit(X, Y, H_init=H_init)
Y_pred = clf.predict(X)
assert_array_equal(np.array(Y_pred), Y)
# test that score is not always 1
assert_true(.98 < clf.score(X_test, Y_test) < 1)
示例4: test_directional_bars
def test_directional_bars():
X, Y = generate_easy(n_samples=10, noise=5, box_size=2, total_size=6, seed=1)
n_labels = 2
crf = LatentDirectionalGridCRF(n_labels=n_labels, n_states_per_label=[1, 4])
clf = LatentSSVM(OneSlackSSVM(model=crf, max_iter=500, C=10.0, inference_cache=50, tol=0.01))
clf.fit(X, Y)
Y_pred = clf.predict(X)
assert_array_equal(np.array(Y_pred), Y)
示例5: main
def main():
X, Y = toy.generate_crosses(n_samples=40, noise=8, n_crosses=2,
total_size=10)
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=.5)
n_labels = len(np.unique(Y_train))
crf = LatentGridCRF(n_labels=n_labels, n_states_per_label=2,
inference_method='lp')
clf = LatentSSVM(problem=crf, max_iter=50, C=1000., verbose=2,
check_constraints=True, n_jobs=-1, break_on_bad=True,
plot=True)
clf.fit(X_train, Y_train)
for X_, Y_, H, name in [[X_train, Y_train, clf.H_init_, "train"],
[X_test, Y_test, [None] * len(X_test), "test"]]:
Y_pred = clf.predict(X_)
i = 0
loss = 0
for x, y, h_init, y_pred in zip(X_, Y_, H, Y_pred):
loss += np.sum(y != y_pred / crf.n_states_per_label)
fig, ax = plt.subplots(3, 2)
ax[0, 0].matshow(y * crf.n_states_per_label,
vmin=0, vmax=crf.n_states - 1)
ax[0, 0].set_title("ground truth")
unary_params = np.repeat(np.eye(2), 2, axis=1)
pairwise_params = np.zeros(10)
w_unaries_only = np.hstack([unary_params.ravel(),
pairwise_params.ravel()])
unary_pred = crf.inference(x, w_unaries_only)
ax[0, 1].matshow(unary_pred, vmin=0, vmax=crf.n_states - 1)
ax[0, 1].set_title("unaries only")
if h_init is None:
ax[1, 0].set_visible(False)
else:
ax[1, 0].matshow(h_init, vmin=0, vmax=crf.n_states - 1)
ax[1, 0].set_title("latent initial")
ax[1, 1].matshow(crf.latent(x, y, clf.w),
vmin=0, vmax=crf.n_states - 1)
ax[1, 1].set_title("latent final")
ax[2, 0].matshow(y_pred, vmin=0, vmax=crf.n_states - 1)
ax[2, 0].set_title("prediction")
ax[2, 1].matshow((y_pred // crf.n_states_per_label)
* crf.n_states_per_label,
vmin=0, vmax=crf.n_states - 1)
ax[2, 1].set_title("prediction")
for a in ax.ravel():
a.set_xticks(())
a.set_yticks(())
fig.savefig("data_%s_%03d.png" % (name, i), bbox_inches="tight")
i += 1
print("loss %s set: %f" % (name, loss))
print(clf.w)
示例6: main
def main():
# get some data
X, Y = toy.generate_bars(n_samples=40, noise=10, total_size=10, separate_labels=False)
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.5)
# train a latent grid crf
n_labels = len(np.unique(Y_train))
crf = LatentDirectionalGridCRF(n_labels=n_labels, n_states_per_label=[1, 6], inference_method="lp")
clf = LatentSSVM(
problem=crf,
max_iter=50,
C=10.0,
verbose=2,
check_constraints=True,
n_jobs=-1,
break_on_bad=False,
tol=-10,
base_svm="1-slack",
)
clf.fit(X_train, Y_train)
# the rest is plotting
for X_, Y_, H, name in [[X_train, Y_train, clf.H_init_, "train"], [X_test, Y_test, [None] * len(X_test), "test"]]:
Y_pred = clf.predict(X_)
i = 0
loss = 0
for x, y, h_init, y_pred in zip(X_, Y_, H, Y_pred):
loss += np.sum(y != y_pred)
fig, ax = plt.subplots(3, 2)
ax[0, 0].matshow(y, vmin=0, vmax=crf.n_labels - 1)
ax[0, 0].set_title("ground truth")
unary_pred = np.argmax(x, axis=-1)
ax[0, 1].matshow(unary_pred, vmin=0, vmax=crf.n_labels - 1)
ax[0, 1].set_title("unaries only")
if h_init is None:
ax[1, 0].set_visible(False)
else:
ax[1, 0].matshow(h_init, vmin=0, vmax=crf.n_states - 1)
ax[1, 0].set_title("latent initial")
ax[1, 1].matshow(crf.latent(x, y, clf.w), vmin=0, vmax=crf.n_states - 1)
ax[1, 1].set_title("latent final")
ax[2, 0].matshow(crf.inference(x, clf.w), vmin=0, vmax=crf.n_states - 1)
ax[2, 0].set_title("prediction")
ax[2, 1].matshow(y_pred, vmin=0, vmax=crf.n_labels - 1)
ax[2, 1].set_title("prediction")
for a in ax.ravel():
a.set_xticks(())
a.set_yticks(())
fig.savefig("data_%s_%03d.png" % (name, i), bbox_inches="tight")
i += 1
print("loss %s set: %f" % (name, loss))
示例7: test_states
def test_states(states, x, y, x_t, y_t, i, jobs):
latent_pbl = GraphLDCRF(n_states_per_label=states, inference_method="qpbo")
base_ssvm = NSlackSSVM(latent_pbl, C=1, tol=0.01, inactive_threshold=1e-3, batch_size=10, verbose=0, n_jobs=jobs)
latent_svm = LatentSSVM(base_ssvm=base_ssvm, latent_iter=3)
latent_svm.fit(x, y)
test = latent_svm.score(x_t, y_t)
train = latent_svm.score(x, y)
plot_cm(latent_svm, y_t, x_t, str(states), i)
print states, "Test:", test, "Train:", train
return test, train
示例8: test_with_crosses_base_svms
def test_with_crosses_base_svms():
# very simple dataset. k-means init is perfect
for base_svm in ['1-slack', 'n-slack', 'subgradient']:
X, Y = toy.generate_crosses(n_samples=10, noise=5, n_crosses=1,
total_size=8)
n_labels = 2
crf = LatentGridCRF(n_labels=n_labels, n_states_per_label=[1, 2],
inference_method='lp')
clf = LatentSSVM(problem=crf, max_iter=150, C=10. ** 5, verbose=2,
check_constraints=True, n_jobs=-1, break_on_bad=True,
base_svm=base_svm, learning_rate=5)
clf.fit(X, Y)
Y_pred = clf.predict(X)
assert_array_equal(np.array(Y_pred), Y)
示例9: test_switch_to_ad3
def test_switch_to_ad3():
# smoketest only
# test if switching between qpbo and ad3 works inside latent svm
# use less perfect initialization
if not get_installed(["qpbo"]) or not get_installed(["ad3"]):
return
X, Y = generate_crosses(n_samples=20, noise=5, n_crosses=1, total_size=8)
X_test, Y_test = X[10:], Y[10:]
X, Y = X[:10], Y[:10]
crf = LatentGridCRF(n_states_per_label=2, inference_method="qpbo")
crf.initialize(X, Y)
H_init = crf.init_latent(X, Y)
np.random.seed(0)
mask = np.random.uniform(size=H_init.shape) > 0.7
H_init[mask] = 2 * (H_init[mask] / 2)
base_ssvm = OneSlackSSVM(
crf,
inactive_threshold=1e-8,
cache_tol=0.0001,
inference_cache=50,
max_iter=10000,
switch_to=("ad3", {"branch_and_bound": True}),
C=10.0 ** 3,
)
clf = LatentSSVM(base_ssvm)
# evil hackery to get rid of ad3 output
try:
devnull = open("/dev/null", "w")
oldstdout_fno = os.dup(sys.stdout.fileno())
os.dup2(devnull.fileno(), 1)
replaced_stdout = True
except:
replaced_stdout = False
clf.fit(X, Y, H_init=H_init)
if replaced_stdout:
os.dup2(oldstdout_fno, 1)
assert_equal(clf.model.inference_method[0], "ad3")
Y_pred = clf.predict(X)
assert_array_equal(np.array(Y_pred), Y)
# test that score is not always 1
assert_true(0.98 < clf.score(X_test, Y_test) < 1)
示例10: test_directional_bars
def test_directional_bars():
for inference_method in ['lp']:
X, Y = toy.generate_easy(n_samples=10, noise=5, box_size=2,
total_size=6, seed=1)
n_labels = 2
crf = LatentDirectionalGridCRF(n_labels=n_labels,
n_states_per_label=[1, 4],
inference_method=inference_method)
clf = LatentSSVM(problem=crf, max_iter=500, C=10. ** 5, verbose=2,
check_constraints=True, n_jobs=-1, break_on_bad=True,
base_svm='1-slack')
clf.fit(X, Y)
Y_pred = clf.predict(X)
assert_array_equal(np.array(Y_pred), Y)
示例11: test_with_crosses_perfect_init
def test_with_crosses_perfect_init():
# very simple dataset. k-means init is perfect
for n_states_per_label in [2, [1, 2]]:
# test with 2 states for both foreground and background,
# as well as with single background state
X, Y = generate_crosses(n_samples=10, noise=5, n_crosses=1, total_size=8)
n_labels = 2
crf = LatentGridCRF(n_labels=n_labels, n_states_per_label=n_states_per_label)
clf = LatentSSVM(
OneSlackSSVM(model=crf, max_iter=500, C=10, check_constraints=False, break_on_bad=False, inference_cache=50)
)
clf.fit(X, Y)
Y_pred = clf.predict(X)
assert_array_equal(np.array(Y_pred), Y)
assert_equal(clf.score(X, Y), 1)
示例12: test_with_crosses_bad_init
def test_with_crosses_bad_init():
# use less perfect initialization
X, Y = toy.generate_crosses(n_samples=10, noise=5, n_crosses=1,
total_size=8)
n_labels = 2
crf = LatentGridCRF(n_labels=n_labels, n_states_per_label=2,
inference_method='lp')
clf = LatentSSVM(problem=crf, max_iter=50, C=10. ** 3, verbose=2,
check_constraints=True, n_jobs=-1, break_on_bad=True)
H_init = crf.init_latent(X, Y)
mask = np.random.uniform(size=H_init.shape) > .7
H_init[mask] = 2 * (H_init[mask] / 2)
clf.fit(X, Y, H_init=H_init)
Y_pred = clf.predict(X)
assert_array_equal(np.array(Y_pred), Y)
示例13: test_with_crosses_base_svms
def test_with_crosses_base_svms():
# very simple dataset. k-means init is perfect
n_labels = 2
crf = LatentGridCRF(n_labels=n_labels, n_states_per_label=[1, 2])
one_slack = OneSlackSSVM(crf, inference_cache=50)
n_slack = NSlackSSVM(crf)
subgradient = SubgradientSSVM(crf, max_iter=400, learning_rate=0.01, decay_exponent=0, decay_t0=10)
X, Y = generate_crosses(n_samples=10, noise=5, n_crosses=1, total_size=8)
for base_ssvm in [one_slack, n_slack, subgradient]:
base_ssvm.C = 100.0
clf = LatentSSVM(base_ssvm=base_ssvm)
clf.fit(X, Y)
Y_pred = clf.predict(X)
assert_array_equal(np.array(Y_pred), Y)
assert_equal(clf.score(X, Y), 1)
示例14: test_with_crosses_base_svms
def test_with_crosses_base_svms():
# very simple dataset. k-means init is perfect
n_labels = 2
crf = LatentGridCRF(n_labels=n_labels, n_states_per_label=[1, 2],
inference_method='lp')
one_slack = OneSlackSSVM(crf)
n_slack = StructuredSVM(crf)
subgradient = SubgradientSSVM(crf, max_iter=150, learning_rate=5)
for base_ssvm in [one_slack, n_slack, subgradient]:
base_ssvm.C = 10. ** 5
base_ssvm.n_jobs = -1
X, Y = toy.generate_crosses(n_samples=10, noise=5, n_crosses=1,
total_size=8)
clf = LatentSSVM(base_ssvm=base_ssvm)
clf.fit(X, Y)
Y_pred = clf.predict(X)
assert_array_equal(np.array(Y_pred), Y)
示例15: test_binary_blocks_cutting_plane_latent_node
def test_binary_blocks_cutting_plane_latent_node():
#testing cutting plane ssvm on easy binary dataset
# we use the LatentNodeCRF without latent nodes and check that it does the
# same as GraphCRF
X, Y = toy.generate_blocks(n_samples=3)
crf = GraphCRF(inference_method='lp')
clf = StructuredSVM(model=crf, max_iter=20, C=100, verbose=0,
check_constraints=True, break_on_bad=False,
n_jobs=1)
x1, x2, x3 = X
y1, y2, y3 = Y
n_states = len(np.unique(Y))
# delete some rows to make it more fun
x1, y1 = x1[:, :-1], y1[:, :-1]
x2, y2 = x2[:-1], y2[:-1]
# generate graphs
X_ = [x1, x2, x3]
G = [make_grid_edges(x) for x in X_]
# reshape / flatten x and y
X_ = [x.reshape(-1, n_states) for x in X_]
Y = [y.ravel() for y in [y1, y2, y3]]
X = zip(X_, G)
clf.fit(X, Y)
Y_pred = clf.predict(X)
for y, y_pred in zip(Y, Y_pred):
assert_array_equal(y, y_pred)
latent_crf = LatentNodeCRF(n_labels=2, inference_method='lp',
n_hidden_states=0)
latent_svm = LatentSSVM(StructuredSVM(model=latent_crf, max_iter=20,
C=100, verbose=0,
check_constraints=True,
break_on_bad=False, n_jobs=1),
latent_iter=3)
X_latent = zip(X_, G, np.zeros(len(X_)))
latent_svm.fit(X_latent, Y, H_init=Y)
Y_pred = latent_svm.predict(X_latent)
for y, y_pred in zip(Y, Y_pred):
assert_array_equal(y, y_pred)
assert_array_almost_equal(latent_svm.w, clf.w)