TensorFlow creates a classifier and tensorflow implements classification.

Source: Internet
Author: User

TensorFlow creates a classifier and tensorflow implements classification.

The examples in this article share the code used to create a classifier in TensorFlow for your reference. The details are as follows:

Create a classifier for the iris dataset.

Load the sample data set and implement a simple binary classifier to predict whether a flower is an iris. There are three types of iris data sets, but here we only predict whether the iris is a mountain. Import the iris dataset and tool library to convert the original dataset accordingly.

# Combining Everything Together # ---------------------------------- # This file will perform binary classification on the # iris dataset. we will only predict if a flower is # I. setosa or not. # We will create a simple binary classifier by creating a line # and running everything through a sigmoid to get a binary predictor. # The two features we will use are pedal length and pedal width. # We will use ba Tch training, but this can be easily # adapted to stochastic training. import matplotlib. pyplot as pltimport numpy as npfrom sklearn import datasetsimport tensorflow as tffrom tensorflow. python. framework import opsops. reset_default_graph () # import the iris dataset # convert the target data to 1 or 0 based on whether the target data is an iris. # Because the iris dataset marks the iris as 0, we set it from 0 to 1 and Mark other species as 0. # This training only uses two features: the petal length and the petal width. These two features are in the third and fourth columns of x-value # iris.tar get = {0, 1, 2 }, where '0' is setosa # iris. data ~ [Sepal. width, sepal. length, pedal. width, pedal. length] iris = datasets. load_iris () binary_target = np. array ([1. if x = 0 else 0. for x in iris.tar get]) iris_2d = np. array ([[x [2], x [3] for x in iris. data]) # declare the batch training size batch_size = 20 # initialize the computing image sess = tf. session () # declare the data placeholder xforwardata = tf. placeholder (shape = [None, 1], dtype = tf. float32) x2_data = tf. placeholder (shape = [None, 1], dtype = tf. float32) y_target = tf. placeh Older (shape = [None, 1], dtype = tf. float32) # declare the model variable # Create variables A and B (0 = x1-A * x2 + B) A = tf. variable (tf. random_normal (shape = [1, 1]) B = tf. variable (tf. random_normal (shape = [1, 1]) # defines a linear model: # If the data point found is above a straight line, then the data point is substituted into the x2-x1 * A-B to calculate the result is greater than 0; # Similarly, the data point found below the line, then the data point is substituted into the x2-x1 * A-B and the calculation result is less than 0. # X1-A * x2 + bmy_mult = tf. matmul (x2_data, A) my_add = tf. add (my_mult, B) my_output = tf. subtract (xforwardeddata, my_add) # added the sigmoid cross entropy loss function (cross entropy) of TensorFlow xentropy = tf. nn. sigmoid_cross_entropy_with_logits (logits = my_output, labels = y_target) # declare the optimizer method my_opt = tf. train. gradientDescentOptimizer (0.05) train_step = my_opt.minimize (xentropy) # create a variable initialization operation init = tf. global_variables_initializer () sess. run (init) #1000 runtime iterations for I in range (1000): rand_index = np. random. choice (len (iris_2d), size = batch_size) # rand_x = np. transpose ([iris_2d [rand_index]) # input three types of data: petal length, petal width, and target variable rand_x = iris_2d [rand_index] rand_x1 = np. array ([[x [0] for x in rand_x]) rand_x2 = np. array ([[x [1] for x in rand_x]) # rand_y = np. transpose ([binary_target [rand_index]) rand_y = np. array ([[y] for y in binary_target [rand_index]) sess. run (train_step, feed_dict = {x1_data: rand_x1, x2_data: rand_x2, y_target: rand_y}) if (I + 1) % 200 = 0: print ('step # '+ str (I + 1) + 'a =' + str (sess. run (A) + ', B =' + str (sess. run (B) # plot # obtain the slope/intercept # Pull out slope/intercept [[slope] = sess. run (A) [[intercept] = sess. run (B) # create a fitting line x = np. linspace (0, 3, num = 50) ablineValues = [] for I in x: ablineValues. append (slope * I + intercept) # plot the fitting curve set1__x = [a [1] for I, a in enumerate (iris_2d) if binary_target [I] = 1] setosa_y = [a [0] for I, a in enumerate (iris_2d) if binary_target [I] = 1] non_set1__x = [a [1] for I, a in enumerate (iris_2d) if binary_target [I] = 0] non_set1__y = [a [0] for I, a in enumerate (iris_2d) if binary_target [I] = 0] plt. plot (set0000_x, set0000_y, 'rx ', MS = 10, mew = 2, label = 'setosa') plt. plot (non_set1__x, non_set1__y, 'ro', label = 'non-setosa ') plt. plot (x, ablineValues, 'B-') plt. xlim ([0.0, 2.7]) plt. ylim ([0.0, 7.1]) plt. suptitle ('linear Separator For I. setosa ', fontsize = 20) plt. xlabel ('petal length') plt. ylabel ('petal width') plt. legend (loc = 'lower right') plt. show ()

Output:

Step #200 A = [[ 8.70572948]], b = [[-3.46638322]]Step #400 A = [[ 10.21302414]], b = [[-4.720438]]Step #600 A = [[ 11.11844635]], b = [[-5.53361702]]Step #800 A = [[ 11.86427212]], b = [[-6.0110755]]Step #1000 A = [[ 12.49524498]], b = [[-6.29990339]]

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.