You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
316 lines
10 KiB
316 lines
10 KiB
{
|
|
"cells": [
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"# Challenge: Analyzing Text about Data Science\n",
|
|
"\n",
|
|
"In this example, let's do a simple exercise that covers all steps of a traditional data science process. You do not have to write any code, you can just click on the cells below to execute them and observe the result. As a challenge, you are encouraged to try this code out with different data. \n",
|
|
"\n",
|
|
"## Goal\n",
|
|
"\n",
|
|
"In this lesson, we have been discussing different concepts related to Data Science. Let's try to discover more related concepts by doing some **text mining**. We will start with a text about Data Science, extract keywords from it, and then try to visualize the result.\n",
|
|
"\n",
|
|
"As a text, I will use the page on Data Science from Wikipedia:"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": []
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"url = 'https://en.wikipedia.org/wiki/Data_science'"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"## Step 1: Getting the Data\n",
|
|
"\n",
|
|
"First step in every data science process is getting the data. We will use `requests` library to do that:"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"import requests\n",
|
|
"\n",
|
|
"# Define a custom header.\n",
|
|
"headers = {\n",
|
|
" 'User-Agent': 'DataScienceChallenge/1.0 (myemail@gmail.com)'\n",
|
|
"}\n",
|
|
"\n",
|
|
"# Pass the headers into the get request\n",
|
|
"response = requests.get(url, headers=headers)\n",
|
|
"\n",
|
|
"if response.status_code == 200:\n",
|
|
" text = response.content.decode('utf-8')\n",
|
|
" print(text[:1000])\n",
|
|
"else:\n",
|
|
" print(f\"Error: {response.status_code}\")"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"## Step 2: Transforming the Data\n",
|
|
"\n",
|
|
"The next step is to convert the data into the form suitable for processing. In our case, we have downloaded HTML source code from the page, and we need to convert it into plain text.\n",
|
|
"\n",
|
|
"There are many ways this can be done. We will use [BeautifulSoup](https://www.crummy.com/software/BeautifulSoup/), a popular Python library for parsing HTML. BeautifulSoup allows us to target specific HTML elements, so we can focus on the main article content from Wikipedia and reduce some navigation menus, sidebars, footers, and other irrelevant content (though some boilerplate text may still remain)."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"First, we need to install the BeautifulSoup library for HTML parsing:"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"import sys\n",
|
|
"!{sys.executable} -m pip install beautifulsoup4"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"from bs4 import BeautifulSoup\n",
|
|
"\n",
|
|
"# Parse the HTML content\n",
|
|
"soup = BeautifulSoup(text, 'html.parser')\n",
|
|
"\n",
|
|
"# Extract only the main article content from Wikipedia\n",
|
|
"# Wikipedia uses 'mw-parser-output' class for the main article content\n",
|
|
"content = soup.find('div', class_='mw-parser-output')\n",
|
|
"\n",
|
|
"def clean_wikipedia_content(content_node):\n",
|
|
" \"\"\"Remove common non-article elements from a Wikipedia content node.\"\"\"\n",
|
|
" # Strip jump links, navboxes, reference lists/superscripts, edit sections, TOC, sidebars, etc.\n",
|
|
" selectors = [\n",
|
|
" '.mw-jump-link',\n",
|
|
" '.navbox',\n",
|
|
" '.reflist',\n",
|
|
" 'sup.reference',\n",
|
|
" '.mw-editsection',\n",
|
|
" '.hatnote',\n",
|
|
" '.metadata',\n",
|
|
" '.infobox',\n",
|
|
" '#toc',\n",
|
|
" '.toc',\n",
|
|
" '.sidebar',\n",
|
|
" ]\n",
|
|
" for selector in selectors:\n",
|
|
" for el in content_node.select(selector):\n",
|
|
" el.decompose()\n",
|
|
"\n",
|
|
"if content:\n",
|
|
" # Clean the content node to better approximate article text only.\n",
|
|
" clean_wikipedia_content(content)\n",
|
|
" text = content.get_text(separator=' ', strip=True)\n",
|
|
" print(text[:1000])\n",
|
|
"else:\n",
|
|
" print(\"Could not find main content. Using full page text.\")\n",
|
|
" text = soup.get_text(separator=' ', strip=True)\n",
|
|
" print(text[:1000])"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"## Step 3: Getting Insights\n",
|
|
"\n",
|
|
"The most important step is to turn our data into some form from which we can draw insights. In our case, we want to extract keywords from the text, and see which keywords are more meaningful.\n",
|
|
"\n",
|
|
"We will use Python library called [RAKE](https://github.com/aneesha/RAKE) for keyword extraction. First, let's install this library in case it is not present: "
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"import sys\n",
|
|
"!{sys.executable} -m pip install nlp_rake"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"The main functionality is available from `Rake` object, which we can customize using some parameters. In our case, we will set the minimum length of a keyword to 5 characters, minimum frequency of a keyword in the document to 3, and maximum number of words in a keyword - to 2. Feel free to play around with other values and observe the result."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"import nlp_rake\n",
|
|
"extractor = nlp_rake.Rake(max_words=2,min_freq=3,min_chars=5)\n",
|
|
"res = extractor.apply(text)\n",
|
|
"res"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"\n",
|
|
"We obtained a list terms together with associated degree of importance. As you can see, the most relevant disciplines, such as machine learning and big data, are present in the list at top positions.\n",
|
|
"\n",
|
|
"## Step 4: Visualizing the Result\n",
|
|
"\n",
|
|
"People can interpret the data best in the visual form. Thus it often makes sense to visualize the data in order to draw some insights. We can use `matplotlib` library in Python to plot simple distribution of the keywords with their relevance:"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"import matplotlib.pyplot as plt\n",
|
|
"\n",
|
|
"def plot(pair_list):\n",
|
|
" k,v = zip(*pair_list)\n",
|
|
" plt.bar(range(len(k)),v)\n",
|
|
" plt.xticks(range(len(k)),k,rotation='vertical')\n",
|
|
" plt.show()\n",
|
|
"\n",
|
|
"plot(res)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"There is, however, even better way to visualize word frequencies - using **Word Cloud**. We will need to install another library to plot the word cloud from our keyword list."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"!{sys.executable} -m pip install wordcloud"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"`WordCloud` object is responsible for taking in either original text, or pre-computed list of words with their frequencies, and returns and image, which can then be displayed using `matplotlib`:"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"from wordcloud import WordCloud\n",
|
|
"import matplotlib.pyplot as plt\n",
|
|
"\n",
|
|
"wc = WordCloud(background_color='white',width=800,height=600)\n",
|
|
"plt.figure(figsize=(15,7))\n",
|
|
"plt.imshow(wc.generate_from_frequencies({ k:v for k,v in res }))"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"We can also pass in the original text to `WordCloud` - let's see if we are able to get similar result:"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"plt.figure(figsize=(15,7))\n",
|
|
"plt.imshow(wc.generate(text))"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"wc.generate(text).to_file('images/ds_wordcloud.png')"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": [
|
|
"You can see that word cloud now looks more impressive, but it also contains a lot of noise (eg. unrelated words such as `Retrieved on`). Also, we get fewer keywords that consist of two words, such as *data scientist*, or *computer science*. This is because RAKE algorithm does much better job at selecting good keywords from text. This example illustrates the importance of data pre-processing and cleaning, because clear picture at the end will allow us to make better decisions.\n",
|
|
"\n",
|
|
"In this exercise we have gone through a simple process of extracting some meaning from Wikipedia text, in the form of keywords and word cloud. This example is quite simple, but it demonstrates well all typical steps a data scientist will take when working with data, starting from data acquisition, up to visualization.\n",
|
|
"\n",
|
|
"In our course we will discuss all those steps in detail. "
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": []
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {},
|
|
"source": []
|
|
}
|
|
],
|
|
"metadata": {
|
|
"interpreter": {
|
|
"hash": "c28e7b6bf4e5b397b8288a85bf0a94ea8d3585ce2b01919feb195678ec71581b"
|
|
},
|
|
"kernelspec": {
|
|
"display_name": "Python 3.8.11 64-bit ('base': conda)",
|
|
"name": "python3"
|
|
},
|
|
"language_info": {
|
|
"codemirror_mode": {
|
|
"name": "ipython",
|
|
"version": 3
|
|
},
|
|
"file_extension": ".py",
|
|
"mimetype": "text/x-python",
|
|
"name": "python",
|
|
"nbconvert_exporter": "python",
|
|
"pygments_lexer": "ipython3",
|
|
"version": "3.8.11"
|
|
}
|
|
},
|
|
"nbformat": 4,
|
|
"nbformat_minor": 2
|
|
}
|