From b484b8a672a907af87e73fe7006497a6ca86c259 Mon Sep 17 00:00:00 2001 From: Navan Chauhan Date: Thu, 21 Mar 2024 13:54:53 -0600 Subject: add polynomial regression for tf 2.0 --- ...3-21-Polynomial-Regression-in-TensorFlow-2.html | 311 +++++++++++++++++++++ 1 file changed, 311 insertions(+) create mode 100644 docs/posts/2024-03-21-Polynomial-Regression-in-TensorFlow-2.html (limited to 'docs/posts/2024-03-21-Polynomial-Regression-in-TensorFlow-2.html') diff --git a/docs/posts/2024-03-21-Polynomial-Regression-in-TensorFlow-2.html b/docs/posts/2024-03-21-Polynomial-Regression-in-TensorFlow-2.html new file mode 100644 index 0000000..c1a4ae4 --- /dev/null +++ b/docs/posts/2024-03-21-Polynomial-Regression-in-TensorFlow-2.html @@ -0,0 +1,311 @@ + + + + + + + + + Polynomial Regression Using TensorFlow 2.x + + + + + + + + + + + + + + + + + + + + + +
+
+ +
+ +

Polynomial Regression Using TensorFlow 2.x

+ +

I have a similar post titled Polynomial Regression Using Tensorflow that used tensorflow.compat.v1 (Which still works as of TF 2.16). But, I thought it would be nicer to redo it with newer TF versions.

+ +

I will be skipping all the introductions about polynomial regression and jumping straight to the code. Personally, I prefer using scikit-learn for this task.

+ +

Position vs Salary Dataset

+ +

Again, we will be using https://drive.google.com/file/d/1tNL4jxZEfpaP4oflfSn6pIHJX7Pachm9/view (Salary vs Position Dataset)

+ +

If you are in a Python Notebook environment like Kaggle or Google Colaboratory, you can simply run:

+ +
+
!wget --no-check-certificate 'https://docs.google.com/uc?export=download&id=1tNL4jxZEfpaP4oflfSn6pIHJX7Pachm9' -O data.csv
+
+
+ +

Code

+ +

If you just want to copy-paste the code, scroll to the bottom for the entire snippet. Here I will try and walk through setting up code for a 3rd-degree (cubic) polynomial

+ +

Imports

+ +
+
import pandas as pd
+import tensorflow as tf
+import matplotlib.pyplot as plt
+import numpy as np
+
+
+ +

Reading the Dataset

+ +
+
df = pd.read_csv("data.csv")
+
+
+ +

Variables and Constants

+ +

Here, we initialize the X and Y values as constants, since they are not going to change. The coefficients are defined as variables.

+ +
+
X = tf.constant(df["Level"], dtype=tf.float32)
+Y = tf.constant(df["Salary"], dtype=tf.float32)
+
+coefficients = [tf.Variable(np.random.randn() * 0.01, dtype=tf.float32) for _ in range(4)]
+
+
+ +

Here, X and Y are the values from our dataset. We initialize the coefficients for the equations as small random values.

+ +

These coefficients are evaluated by Tensorflow's tf.math.poyval function which returns the n-th order polynomial based on how many coefficients are passed. Since our list of coefficients contains 4 different variables, it will be evaluated as:

+ +
y = (x**3)*coefficients[3] + (x**2)*coefficients[2] + (x**1)*coefficients[1] (x**0)*coefficients[0]
+
+ +

Which is equivalent to the general cubic equation:

+ +

+ +$$ +y = ax^3 + bx^2 + cx + d +$$ + +### Optimizer Selection & Training +

+ +
optimizer = tf.keras.optimizers.Adam(learning_rate=0.3)
+num_epochs = 10_000
+
+for epoch in range(num_epochs):
+    with tf.GradientTape() as tape:
+        y_pred = tf.math.polyval(coefficients, X)
+        loss = tf.reduce_mean(tf.square(y - y_pred))
+    grads = tape.gradient(loss, coefficients)
+    optimizer.apply_gradients(zip(grads, coefficients))
+    if (epoch+1) % 1000 == 0:
+        print(f"Epoch: {epoch+1}, Loss: {loss.numpy()}"
+
+ +
+ + +In TensorFlow 1, we would have been using `tf.Session` instead. + +Here we are using `GradientTape()` instead, to keep track of the loss evaluation and coefficients. This is crucial, as our optimizer needs these gradients to be able to optimize our coefficients. + +Our loss function is Mean Squared Error (MSE) + +$$ += \frac{1}{n}\sum_{i=1}^{n} (Y_i - \^{Y_i}) +$$ + +Where $\^{Y_i}$ is the predicted value and $Y_i$ is the actual value + +### Plotting Final Coefficients +
+ +
final_coefficients = [c.numpy() for c in coefficients]
+print("Final Coefficients:", final_coefficients)
+
+plt.plot(df["Level"], df["Salary"], label="Original Data")
+plt.plot(df["Level"],[tf.math.polyval(final_coefficients, tf.constant(x, dtype=tf.float32)).numpy() for x in df["Level"]])
+plt.ylabel('Salary')
+plt.xlabel('Position')
+plt.title("Salary vs Position")
+plt.show()
+
+ +
+ + + +## Code Snippet for a Polynomial of Degree N + +### Using Gradient Tape + +This should work regardless of the Keras backend version (2 or 3) +
+ +
import tensorflow as tf
+import numpy as np
+import pandas as pd
+import matplotlib.pyplot as plt
+
+df = pd.read_csv("data.csv")
+
+############################
+## Change Parameters Here ##
+############################
+x_column = "Level"         #
+y_column = "Salary"        #
+degree = 2                 #
+learning_rate = 0.3        #
+num_epochs = 25_000        #
+############################
+
+X = tf.constant(df[x_column], dtype=tf.float32)
+Y = tf.constant(df[y_column], dtype=tf.float32)
+
+coefficients = [tf.Variable(np.random.randn() * 0.01, dtype=tf.float32) for _ in range(degree + 1)]
+
+optimizer = tf.keras.optimizers.Adam(learning_rate=learning_rate)
+
+for epoch in range(num_epochs):
+    with tf.GradientTape() as tape:
+        y_pred = tf.math.polyval(coefficients, X)
+        loss = tf.reduce_mean(tf.square(Y - y_pred))
+    grads = tape.gradient(loss, coefficients)
+    optimizer.apply_gradients(zip(grads, coefficients))
+    if (epoch+1) % 1000 == 0:
+        print(f"Epoch: {epoch+1}, Loss: {loss.numpy()}")
+
+final_coefficients = [c.numpy() for c in coefficients]
+print("Final Coefficients:", final_coefficients)
+
+print("Final Equation:", end=" ")
+for i in range(degree+1):
+  print(f"{final_coefficients[i]} * x^{degree-i}", end=" + " if i < degree else "\n")
+
+plt.plot(X, Y, label="Original Data")
+plt.plot(X,[tf.math.polyval(final_coefficients, tf.constant(x, dtype=tf.float32)).numpy() for x in df[x_column]]), label="Our Poynomial"
+plt.ylabel(y_column)
+plt.xlabel(x_column)
+plt.title(f"{x_column} vs {y_column}")
+plt.legend()
+plt.show()
+
+ +
+ + +### Without Gradient Tape + +This relies on the Optimizer's `minimize` function and uses the `var_list` parameter to update the variables. + +This will not work with Keras 3 backend in TF 2.16.0 and above unless you switch to the legacy backend. +
+ +
import tensorflow as tf
+import numpy as np
+import pandas as pd
+import matplotlib.pyplot as plt
+
+df = pd.read_csv("data.csv")
+
+############################
+## Change Parameters Here ##
+############################
+x_column = "Level"         #
+y_column = "Salary"        #
+degree = 2                 #
+learning_rate = 0.3        #
+num_epochs = 25_000        #
+############################
+
+X = tf.constant(df[x_column], dtype=tf.float32)
+Y = tf.constant(df[y_column], dtype=tf.float32)
+
+coefficients = [tf.Variable(np.random.randn() * 0.01, dtype=tf.float32) for _ in range(degree + 1)]
+
+optimizer = tf.keras.optimizers.Adam(learning_rate=learning_rate)
+
+def loss_function():
+  pred_y = tf.math.polyval(coefficients, X)
+  return tf.reduce_mean(tf.square(pred_y - Y))
+
+for epoch in range(num_epochs):
+    optimizer.minimize(loss_function, var_list=coefficients)
+    if (epoch+1) % 1000 == 0:
+        current_loss = loss_function().numpy()
+        print(f"Epoch {epoch+1}: Training Loss: {current_loss}")
+
+final_coefficients = coefficients.numpy()
+print("Final Coefficients:", final_coefficients)
+
+print("Final Equation:", end=" ")
+for i in range(degree+1):
+  print(f"{final_coefficients[i]} * x^{degree-i}", end=" + " if i < degree else "\n")
+
+plt.plot(X, Y, label="Original Data")
+plt.plot(X,[tf.math.polyval(final_coefficients, tf.constant(x, dtype=tf.float32)).numpy() for x in df[x_column]], label="Our Polynomial")
+plt.ylabel(y_column)
+plt.xlabel(x_column)
+plt.legend()
+plt.title(f"{x_column} vs {y_column}")
+plt.show()
+
+ +
+ + + +As always, remember to tweak the parameters and choose the correct model for the job. A polynomial regression model might not even be the best model for this particular dataset. + +## Further Programming + +How would you modify this code to use another type of nonlinear regression? Say, $ y = ab^x $ + +Hint: Your loss calculation would be similar to: +
+ +
bx = tf.pow(coefficients[1], X)
+pred_y = tf.math.multiply(coefficients[0], bx)
+loss = tf.reduce_mean(tf.square(pred_y - Y))
+
+ +

+ +
If you have scrolled this far, consider subscribing to my mailing list here. You can subscribe to either a specific type of post you are interested in, or subscribe to everything with the "Everything" list.
+ +
+ +
+
+ + + + + \ No newline at end of file -- cgit v1.2.3 From 37661080a111768e565ae53299c4796ebe711a71 Mon Sep 17 00:00:00 2001 From: Navan Chauhan Date: Thu, 21 Mar 2024 14:29:50 -0600 Subject: fix mathjax stuff --- ...3-21-Polynomial-Regression-in-TensorFlow-2.html | 62 +++++++++------------- 1 file changed, 26 insertions(+), 36 deletions(-) (limited to 'docs/posts/2024-03-21-Polynomial-Regression-in-TensorFlow-2.html') diff --git a/docs/posts/2024-03-21-Polynomial-Regression-in-TensorFlow-2.html b/docs/posts/2024-03-21-Polynomial-Regression-in-TensorFlow-2.html index c1a4ae4..7a25daf 100644 --- a/docs/posts/2024-03-21-Polynomial-Regression-in-TensorFlow-2.html +++ b/docs/posts/2024-03-21-Polynomial-Regression-in-TensorFlow-2.html @@ -103,18 +103,17 @@

Which is equivalent to the general cubic equation:

-

- + -$$ +

$$ y = ax^3 + bx^2 + cx + d -$$ +$$

-### Optimizer Selection & Training -
+

Optimizer Selection & Training

+
optimizer = tf.keras.optimizers.Adam(learning_rate=0.3)
 num_epochs = 10_000
 
@@ -127,25 +126,23 @@ $$
     if (epoch+1) % 1000 == 0:
         print(f"Epoch: {epoch+1}, Loss: {loss.numpy()}"
 
-
+

In TensorFlow 1, we would have been using tf.Session instead.

-In TensorFlow 1, we would have been using `tf.Session` instead. +

Here we are using GradientTape() instead, to keep track of the loss evaluation and coefficients. This is crucial, as our optimizer needs these gradients to be able to optimize our coefficients.

-Here we are using `GradientTape()` instead, to keep track of the loss evaluation and coefficients. This is crucial, as our optimizer needs these gradients to be able to optimize our coefficients. +

Our loss function is Mean Squared Error (MSE):

-Our loss function is Mean Squared Error (MSE) +

$$ += \frac{1}{n} \sum_{i=1}^{n}{(Y_i - \hat{Y_i})^2} +$$

-$$ -= \frac{1}{n}\sum_{i=1}^{n} (Y_i - \^{Y_i}) -$$ +

Where Yi^ is the predicted value and Yi is the actual value

-Where $\^{Y_i}$ is the predicted value and $Y_i$ is the actual value +

Plotting Final Coefficients

-### Plotting Final Coefficients
-
final_coefficients = [c.numpy() for c in coefficients]
 print("Final Coefficients:", final_coefficients)
 
@@ -156,18 +153,15 @@ Where $\^{Y_i}$ is the predicted value and $Y_i$ is the actual value
 plt.title("Salary vs Position")
 plt.show()
 
-
+

Code Snippet for a Polynomial of Degree N

+

Using Gradient Tape

-## Code Snippet for a Polynomial of Degree N - -### Using Gradient Tape +

This should work regardless of the Keras backend version (2 or 3)

-This should work regardless of the Keras backend version (2 or 3)
-
import tensorflow as tf
 import numpy as np
 import pandas as pd
@@ -216,17 +210,15 @@ This should work regardless of the Keras backend version (2 or 3)
 plt.legend()
 plt.show()
 
-
+

Without Gradient Tape

-### Without Gradient Tape +

This relies on the Optimizer's minimize function and uses the var_list parameter to update the variables.

-This relies on the Optimizer's `minimize` function and uses the `var_list` parameter to update the variables. +

This will not work with Keras 3 backend in TF 2.16.0 and above unless you switch to the legacy backend.

-This will not work with Keras 3 backend in TF 2.16.0 and above unless you switch to the legacy backend.
-
import tensorflow as tf
 import numpy as np
 import pandas as pd
@@ -276,26 +268,24 @@ This will not work with Keras 3 backend in TF 2.16.0 and above unless you switch
 plt.title(f"{x_column} vs {y_column}")
 plt.show()
 
-
+

As always, remember to tweak the parameters and choose the correct model for the job. A polynomial regression model might not even be the best model for this particular dataset.

+

Further Programming

-As always, remember to tweak the parameters and choose the correct model for the job. A polynomial regression model might not even be the best model for this particular dataset. +

How would you modify this code to use another type of nonlinear regression? Say,

-## Further Programming +

$$ y = ab^x $$

-How would you modify this code to use another type of nonlinear regression? Say, $ y = ab^x $ +

Hint: Your loss calculation would be similar to:

-Hint: Your loss calculation would be similar to:
-
bx = tf.pow(coefficients[1], X)
 pred_y = tf.math.multiply(coefficients[0], bx)
 loss = tf.reduce_mean(tf.square(pred_y - Y))
 
- -

+
If you have scrolled this far, consider subscribing to my mailing list here. You can subscribe to either a specific type of post you are interested in, or subscribe to everything with the "Everything" list.
-

$$ -y = ax^3 + bx^2 + cx + d -$$

+y=ax3+bx2+cx+d

Optimizer Selection & Training

@@ -134,9 +132,7 @@ $$

Our loss function is Mean Squared Error (MSE):

-

$$ -= \frac{1}{n} \sum_{i=1}^{n}{(Y_i - \hat{Y_i})^2} -$$

+=1ni=1n(Y_iY_i^)2

Where Yi^ is the predicted value and Yi is the actual value

@@ -276,7 +272,7 @@ $$

How would you modify this code to use another type of nonlinear regression? Say,

-

$$ y = ab^x $$

+y=abx

Hint: Your loss calculation would be similar to:

-- cgit v1.2.3 From f6d2141a480dd6b5b8ee0e48d43bb64773232791 Mon Sep 17 00:00:00 2001 From: Navan Chauhan Date: Tue, 26 Mar 2024 23:38:14 -0600 Subject: add header ids --- ...3-21-Polynomial-Regression-in-TensorFlow-2.html | 30 +++++++++++----------- 1 file changed, 15 insertions(+), 15 deletions(-) (limited to 'docs/posts/2024-03-21-Polynomial-Regression-in-TensorFlow-2.html') diff --git a/docs/posts/2024-03-21-Polynomial-Regression-in-TensorFlow-2.html b/docs/posts/2024-03-21-Polynomial-Regression-in-TensorFlow-2.html index ab46ec7..0d958b2 100644 --- a/docs/posts/2024-03-21-Polynomial-Regression-in-TensorFlow-2.html +++ b/docs/posts/2024-03-21-Polynomial-Regression-in-TensorFlow-2.html @@ -6,13 +6,13 @@ - Polynomial Regression Using TensorFlow 2.x + id="polynomial-regression-using-tensorflow-2x">Polynomial Regression Using TensorFlow 2.x - - + Polynomial Regression Using TensorFlow 2.x" /> + Polynomial Regression Using TensorFlow 2.x" /> @@ -44,13 +44,13 @@
-

Polynomial Regression Using TensorFlow 2.x

+

Polynomial Regression Using TensorFlow 2.x

I have a similar post titled Polynomial Regression Using Tensorflow that used tensorflow.compat.v1 (Which still works as of TF 2.16). But, I thought it would be nicer to redo it with newer TF versions.

I will be skipping all the introductions about polynomial regression and jumping straight to the code. Personally, I prefer using scikit-learn for this task.

-

Position vs Salary Dataset

+

Position vs Salary Dataset

Again, we will be using https://drive.google.com/file/d/1tNL4jxZEfpaP4oflfSn6pIHJX7Pachm9/view (Salary vs Position Dataset)

@@ -61,11 +61,11 @@ -

Code

+

Code

If you just want to copy-paste the code, scroll to the bottom for the entire snippet. Here I will try and walk through setting up code for a 3rd-degree (cubic) polynomial

-

Imports

+

Imports

import pandas as pd
@@ -75,14 +75,14 @@
 
-

Reading the Dataset

+

Reading the Dataset

df = pd.read_csv("data.csv")
 
-

Variables and Constants

+

Variables and Constants

Here, we initialize the X and Y values as constants, since they are not going to change. The coefficients are defined as variables.

@@ -109,7 +109,7 @@ y=ax3+bx2+cx+d -

Optimizer Selection & Training

+

Optimizer Selection & Training

optimizer = tf.keras.optimizers.Adam(learning_rate=0.3)
@@ -136,7 +136,7 @@
 
 

Where Yi^ is the predicted value and Yi is the actual value

-

Plotting Final Coefficients

+

Plotting Final Coefficients

final_coefficients = [c.numpy() for c in coefficients]
@@ -151,9 +151,9 @@
 
-

Code Snippet for a Polynomial of Degree N

+

Code Snippet for a Polynomial of Degree N

-

Using Gradient Tape

+

Using Gradient Tape

This should work regardless of the Keras backend version (2 or 3)

@@ -208,7 +208,7 @@
-

Without Gradient Tape

+

Without Gradient Tape

This relies on the Optimizer's minimize function and uses the var_list parameter to update the variables.

@@ -268,7 +268,7 @@

As always, remember to tweak the parameters and choose the correct model for the job. A polynomial regression model might not even be the best model for this particular dataset.

-

Further Programming

+

Further Programming

How would you modify this code to use another type of nonlinear regression? Say,

-- cgit v1.2.3 From 9e620084e57378952c1a7f8e0a772ebebd18932b Mon Sep 17 00:00:00 2001 From: Navan Chauhan Date: Wed, 27 Mar 2024 20:35:09 -0600 Subject: quick fix --- docs/posts/2024-03-21-Polynomial-Regression-in-TensorFlow-2.html | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'docs/posts/2024-03-21-Polynomial-Regression-in-TensorFlow-2.html') diff --git a/docs/posts/2024-03-21-Polynomial-Regression-in-TensorFlow-2.html b/docs/posts/2024-03-21-Polynomial-Regression-in-TensorFlow-2.html index 0d958b2..e2edc19 100644 --- a/docs/posts/2024-03-21-Polynomial-Regression-in-TensorFlow-2.html +++ b/docs/posts/2024-03-21-Polynomial-Regression-in-TensorFlow-2.html @@ -6,13 +6,13 @@ - id="polynomial-regression-using-tensorflow-2x">Polynomial Regression Using TensorFlow 2.x + Polynomial Regression Using TensorFlow 2.x - Polynomial Regression Using TensorFlow 2.x" /> - Polynomial Regression Using TensorFlow 2.x" /> + + -- cgit v1.2.3 From 01ff93c9c16867216f2d249664803860e1d6d5eb Mon Sep 17 00:00:00 2001 From: Navan Chauhan Date: Wed, 27 Mar 2024 22:49:40 -0600 Subject: generate new theme --- ...3-21-Polynomial-Regression-in-TensorFlow-2.html | 55 +++++++++++++++------- 1 file changed, 37 insertions(+), 18 deletions(-) (limited to 'docs/posts/2024-03-21-Polynomial-Regression-in-TensorFlow-2.html') diff --git a/docs/posts/2024-03-21-Polynomial-Regression-in-TensorFlow-2.html b/docs/posts/2024-03-21-Polynomial-Regression-in-TensorFlow-2.html index e2edc19..6dcd62b 100644 --- a/docs/posts/2024-03-21-Polynomial-Regression-in-TensorFlow-2.html +++ b/docs/posts/2024-03-21-Polynomial-Regression-in-TensorFlow-2.html @@ -2,14 +2,26 @@ - + + + + + Polynomial Regression Using TensorFlow 2.x + + + + + + + - Polynomial Regression Using TensorFlow 2.x - @@ -29,21 +41,27 @@ - -
-
+ + +
-
- +

Polynomial Regression Using TensorFlow 2.x

I have a similar post titled Polynomial Regression Using Tensorflow that used tensorflow.compat.v1 (Which still works as of TF 2.16). But, I thought it would be nicer to redo it with newer TF versions.

@@ -283,14 +301,15 @@
+
If you have scrolled this far, consider subscribing to my mailing list here. You can subscribe to either a specific type of post you are interested in, or subscribe to everything with the "Everything" list.
-
+ -- cgit v1.2.3 From de19543d7fb44d343b052dc9b34ede78620c4a46 Mon Sep 17 00:00:00 2001 From: Navan Chauhan Date: Wed, 27 Mar 2024 23:36:55 -0600 Subject: Generate --- ...2024-03-21-Polynomial-Regression-in-TensorFlow-2.html | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) (limited to 'docs/posts/2024-03-21-Polynomial-Regression-in-TensorFlow-2.html') diff --git a/docs/posts/2024-03-21-Polynomial-Regression-in-TensorFlow-2.html b/docs/posts/2024-03-21-Polynomial-Regression-in-TensorFlow-2.html index 6dcd62b..20cce37 100644 --- a/docs/posts/2024-03-21-Polynomial-Regression-in-TensorFlow-2.html +++ b/docs/posts/2024-03-21-Polynomial-Regression-in-TensorFlow-2.html @@ -46,7 +46,7 @@ + +
-- cgit v1.2.3 From a982ceab0b45609991179b3020a00260eed6f798 Mon Sep 17 00:00:00 2001 From: Navan Chauhan Date: Wed, 27 Mar 2024 23:45:59 -0600 Subject: css --- docs/posts/2024-03-21-Polynomial-Regression-in-TensorFlow-2.html | 1 + 1 file changed, 1 insertion(+) (limited to 'docs/posts/2024-03-21-Polynomial-Regression-in-TensorFlow-2.html') diff --git a/docs/posts/2024-03-21-Polynomial-Regression-in-TensorFlow-2.html b/docs/posts/2024-03-21-Polynomial-Regression-in-TensorFlow-2.html index 20cce37..80ccad2 100644 --- a/docs/posts/2024-03-21-Polynomial-Regression-in-TensorFlow-2.html +++ b/docs/posts/2024-03-21-Polynomial-Regression-in-TensorFlow-2.html @@ -5,6 +5,7 @@ + Polynomial Regression Using TensorFlow 2.x -- cgit v1.2.3