瀏覽代碼

added linear and logistic reg

aymericdamien 9 年之前
父節點
當前提交
fc9f191966
共有 2 個文件被更改,包括 89 次插入0 次删除
  1. 47 0
      linear_regression.py
  2. 42 0
      logistic_regression.py

+ 47 - 0
linear_regression.py

@@ -0,0 +1,47 @@
+import tensorflow as tf
+import numpy
+import matplotlib.pyplot as plt
+rng = numpy.random
+
+# Parameters
+learning_rate = 0.01
+training_epochs = 2000
+display_step = 50
+
+# Training Data
+train_X = numpy.asarray([3.3,4.4,5.5,6.71,6.93,4.168,9.779,6.182,7.59,2.167,7.042,10.791,5.313,7.997,5.654,9.27,3.1])
+train_Y = numpy.asarray([1.7,2.76,2.09,3.19,1.694,1.573,3.366,2.596,2.53,1.221,2.827,3.465,1.65,2.904,2.42,2.94,1.3])
+
+# Create Model
+W = tf.Variable(rng.randn(), name="weight")
+b = tf.Variable(rng.randn(), name="bias")
+
+X = tf.placeholder("float")
+Y = tf.placeholder("float")
+n_samples = train_X.shape[0]
+
+activation = tf.add(tf.mul(X, W), b) #linear
+cost = tf.reduce_sum(tf.pow(activation-Y, 2))/(2*n_samples) #L2
+
+optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)
+
+init = tf.initialize_all_variables()
+
+with tf.Session() as sess:
+    sess.run(init)
+
+    for epoch in range(training_epochs):
+        for (x, y) in zip(train_X, train_Y):
+            sess.run(optimizer, feed_dict={X: x, Y: y})
+
+        if epoch % display_step == 0:
+            print "Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(sess.run(cost, feed_dict={X: train_X, Y:train_Y})), \
+                "W=", sess.run(W), "b=", sess.run(b)
+
+    print "Optimization Finished!"
+    print "cost=", sess.run(cost, feed_dict={X: train_X, Y: train_Y}), "W=", sess.run(W), "b=", sess.run(b)
+
+    plt.plot(train_X, train_Y, 'ro', label='Original data')
+    plt.plot(train_X, sess.run(W) * train_X + sess.run(b), label='Fitted line')
+    plt.legend()
+    plt.show()

+ 42 - 0
logistic_regression.py

@@ -0,0 +1,42 @@
+# Import MINST data
+import input_data
+mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)
+
+import tensorflow as tf
+
+# Parameters
+learning_rate = 0.01
+training_epochs = 25
+batch_size = 100
+display_step = 1
+
+# Create model
+x = tf.placeholder("float", [None, 784])
+y = tf.placeholder("float", [None,10])
+W = tf.Variable(tf.zeros([784,10]))
+b = tf.Variable(tf.zeros([10]))
+
+activation = tf.nn.softmax(tf.matmul(x,W) + b) #softmax
+cost = -tf.reduce_sum(y*tf.log(activation)) #cross entropy
+optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)
+
+# Train
+init = tf.initialize_all_variables()
+with tf.Session() as sess:
+    sess.run(init)
+    for epoch in range(training_epochs):
+        avg_cost = 0.
+        total_batch = int(mnist.train.num_examples/batch_size)
+        for i in range(total_batch):
+            batch_xs, batch_ys = mnist.train.next_batch(batch_size)
+            sess.run(optimizer, feed_dict={x: batch_xs, y: batch_ys})
+            avg_cost += sess.run(cost, feed_dict={x: batch_xs, y: batch_ys})/total_batch
+        if epoch % display_step == 0:
+            print "Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(avg_cost)
+
+    print "Optimization Finished!"
+
+    # Test trained model
+    correct_prediction = tf.equal(tf.argmax(activation,1), tf.argmax(y,1))
+    accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
+    print "Accuracy:", accuracy.eval({x: mnist.test.images, y: mnist.test.labels})