Advertisement
unnumsykar

imdb

Apr 27th, 2024
745
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.55 KB | None | 0 0
  1. from sklearn.datasets import load_files
  2. from sklearn.model_selection import train_test_split
  3. from sklearn.feature_extraction.text import TfidfVectorizer
  4. from sklearn.naive_bayes import MultinomialNB
  5. from sklearn.metrics import accuracy_score
  6.  
  7. # Load the dataset
  8. movie_reviews_data = load_files('path_to_dataset', encoding='utf-8')
  9.  
  10. # Split the dataset into training and testing sets
  11. X_train, X_test, y_train, y_test = train_test_split(
  12.     movie_reviews_data.data, movie_reviews_data.target, test_size=0.2, random_state=42)
  13.  
  14. # Vectorize the text data
  15. vectorizer = TfidfVectorizer(max_features=5000)
  16. X_train = vectorizer.fit_transform(X_train)
  17. X_test = vectorizer.transform(X_test)
  18.  
  19. # Train the classifier
  20. classifier = MultinomialNB()
  21. classifier.fit(X_train, y_train)
  22.  
  23. # Predict on the test set
  24. y_pred = classifier.predict(X_test)
  25.  
  26. # Calculate accuracy
  27. accuracy = accuracy_score(y_test, y_pred)
  28. print("Accuracy:", accuracy)
  29.  
  30. # Example usage
  31. def classify_review(review):
  32.     review_vectorized = vectorizer.transform([review])
  33.     prediction = classifier.predict(review_vectorized)
  34.     if prediction[0] == 1:
  35.         return "Positive"
  36.     else:
  37.         return "Negative"
  38.  
  39. # Example usage
  40. review = "This movie was fantastic! I loved every moment of it."
  41. classification = classify_review(review)
  42. print("Review:", review)
  43. print("Classification:", classification)
  44.  
  45. review = "The movie was terrible. I wouldn't recommend it to anyone."
  46. classification = classify_review(review)
  47. print("Review:", review)
  48. print("Classification:", classification)
  49.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement