0% found this document useful (0 votes)
3 views11 pages

DL Lab Programs

The document contains various code snippets demonstrating different aspects of data processing and machine learning techniques. It covers text processing in NLP, decision trees using ID3, autoencoders, MLP classifiers, iris classification, TensorFlow arithmetic operations, and more. Each section includes code examples and explanations for tasks such as data normalization, model training, and evaluation.

Uploaded by

akkatiakshitha
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views11 pages

DL Lab Programs

The document contains various code snippets demonstrating different aspects of data processing and machine learning techniques. It covers text processing in NLP, decision trees using ID3, autoencoders, MLP classifiers, iris classification, TensorFlow arithmetic operations, and more. Each section includes code examples and explanations for tasks such as data normalization, model training, and evaluation.

Uploaded by

akkatiakshitha
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1.

Text Processing in NLP


#Code
text = 'Wisdoms daughter walks alone. The mark of Athena burns
through rome'
words = [Link]()
print(words)
#Case normalization
text = "'To Sleep Or NOT to SLEep, THAT is THe Question'"
def lower_case(text):
text = [Link]()
return text
lower_case = lower_case(text)#converts everthing to lowercase
print(lower_case)
#punctuation removal
import re
text = ' (to love is to destroy, and to be loved, is to be "the" one
<destroyed>} '
def remove_punctuations(text):
punctuation = [Link](r'[{};():,."/<>-]')
text = [Link](' ', text)
return text
clean_text = remove_punctuations(text)
print(clean_text)
2. Decision Tree Using ID3.
#Code
import pandas as pd
import numpy as np
import pprint
df = pd.read_csv("C:/Users/srira/Downloads/[Link]")
df = [Link]('day', axis=1) # Drop the day column
def entropy(target_col):
values, counts = [Link](target_col, return_counts=True)
total = sum(counts)
entropy = 0
for i in range(len(values)):
p = counts[i] / total
entropy += -p * np.log2(p)
return entropy
def info_gain(data, feature, target):
total_entropy = entropy(data[target])
vals, counts = [Link](data[feature], return_counts=True)
weighted_entropy = 0
for i in range(len(vals)):
subset = data[data[feature] == vals[i]]
weighted_entropy += (counts[i] / sum(counts)) * entropy(subset[target])
return total_entropy - weighted_entropy
def best_feature(data, target):
features = [col for col in [Link] if col != target]
gains = [info_gain(data, feature, target) for feature in features]
return features[[Link](gains)]
def build_tree(data, target):
labels = [Link](data[target])
if len(labels) == 1:
return labels[0]
if len([Link]) == 1:
return data[target].mode()[0]
best = best_feature(data, target)
tree = {best: {}}
for val in [Link](data[best]):
sub_data = data[data[best] == val].drop(columns=[best])
subtree = build_tree(sub_data, target)
tree[best][val] = subtree
return tree
tree = build_tree(df, target='play')
[Link](tree)
3. Autoencoders Program

import numpy as np
import [Link] as plt
from [Link] import mnist
from [Link] import Sequential
from [Link] import Dense, Input
from [Link] import Adam
(x_train, _), (x_test, _) = mnist.load_data()
x_train = x_train.reshape(-1, 784).astype("float32") / 255
x_test = x_test.reshape(-1, 784).astype("float32") / 255
model = Sequential()
[Link](Input(shape=(784,)))
[Link](Dense(15, activation='relu'))# Encoder
[Link](Dense(784, activation='sigmoid'))# Decoder
[Link](optimizer=Adam(), loss='binary_crossentropy')
[Link](x_train, x_train,
epochs=10,
batch_size=256,
validation_data=(x_test, x_test))
decoded_images = [Link](x_test)
[Link](figsize=(10, 4))
for i in range(5):
ax = [Link](2, 5, i + 1)
[Link](x_test[i].reshape(28, 28), cmap='gray')
[Link]('off')
ax = [Link](2, 5, i + 6)
[Link](decoded_images[i].reshape(28, 28), cmap='gray')
[Link]('off')
plt.tight_layout() [Link]()
4. MLP Example
#Code
from sklearn.neural_network import MLPClassifier
from [Link] import make_classification
from sklearn.model_selection import train_test_split
from [Link] import accuracy_score
X, y = make_classification(n_samples=1000, n_features=20,
n_classes=2, random_state=42)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,
random_state=42)
mlp_classifier = MLPClassifier(hidden_layer_sizes=(64, 32),
activation='relu', solver='adam', max_iter=1000, random_state=42)
mlp_classifier.fit(X_train, y_train)
y_pred = mlp_classifier.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
5. Iris Classification
import pandas as pd
from [Link] import load_iris
from sklearn.model_selection import train_test_split
from [Link] import RandomForestClassifier
from [Link] import accuracy_score
iris = load_iris()
X = [Link] # Features
y = [Link] # Labels
df = [Link](data=[Link], columns=iris.feature_names)
print([Link]())
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)
model = RandomForestClassifier(n_estimators=100)
[Link](X_train, y_train)
predictions = [Link](X_test)
print("Accuracy:", accuracy_score(y_test, predictions))
sample = [[3, 5, 4, 2]]
predicted_class = [Link](sample)[0]
print("Predicted Species:", iris.target_names[predicted_class])
6. TensorFlow Arithmetic Operations.
import tensorflow as tf
a = float(input("Enter the first number (a): "))
b = float(input("Enter the second number (b): "))
a_tensor = [Link](a)
b_tensor = [Link](b)
# Arithmetic Operations
# Addition
addition = [Link](a_tensor, b_tensor)
print(f"Addition: {[Link]()}")
# Subtraction
subtraction = [Link](a_tensor, b_tensor)
print(f"Subtraction: {[Link]()}")
# Multiplication
multiplication = [Link](a_tensor, b_tensor)
print(f"Multiplication: {[Link]()}")
# Division
division = [Link](a_tensor, b_tensor)
print(f"Division: {[Link]()}")
# Floor Division
floor_division = [Link](a_tensor, b_tensor)
print(f"Floor Division: {floor_division.numpy()}")
# Exponentation
exponential = [Link](a_tensor, b_tensor)
print(f"Exponentiation: {[Link]()}")
7. Sci-Kit Learn
from [Link] import load_digits
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from [Link] import classification_report
# Load dataset
digits = load_digits()
X, y = [Link], [Link]
# Split data
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2,
random_state=42)
# Train model
model = LogisticRegression(max_iter=10000)
[Link](X_train, y_train)
# Predict and evaluate
y_pred = [Link](X_test)
print("Classification Report:\n", classification_report(y_test, y_pred))
8. NumPy Arrays (2D, 3D)
import numpy as np
# Create Two 2D Arrays
array_2d_1 = [Link]([[1, 2], [3, 4]])
array_2d_2 = [Link]([[5, 6], [7, 8]])
# Arithmetic Operations on 2D Arrays
print("Arithmetic Operations on 2D Arrays: ")
print("\nAddition:\n", array_2d_1 + array_2d_2)
print("Subtraction:\n", array_2d_1 - array_2d_2)
print("Multiplication:\n", array_2d_1 * array_2d_2)
print("Division:\n", array_2d_1 / array_2d_2)
# Create Two 3D Arrays ---
array_3d_1 = [Link]([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
array_3d_2 = [Link]([[[8, 7], [6, 5]], [[4, 3], [2, 1]]])
# Arithmetic Operations on 3D Arrays
print("Arithmetic Operations on 3D Arrays: ")
print("\nAddition :\n", array_3d_1 + array_3d_2)
print("Subtraction :\n", array_3d_1 - array_3d_2)
print("Multiplication :\n", array_3d_1 * array_3d_2)
print("Division :\n", array_3d_1 / array_3d_2)
9. Pandas Series and DataFrames
import pandas as pd
import numpy as np
a = [Link]([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
df1 = [Link](a, columns=['A', 'B', 'C'])
d = {'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 28],
'City': ['New York', 'London', 'Paris']}
df2 = [Link](d)
l = [['John', 24, 'Los Angeles'],
['Jane', 22, 'Chicago'],
['Mike', 26, 'Houston']]
df3 = [Link](l, columns=['Name', 'Age', 'City'])
print("From NumPy:\n", df1)
print("\nFrom Dict:\n", df2)
print("\nFrom List:\n", df3)
10. MLP Digit Classification
import [Link] as plt
import seaborn as sns
from [Link] import mnist
from sklearn.model_selection import train_test_split
from sklearn.neural_network import MLPClassifier
import pandas as pd
(X, y), (X_test, y_test) = mnist.load_data()
X = [Link](len(X), -1)
X_test = X_test.reshape(len(X_test), -1)
dig = list(range(10))
num = [sum(y == i) for i in dig]
df1 = [Link]({'Digit': dig, 'Count': num})
[Link](x="Count", y="Digit", data=df1, orient='h')
[Link]()
[Link](X[14].reshape(28, 28), cmap='gray')
[Link]()
[Link](X[4].reshape(28, 28), cmap='gray')
[Link]()
X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.33,
random_state=42)
model = MLPClassifier(hidden_layer_sizes=(100,), random_state=42)
[Link](X_train, y_train)
print("Train Accuracy: {:.2%}".format([Link](X_train, y_train)))
print("Test Accuracy: {:.2%}".format([Link](X_val, y_val)))
y_pred = [Link](X_val)
df_mlp = [Link]({'true': y_val, 'predicted': y_pred})
df_mlp['diff'] = df_mlp['predicted'] - df_mlp['true']
df_mlp

You might also like