11. Binary Classification with TensorFlow

Binary classification with tensorflow

tensorflow

TOC

Binary Classification for Simple Data

import tensorflow as tf
import matplotlib.pyplot as plt

# Simple input data, 6 x 2
x_data = [[1,2], [2,3], [3,1], [4,3], [5,3], [6,2]]
# Answer, 6 x 1
y_data = [[0,], [0], [0], [1], [1], [1]]

# Placeholders for a tensor that will be always fed.
X = tf.placeholder(tf.float32, shape=[None, 2])
Y = tf.placeholder(tf.float32, shape=[None, 1])
# Weight, 2 x 1
W = tf.Variable(tf.random_normal([2,1]), name='weight')
# Bias, 1
b = tf.Variable(tf.random_normal([1]), name='bias')

# Hypothesis using sigmoid: tf.div(1., 1. + tf.exp(tf.matmul(X, W) + b))
hypothesis = tf.sigmoid(tf.matmul(X, W) + b)

# Cost function
cost = -tf.reduce_mean(\
        Y * tf.log(hypothesis) + (1 - Y) * tf.log(1 - hypothesis))
# Gradient descent optimizer
train = tf.train.GradientDescentOptimizer(learning_rate=0.01).minimize(cost)

# Output function: True if hypthesis>.5 else False
predicted = tf.cast(hypothesis > 0.5, dtype=tf.float32)
# Accuracy computation
accuracy = tf.reduce_mean(tf.cast(tf.equal(predicted, Y), dtype=tf.float32))

trials = [i for i in range(10001)]
costs = []
# Launch graph
with tf.Session() as sess:
    # Initialize Tensorflow variables
    sess.run(tf.global_variables_initializer())

    for step in range(10001):
        # Training
        cost_val, _ = sess.run([cost, train], feed_dict={X:x_data, Y:y_data})
        costs.append(cost_val)

    # Accuracy check for trained input data
    h, p, a = sess.run([hypothesis, predicted, accuracy],\
                      feed_dict={X:x_data, Y:y_data})

    print("Hypothesis, Prediction")
    for i in range(len(h)):
        print("{0} {1}".format(h[i], p[i]))
    print("Acuracy: {0}".format(a))

    plt.plot(trials, costs)
    plt.title("Costs")
    plt.xlabel("trial")
    plt.ylabel("costs")
    plt.grid()
    plt.show()
Hypothesis, Prediction
[ 0.041998] [ 0.]
[ 0.17176442] [ 0.]
[ 0.35488054] [ 0.]
[ 0.75937283] [ 1.]
[ 0.92487144] [ 1.]
[ 0.97536916] [ 1.]
Accuracy: 1.0
output_1_1
Image 1. Binary classification for simple data

Classifying diabetes

  • Data for diabetes
  • X_n is a factor for diabetes.
  • If Y is 1, he/she has diabetes. If 0, he/she does not.
diabetes
Image 2. Input & output for diabetes
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt

# Load data from file
xy = np.loadtxt("data-03-diabetes.csv", delimiter=",", dtype=np.float32)
# Input, all rows and n-1 columns
x_data = xy[:, 0:-1]
# Answer, all rows and last column
y_data = xy[:, [-1]]

# Placeholders for a tensor that will be always fed.
X = tf.placeholder(tf.float32, shape=[None, 8])
Y = tf.placeholder(tf.float32, shape=[None, 1])
# Weight, 2 x 1
W = tf.Variable(tf.random_normal([8,1]), name='weight')
# Bias, 1
b = tf.Variable(tf.random_normal([1]), name='bias')

# Hypothesis using sigmoid: tf.div(1., 1. + tf.exp(tf.matmul(X, W) + b))
hypothesis = tf.sigmoid(tf.matmul(X, W) + b)

# Cost function
cost = -tf.reduce_mean(\
        Y * tf.log(hypothesis) + (1 - Y) * tf.log(1 - hypothesis))
# Gradient descent optimizer
train = tf.train.GradientDescentOptimizer(learning_rate=0.01).minimize(cost)

# Output function: True if hypthesis>.5 else False
predicted = tf.cast(hypothesis > 0.5, dtype=tf.float32)
# Accuracy computation
accuracy = tf.reduce_mean(tf.cast(tf.equal(predicted, Y), dtype=tf.float32))

maxTrials = 20001
trials = [i for i in range(maxTrials)]
costs = []
# Launch graph
with tf.Session() as sess:
    # Initialize Tensorflow variables
    sess.run(tf.global_variables_initializer())

    for step in range(maxTrials):
        # Training
        cost_val, _ = sess.run([cost, train], feed_dict={X:x_data, Y:y_data})
        costs.append(cost_val)

    # Accuracy check for trained input data
    h, p, a = sess.run([hypothesis, predicted, accuracy],\
                      feed_dict={X:x_data, Y:y_data})

    print("Acuracy: {0}".format(a))

    plt.plot(trials, costs)
    plt.title("Costs")
    plt.xlabel("trial")
    plt.ylabel("costs")
    plt.grid()
    plt.show()
Accuracy: 0.7694334387779236
output_3_1
Image 3. Binary classification for diabetes

COMMENTS

Name

0 weights,1,abstract class,1,active function,3,adam,2,Adapter,1,affine,2,argmax,1,back propagation,3,binary classification,3,blog,2,Bucket list,1,C++,11,Casting,1,cee,1,checkButton,1,cnn,3,col2im,1,columnspan,1,comboBox,1,concrete class,1,convolution,2,cost function,6,data preprocessing,2,data set,1,deep learning,31,Design Pattern,12,DIP,1,django,1,dnn,2,Don't Repeat Your code,1,drop out,2,ensemble,2,epoch,2,favicon,1,fcn,1,frame,1,gradient descent,5,gru,1,he,1,identify function,1,im2col,1,initialization,1,Lab,9,learning rate,2,LifeLog,1,linear regression,6,logistic function,1,logistic regression,3,logit,3,LSP,1,lstm,1,machine learning,31,matplotlib,1,menu,1,message box,1,mnist,3,mse,1,multinomial classification,3,mutli layer neural network,1,Non Virtual Interface,1,normalization,2,Note,21,numpy,4,one-hot encoding,3,OOP Principles,2,Open Close Principle,1,optimization,1,overfitting,1,padding,2,partial derivative,2,pooling,2,Prototype,1,pure virtual function,1,queue runner,1,radioButton,1,RBM,1,regularization,1,relu,2,reshape,1,restricted boltzmann machine,1,rnn,2,scrolledText,1,sigmoid,2,sigmoid function,1,single layer neural network,1,softmax,6,softmax classification,3,softmax cross entropy with logits,1,softmax function,2,softmax regression,3,softmax-with-loss,2,spinBox,1,SRP,1,standardization,1,sticky,1,stride,1,tab,1,Template Method,1,TensorFlow,31,testing data,1,this,2,tkinter,5,tooltip,1,Toplevel,1,training data,1,vanishing gradient,1,Virtual Copy Constructor,1,Virtual Destructor,1,Virtual Function,1,weight decay,1,xavier,2,xor,3,
ltr
item
Universe In Computer: 11. Binary Classification with TensorFlow
11. Binary Classification with TensorFlow
Binary classification with tensorflow
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiE9QfIQg9MqxmXv8wo1jRHrMgva3N0n9uaoJIHiM44Vt8k6nlufCwcOrXM4piATO-QqQmLgh_JEZUv2KXJVRIATvdu0xwckn-JPaRyfJpu9tFP929dbQgKHcd0zfVFfe9EjSkH18A4MxU4/s0/
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiE9QfIQg9MqxmXv8wo1jRHrMgva3N0n9uaoJIHiM44Vt8k6nlufCwcOrXM4piATO-QqQmLgh_JEZUv2KXJVRIATvdu0xwckn-JPaRyfJpu9tFP929dbQgKHcd0zfVFfe9EjSkH18A4MxU4/s72-c/
Universe In Computer
https://kunicom.blogspot.com/2017/07/11-binary-classification-with-tensorflow.html
https://kunicom.blogspot.com/
https://kunicom.blogspot.com/
https://kunicom.blogspot.com/2017/07/11-binary-classification-with-tensorflow.html
true
2543631451419919204
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS CONTENT IS PREMIUM Please share to unlock Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy