near_me
Linear Algebra
keyboard_arrow_down 54 guides
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 tocTable of Contents
expand_more Master the mathematics behind data science with 100+ top-tier guides
Start your free 7-days trial now!
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
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
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]). # 4
model.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]) # 4
model = 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.
Published by Isshin Inada
Edited by 0 others
Did you find this page useful?
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!