Advertisement
sepi0l

dl_imdb

Apr 25th, 2024
784
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
JSON 6.99 KB | None | 0 0
  1. {
  2.  "cells": [
  3.   {
  4.    "cell_type": "code",
  5.    "execution_count": null,
  6.    "metadata": {},
  7.    "outputs": [],
  8.    "source": [
  9.     "import numpy as np\n",
  10.     "from keras.datasets import imdb\n",
  11.     "from keras import models\n",
  12.     "from keras import layers\n",
  13.     "from keras import optimizers\n",
  14.     "from keras import losses\n",
  15.     "from keras import metrics\n",
  16.     "import matplotlib.pyplot as plt\n",
  17.     "%matplotlib inline"
  18.    ]
  19.   },
  20.   {
  21.    "cell_type": "code",
  22.    "execution_count": null,
  23.    "metadata": {},
  24.    "outputs": [],
  25.    "source": [
  26.     "# Load the data, keeping only 10,000 of the most frequently occuring words\n",
  27.     "(train_data, train_labels), (test_data, test_labels) = imdb.load_data(num_words = 10000)"
  28.    ]
  29.   },
  30.   {
  31.    "cell_type": "code",
  32.    "execution_count": null,
  33.    "metadata": {},
  34.    "outputs": [],
  35.    "source": [
  36.     "# Check the first label\n",
  37.     "train_labels[0]"
  38.    ]
  39.   },
  40.   {
  41.    "cell_type": "code",
  42.    "execution_count": null,
  43.    "metadata": {},
  44.    "outputs": [],
  45.    "source": [
  46.     "# Here is a list of maximum indexes in every review --- we search the maximum index in this\n",
  47.     "print(type([max(sequence) for sequence in train_data]))\n",
  48.     "# Find the maximum of all max indexes\n",
  49.     "max([max(sequence) for sequence in train_data])\n"
  50.    ]
  51.   },
  52.   {
  53.    "cell_type": "code",
  54.    "execution_count": null,
  55.    "metadata": {},
  56.    "outputs": [],
  57.    "source": [
  58.     "# Let's quickly decode a review\n",
  59.     "# step 1: load the dictionary mappings from word to integer index\n",
  60.     "word_index = imdb.get_word_index()\n",
  61.     "# step 2: reverse word index to map integer indexes to their respective words\n",
  62.     "reverse_word_index = dict([(value, key) for (key, value) in word_index.items()])\n",
  63.     "# Step 3: decode the review, mapping integer indices to words\n",
  64.     "#\n",
  65.     "# indices are off by 3 because 0, 1, and 2 are reserverd indices for \"padding\", \"Start of se\n",
  66.     "decoded_review = ' '.join([reverse_word_index.get(i-3, '?') for i in train_data[0]])\n",
  67.     "decoded_review"
  68.    ]
  69.   },
  70.   {
  71.    "cell_type": "code",
  72.    "execution_count": null,
  73.    "metadata": {},
  74.    "outputs": [],
  75.    "source": [
  76.     "len(reverse_word_index)"
  77.    ]
  78.   },
  79.   {
  80.    "cell_type": "code",
  81.    "execution_count": null,
  82.    "metadata": {},
  83.    "outputs": [],
  84.    "source": [
  85.     "def vectorize_sequences(sequences, dimension=10000):\n",
  86.     "    results = np.zeros((len(sequences), dimension)) # Creates an all zero matrix of shape\n",
  87.     "    for i,sequence in enumerate(sequences):\n",
  88.     "        results[i,sequence] = 1\n",
  89.     "    return results\n",
  90.     "\n",
  91.     "# Vectorize training Data\n",
  92.     "X_train = vectorize_sequences(train_data)\n",
  93.     "# Vectorize testing Data\n",
  94.     "X_test = vectorize_sequences(test_data)"
  95.    ]
  96.   },
  97.   {
  98.    "cell_type": "code",
  99.    "execution_count": null,
  100.    "metadata": {},
  101.    "outputs": [],
  102.    "source": [
  103.     "X_train[0]"
  104.    ]
  105.   },
  106.   {
  107.    "cell_type": "code",
  108.    "execution_count": null,
  109.    "metadata": {},
  110.    "outputs": [],
  111.    "source": [
  112.     "X_train.shape"
  113.    ]
  114.   },
  115.   {
  116.    "cell_type": "code",
  117.    "execution_count": null,
  118.    "metadata": {},
  119.    "outputs": [],
  120.    "source": [
  121.     "#vectorize labels\n",
  122.     "y_train = np.asarray(train_labels).astype('float32')\n",
  123.     "y_test = np.asarray(test_labels).astype('float32')\n"
  124.    ]
  125.   },
  126.   {
  127.    "cell_type": "code",
  128.    "execution_count": null,
  129.    "metadata": {},
  130.    "outputs": [],
  131.    "source": [
  132.     "#model definition\n",
  133.     "model = models.Sequential()\n",
  134.     "model.add(layers.Dense(16, activation='relu', input_shape=(10000,)))\n",
  135.     "model.add(layers.Dense(16, activation='relu'))\n",
  136.     "model.add(layers.Dense(1, activation='sigmoid'))\n"
  137.    ]
  138.   },
  139.   {
  140.    "cell_type": "code",
  141.    "execution_count": null,
  142.    "metadata": {},
  143.    "outputs": [],
  144.    "source": [
  145.     "#compiling model\n",
  146.     "model.compile(\n",
  147.     "optimizer=optimizers.RMSprop(learning_rate=0.001),\n",
  148.     "loss = losses.binary_crossentropy,\n",
  149.     "metrics = [metrics.binary_accuracy]\n",
  150.     ")\n"
  151.    ]
  152.   },
  153.   {
  154.    "cell_type": "code",
  155.    "execution_count": null,
  156.    "metadata": {},
  157.    "outputs": [],
  158.    "source": [
  159.     "# Input for Validation\n",
  160.     "X_val = X_train[:10000]\n",
  161.     "partial_X_train = X_train[10000:]\n",
  162.     "# Labels for validation\n",
  163.     "y_val = y_train[:10000]\n",
  164.     "partial_y_train = y_train[10000:]\n"
  165.    ]
  166.   },
  167.   {
  168.    "cell_type": "code",
  169.    "execution_count": null,
  170.    "metadata": {},
  171.    "outputs": [],
  172.    "source": [
  173.     "history = model.fit(\n",
  174.     "partial_X_train,\n",
  175.     "partial_y_train,\n",
  176.     "epochs=20,\n",
  177.     "batch_size=512,\n",
  178.     "validation_data=(X_val, y_val)\n",
  179.     ")"
  180.    ]
  181.   },
  182.   {
  183.    "cell_type": "code",
  184.    "execution_count": null,
  185.    "metadata": {},
  186.    "outputs": [],
  187.    "source": [
  188.     "history_dict = history.history\n",
  189.     "history_dict.keys()\n"
  190.    ]
  191.   },
  192.   {
  193.    "cell_type": "code",
  194.    "execution_count": null,
  195.    "metadata": {},
  196.    "outputs": [],
  197.    "source": [
  198.     "# Plotting losses\n",
  199.     "loss_values = history_dict['loss']\n",
  200.     "val_loss_values = history_dict['val_loss']\n",
  201.     "epochs = range(1, len(loss_values) + 1)\n",
  202.     "plt.plot(epochs, loss_values, 'g', label=\"Training Loss\")\n",
  203.     "plt.plot(epochs, val_loss_values, 'b', label=\"Validation Loss\")\n",
  204.     "plt.title('Training and Validation Loss')\n",
  205.     "plt.xlabel('Epochs')\n",
  206.     "plt.ylabel('Loss Value')\n",
  207.     "plt.legend()\n",
  208.     "plt.show()"
  209.    ]
  210.   },
  211.   {
  212.    "cell_type": "code",
  213.    "execution_count": null,
  214.    "metadata": {},
  215.    "outputs": [],
  216.    "source": [
  217.     "\n",
  218.     "# Training and Validation Accuracy\n",
  219.     "acc_values = history_dict['binary_accuracy']\n",
  220.     "val_acc_values = history_dict['val_binary_accuracy']\n",
  221.     "epochs = range(1, len(loss_values) + 1)\n",
  222.     "plt.plot(epochs, acc_values, 'g', label=\"Training Accuracy\")\n",
  223.     "plt.plot(epochs, val_acc_values, 'b', label=\"Validation Accuracy\")\n",
  224.     "plt.title('Training and Validation Accuraccy')\n",
  225.     "plt.xlabel('Epochs')\n",
  226.     "plt.ylabel('Accuracy')\n",
  227.     "plt.legend()\n",
  228.     "plt.show()\n"
  229.    ]
  230.   },
  231.   {
  232.    "cell_type": "code",
  233.    "execution_count": null,
  234.    "metadata": {},
  235.    "outputs": [],
  236.    "source": [
  237.     "# Making Predictions for testing data\n",
  238.     "np.set_printoptions(suppress=True)\n",
  239.     "result = model.predict(X_test)\n"
  240.    ]
  241.   },
  242.   {
  243.    "cell_type": "code",
  244.    "execution_count": null,
  245.    "metadata": {},
  246.    "outputs": [],
  247.    "source": [
  248.     "result"
  249.    ]
  250.   }
  251.  ],
  252.  "metadata": {
  253.   "kernelspec": {
  254.    "display_name": "Python 3 (ipykernel)",
  255.    "language": "python",
  256.    "name": "python3"
  257.   },
  258.   "language_info": {
  259.    "codemirror_mode": {
  260.     "name": "ipython",
  261.     "version": 3
  262.    },
  263.    "file_extension": ".py",
  264.    "mimetype": "text/x-python",
  265.    "name": "python",
  266.    "nbconvert_exporter": "python",
  267.    "pygments_lexer": "ipython3",
  268.    "version": "3.11.8"
  269.   }
  270.  },
  271.  "nbformat": 4,
  272.  "nbformat_minor": 4
  273. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement