Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
suyashi29
GitHub Repository: suyashi29/python-su
Path: blob/master/Generative NLP Models using Python/Lab for Neural Network Fundamentals.ipynb
3074 views
Kernel: Python 3 (ipykernel)

Lab Exercise: Neural Network for Sequence Generation

Objective:build and train simple neural networks to model two different functions:

  • Linear: y = 2 * X (50 random data points)

  • Non-linear: y = X² (100 random data points)

import numpy as np import tensorflow as tf import matplotlib.pyplot as plt # Set random seed for reproducibility np.random.seed(42) tf.random.set_seed(42) # Function 1: y = 2 * X (Linear) X1 = np.random.rand(50) * 10 # Random X values between 0 and 10 y1 = 2 * X1 # Function 2: y = X^2 (Non-linear) X2 = np.random.rand(100) * 10 y2 = X2 ** 2 # Reshape input for Keras (expects 2D input) X1 = X1.reshape(-1, 1) y1 = y1.reshape(-1, 1) X2 = X2.reshape(-1, 1) y2 = y2.reshape(-1, 1)

Model 1: Linear Relationship (y = 2X)

model1 = tf.keras.Sequential([ tf.keras.layers.Dense(1, input_shape=[1]) ]) model1.compile(optimizer='adam', loss='mean_squared_error') model1.fit(X1, y1, epochs=100, verbose=0) # Prediction and plot y1_pred = model1.predict(X1) plt.scatter(X1, y1, label='Actual') plt.plot(X1, y1_pred, color='red', label='Predicted') plt.title('Model 1: y = 2X') plt.xlabel('X') plt.ylabel('y') plt.legend() plt.show()
C:\Users\Suyashi144893\AppData\Local\anaconda3\Lib\site-packages\keras\src\layers\core\dense.py:87: UserWarning: Do not pass an `input_shape`/`input_dim` argument to a layer. When using Sequential models, prefer using an `Input(shape)` object as the first layer in the model instead. super().__init__(activity_regularizer=activity_regularizer, **kwargs)
2/2 ━━━━━━━━━━━━━━━━━━━━ 0s 27ms/step
Image in a Jupyter notebook

Model 2: Non-Linear Relationship (y = X²)

model2 = tf.keras.Sequential([ tf.keras.layers.Dense(10, activation='relu', input_shape=[1]), tf.keras.layers.Dense(10, activation='relu'), tf.keras.layers.Dense(1) ]) model2.compile(optimizer='adam', loss='mean_squared_error') model2.fit(X2, y2, epochs=200, verbose=0) # Prediction and plot y2_pred = model2.predict(X2) plt.scatter(X2, y2, label='Actual') plt.scatter(X2, y2_pred, color='red', label='Predicted', alpha=0.5) plt.title('Model 2: y = X²') plt.xlabel('X') plt.ylabel('y') plt.legend() plt.show()
4/4 ━━━━━━━━━━━━━━━━━━━━ 0s 13ms/step
Image in a Jupyter notebook