Created
February 28, 2018 07:17
-
-
Save redwrasse/2a26b08a48bc7fa41226f895a1596043 to your computer and use it in GitHub Desktop.
margin perceptron in tensorflow
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def margin_perceptron(): | |
import numpy as np | |
import tensorflow as tf | |
c1 = np.random.randn(50, 100) + 1 | |
c2 = np.random.randn(50, 100) - 1 | |
X = np.vstack([c1, c2]) | |
Y = np.concatenate([np.ones((50, 1)), 1 - np.zeros((50, 1))]) | |
w = tf.Variable(tf.random_normal((100, 1)), | |
name='w', dtype=tf.float32) | |
input = tf.placeholder(tf.float32, [None, 100]) | |
target = tf.placeholder(tf.float32, [None, 1]) | |
loss = 1.0 / 100.0 * tf.reduce_sum(tf.maximum(0.0, target * tf.matmul(input, w))) | |
optimizer = tf.train.AdamOptimizer(learning_rate=1e-4).minimize(loss) | |
with tf.Session() as sess: | |
sess.run(tf.global_variables_initializer()) | |
ls = 1.0 | |
i = 0 | |
while ls > 0.05: | |
_, ls = sess.run([optimizer, loss], feed_dict={input: X, target: Y}) | |
if i % 100 == 0: | |
print("Loss: {}".format(ls)) | |
i += 1 | |
print("Final loss: {}".format(ls)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment