DL p
INDEX
Practical 1
Aim :-
To perform Matrix Multiplication and find Eigenvalues and Eigenvectors using TensorFlow in Google Colab.
Code & output :
import tensorflow as tf
A = tf.constant([[1.0, 2.0],
[3.0, 4.0]])
B = tf.constant([[5.0, 6.0],
[7.0, 8.0]])
print("Matrix A:")
print(A.numpy())
print("Matrix B:")
print(B.numpy())
result = tf.matmul(A, B)
print("Matrix Multiplication:")
print(result.numpy())
C = tf.constant([[2.0, 1.0],
[1.0, 2.0]])
eigenvalues, eigenvectors = tf.linalg.eigh(C)
print("Eigenvalues:")
print(eigenvalues.numpy())
print("Eigenvectors:")
print(eigenvectors.numpy())
Practical No. 2
Aim:-
To implement a Deep Feed Forward Neural Network (DFFNN) using TensorFlow/Keras to
solve the XOR (Exclusive OR) problem and understand why hidden layers are essential for
solving non-linear classification problems.
Code & output :
import numpy as np import tensorflow as tf from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense tf.keras.utils.set_random_seed(42) X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]], dtype=float) y = np.array([0, 1, 1, 0]) model = Sequential([ tf.keras.Input(shape=(2,)), Dense(8, activation='tanh'), Dense(8, activation='tanh'), Dense(1, activation='sigmoid') ]) model.compile( optimizer=tf.keras.optimizers.Adam(learning_rate=0.05), loss='binary_crossentropy', metrics=['accuracy'] ) model.fit(X, y, epochs=2000, verbose=0) predictions = model.predict(X, verbose=0) print("XOR Predictions:") for i in range(len(X)): print(X[i], "=", predictions[i][0]) print("Final Predicted Classes:") print((predictions >= 0.5).astype(int).flatten())
Practical No. 3
Aim
To implement a Deep Neural Network (DNN) using TensorFlow/Keras for performing a
Binary Classification task.
Code & output :
Practical No. 4(a)
Aim: -
To implement a Deep Feed Forward Neural Network (DFFNN) using TensorFlow/Keras for
performing Multiclass Classification and predicting the class of a given input.
Code & output : -
import numpy as np import tensorflow as tf from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense X = np.array([[1], [2], [3], [4], [5], [6], [7], [8], [9], [10]], dtype=float) y = np.array([0, 0, 0, 1, 1, 1, 1, 2, 2, 2]) model = Sequential([ tf.keras.Input(shape=(1,)), Dense(16, activation='relu'), Dense(16, activation='relu'), Dense(3, activation='softmax') ]) model.compile( optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'] ) model.fit(X, y, epochs=500, verbose=0) test = np.array([[8.0]]) prediction = model.predict(test, verbose=0) classes = ['Poor', 'Average', 'Excellent'] predicted_class = np.argmax(prediction) print("Input:", test[0][0]) print("Predicted Class:", classes[predicted_class])
Practical No. 4(b)
Aim:-
To implement a Deep Feed Forward Neural Network (DFFNN) using TensorFlow/Keras for
multiclass classification and predict the probability of each class.
Code & output :-
import numpy as np
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
X = np.array([[1], [2], [3], [4], [5],
[6], [7], [8], [9], [10]], dtype=float)
y = np.array([0, 0, 0, 1, 1,
1, 1, 2, 2, 2])
model = Sequential([
tf.keras.Input(shape=(1,)),
Dense(16, activation='relu'),
Dense(16, activation='relu'),
Dense(3, activation='softmax')
])
model.compile(
optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy']
)
model.fit(X, y, epochs=500, verbose=0)
test = np.array([[6.0]])
prediction = model.predict(test, verbose=0)[0]
classes = ['Poor', 'Average', 'Excellent']
print("Class Probabilities:")
for i in range(len(classes)):
print(classes[i], ":", prediction[i])
predicted_class = np.argmax(prediction)
print("Predicted Class:", classes[predicted_class])
Practical No. 4(c)
Aim
To implement a Deep Feed Forward Neural Network (DFFNN) using TensorFlow/Keras for
performing Linear Regression and predicting continuous values.
Code :
Practical No. 5
Aim: To evaluate a Deep Feed Forward Neural Network (DFFNN) for Regression and Multiclass
Classification using K-Fold Cross-Validation.
Code & output:
import numpy as np
import tensorflow as tf
from sklearn.model_selection import KFold
from sklearn.preprocessing import StandardScaler
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
X = np.arange(1, 51, dtype=float).reshape(-1, 1)
y = 2 * X.flatten() + 5
kf = KFold(
n_splits=5,
shuffle=True,
random_state=42
)
mse_scores = []
for fold, (train_index, test_index) in enumerate(kf.split(X), 1):
scaler = StandardScaler()
X_train = scaler.fit_transform(X[train_index])
X_test = scaler.transform(X[test_index])
model = Sequential([
tf.keras.Input(shape=(1,)),
Dense(16, activation='relu'),
Dense(8, activation='relu'),
Dense(1)
])
model.compile(
optimizer='adam',
loss='mean_squared_error'
)
model.fit(
X_train,
y[train_index],
epochs=300,
verbose=0
)
mse = model.evaluate(
X_test,
y[test_index],
verbose=0
)
mse_scores.append(mse)
print("Fold", fold, "MSE:", mse)
print("Average MSE:", np.mean(mse_scores))
Practical No. 6
Aim : To implement Regularization in a Deep Feed Forward Neural Network using TensorFlow/Keras to reduce overfitting in binary classification.
Code :
Practical No. 7
Aim:
To implement a Recurrent Neural Network (RNN) using TensorFlow/Keras for sequence analysis and stock price prediction.
Code :
import numpy as np import tensorflow as tf import matplotlib.pyplot as plt from sklearn.preprocessing import MinMaxScaler from tensorflow.keras.models import Sequential from tensorflow.keras.layers import SimpleRNN, Dense np.random.seed(42) # Generate sample stock price data prices = np.linspace(100, 200, 200) + np.random.randn(200) * 3 prices = prices.reshape(-1, 1) scaler = MinMaxScaler() scaled_prices = scaler.fit_transform(prices) X = [] y = [] for i in range(10, len(scaled_prices)): X.append(scaled_prices[i-10:i]) y.append(scaled_prices[i]) X = np.array(X) y = np.array(y) split = int(len(X) * 0.8) X_train = X[:split] X_test = X[split:] y_train = y[:split] y_test = y[split:] model = Sequential([ tf.keras.Input(shape=(10, 1)), SimpleRNN(50, activation='tanh'), Dense(1) ]) model.compile( optimizer='adam', loss='mean_squared_error' ) model.fit( X_train, y_train, epochs=100, batch_size=16, verbose=0 ) predictions = model.predict(X_test, verbose=0) actual = scaler.inverse_transform(y_test) predicted = scaler.inverse_transform(predictions) print("Actual Stock Prices:") print(actual[:5].flatten()) print("Predicted Stock Prices:") print(predicted[:5].flatten()) next_input = scaled_prices[-10:].reshape(1, 10, 1) next_price = model.predict(next_input, verbose=0) next_price = scaler.inverse_transform(next_price) print("Next Predicted Stock Price:", next_price[0][0]) plt.plot(actual, label="Actual Price") plt.plot(predicted, label="Predicted Price") plt.title("RNN Stock Price Prediction") plt.xlabel("Time") plt.ylabel("Stock Price") plt.legend() plt.show()
Comments
Post a Comment