search
Search
Unlock 100+ guides
search toc
close
Cancel
Post
account_circle
Profile
exit_to_app
Sign out
What does this mean?
Why is this true?
Give me some examples!
search
keyboard_voice
close
Searching Tips
Search for a recipe:
"Creating a table in MySQL"
Search for an API documentation: "@append"
Search for code: "!dataframe"
Apply a tag filter: "#python"
Useful Shortcuts
/ to open search panel
Esc to close search panel
to navigate between search results
d to clear all current filters
Enter to expand content preview
Doc Search
Code Search Beta
SORRY NOTHING FOUND!
mic
Start speaking...
Voice search is only supported in Safari and Chrome.
Shrink
Navigate to
near_me
Linear Algebra
54 guides
keyboard_arrow_down
chevron_leftTensorFlow
check_circle
Mark as learned
thumb_up
0
thumb_down
0
chat_bubble_outline
0
Comment
auto_stories Bi-column layout
settings

# Introduction to TensorFlow

schedule Aug 10, 2023
Last updated
local_offer
Tags
mode_heat
Master the mathematics behind data science with 100+ top-tier guides
Start your free 7-days trial now!

In this introduction, we use TensorFlow to train a neural network to classify Iris using the the classic tabular Iris dataset.

# Importing and preprocessing dataset

``` bunch_iris = datasets.load_iris()# Construct a DataFrame from the Bunch Objectdf_data = pd.DataFrame(data=np.c_[bunch_iris['data'], bunch_iris['target']], columns=bunch_iris['feature_names'] + ['target'])df_data.head() sepal length (cm) sepal width (cm) petal length (cm) petal width (cm) target0 5.1 3.5 1.4 0.2 0.01 4.9 3.0 1.4 0.2 0.02 4.7 3.2 1.3 0.2 0.03 4.6 3.1 1.5 0.2 0.04 5.0 3.6 1.4 0.2 0.0 `````` # Break into X (features) and y (target)df_X = df_data.iloc[:,:4]df_y = df_data.iloc[:,-1]df_X_train, df_X_test, ser_y_train, ser_y_test = train_test_split(df_X, df_y, test_size=0.2, random_state=50) ```

To convert the targets into one-hot encoded:

``` np_two_y_train = tf.keras.utils.to_categorical(ser_y_train)np_two_y_test = tf.keras.utils.to_categorical(ser_y_test)np_two_y_train[:3] array([[0., 0., 1.], [0., 1., 0.], [0., 1., 0.]], dtype=float32) ```

# Building and training model

For this task, we build a neural network with the following architecture:

We define and compile the model:

``` model = Sequential()tuple_input_shape = (df_X_train.shape[1], )int_output_size = len(np_two_y_train[0]). # 4model.add(Dense(64, activation='relu', input_shape=tuple_input_shape))model.add(Dense(64, activation='relu'))model.add(Dense(int_output_size, activation='softmax'))model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) ```

Note that we can equivalently do the following:

``` tuple_input_shape = (df_X_train.shape[1], )int_output_size = len(np_two_y_train[0]) # 4model = tf.keras.Sequential([ tf.keras.layers.Dense(64, activation=tf.nn.relu, input_shape=tuple_input_shape), tf.keras.layers.Dense(64, activation=tf.nn.relu), tf.keras.layers.Dense(int_output_size, activation=tf.nn.softmax)])model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) ```

We can then fit the compiled model:

``` model.fit(df_X_train, np_two_y_train, epochs=50, validation_split=0.2) Epoch 1/503/3 [==============================] - 0s 78ms/step - loss: 1.0546 - accuracy: 0.5521 - val_loss: 0.9506 - val_accuracy: 0.7083Epoch 2/503/3 [==============================] - 0s 9ms/step - loss: 0.9357 - accuracy: 0.6771 - val_loss: 0.8631 - val_accuracy: 0.7083....Epoch 50/503/3 [==============================] - 0s 19ms/step - loss: 0.1525 - accuracy: 0.9792 - val_loss: 0.1762 - val_accuracy: 0.9583 ```

# Evaluating model

``` loss, acc = model.evaluate(df_X_test, np_two_y_test, verbose=0)print('Test Accuracy: %.3f' % acc) Test Accuracy: 0.967 ```

# Visualising training results

``` plt.plot(history.history['accuracy'], color='blue')plt.plot(history.history['val_accuracy'], color='red')plt.title('Model accuracy')plt.ylabel('Accuracy')plt.xlabel('Epoch')plt.legend(['train', 'test'], loc='lower right')plt.show() ```

This produces the following graph:

To visualise the loss over epochs:

``` plt.plot(history.history['loss'], color='blue')plt.plot(history.history['val_loss'], color='red')plt.title('Model loss')plt.ylabel('Loss')plt.xlabel('Epoch')plt.legend(['train', 'test'], loc='lower right')plt.show() ```

This produces the following graph:

# Making new predictions

``` new_data = [3,4,2,1]np_one_pred = model.predict([new_data])print('Predicted: %s (class=%d)' % (np_one_pred, argmax(np_one_pred))) Predicted: [[0.9646685 0.03399274 0.00133864]] (class=0) ```

# Saving model

To save a Keras model:

``` model.save("my_model") ```

This creates a folder called `my_model`, which holds all the weights and relevant environment configs, in the same directory as the script.

Edited by 0 others
thumb_up
thumb_down
Comment
Citation
Ask a question or leave a feedback...
thumb_up
0
thumb_down
0
chat_bubble_outline
0
settings
Enjoy our search
Hit / to insta-search docs and recipes!