Sentiment analysis /opinion mining

It uses natural language processing (NLP) and machine learning to identify, extract, and quantify subjective information from text, classifying it as positive, negative, or neutral. It enables businesses to monitor brand reputation, analyze customer feedback, and understand emotional tones in large volumes of data like social media, emails, and reviews.

Let us say that we have two documents A and B with statements

The Car Is Driven On The Road. and The Truck Is Driven On The Highway respectively.

TF-IDF (Term Frequency-Inverse Document Frequency) is a statistical formula used in Natural Language Processing (NLP) and information retrieval to evaluate how important a word is to a specific document within a larger collection (corpus)."""

TF_idf_img.png

In [1]:
# Step 1: Import libraries
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression

# Step 2: Small training dataset
texts = [
    "I love this product",
    "This is amazing",
    "Very happy and satisfied",
    "I hate this",
    "Ok Product",
    "Very bad experience",
    "This is terrible",
    "fine"
]

labels = [
    "positive",
    "positive",
    "positive",
    "negative",
    "neutral",
    "negative",
    "negative",
    "neutral"
]

# Step 3: Convert text into numbers
vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(texts)

# Step 4: Train model
model = LogisticRegression()
model.fit(X, labels)

# Step 5: Chat loop
while True:
    user = input("Enter sentence (type 'exit' to stop): ")
    if user == "exit":
        break

    test = vectorizer.transform([user])
    prediction = model.predict(test)[0]

    print("Sentiment:", prediction)
Enter sentence (type 'exit' to stop): i hate this
Sentiment: negative
Enter sentence (type 'exit' to stop): love
Sentiment: positive
Enter sentence (type 'exit' to stop): hate
Sentiment: negative
Enter sentence (type 'exit' to stop): ok
Sentiment: neutral
Enter sentence (type 'exit' to stop): very bad
Sentiment: negative
Enter sentence (type 'exit' to stop): very good
Sentiment: negative
Enter sentence (type 'exit' to stop): exit
In [ ]: