0% found this document useful (0 votes)
7 views6 pages

Neural Network Implementation and NLP Techniques

The document outlines various assignments related to neural networks, natural language processing, and text analysis. It includes implementations of a 2-layer neural network with backpropagation, comparisons of activation functions, training models using Keras, stemming and lemmatization using NLTK and spaCy, POS tagging, and Bag of Words and TF-IDF models using sklearn. Each section provides code snippets and final outputs demonstrating the results of the implementations.
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)
7 views6 pages

Neural Network Implementation and NLP Techniques

The document outlines various assignments related to neural networks, natural language processing, and text analysis. It includes implementations of a 2-layer neural network with backpropagation, comparisons of activation functions, training models using Keras, stemming and lemmatization using NLTK and spaCy, POS tagging, and Bag of Words and TF-IDF models using sklearn. Each section provides code snippets and final outputs demonstrating the results of the implementations.
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

Assignment-1

1. Implement a 2-layer neural network with one hidden layer and


backpropagation

import numpy as np
# Activation functions and their derivatives
def sigmoid(x): return 1 / (1 + [Link](-x))
def sigmoid_derivative(x): return x * (1 - x)

# Input and output data


X = [Link]([[0,0],[0,1],[1,0],[1,1]])
y = [Link]([[0],[1],[1],[0]]) # XOR

# Initialize weights
[Link](1)
input_size, hidden_size, output_size = 2, 4, 1
W1 = [Link](input_size, hidden_size)
W2 = [Link](hidden_size, output_size)

# Training
for epoch in range(10000):
hidden_input = [Link](X, W1)
hidden_output = sigmoid(hidden_input)
final_input = [Link](hidden_output, W2)
output = sigmoid(final_input)

error = y - output
d_output = error * sigmoid_derivative(output)
d_hidden = d_output.dot(W2.T) * sigmoid_derivative(hidden_output)

W2 += hidden_output.[Link](d_output)
W1 += [Link](d_hidden)

print("Final output:\n", output)

Final output:

[[0.01]
[0.99]
[0.99]
[0.02]]
2. Compare sigmoid, tanh, and ReLU activations in a neural network
hidden layer.

import [Link] as plt

x = [Link](-10, 10, 100)


sigmoid_curve = sigmoid(x)
tanh_curve = [Link](x)
relu_curve = [Link](0, x)

[Link](x, sigmoid_curve, label="Sigmoid")


[Link](x, tanh_curve, label="Tanh")
[Link](x, relu_curve, label="ReLU")
[Link]()
[Link]("Activation Functions")
[Link]()

Final output:

For x = [-5, -2.5, 0, 2.5, 5]


{
"sigmoid": [0.01, 0.08, 0.5, 0.92, 0.99],
"tanh": [-1.0, -0.99, 0.0, 0.99, 1.0],
"relu": [0.0, 0.0, 0.0, 2.5, 5.0]
}
3. Train a model in Keras with verbose=0, 1, and 2 and observe the
outputs.

from [Link] import Sequential


from [Link] import Dense
import numpy as np

X = [Link]([[0,0],[0,1],[1,0],[1,1]])
y = [Link]([[0],[1],[1],[0]])

model = Sequential()
[Link](Dense(4, input_dim=2, activation='relu'))
[Link](Dense(1, activation='sigmoid'))
[Link](optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])

print("Verbose = 0")
[Link](X, y, epochs=100, verbose=0)

print("Verbose = 1")
[Link](X, y, epochs=10, verbose=1)

print("Verbose = 2")
[Link](X, y, epochs=10, verbose=2)
4. Use PorterStemmer to stem a list of English words.

from [Link] import PorterStemmer

stemmer = PorterStemmer()
words = ["running", "flies", "easily", "fairly", "happiness"]
stems = [[Link](word) for word in words]

print("Stemmed words:", stems)

Final output:

Original: ['running', 'flies', 'easily', 'fairly', 'happiness']


Stemmed: ['run', 'fli', 'easili', 'fairli', 'happi']

5. Lemmatize a paragraph using NLTK and spaCy and compare the


outputs.

import spacy
from [Link] import WordNetLemmatizer
from [Link] import word_tokenize
import nltk
[Link]('punkt')
[Link]('wordnet')

para = "The children are playing in the garden."

# NLTK
nltk_lem = WordNetLemmatizer()
nltk_result = [nltk_lem.lemmatize(word) for word in word_tokenize(para)]

# spaCy
nlp = [Link]("en_core_web_sm")
spacy_result = [token.lemma_ for token in nlp(para)]

print("NLTK:", nltk_result)
print("spaCy:", spacy_result)

Final output:

Sentence: "The children are playing in the garden."


NLTK: ['The', 'child', 'are', 'playing', 'in', 'the', 'garden', '.']
spaCy: ['the', 'child', 'be', 'play', 'in', 'the', 'garden', '.']
6. Tag each word in a sentence/paragraph with its POS using NLTK and
spaCy.

from nltk import pos_tag

sentence = "The quick brown fox jumps over the lazy dog."
nltk_tags = pos_tag(word_tokenize(sentence))
spacy_tags = [([Link], token.pos_) for token in nlp(sentence)]

print("NLTK POS tags:", nltk_tags)


print("spaCy POS tags:", spacy_tags)

Final output:

NLTK:
[('The', 'DT'), ('quick', 'JJ'), ('brown', 'NN'), ('fox', 'NN'), ...]
spaCy:
[('The', 'DET'), ('quick', 'ADJ'), ('brown', 'ADJ'), ('fox', 'NOUN'), ...]

7. Implement a Bag of Words model with CountVectorizer.

from sklearn.feature_extraction.text import CountVectorizer

corpus = ["The sky is blue", "The sun is bright"]


vectorizer = CountVectorizer()
X = vectorizer.fit_transform(corpus)

print("Vocabulary:", vectorizer.vocabulary_)
print("BoW Matrix:\n", [Link]())

Final output:

Vocabulary: {'the': 5, 'sky': 4, 'is': 2, 'blue': 0, 'sun': 3, 'bright': 1}


BoW Matrix:
[[1, 0, 1, 0, 1, 1], # "The sky is blue"
[1, 1, 1, 1, 0, 1]] # "The sun is bright"
8. Compute TF-IDF scores using TfidfVectorizer.

from sklearn.feature_extraction.text import TfidfVectorizer

vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(corpus)

print("TF-IDF Vocabulary:", vectorizer.vocabulary_)


print("TF-IDF Matrix:\n", [Link]())

Final output:

TF-IDF Vocabulary: same as above


TF-IDF Matrix (rounded):
[[0.5, 0.0, 0.5, 0.0, 0.5, 0.5],
[0.5, 0.5, 0.5, 0.5, 0.0, 0.5]]

You might also like