Sunday, November 27, 2022
HomeSoftware DevelopmentLinear Classifier in Tensorflow - GeeksforGeeks

Linear Classifier in Tensorflow – GeeksforGeeks


On this article, we shall be utilizing tf.estimator.LinearClassifier to construct a mannequin and prepare it on the well-known titanic dataset. All of this shall be accomplished through the use of the TensorFlow API.

Importing Libraries 

Python libraries make it simple for us to deal with the info and carry out typical and sophisticated duties with a single line of code.

  • Pandas – This library helps to load the info body in a 2D array format and has a number of capabilities to carry out evaluation duties in a single go.
  • Numpy – Numpy arrays are very quick and might carry out giant computations in a really brief time.
  • Matplotlib/Seaborn – This library is used to attract visualizations.

Python3

import tensorflow as tf

import tensorflow.feature_column as fc

  

import numpy as np

import pandas as pd

import matplotlib.pyplot as plt

  

import warnings

warnings.filterwarnings('ignore')

Importing Dataset

We’ll import the dataset through the use of the Tensorflow API for datasets after which load it into the panda’s knowledge body.

Output:

 

Python3

y_train = x_train.pop('survived')

y_val = x_val.pop('survived')

We’ll want the info for the explicit columns and the numeric(steady) column current within the dataset individually to initialize our Linear Classifier mannequin.

Python3

objects = []

numerics = []

  

for col in x_train.columns:

    if x_train[col].dtype == 'object':

        objects.append(col)

          

    elif x_train[col].dtype == 'int':

        objects.append(col)

          

    else:

        numerics.append(col)

  

print(objects)

print(numerics)

Output:

['sex', 'n_siblings_spouses', 'parch', 'class', 'deck', 'embark_town', 'alone']
['age', 'fare']

Python3

feat_cols = []

for feat_name in objects:

    vocabulary = x_train[feat_name].distinctive()

    feat_cols.append(fc.categorical_column_with_vocabulary_list(feat_name,

                                                                vocabulary))

  

for feat_name in numerics:

    feat_cols.append(fc.numeric_column(feat_name,

                                       dtype=tf.float32))

We have to make a callable operate that may be handed to the LinearClassifier operate.

Python3

def make_input_fn(knowledge, label,

                  num_epochs=10,

                  shuffle=True,

                  batch_size=32):

    def input_function():

        ds = tf.knowledge.Dataset

            .from_tensor_slices((dict(knowledge),

                                 label))

        if shuffle:

            ds = ds.shuffle(1000)

        ds = ds.batch(batch_size)

            .repeat(num_epochs)

        return ds

    return input_function

  

  

train_input_fn = make_input_fn(x_train, y_train)

val_input_fn = make_input_fn(x_val, y_val, num_epochs=1, shuffle=False)

Now we’re good to go to coach the tf.estimator.LinearClassifier mannequin utilizing the titanic dataset. Linear Classifier because the title suggests is a Linear mannequin which is used to study choice boundaries between a number of courses of the item however that must be Linear not non-Linear as we achieve this within the SVM algorithm.

LinearClassifier Mannequin

Python3

linear_est = tf.estimator.LinearClassifier(feature_columns=feat_cols)

linear_est.prepare(train_input_fn)

end result = linear_est.consider(val_input_fn)

  

print(end result)

Output:

{'accuracy': 0.75,
 'accuracy_baseline': 0.625,
 'auc': 0.8377411,
 'auc_precision_recall': 0.7833674,
 'average_loss': 0.47364476,
 'label/imply': 0.375, 'loss': 0.4666896,
 'precision': 0.6666667,
 'prediction/imply': 0.37083066,
 'recall': 0.6666667,
 'global_step': 200}

Right here we are able to observe that the mannequin has been evaluated on a number of matrices utilizing the validation dataset and the accuracy obtained can also be very passable.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments