Skip to content

Instantly share code, notes, and snippets.

@prehensilecode
Last active June 18, 2020 17:27
Show Gist options
  • Save prehensilecode/a3408b9493b6e429f51df445178dc46d to your computer and use it in GitHub Desktop.
Save prehensilecode/a3408b9493b6e429f51df445178dc46d to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3.6
import numpy as np
import tensorflow as tf
# Mash-up of:
# - https://stackoverflow.com/a/49497004
# - https://ml-with-tensorflow.info/2017/03/01/svm-with-tensorflow/
X = np.zeros([157, 128])
Y = np.zeros([157], dtype=np.int32)
example_id = np.array(['%d' % i for i in range(len(Y))])
x_column_name = 'x'
example_id_column_name = 'example_id'
train_input_fn = tf.estimator.inputs.numpy_input_fn(
x={x_column_name: X, example_id_column_name: example_id},
y=Y,
num_epochs=None,
shuffle=True)
svm = tf.contrib.learn.SVM(
example_id_column=example_id_column_name,
feature_columns=(tf.contrib.layers.real_valued_column(
column_name=x_column_name, dimension=128),),
l2_regularization=0.1)
svm.fit(input_fn=train_input_fn, steps=10)
metrics = svm.evaluate(input_fn=train_input_fn, steps=1)
print("Loss", metrics['loss'], "\nAccuracy", metrics['accuracy'])
min_x = np.amin(X)
max_x = np.amax(X)
min_y = np.amin(Y)
max_y = np.amax(Y)
x_predict = np.random.uniform(min_x, max_x, (157, 128, 1))
y_predict = np.random.uniform(min_y, max_y, (157, 1))
def predict_fn():
return {
'x': tf.constant(x_predict),
'y': tf.constant(y_predict),
}
pred = list(svm.predict(input_fn=predict_fn))
predicted_class = map(lambda x: x['classes'], pred)
annotations = map(lambda x: '%.2f' % x['logits'][0], pred)
for a in annotations:
print(a)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment