4

#1.load the IMDB dataset:

import numpy as np

from tensorflow.keras.datasets import imdb

from tensorflow.keras.preprocessing.sequence import pad_sequences

#load dataset

(x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=10000)


#pad sequences to ensure equal length inputs

x_train = pad_sequences(x_train, maxlen=200)

x_test = pad_sequences(x_test, maxlen=200)


#2.define the LSTM model with an embedding layer:

model = tf.keras.Sequential([

  tf.keras.layers.Embedding(input_dim=10000, output_dim=128, input_length=200),

  tf.keras.layers.LSTM(128, return_sequences=False),

  tf.keras.layers.Dense(1, activation='sigmoid')

])


model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])

#3.train the model on the IMDB dataset:

history = model.fit(x_train, y_train, epochs=10, batch_size=64, validation_data=(x_test, y_test))


#4.visualize training progress:

import matplotlib.pyplot as plt

#plot accuracy

plt.plot(history.history['accuracy'], label='Training Accuracy')

plt.plot(history.history['val_accuracy'], label='Validation Accuracy')

plt.xlabel('Epochs')

plt.ylabel('Accuracy')

plt.legend()

plt.show()


#5.evalate the model using precision,recall,and f1 score:

from sklearn.metrics import precision_score, recall_score, f1_score


# get preictions and round them to nearest integer

y_pred = (model.predict(x_test) > 0.5).astype("int32")


#evaluate performance

precision = precision_score(y_test, y_pred)

recall = recall_score(y_test, y_pred)

f1 = f1_score(y_test, y_pred)

print(f"'Precision:', {precision}, 'Recall:', {recall}, 'F1 Score:', {f1}")


#6.analyze model perfaormance on sequential data:

def preprocess_input(text):

  tokenizer = Tokenizer(num_words=max_features)

  tokenizer.fit_on_texts([text])

  sequence = tokenizer.texts_to_sequences([text])

  padded_sequence = pad_sequences(sequence, maxlen=maxlen)

  return padded_sequence

#get user input

user_input = input("Enter a movie review: ")

#preprocess input

preprocessed_input = preprocess_input(user_input)

#make prediction

prediction = model.predict(preprocessed_input)

sentiment = "positive" if prediction > 0.5 else "negative"

#output

print(f"The predicted sentiment is: {sentiment} (probability: {prediction[0][0]:.2f})") 

Comments

Popular posts from this blog

2

1

3