microsoft/AI-For-Beginners

Public

mirrored fromhttps://github.com/microsoft/AI-For-BeginnersAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
3a3a2857a0ee0bcb21913d1ec1523402afb3e582

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

2-Symbolic/MSConceptGraph.ipynb

535lines · modecode

1{
2 "cells": [
3 {
4 "cell_type": "markdown",
5 "metadata": {
6 "collapsed": true
7 },
8 "source": [
9 "## Microsoft Concept Graph\n",
10 "\n",
11 "[Microsoft Concept Graph](https://concept.research.microsoft.com/) is a large taxonomy of terms mined from the internet, with `is-a` relations between concepts. \n",
12 "\n",
13 "Context Graph is available in two forms:\n",
14 " * Large text file for download\n",
15 " * REST API\n",
16 "\n",
17 "Statistics:\n",
18 " * 5401933 unique concepts, \n",
19 " * 12551613 unique instances\n",
20 " * 87603947 `is-a` relations"
21 ]
22 },
23 {
24 "cell_type": "markdown",
25 "metadata": {},
26 "source": [
27 "## Using Web Service\n",
28 "\n",
29 "Web service offers different calls to estimate probability of a concept belonging to different groups. More info is available [here](https://concept.research.microsoft.com/Home/Api).\n",
30 "Here is the sample URL to call: `https://concept.research.microsoft.com/api/Concept/ScoreByProb?instance=microsoft&topK=10`"
31 ]
32 },
33 {
34 "cell_type": "code",
35 "execution_count": 7,
36 "metadata": {
37 "trusted": true
38 },
39 "outputs": [
40 {
41 "data": {
42 "text/plain": [
43 "{'company': 0.6105356614382954,\n",
44 " 'vendor': 0.08858636677518003,\n",
45 " 'client': 0.048239124001183784,\n",
46 " 'firm': 0.045476965571668145,\n",
47 " 'large company': 0.043109401203511886,\n",
48 " 'organization': 0.043010752688172046,\n",
49 " 'corporation': 0.035908059583703265,\n",
50 " 'brand': 0.03383644076156654,\n",
51 " 'software company': 0.027522935779816515,\n",
52 " 'technology company': 0.023774292196902438}"
53 ]
54 },
55 "execution_count": 7,
56 "metadata": {},
57 "output_type": "execute_result"
58 }
59 ],
60 "source": [
61 "import urllib\n",
62 "import json\n",
63 "import ssl\n",
64 "\n",
65 "def http(x):\n",
66 " ssl._create_default_https_context = ssl._create_unverified_context\n",
67 " response = urllib.request.urlopen(x)\n",
68 " data = response.read()\n",
69 " return data.decode('utf-8')\n",
70 "\n",
71 "def query(x):\n",
72 " return json.loads(http(\"https://concept.research.microsoft.com/api/Concept/ScoreByProb?instance={}&topK=10\".format(urllib.parse.quote(x))))\n",
73 "\n",
74 "query('microsoft')"
75 ]
76 },
77 {
78 "cell_type": "markdown",
79 "metadata": {},
80 "source": [
81 "Let's try to categorize the news titles using parent concepts. To get news titles, we will use [NewsApi.org](http://newsapi.org) service. You need to obtain your own API key in order to use the service - go to the web site and register for free developer plan."
82 ]
83 },
84 {
85 "cell_type": "code",
86 "execution_count": 20,
87 "metadata": {
88 "trusted": true
89 },
90 "outputs": [],
91 "source": [
92 "newsapi_key = '<your API key here>'\n",
93 "def get_news(country='us'):\n",
94 " res = json.loads(http(\"https://newsapi.org/v2/top-headlines?country={0}&apiKey={1}\".format(country,newsapi_key)))\n",
95 " return res['articles']\n",
96 "\n",
97 "all_titles = [x['title'] for x in get_news('us')+get_news('gb')]"
98 ]
99 },
100 {
101 "cell_type": "code",
102 "execution_count": 21,
103 "metadata": {},
104 "outputs": [
105 {
106 "data": {
107 "text/plain": [
108 "['Covid-19 Live Updates: Vaccines and Boosters News - The New York Times',\n",
109 " 'Ukrainians Flee Mariupol as Russian Forces Push to Take Port City - The Wall Street Journal',\n",
110 " 'Bond Yields Jump, Stock Futures Rise After Powell Says Fed Is Ready to Be More Aggressive - The Wall Street Journal',\n",
111 " 'Putin critic Alexei Navalny found guilty by Russian court - New York Post ',\n",
112 " \"Supreme Court nominee Ketanji Brown Jackson will face questions at confirmation hearing's second day - CNN\",\n",
113 " '2 teachers killed at Swedish high school, student arrested - ABC News',\n",
114 " 'Clues to Covid-19’s Next Moves Come From Sewers - The Wall Street Journal',\n",
115 " 'Republicans to roll dice by grilling Jackson over child-pornography sentencing decisions | TheHill - The Hill',\n",
116 " '‘Clear sign’ Putin considering using chemical weapons in Ukraine, claims President Biden - The Independent',\n",
117 " 'NASA confirms there are 5,000 planets outside our solar system - Daily Mail',\n",
118 " \"US stocks whipsawed overnight after Fed Chair Powell's remarks - Fox Business\",\n",
119 " \"'We've learned absolutely nothing': Tests could again be in short supply if Covid surges - POLITICO\",\n",
120 " \"Duchess of Cambridge swaps khaki jungle gear for Vampire's Wife dress on Belize trip - Daily Mail\",\n",
121 " 'China searches for victims, flight recorders after first plane crash in 12 years - Reuters',\n",
122 " 'Second superyacht linked to Russian oligarch Abramovich docks in Turkey - Reuters',\n",
123 " 'Live updates: Russia stops talks with Japan over sanctions - The Associated Press - en Español',\n",
124 " 'Powers Remain and Threats Lurk as Women’s Sweet 16 Is Set - The New York Times',\n",
125 " 'Webb Space Telescope Begins Multi-Instrument Alignment - SciTechDaily',\n",
126 " \"UConn vs UCF - NCAA women's tournament second-round highlights - March Madness\",\n",
127 " 'Bucking Republican Trend, Indiana Governor Vetoes Transgender Sports Bill - The New York Times',\n",
128 " \"Maggie Fox dead: Coronation Street and Shameless actress dies after 'sudden accident' - Mirror Online - The Mirror\",\n",
129 " 'China plane crash – live: Search for survivors continues as witness describes moment flight fell from sky - The Independent',\n",
130 " 'Daniel Morgan murder: damning report condemns Met police - The Guardian',\n",
131 " 'What to expect from Rishi Sunak’s Spring Statement - BBC.com',\n",
132 " 'UK and Republic of Ireland in line to host Euro 2028 after no one else bids - The Guardian',\n",
133 " \"Friends beg Vladimir Putin's 'lover' to persuade him to end Ukraine invasion - The Mirror\",\n",
134 " 'Brass Eye’s outtakes show the brutal TV comedy was the tip of an iceberg - The Guardian',\n",
135 " \"Vladimir Putin threatens civilians to break Mariupol's spirit - The Times\",\n",
136 " 'Shell U-turn on Cambo oilfield would threaten green targets, say campaigners - The Guardian',\n",
137 " 'St Helens dog attack: Girl aged 17 months killed at home - BBC',\n",
138 " \"PlayStation to buy 'Assassin's Creed' veteran Jade Raymond's Haven Studios - NME\",\n",
139 " '‘Clear sign’ Putin considering using chemical weapons in Ukraine, claims President Biden - The Independent',\n",
140 " 'NASA confirms there are 5,000 planets outside our solar system - Daily Mail',\n",
141 " 'Nintendo Switch finally has folders • Eurogamer.net - Eurogamer.net',\n",
142 " 'FA to “find a solution” as Liverpool fan group blasts “shambolic” Wembley travel - This Is Anfield',\n",
143 " 'Manchester United transfer news LIVE Erik ten Hag latest and Man Utd manager updates - Manchester Evening News',\n",
144 " 'Inflation raises cost of UK government borrowing in February; crude oil up again – business live - The Guardian',\n",
145 " 'Alexei Navalny: Kremlin critic found guilty of large-scale fraud and contempt of court by Russian court - Sky News',\n",
146 " \"UK prepares to nationalize Russia natural gas giant Gazprom's retail unit - Business Insider\",\n",
147 " 'Zaghari-Ratcliffe: Hunt calls for inquiry into delay over Iran debt payment - The Guardian']"
148 ]
149 },
150 "execution_count": 21,
151 "metadata": {},
152 "output_type": "execute_result"
153 }
154 ],
155 "source": [
156 "all_titles"
157 ]
158 },
159 {
160 "cell_type": "markdown",
161 "metadata": {},
162 "source": [
163 "First of all, we want to be able to extract nouns from news titles. We will use `TextBlob` library to do this, which simplifies a lot of typical NLP tasks like this."
164 ]
165 },
166 {
167 "cell_type": "code",
168 "execution_count": 15,
169 "metadata": {
170 "trusted": true
171 },
172 "outputs": [
173 {
174 "name": "stdout",
175 "output_type": "stream",
176 "text": [
177 "Requirement already satisfied: textblob in c:\\winapp\\miniconda3\\lib\\site-packages (0.17.1)\n",
178 "Requirement already satisfied: nltk>=3.1 in c:\\winapp\\miniconda3\\lib\\site-packages (from textblob) (3.5)\n",
179 "Requirement already satisfied: joblib in c:\\winapp\\miniconda3\\lib\\site-packages (from nltk>=3.1->textblob) (1.0.1)\n",
180 "Requirement already satisfied: regex in c:\\winapp\\miniconda3\\lib\\site-packages (from nltk>=3.1->textblob) (2021.11.10)\n",
181 "Requirement already satisfied: tqdm in c:\\winapp\\miniconda3\\lib\\site-packages (from nltk>=3.1->textblob) (4.61.2)\n",
182 "Requirement already satisfied: click in c:\\winapp\\miniconda3\\lib\\site-packages (from nltk>=3.1->textblob) (8.0.3)\n",
183 "Requirement already satisfied: colorama in c:\\winapp\\miniconda3\\lib\\site-packages (from click->nltk>=3.1->textblob) (0.4.4)\n",
184 "Finished.\n"
185 ]
186 },
187 {
188 "name": "stderr",
189 "output_type": "stream",
190 "text": [
191 "[nltk_data] Downloading package brown to\n",
192 "[nltk_data] C:\\Users\\dmitryso\\AppData\\Roaming\\nltk_data...\n",
193 "[nltk_data] Package brown is already up-to-date!\n",
194 "[nltk_data] Downloading package punkt to\n",
195 "[nltk_data] C:\\Users\\dmitryso\\AppData\\Roaming\\nltk_data...\n",
196 "[nltk_data] Package punkt is already up-to-date!\n",
197 "[nltk_data] Downloading package wordnet to\n",
198 "[nltk_data] C:\\Users\\dmitryso\\AppData\\Roaming\\nltk_data...\n",
199 "[nltk_data] Package wordnet is already up-to-date!\n",
200 "[nltk_data] Downloading package averaged_perceptron_tagger to\n",
201 "[nltk_data] C:\\Users\\dmitryso\\AppData\\Roaming\\nltk_data...\n",
202 "[nltk_data] Package averaged_perceptron_tagger is already up-to-\n",
203 "[nltk_data] date!\n",
204 "[nltk_data] Downloading package conll2000 to\n",
205 "[nltk_data] C:\\Users\\dmitryso\\AppData\\Roaming\\nltk_data...\n",
206 "[nltk_data] Package conll2000 is already up-to-date!\n",
207 "[nltk_data] Downloading package movie_reviews to\n",
208 "[nltk_data] C:\\Users\\dmitryso\\AppData\\Roaming\\nltk_data...\n",
209 "[nltk_data] Package movie_reviews is already up-to-date!\n"
210 ]
211 }
212 ],
213 "source": [
214 "import sys\n",
215 "!{sys.executable} -m pip install textblob\n",
216 "!{sys.executable} -m textblob.download_corpora\n",
217 "from textblob import TextBlob"
218 ]
219 },
220 {
221 "cell_type": "code",
222 "execution_count": 22,
223 "metadata": {
224 "trusted": true
225 },
226 "outputs": [
227 {
228 "data": {
229 "text/plain": [
230 "{'covid-19 live updates': 1,\n",
231 " 'vaccines': 1,\n",
232 " 'boosters': 1,\n",
233 " 'york': 4,\n",
234 " 'ukrainians flee mariupol': 1,\n",
235 " 'forces push': 1,\n",
236 " 'port city': 1,\n",
237 " 'wall street journal': 3,\n",
238 " 'bond yields': 1,\n",
239 " 'futures rise': 1,\n",
240 " 'powell says fed': 1,\n",
241 " 'ready': 1,\n",
242 " 'be': 1,\n",
243 " 'aggressive': 1,\n",
244 " 'putin': 3,\n",
245 " 'alexei navalny': 2,\n",
246 " 'russian': 2,\n",
247 " 'supreme court nominee': 1,\n",
248 " 'ketanji brown jackson': 1,\n",
249 " \"confirmation hearing 's\": 1,\n",
250 " 'cnn': 1,\n",
251 " 'swedish': 1,\n",
252 " 'high school': 1,\n",
253 " 'abc': 1,\n",
254 " 'clues': 1,\n",
255 " 'covid-19': 1,\n",
256 " '’ s': 2,\n",
257 " 'moves': 1,\n",
258 " 'sewers': 1,\n",
259 " 'roll dice': 1,\n",
260 " 'jackson': 1,\n",
261 " 'decisions |': 1,\n",
262 " 'thehill': 1,\n",
263 " 'clear': 2,\n",
264 " 'chemical weapons': 2,\n",
265 " 'ukraine': 3,\n",
266 " 'claims president': 2,\n",
267 " 'biden': 2,\n",
268 " 'nasa': 2,\n",
269 " 'solar system': 2,\n",
270 " 'daily mail': 3,\n",
271 " 'us stocks': 1,\n",
272 " 'fed chair powell': 1,\n",
273 " \"'s remarks\": 1,\n",
274 " 'fox': 1,\n",
275 " \"'we 've\": 1,\n",
276 " 'tests': 1,\n",
277 " 'covid': 1,\n",
278 " 'politico': 1,\n",
279 " 'duchess': 1,\n",
280 " 'cambridge': 1,\n",
281 " 'swaps khaki jungle gear': 1,\n",
282 " 'vampire': 1,\n",
283 " 'wife': 1,\n",
284 " 'belize': 1,\n",
285 " 'china': 2,\n",
286 " 'flight recorders': 1,\n",
287 " 'plane crash': 1,\n",
288 " 'reuters': 2,\n",
289 " 'russian oligarch': 1,\n",
290 " 'abramovich': 1,\n",
291 " 'live': 1,\n",
292 " 'russia': 2,\n",
293 " 'stops talks': 1,\n",
294 " 'japan': 1,\n",
295 " 'español': 1,\n",
296 " 'powers remain': 1,\n",
297 " 'threats lurk': 1,\n",
298 " 'set': 1,\n",
299 " 'webb': 1,\n",
300 " 'telescope begins multi-instrument alignment': 1,\n",
301 " 'scitechdaily': 1,\n",
302 " 'uconn': 1,\n",
303 " 'ucf': 1,\n",
304 " 'ncaa': 1,\n",
305 " \"women 's tournament second-round highlights\": 1,\n",
306 " 'march madness': 1,\n",
307 " 'bucking republican trend': 1,\n",
308 " 'indiana': 1,\n",
309 " 'vetoes transgender': 1,\n",
310 " 'bill': 1,\n",
311 " 'maggie fox': 1,\n",
312 " 'coronation': 1,\n",
313 " 'shameless': 1,\n",
314 " \"'sudden accident\": 1,\n",
315 " 'mirror online': 1,\n",
316 " 'mirror': 2,\n",
317 " 'plane crash –': 1,\n",
318 " 'search': 1,\n",
319 " 'moment flight': 1,\n",
320 " 'daniel morgan': 1,\n",
321 " 'report condemns': 1,\n",
322 " 'met': 1,\n",
323 " 'guardian': 6,\n",
324 " 'rishi sunak': 1,\n",
325 " '’ s spring': 1,\n",
326 " 'statement': 1,\n",
327 " 'bbc.com': 1,\n",
328 " 'uk': 3,\n",
329 " 'ireland': 1,\n",
330 " 'euro': 1,\n",
331 " 'vladimir putin': 2,\n",
332 " \"'s 'lover\": 1,\n",
333 " 'brass eye': 1,\n",
334 " '’ s outtakes': 1,\n",
335 " 'brutal tv comedy': 1,\n",
336 " 'threatens civilians': 1,\n",
337 " 'mariupol': 1,\n",
338 " \"'s spirit\": 1,\n",
339 " 'shell u-turn': 1,\n",
340 " 'cambo': 1,\n",
341 " 'green targets': 1,\n",
342 " 'st helens': 1,\n",
343 " 'dog attack': 1,\n",
344 " 'girl': 1,\n",
345 " 'bbc': 1,\n",
346 " 'playstation': 1,\n",
347 " \"'assassin 's\": 1,\n",
348 " 'creed': 1,\n",
349 " 'jade raymond': 1,\n",
350 " 'haven studios': 1,\n",
351 " 'nme': 1,\n",
352 " 'nintendo switch': 1,\n",
353 " 'folders •': 1,\n",
354 " 'eurogamer.net': 2,\n",
355 " 'fa': 1,\n",
356 " 'solution ”': 1,\n",
357 " 'liverpool': 1,\n",
358 " 'fan group blasts “ shambolic ”': 1,\n",
359 " 'wembley': 1,\n",
360 " 'anfield': 1,\n",
361 " 'manchester': 1,\n",
362 " 'live erik': 1,\n",
363 " 'hag': 1,\n",
364 " 'utd': 1,\n",
365 " 'manager updates': 1,\n",
366 " 'manchester evening': 1,\n",
367 " 'inflation': 1,\n",
368 " 'government borrowing': 1,\n",
369 " 'february': 1,\n",
370 " 'crude oil': 1,\n",
371 " '– business': 1,\n",
372 " 'kremlin': 1,\n",
373 " 'large-scale fraud': 1,\n",
374 " 'sky': 1,\n",
375 " 'natural gas': 1,\n",
376 " 'gazprom': 1,\n",
377 " 'retail unit': 1,\n",
378 " 'insider': 1,\n",
379 " 'zaghari-ratcliffe': 1,\n",
380 " 'hunt': 1,\n",
381 " 'iran': 1,\n",
382 " 'debt payment': 1}"
383 ]
384 },
385 "execution_count": 22,
386 "metadata": {},
387 "output_type": "execute_result"
388 }
389 ],
390 "source": [
391 "w = {}\n",
392 "for x in all_titles:\n",
393 " for n in TextBlob(x).noun_phrases:\n",
394 " if n in w:\n",
395 " w[n].append(x)\n",
396 " else:\n",
397 " w[n]=[x]\n",
398 "{ x:len(w[x]) for x in w.keys()}"
399 ]
400 },
401 {
402 "cell_type": "markdown",
403 "metadata": {},
404 "source": [
405 "We can see that nouns do not give us large thematic groups. Let's substitute nouns by more general terms obtained from the concept graph. This will take some time, because we are doing REST call for each noun phrase."
406 ]
407 },
408 {
409 "cell_type": "code",
410 "execution_count": 23,
411 "metadata": {
412 "trusted": true
413 },
414 "outputs": [],
415 "source": [
416 "w = {}\n",
417 "for x in all_titles:\n",
418 " for noun in TextBlob(x).noun_phrases:\n",
419 " terms = query(noun.replace(' ','%20'))\n",
420 " for term in [u for u in terms.keys() if terms[u]>0.1]:\n",
421 " if term in w:\n",
422 " w[term].append(x)\n",
423 " else:\n",
424 " w[term]=[x]"
425 ]
426 },
427 {
428 "cell_type": "code",
429 "execution_count": 24,
430 "metadata": {
431 "trusted": true
432 },
433 "outputs": [
434 {
435 "data": {
436 "text/plain": [
437 "{'city': 9,\n",
438 " 'brand': 4,\n",
439 " 'place': 9,\n",
440 " 'town': 4,\n",
441 " 'factor': 4,\n",
442 " 'film': 4,\n",
443 " 'nation': 11,\n",
444 " 'state': 5,\n",
445 " 'person': 4,\n",
446 " 'organization': 5,\n",
447 " 'publication': 10,\n",
448 " 'market': 5,\n",
449 " 'economy': 4,\n",
450 " 'company': 6,\n",
451 " 'newspaper': 6,\n",
452 " 'relationship': 6}"
453 ]
454 },
455 "execution_count": 24,
456 "metadata": {},
457 "output_type": "execute_result"
458 }
459 ],
460 "source": [
461 "{ x:len(w[x]) for x in w.keys() if len(w[x])>3}"
462 ]
463 },
464 {
465 "cell_type": "code",
466 "execution_count": 27,
467 "metadata": {
468 "trusted": true
469 },
470 "outputs": [
471 {
472 "name": "stdout",
473 "output_type": "stream",
474 "text": [
475 "\n",
476 "ECONOMY:\n",
477 "China searches for victims, flight recorders after first plane crash in 12 years - Reuters\n",
478 "Live updates: Russia stops talks with Japan over sanctions - The Associated Press - en Español\n",
479 "China plane crash – live: Search for survivors continues as witness describes moment flight fell from sky - The Independent\n",
480 "UK prepares to nationalize Russia natural gas giant Gazprom's retail unit - Business Insider\n",
481 "\n",
482 "NATION:\n",
483 "‘Clear sign’ Putin considering using chemical weapons in Ukraine, claims President Biden - The Independent\n",
484 "Duchess of Cambridge swaps khaki jungle gear for Vampire's Wife dress on Belize trip - Daily Mail\n",
485 "China searches for victims, flight recorders after first plane crash in 12 years - Reuters\n",
486 "Live updates: Russia stops talks with Japan over sanctions - The Associated Press - en Español\n",
487 "Live updates: Russia stops talks with Japan over sanctions - The Associated Press - en Español\n",
488 "China plane crash – live: Search for survivors continues as witness describes moment flight fell from sky - The Independent\n",
489 "UK and Republic of Ireland in line to host Euro 2028 after no one else bids - The Guardian\n",
490 "Friends beg Vladimir Putin's 'lover' to persuade him to end Ukraine invasion - The Mirror\n",
491 "‘Clear sign’ Putin considering using chemical weapons in Ukraine, claims President Biden - The Independent\n",
492 "UK prepares to nationalize Russia natural gas giant Gazprom's retail unit - Business Insider\n",
493 "Zaghari-Ratcliffe: Hunt calls for inquiry into delay over Iran debt payment - The Guardian\n",
494 "\n",
495 "PERSON:\n",
496 "‘Clear sign’ Putin considering using chemical weapons in Ukraine, claims President Biden - The Independent\n",
497 "Duchess of Cambridge swaps khaki jungle gear for Vampire's Wife dress on Belize trip - Daily Mail\n",
498 "Second superyacht linked to Russian oligarch Abramovich docks in Turkey - Reuters\n",
499 "‘Clear sign’ Putin considering using chemical weapons in Ukraine, claims President Biden - The Independent\n"
500 ]
501 }
502 ],
503 "source": [
504 "print('\\nECONOMY:\\n'+'\\n'.join(w['economy']))\n",
505 "print('\\nNATION:\\n'+'\\n'.join(w['nation']))\n",
506 "print('\\nPERSON:\\n'+'\\n'.join(w['person']))"
507 ]
508 }
509 ],
510 "metadata": {
511 "kernelspec": {
512 "display_name": "Python 3.7.4 64-bit (conda)",
513 "metadata": {
514 "interpreter": {
515 "hash": "86193a1ab0ba47eac1c69c1756090baa3b420b3eea7d4aafab8b85f8b312f0c5"
516 }
517 },
518 "name": "python3"
519 },
520 "language_info": {
521 "codemirror_mode": {
522 "name": "ipython",
523 "version": 3
524 },
525 "file_extension": ".py",
526 "mimetype": "text/x-python",
527 "name": "python",
528 "nbconvert_exporter": "python",
529 "pygments_lexer": "ipython3",
530 "version": "3.9.5"
531 }
532 },
533 "nbformat": 4,
534 "nbformat_minor": 2
535}
536