Advertisement
makispaiktis

ML - Lab 3 - Categorical NB, Laplacian Smoothing

Oct 19th, 2022 (edited)
1,145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.82 KB | None | 0 0
  1. import pandas as pd
  2. from matplotlib.pyplot import plot as plt
  3. from sklearn.preprocessing import OneHotEncoder
  4. from sklearn.naive_bayes import CategoricalNB
  5.  
  6.  
  7. # NAIVE BAYES
  8. # Load data
  9. traffic = pd.read_csv("./traffic.txt")
  10. X = traffic.loc[:, ["Weather", "Day"]]
  11. y = traffic.loc[:, "HighTraffic"]
  12. print()
  13. print("****************************************************")
  14. print("**** NAIVE BAYES ****")
  15. print("Traffic = ")
  16. print(traffic)
  17. print()
  18.  
  19. # Encoder
  20. encoder = OneHotEncoder(handle_unknown="ignore", sparse=False)
  21. encoder = encoder.fit(X)
  22. X = encoder.transform(X)
  23.  
  24. # Classification with Naive-Bayes
  25. clf = CategoricalNB(alpha=0.0001)
  26. clf.fit(X, y)
  27.  
  28. # Prediction
  29. new1 = {"Weather": ["Hot"], "Day": ["Vacation"]}
  30. new_data = pd.DataFrame(new1)
  31. transformed_new_data = encoder.transform(new_data)
  32. print("New1 = " + str(new1))
  33. print("Prediction = " + str(clf.predict(transformed_new_data)))
  34. print("Probabilities = " + str(clf.predict_proba(transformed_new_data)))
  35. print()
  36. new2 = {"Weather": ["Hot"], "Day": ["Weekend"]}
  37. new_data2 = pd.DataFrame(new2)
  38. transformed_new_data2 = encoder.transform(new_data2)
  39. print("New2 = " + str(new2))
  40. print("Prediction = " + str(clf.predict(transformed_new_data2)))
  41. print("Probabilities = " + str(clf.predict_proba(transformed_new_data2)))
  42. print()
  43. print()
  44. print()
  45. print()
  46.  
  47.  
  48.  
  49.  
  50. # LAPLACE SMOOTHING
  51. print("****************************************************")
  52. print("**** LAPLACE SMOOTHING ****")
  53.  
  54. # Classification with Naive-Bayes
  55. clf = CategoricalNB(alpha=0.9999)
  56. clf.fit(X, y)
  57. new2 = {"Weather": ["Hot"], "Day": ["Weekend"]}
  58. new_data2 = pd.DataFrame(new2)
  59. transformed_new_data2 = encoder.transform(new_data2)
  60. print("New2 = " + str(new2))
  61. print("Prediction = " + str(clf.predict(transformed_new_data2)))
  62. print("Probabilities = " + str(clf.predict_proba(transformed_new_data2)))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement