{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Assignment 3: Hello Vectors\n", "\n", "Welcome to this week's programming assignment of the specialization. In this assignment we will explore word vectors.\n", "In natural language processing, we represent each word as a vector consisting of numbers.\n", "The vector encodes the meaning of the word. These numbers (or weights) for each word are learned using various machine\n", "learning models, which we will explore in more detail later in this specialization. Rather than make you code the\n", "machine learning models from scratch, we will show you how to use them. In the real world, you can always load the\n", "trained word vectors, and you will almost never have to train them from scratch. In this assignment you will\n", "\n", "- Predict analogies between words.\n", "- Use PCA to reduce the dimensionality of the word embeddings and plot them in two dimensions.\n", "- Compare word embeddings by using a similarity measure (the cosine similarity).\n", "- Understand how these vector space models work.\n", "\n", "\n", "\n", "## 1.0 Predict the Countries from Capitals\n", "\n", "During the presentation of the module, we have illustrated the word analogies\n", "by finding the capital of a country from the country. In this part of the assignment\n", "we have changed the problem a bit. You are asked to predict the **countries** \n", "that corresponde to some **capitals**.\n", "You are playing trivia against some second grader who just took their geography test and knows all the capitals by heart.\n", "Thanks to NLP, you will be able to answer the questions properly. In other words, you will write a program that can give\n", "you the country by its capital. That way you are pretty sure you will win the trivia game. We will start by exploring the data set.\n", "\n", " \n", "\n", "## Important Note on Submission to the AutoGrader\n", "\n", "Before submitting your assignment to the AutoGrader, please make sure you are not doing the following:\n", "\n", "1. You have not added any _extra_ print statement(s) in the assignment.\n", "2. You have not added any _extra_ code cell(s) in the assignment.\n", "3. You have not changed any of the function parameters.\n", "4. You are not using any global variables inside your graded exercises. Unless specifically instructed to do so, please refrain from it and use the local variables instead.\n", "5. You are not changing the assignment code where it is not required, like creating _extra_ variables.\n", "\n", "If you do any of the following, you will get something like, Grader not found (or similarly unexpected) error upon submitting your assignment. Before asking for help/debugging the errors in your assignment, check for these first. If this is the case, and you don't remember the changes you have made, you can get a fresh copy of the assignment by following these [instructions](https://www.coursera.org/learn/classification-vector-spaces-in-nlp/supplement/YLuAg/h-ow-to-refresh-your-workspace).\n", "\n", "### 1.1 Importing the data\n", "\n", "As usual, you start by importing some essential Python libraries and the load dataset.\n", "The dataset will be loaded as a [Pandas DataFrame](https://pandas.pydata.org/pandas-docs/stable/getting_started/dsintro.html),\n", "which is very a common method in data science. Because of the large size of the data,\n", "this may take a few minutes." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Run this cell to import packages.\n", "import pickle\n", "import numpy as np\n", "import pandas as pd\n", "import matplotlib.pyplot as plt\n", "import w3_unittest\n", "\n", "from utils import get_vectors" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
city1country1city2country2
0AthensGreeceBangkokThailand
1AthensGreeceBeijingChina
2AthensGreeceBerlinGermany
3AthensGreeceBernSwitzerland
4AthensGreeceCairoEgypt
\n", "
" ], "text/plain": [ " city1 country1 city2 country2\n", "0 Athens Greece Bangkok Thailand\n", "1 Athens Greece Beijing China\n", "2 Athens Greece Berlin Germany\n", "3 Athens Greece Bern Switzerland\n", "4 Athens Greece Cairo Egypt" ] }, "execution_count": null, "metadata": {}, "output_type": "execute_result" } ], "source": [ "data = pd.read_csv('./data/capitals.txt', delimiter=' ')\n", "data.columns = ['city1', 'country1', 'city2', 'country2']\n", "\n", "# print first five elements in the DataFrame\n", "data.head(5)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "***\n", "\n", "### To Run This Code On Your Own Machine:\n", "Note that because the original google news word embedding dataset is about 3.64 gigabytes,\n", "the workspace is not able to handle the full file set. So we've downloaded the full dataset,\n", "extracted a sample of the words that we're going to analyze in this assignment, and saved\n", "it in a pickle file called word_embeddings_capitals.p\n", "\n", "If you want to download the full dataset on your own and choose your own set of word embeddings,\n", "please see the instructions and some helper code.\n", "\n", "- Download the dataset from this [page](https://code.google.com/archive/p/word2vec/).\n", "- Search in the page for 'GoogleNews-vectors-negative300.bin.gz' and click the link to download.\n", "- You'll need to unzip the file." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Copy-paste the code below and run it on your local machine after downloading\n", "the dataset to the same directory as the notebook.\n", "\n", "python\n", "import nltk\n", "from gensim.models import KeyedVectors\n", "\n", "\n", "embeddings = KeyedVectors.load_word2vec_format('./GoogleNews-vectors-negative300.bin', binary = True)\n", "f = open('capitals.txt', 'r').read()\n", "set_words = set(nltk.word_tokenize(f))\n", "select_words = words = ['king', 'queen', 'oil', 'gas', 'happy', 'sad', 'city', 'town', 'village', 'country', 'continent', 'petroleum', 'joyful']\n", "for w in select_words:\n", " set_words.add(w)\n", "\n", "def get_word_embeddings(embeddings):\n", "\n", " word_embeddings = {}\n", " for word in embeddings.vocab:\n", " if word in set_words:\n", " word_embeddings[word] = embeddings[word]\n", " return word_embeddings\n", "\n", "\n", "# Testing your function\n", "word_embeddings = get_word_embeddings(embeddings)\n", "print(len(word_embeddings))\n", "pickle.dump( word_embeddings, open( \"word_embeddings_subset.p\", \"wb\" ) )\n", "\n", "\n", "***" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now we will load the word embeddings as a [Python dictionary](https://docs.python.org/3/tutorial/datastructures.html#dictionaries).\n", "As stated, these have already been obtained through a machine learning algorithm. " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "243" ] }, "execution_count": null, "metadata": {}, "output_type": "execute_result" } ], "source": [ "word_embeddings = pickle.load(open(\"./data/word_embeddings_subset.p\", \"rb\"))\n", "len(word_embeddings) # there should be 243 words that will be used in this assignment" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Each of the word embedding is a 300-dimensional vector." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "dimension: 300\n" ] } ], "source": [ "print(\"dimension: {}\".format(word_embeddings['Spain'].shape))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Predict relationships among words\n", "\n", "Now you will write a function that will use the word embeddings to predict relationships among words.\n", "* The function will take as input three words.\n", "* The first two are related to each other.\n", "* It will predict a 4th word which is related to the third word in a similar manner as the two first words are related to each other.\n", "* As an example, \"Athens is to Greece as Bangkok is to ______\"?\n", "* You will write a program that is capable of finding the fourth word.\n", "* We will give you a hint to show you how to compute this.\n", "\n", "A similar analogy would be the following:\n", "\n", " \n", "\n", "You will implement a function that can tell you the capital of a country.\n", "You should use the same methodology shown in the figure above. To do this,\n", "you'll first compute the cosine similarity metric or the Euclidean distance." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 1.2 Cosine Similarity\n", "\n", "The cosine similarity function is:\n", "\n", "$$\\cos (\\theta)=\\frac{\\mathbf{A} \\cdot \\mathbf{B}}{\\|\\mathbf{A}\\|\\|\\mathbf{B}\\|}=\\frac{\\sum_{i=1}^{n} A_{i} B_{i}}{\\sqrt{\\sum_{i=1}^{n} A_{i}^{2}} \\sqrt{\\sum_{i=1}^{n} B_{i}^{2}}}\\tag{1}$$\n", "\n", "$A$ and $B$ represent the word vectors and $A_i$ or $B_i$ represent index i of that vector. Note that if A and B are identical, you will get $cos(\\theta) = 1$.\n", "* Otherwise, if they are the total opposite, meaning, $A= -B$, then you would get $cos(\\theta) = -1$.\n", "* If you get $cos(\\theta) =0$, that means that they are orthogonal (or perpendicular).\n", "* Numbers between 0 and 1 indicate a similarity score.\n", "* Numbers between -1 and 0 indicate a dissimilarity score.\n", "\n", "**Instructions**: Implement a function that takes in two word vectors and computes the cosine distance." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "\n", " Hints\n", "\n", "

\n", "

\n", "

" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# UNQ_C1 GRADED FUNCTION: cosine_similarity\n", "\n", "def cosine_similarity(A, B):\n", " '''\n", " Input:\n", " A: a numpy array which corresponds to a word vector\n", " B: A numpy array which corresponds to a word vector\n", " Output:\n", " cos: numerical number representing the cosine similarity between A and B.\n", " '''\n", "\n", " ### START CODE HERE ###\n", " dot = A@B\n", " norma = np.linalg.norm(A)\n", " normb = np.linalg.norm(B)\n", " cos = dot/(norma*normb)\n", "\n", " ### END CODE HERE ###\n", " return cos" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0.6510956" ] }, "execution_count": null, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# feel free to try different words\n", "king = word_embeddings['king']\n", "queen = word_embeddings['queen']\n", "\n", "cosine_similarity(king, queen)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Expected Output**:\n", "\n", "$\\approx$ 0.651095" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\u001b[92m All tests passed\n" ] } ], "source": [ "# Test your function\n", "w3_unittest.test_cosine_similarity(cosine_similarity)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 1.3 Euclidean distance\n", "\n", "You will now implement a function that computes the similarity between two vectors using the Euclidean distance.\n", "Euclidean distance is defined as:\n", "\n", "\\begin{aligned} d(\\mathbf{A}, \\mathbf{B})=d(\\mathbf{B}, \\mathbf{A}) &=\\sqrt{\\left(A_{1}-B_{1}\\right)^{2}+\\left(A_{2}-B_{2}\\right)^{2}+\\cdots+\\left(A_{n}-B_{n}\\right)^{2}} \\\\ &=\\sqrt{\\sum_{i=1}^{n}\\left(A_{i}-B_{i}\\right)^{2}} \\end{aligned}\n", "\n", "* $n$ is the number of elements in the vector\n", "* $A$ and $B$ are the corresponding word vectors. \n", "* The more similar the words, the more likely the Euclidean distance will be close to 0. \n", "\n", "**Instructions**: Write a function that computes the Euclidean distance between two vectors." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "\n", " Hints\n", "\n", "

\n", "

\n", "

" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# UNQ_C2 GRADED FUNCTION: euclidean\n", "\n", "def euclidean(A, B):\n", " \"\"\"\n", " Input:\n", " A: a numpy array which corresponds to a word vector\n", " B: A numpy array which corresponds to a word vector\n", " Output:\n", " d: numerical number representing the Euclidean distance between A and B.\n", " \"\"\"\n", "\n", " ### START CODE HERE ###\n", "\n", " # euclidean distance \n", " d = np.linalg.norm(A-B)\n", "\n", " ### END CODE HERE ###\n", "\n", " return d" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "2.4796925" ] }, "execution_count": null, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Test your function\n", "euclidean(king, queen)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Expected Output:**\n", "\n", "2.4796925" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\u001b[92m All tests passed\n" ] } ], "source": [ "# Test your function\n", "w3_unittest.test_euclidean(euclidean)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 1.4 Finding the country of each capital\n", "\n", "Now, you will use the previous functions to compute similarities between vectors,\n", "and use these to find the capital cities of countries. You will write a function that\n", "takes in three words, and the embeddings dictionary. Your task is to find the\n", "capital cities. For example, given the following words: \n", "\n", "- 1: Athens 2: Greece 3: Baghdad,\n", "\n", "your task is to predict the country 4: Iraq.\n", "\n", "**Instructions**: \n", "\n", "1. To predict the capital you might want to look at the *King - Man + Woman = Queen* example above, and implement that scheme into a mathematical function, using the word embeddings and a similarity function.\n", "\n", "2. Iterate over the embeddings dictionary and compute the cosine similarity score between your vector and the current word embedding.\n", "\n", "3. You should add a check to make sure that the word you return is not any of the words that you fed into your function. Return the one with the highest score." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# UNQ_C3 GRADED FUNCTION: get_country\n", "\n", "def get_country(city1, country1, city2, embeddings, cosine_similarity=cosine_similarity):\n", " \"\"\"\n", " Input:\n", " city1: a string (the capital city of country1)\n", " country1: a string (the country of capital1)\n", " city2: a string (the capital city of country2)\n", " embeddings: a dictionary where the keys are words and\n", " Output:\n", " countries: a dictionary with the most likely country and its similarity score\n", " \"\"\"\n", " ### START CODE HERE ###\n", "\n", " # store the city1, country 1, and city 2 in a set called group\n", " group = set([city1, country1, city2])\n", "\n", " # get embeddings of city 1\n", " city1_emb = embeddings[city1]\n", "\n", " # get embedding of country 1\n", " country1_emb = embeddings[country1]\n", "\n", " # get embedding of city 2\n", " city2_emb = embeddings[city2]\n", "\n", " # get embedding of country 2 (it's a combination of the embeddings of country 1, city 1 and city 2)\n", " # Remember: King - Man + Woman = None\n", " vec = city2_emb-city1_emb+country1_emb\n", "\n", " # Initialize the similarity to -1 (it will be replaced by a similarities that are closer to +1)\n", " similarity = -1\n", "\n", " # initialize country to an empty string\n", " country = ''\n", "\n", " # loop through all words in the embeddings dictionary\n", " for word in embeddings.keys():\n", "\n", " # first check that the word is not already in the 'group'\n", " if word not in group:\n", "\n", " # get the word embedding\n", " word_emb = embeddings[word]\n", "\n", " # calculate cosine similarity between embedding of country 2 and the word in the embeddings dictionary\n", " cur_similarity = cosine_similarity(word_emb, vec)\n", "\n", " # if the cosine similarity is more similar than the previously best similarity...\n", " if cur_similarity > similarity:\n", "\n", " # update the similarity to the new, better similarity\n", " similarity = cur_similarity\n", "\n", " # store the country as a tuple, which contains the word and the similarity\n", " country = (word, similarity)\n", "\n", " ### END CODE HERE ###\n", "\n", " return country" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "('Egypt', 0.7626822)" ] }, "execution_count": null, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Testing your function, note to make it more robust you can return the 5 most similar words.\n", "get_country('Athens', 'Greece', 'Cairo', word_embeddings)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Expected Output: (Approximately)**\n", "\n", "('Egypt', 0.7626821)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\u001b[92m All tests passed\n" ] } ], "source": [ "# Test your function\n", "w3_unittest.test_get_country(get_country)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 1.5 Model Accuracy\n", "\n", "Now you will test your new function on the dataset and check the accuracy of the model:\n", "\n", "$$\\text{Accuracy}=\\frac{\\text{Correct # of predictions}}{\\text{Total # of predictions}}$$\n", "\n", "**Instructions**: Write a program that can compute the accuracy on the dataset provided for you. You have to iterate over every row to get the corresponding words and feed them into you get_country function above. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "\n", " Hints\n", "\n", "

\n", "

\n", "

" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# UNQ_C4 GRADED FUNCTION: get_accuracy\n", "\n", "def get_accuracy(word_embeddings, data, get_country=get_country):\n", " '''\n", " Input:\n", " word_embeddings: a dictionary where the key is a word and the value is its embedding\n", " data: a pandas data frame as\n", "\n", " '''\n", "\n", " ### START CODE HERE ###\n", " # initialize num correct to zero\n", " num_correct = 0\n", "\n", " # loop through the rows of the dataframe\n", " for i, row in data.iterrows():\n", "\n", " # get city1\n", " city1 = row['city1']\n", "\n", " # get country1\n", " country1 = row['country1']\n", "\n", " # get city2\n", " city2 = row['city2']\n", "\n", " # get country2\n", " country2 = row['country2']\n", "\n", " # use get_country to find the predicted country2\n", " predicted_country2, _ = get_country(city1, country1, city2, word_embeddings, cosine_similarity=cosine_similarity)\n", "\n", " # if the predicted country2 is the same as the actual country2...\n", " if predicted_country2 == country2:\n", " # increment the number of correct by 1\n", " num_correct += 1\n", "\n", " # get the number of rows in the data dataframe (length of dataframe)\n", " m = len(data)\n", "\n", " # calculate the accuracy by dividing the number correct by m\n", " accuracy = num_correct/m\n", "\n", " ### END CODE HERE ###\n", " return accuracy\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**NOTE: The cell below takes about 30 SECONDS to run.**" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Accuracy is 0.92\n" ] } ], "source": [ "accuracy = get_accuracy(word_embeddings, data)\n", "print(f\"Accuracy is {accuracy:.2f}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Expected Output:**\n", "\n", "$\\approx$ 0.92" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\u001b[92m All tests passed\n" ] } ], "source": [ "# Test your function\n", "w3_unittest.test_get_accuracy(get_accuracy, data)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 3.0 Plotting the vectors using PCA\n", "\n", "Now you will explore the distance between word vectors after reducing their dimension.\n", "The technique we will employ is known as\n", "[*principal component analysis* (PCA)](https://en.wikipedia.org/wiki/Principal_component_analysis).\n", "As we saw, we are working in a 300-dimensional space in this case.\n", "Although from a computational perspective we were able to perform a good job,\n", "it is impossible to visualize results in such high dimensional spaces.\n", "\n", "You can think of PCA as a method that projects our vectors in a space of reduced\n", "dimension, while keeping the maximum information about the original vectors in\n", "their reduced counterparts. In this case, by *maximum infomation* we mean that the\n", "Euclidean distance between the original vectors and their projected siblings is\n", "minimal. Hence vectors that were originally close in the embeddings dictionary,\n", "will produce lower dimensional vectors that are still close to each other.\n", "\n", "You will see that when you map out the words, similar words will be clustered\n", "next to each other. For example, the words 'sad', 'happy', 'joyful' all describe\n", "emotion and are supposed to be near each other when plotted.\n", "The words: 'oil', 'gas', and 'petroleum' all describe natural resources.\n", "Words like 'city', 'village', 'town' could be seen as synonyms and describe a\n", "similar thing.\n", "\n", "Before plotting the words, you need to first be able to reduce each word vector\n", "with PCA into 2 dimensions and then plot it. The steps to compute PCA are as follows:\n", "\n", "1. Mean normalize the data\n", "2. Compute the covariance matrix of your data ($\\Sigma$). \n", "3. Compute the eigenvectors and the eigenvalues of your covariance matrix\n", "4. Multiply the first K eigenvectors by your normalized data. The transformation should look something as follows:\n", "\n", " " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Instructions**: \n", "\n", "You will write a program that takes in a data set where each row corresponds to a word vector. \n", "* The word vectors are of dimension 300. \n", "* Use PCA to change the 300 dimensions to n_components dimensions. \n", "* The new matrix should be of dimension m, n_componentns. \n", "\n", "* First de-mean the data\n", "* Get the eigenvalues using linalg.eigh. Use 'eigh' rather than 'eig' since R is symmetric. The performance gain when using eigh instead of eig is substantial.\n", "* Sort the eigenvectors and eigenvalues by decreasing order of the eigenvalues.\n", "* Get a subset of the eigenvectors (choose how many principle components you want to use using n_components).\n", "* Return the new transformation of the data by multiplying the eigenvectors with the original data." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "\n", " Hints\n", "\n", "

\n", "

\n", "
• Use numpy.mean(a,axis=None) : If you set axis = 0, you take the mean for each column. If you set axis = 1, you take the mean for each row. Remember that each row is a word vector, and the number of columns are the number of dimensions in a word vector.
• \n", "
• Use numpy.cov(m, rowvar=True) . This calculates the covariance matrix. By default rowvar is True. From the documentation: \"If rowvar is True (default), then each row represents a variable, with observations in the columns.\" In our case, each row is a word vector observation, and each column is a feature (variable).
• \n", "
• Use numpy.linalg.eigh(a, UPLO='L')
• \n", "
• Use numpy.argsort sorts the values in an array from smallest to largest, then returns the indices from this sort.
• \n", "
• In order to reverse the order of a list, you can use: x[::-1].
• \n", "
• To apply the sorted indices to eigenvalues, you can use this format x[indices_sorted].
• \n", "
• When applying the sorted indices to eigen vectors, note that each column represents an eigenvector. In order to preserve the rows but sort on the columns, you can use this format x[:,indices_sorted]
• \n", "
• To transform the data using a subset of the most relevant principle components, take the matrix multiplication of the eigenvectors with the original data.
• \n", "
• The data is of shape (n_observations, n_features).
• \n", "
• The subset of eigenvectors are in a matrix of shape (n_features, n_components).
• \n", "
• To multiply these together, take the transposes of both the eigenvectors (n_components, n_features) and the data (n_features, n_observations).
• \n", "
• The product of these two has dimensions (n_components,n_observations). Take its transpose to get the shape (n_observations, n_components).
• \n", "
\n", "

" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# UNQ_C5 GRADED FUNCTION: compute_pca\n", "\n", "\n", "def compute_pca(X, n_components=2):\n", " \"\"\"\n", " Input:\n", " X: of dimension (m,n) where each row corresponds to a word vector\n", " n_components: Number of components you want to keep.\n", " Output:\n", " X_reduced: data transformed in 2 dims/columns + regenerated original data\n", " pass in: data as 2D NumPy array\n", " \"\"\"\n", "\n", " ### START CODE HERE ###\n", " # mean center the data\n", " X_demeaned = (X - X.mean(axis=0))\n", "\n", " # calculate the covariance matrix\n", " covariance_matrix = np.cov(X, rowvar=False)\n", "\n", " # calculate eigenvectors & eigenvalues of the covariance matrix\n", " eigen_vals, eigen_vecs = np.linalg.eigh(covariance_matrix)\n", "\n", " # sort eigenvalue in increasing order (get the indices from the sort)\n", " idx_sorted = np.argsort(eigen_vals)\n", " \n", " # reverse the order so that it's from highest to lowest.\n", " idx_sorted_decreasing = idx_sorted[::-1]\n", "\n", " # sort the eigen values by idx_sorted_decreasing\n", " eigen_vals_sorted = eigen_vals[idx_sorted_decreasing]\n", "\n", " # sort eigenvectors using the idx_sorted_decreasing indices\n", " eigen_vecs_sorted = eigen_vecs[:,idx_sorted_decreasing]\n", "\n", " # select the first n eigenvectors (n is desired dimension\n", " # of rescaled data array, or dims_rescaled_data)\n", " eigen_vecs_subset = eigen_vecs_sorted[:, 0:n_components]\n", "\n", " # transform the data by multiplying the transpose of the eigenvectors with the transpose of the de-meaned data\n", " # Then take the transpose of that product.\n", " X_reduced = (eigen_vecs_subset.T@X_demeaned.T).T\n", "\n", " ### END CODE HERE ###\n", "\n", " return X_reduced" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Your original matrix was (3, 10) and it became:\n", "[[ 0.43437323 0.49820384]\n", " [ 0.42077249 -0.50351448]\n", " [-0.85514571 0.00531064]]\n" ] } ], "source": [ "# Testing your function\n", "np.random.seed(1)\n", "X = np.random.rand(3, 10)\n", "X_reduced = compute_pca(X, n_components=2)\n", "print(\"Your original matrix was \" + str(X.shape) + \" and it became:\")\n", "print(X_reduced)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\u001b[92m All tests passed\n" ] } ], "source": [ "# Test your function\n", "w3_unittest.test_compute_pca(compute_pca)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Expected Output:**\n", "\n", "Your original matrix was: (3,10) and it became:\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
 \n", " 0.43437323\n", " \n", " 0.49820384\n", " \n", " 0.42077249\n", " \n", " -0.50351448\n", " \n", " -0.85514571\n", " \n", " 0.00531064\n", "