python code, neural network to classify a list of text snippets into three different…
- User
python code, neural network to classify a list of text snippets into three different categories
Assistant
python code, neural network to classify a list of text snippets into three different categories
In this example, we'll build a simple neural network using the Keras library in Python to classify a list of text snippets into three different categories.
keras: A high-level neural networks API for Python.numpy: The NumPy library for efficient numerical computation.pandas: The Pandas library for data manipulation and analysis.sklearn: The scikit-learn library for machine learning.nltk: The Natural Language Toolkit library for text processing.# Import required libraries
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.utils import to_categorical
from keras.models import Sequential
from keras.layers import Embedding, Dropout, Dense
from keras.callbacks import EarlyStopping
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
import nltk
nltk.download('wordnet')
nltk.download('stopwords')
# Sample dataset
data = {
'text': [
'This is a great product, I love it!',
'I hate this product, it\'s terrible.',
'This product is okay, I guess.',
'I\'m not sure about this product.',
'I love this product, it\'s amazing!',
'This product is terrible, I wouldn\'t recommend it.',
'I\'m neutral about this product.',
'This product is great, I highly recommend it.',
'I don\'t like this product at all.',
'This product is just okay.',
'I love this product, it\'s the best!',
'I hate this product, it\'s the worst.'
],
'category': [
'positive',
'negative',
'neutral',
'neutral',
'positive',
'negative',
'neutral',
'positive',
'negative',
'neutral',
'positive',
'negative'
]
}
# Create a DataFrame from the dataset
df = pd.DataFrame(data)
# Define the categories
categories = ['negative', 'neutral', 'positive']
# Use LabelEncoder to convert categorical labels to numerical labels
le = LabelEncoder()
df['category'] = le.fit_transform(df['category'])
# Split the data into training and testing sets
train_text, test_text, train_labels, test_labels = train_test_split(df['text'], df['category'], test_size=0.2, random_state=42)
# Create a Tokenizer instance
tokenizer = Tokenizer(num_words=1000)
tokenizer.fit_on_texts(train_text)
# Convert the text data into sequences of words
train_sequences = tokenizer.texts_to_sequences(train_text)
test_sequences = tokenizer.texts_to_sequences(test_text)
# Pad the sequences to have the same length
max_length = 100
padded_train = pad_sequences(train_sequences, maxlen=max_length)
padded_test = pad_sequences(test_sequences, maxlen=max_length)
# One-hot encode the labels
num_classes = 3
train_labels_onehot = to_categorical(train_labels, num_classes)
test_labels_onehot = to_categorical(test_labels, num_classes)
# Define the neural network model
model = Sequential()
model.add(Embedding(1000, 64, input_length=max_length))
model.add(Dropout(0.5))
model.add(Dense(64, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(num_classes, activation='softmax'))
# Compile the model
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
# Define early stopping callback
early_stopping = EarlyStopping(patience=5, min_delta=0.001)
# Train the model
model.fit(padded_train, train_labels_onehot, epochs=100, batch_size=32, validation_data=(padded_test, test_labels_onehot), callbacks=[early_stopping])
# Evaluate the model
loss, accuracy = model.evaluate(padded_test, test_labels_onehot)
print(f'Test accuracy: {accuracy:.2f}')
# Make predictions
predictions = model.predict(padded_test)
predicted_classes = np.argmax(predictions, axis=1)
# Convert the predicted classes back to categorical labels
predicted_labels = le.inverse_transform(predicted_classes)
# Print the predicted labels
for i, label in enumerate(predicted_labels):
print(f'Text: {test_text.iloc[i]}, Predicted label: {label}')
This code defines a simple neural network with an embedding layer, two dense layers, and a softmax output layer. It trains the model on the training data and evaluates its performance on the testing data. Finally, it makes predictions on the testing data and prints the predicted labels.
Not yet included in a published release.