hexsha
stringlengths
40
40
size
int64
6
14.9M
ext
stringclasses
1 value
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
6
260
max_stars_repo_name
stringlengths
6
119
max_stars_repo_head_hexsha
stringlengths
40
41
max_stars_repo_licenses
list
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
6
260
max_issues_repo_name
stringlengths
6
119
max_issues_repo_head_hexsha
stringlengths
40
41
max_issues_repo_licenses
list
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
6
260
max_forks_repo_name
stringlengths
6
119
max_forks_repo_head_hexsha
stringlengths
40
41
max_forks_repo_licenses
list
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
avg_line_length
float64
2
1.04M
max_line_length
int64
2
11.2M
alphanum_fraction
float64
0
1
cells
list
cell_types
list
cell_type_groups
list
4a0a4094df5f27fa03f0d446d349969c415fe51f
3,176
ipynb
Jupyter Notebook
src/example_branin.ipynb
jungtaekkim/ksc-2020-tutorial-on-bo
a6ee43ac70d46c473f34ed0f32e5a68cce55025b
[ "MIT" ]
null
null
null
src/example_branin.ipynb
jungtaekkim/ksc-2020-tutorial-on-bo
a6ee43ac70d46c473f34ed0f32e5a68cce55025b
[ "MIT" ]
null
null
null
src/example_branin.ipynb
jungtaekkim/ksc-2020-tutorial-on-bo
a6ee43ac70d46c473f34ed0f32e5a68cce55025b
[ "MIT" ]
null
null
null
24.244275
106
0.529912
[ [ [ "import numpy as np\n\nfrom bayeso import bo\nfrom benchmarks.two_dim_branin import Branin\nfrom bayeso.wrappers import wrappers_bo\nfrom bayeso.utils import utils_plotting\nfrom bayeso.utils import utils_bo", "_____no_output_____" ], [ "obj_fun = Branin()\nbounds = obj_fun.get_bounds()\n\ndef fun_target(X):\n return obj_fun.output(X)", "_____no_output_____" ], [ "str_fun = 'branin'\n\nnum_bo = 5\nnum_iter = 25\nnum_init = 5", "_____no_output_____" ], [ "model_bo = bo.BO(bounds, debug=False)\nlist_X = []\nlist_Y = []\nlist_time = []\n\nfor ind_bo in range(0, num_bo):\n print('BO Round', ind_bo + 1)\n X_final, Y_final, time_final, _, _ = wrappers_bo.run_single_round(\n model_bo, fun_target, num_init, num_iter,\n seed=42 * ind_bo\n )\n list_X.append(X_final)\n list_Y.append(Y_final)\n list_time.append(time_final)\n\narr_X = np.array(list_X)\narr_Y = np.array(list_Y)\narr_time = np.array(list_time)\n\narr_Y = np.expand_dims(np.squeeze(arr_Y), axis=0)\narr_time = np.expand_dims(arr_time, axis=0)", "_____no_output_____" ], [ "for ind_bo in range(0, num_bo):\n bx_best, y_best = utils_bo.get_best_acquisition_by_history(arr_X[ind_bo],\n arr_Y[0, ind_bo][..., np.newaxis])\n \n print('BO Round', ind_bo + 1)\n print(bx_best, y_best)", "_____no_output_____" ], [ "utils_plotting.plot_minimum_vs_iter(arr_Y, [str_fun], num_init, True,\n str_x_axis='Iteration',\n str_y_axis='Mininum function value')\nutils_plotting.plot_minimum_vs_time(arr_time, arr_Y, [str_fun], num_init, True,\n str_x_axis='Time (sec.)',\n str_y_axis='Mininum function value')", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code" ] ]
4a0a446c22e31076b8fdc48b78985193640f9f00
1,747
ipynb
Jupyter Notebook
Week1-Introduction-to-Python-_-NumPy/Introductory_Example.ipynb
isabella232/Bitcamp-DataSci
78b921b60b66d8cfb88ce54dcfdef37664004552
[ "MIT" ]
1
2020-10-02T19:18:36.000Z
2020-10-02T19:18:36.000Z
Week1-Introduction-to-Python-_-NumPy/Introductory_Example.ipynb
kylebegovich/Bitcamp-DataSci
0bf52ca1d250a915c3e7e4ba2eb6bc1edfb2766b
[ "MIT" ]
2
2020-09-10T05:45:50.000Z
2020-09-25T07:23:26.000Z
Week1-Introduction-to-Python-_-NumPy/Introductory_Example.ipynb
kylebegovich/Bitcamp-DataSci
0bf52ca1d250a915c3e7e4ba2eb6bc1edfb2766b
[ "MIT" ]
3
2020-09-03T03:43:47.000Z
2020-12-27T02:33:49.000Z
24.605634
274
0.5581
[ [ [ "<a href=\"https://colab.research.google.com/github/bitprj/Bitcamp-DataSci/blob/master/Week1-Introduction-to-Python-_-NumPy/Introductory_Example.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ] ], [ [ "# reads in the text file whose name is specified on the command line,\n# and reports the number of lines and words\n\nimport sys\n\ndef checkline():\n global l\n global wordcount\n w = l.split()\n wordcount += len(w)\n \n wordcount = 0\n f = open(sys.argv[1]) # THIS VERSION IS FOR COMMAND LINE, CAN ALSO IMPORT FILE INTO COLAB\n flines = f.readlines()\n linecount = len(flines)\n for l in flines:\n checkline()\n print(linecount, wordcount)", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code" ] ]
4a0a45ba6acdb7bd74908e07f6fc6eedbdc591f3
43,201
ipynb
Jupyter Notebook
Untitled14.ipynb
crazysuryaa/Deeplearning_PlayGround
94ddc3ddba157e3eb7cde4514e8824fe2c428551
[ "MIT" ]
null
null
null
Untitled14.ipynb
crazysuryaa/Deeplearning_PlayGround
94ddc3ddba157e3eb7cde4514e8824fe2c428551
[ "MIT" ]
null
null
null
Untitled14.ipynb
crazysuryaa/Deeplearning_PlayGround
94ddc3ddba157e3eb7cde4514e8824fe2c428551
[ "MIT" ]
null
null
null
45.426919
167
0.49191
[ [ [ "import pyttsx3\nimport webbrowser\nimport smtplib\nimport random\nimport speech_recognition as sr\nimport wikipedia\nimport datetime\nimport wolframalpha\nimport os\nimport sys\nimport tkinter as tk\nfrom tkinter import *\nfrom datetime import datetime\nimport random\nimport re\nfrom tkinter import messagebox\nfrom tkinter.font import Font\nfrom tkinter import font as tkfont # python 3\nfrom tkinter import filedialog\nimport textwrap\nfrom random import choice\nfrom PIL import Image, ImageTk, ImageSequence\nfrom itertools import count\nfrom contextlib import redirect_stdout\nimport tkinter\nimport matplotlib\nmatplotlib.use(\"TkAgg\")\nfrom matplotlib.backends.backend_tkagg import (\n FigureCanvasTkAgg, NavigationToolbar2Tk)\nfrom matplotlib.backend_bases import key_press_handler\nfrom matplotlib.figure import Figure\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom numpy import expand_dims\n\n# In[2]:\n\n\nimport tensorflow.keras as keras\nimport tensorflow as tf\nfrom tensorflow.keras.layers import *\nfrom tensorflow.keras.utils import plot_model\nfrom tensorflow.keras.preprocessing.image import load_img\nfrom tensorflow.keras.preprocessing.image import img_to_array\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.utils import *\nfrom text_editor import Editor\n# In[ ]:\n\n\n# In[ ]:\n\n\n# In[3]:\n\n\nclient = wolframalpha.Client('QAEXLK-RY9HY2PHAT')\nimport pyttsx3\n\nengine = pyttsx3.init()\n# engine.say(\"In supervised machine learning, a crazy man just runs away what is deep learning\")\nengine.setProperty('volume', 1)\nengine.setProperty('rate', 170)\nengine.setProperty('voice', 'english+f4')\n# engine.setProperty('voice', voices[1].id)\nengine.runAndWait()\n\n# In[4]:\n\n\nname = \"crazy\"\n\nquestions = []\nfile1 = open('/mnt/DATA/UI/questions.txt', 'r')\nLines = file1.readlines()\ncount = 0\nfor line in Lines:\n # print(line)\n questions.append(line[:-1])\n\nanswers = []\nfile1 = open('/mnt/DATA/UI/answers.txt', 'r')\nLines = file1.readlines()\ncount = 0\nfor line in Lines:\n answers.append(line[:-1])\n\nweblinks = []\nfile1 = open('/mnt/DATA/UI/weblinks.txt', 'r')\nLines = file1.readlines()\ncount = 0\nfor line in Lines:\n weblinks.append(line[:-1])\n\n# In[5]:\n\n\nlayerdic = [{\"name\": None, \"args\": [], \"defs\": []} for i in range(20)]\nlayernames = [None] * 20\n\nfolderpath = \"/mnt/DATA/UI/layers/\"\nfor i, layer in enumerate(os.listdir(folderpath)):\n layernames[i] = layer[:-4]\n layerpath = folderpath + layer\n file1 = open(layerpath, 'r')\n Lines = file1.readlines()\n\n for ind, line in enumerate(Lines[:-2]):\n if ind == 0:\n layerdic[i][\"name\"] = line[:-2]\n else:\n k = 0\n m = 0\n for ind, char in enumerate(line[:-2]):\n if char == \"=\":\n k = ind\n layerdic[i][\"args\"].append(line[4:k])\n layerdic[i][\"defs\"].append(line[k + 1:-2])\n\n# In[6]:\n\n\nimport sys\n#\n# sys.path.insert(1, '/mnt/DATA/UI/ide/crossviper-master')\n# sys.path.insert(1, '/mnt/DATA/DeeplearningUI/')\n# sys.path.insert(1, '/mnt/DATA/UI/labelImgmaster')\nsys.path.insert(1, '/mnt/DATA/UI/ide/crossviper-master')\nsys.path.insert(1, '/mnt/DATA/DeeplearningUI/')\nsys.path.insert(1, '/mnt/DATA/UI/labelImgmaster')\n\n\n\nfrom FlattenDialog import *\nfrom AddDialog import *\nfrom CodeImageDialog import *\nfrom CompileDialog import *\nfrom ConvDialog import *\nfrom DenseDialog import *\nfrom plotgraphDialog import *\nfrom summaryDialog import *\nfrom tokoDialog import *\nfrom trainDialog import *\nfrom InputDialog import *\nfrom OutputDialog import *\nfrom ideDialog import *\n# from StartPage import *\n# from Existing import *\n# from NewProject import *\n# from ImageClassification import *\n# from ObjectDetection import *\n\nfrom labelImg import main as labelmain\nfrom reshapeimages import reshape\n\n# In[7]:\n\n\nwidgetspath = '/mnt/DATA/UI/widgets/inactive/'\n# buttonspath = '/mnt/DATA/UI/buttons/'\nbuttonspath = \"/home/crazy/UI/buttons/\"\nbgpath = '/mnt/DATA/UI/backgrounds/'\n\n# In[ ]:\n\n\n# In[8]:\n\n\ndic = [{} for i in range(20)]\ngraph = [[] for i in range(20)]\ninvgraph = [[] for i in range(20)]\nnodes = []\nconnectionsdic = [[] for i in range(20)]\n\n\n# In[9]:\n\n\ndef getplotimage():\n plot = ImageTk.PhotoImage(Image.open(\"/home/crazy/UI/modelplot.png\"))\n return plot\n\n\nopen('model.py', 'w').close()\nwith open(\"model.py\", \"a\") as myfile:\n myfile.write(\"import tensorflow as tf\\n\")\n myfile.write(\"import numpy as np\\n\")\n myfile.write(\" \\n\")\n myfile.write(\"def mymodel():\\n\")\n\n\nclass Window(Frame):\n\n def __init__(self, buttonsbg, root, master=None):\n Frame.__init__(self, master)\n\n # self.traindatagen = root.traindatagen\n # self.testdatagen = root.testdatagen\n\n # obj = next(self.traindatagen)\n # print(obj[0], obj[1])\n\n self.master = master\n global layerdic, layernames, buttonspath, bgpath, widgetspath, dic, graph, invgraph, nodes, connectionsdic\n\n self.dic = dic\n self.graph = graph\n self.invgraph = invgraph\n self.nodes = nodes\n self.connectionsdic = connectionsdic\n\n self.layerdic = layerdic\n self.layernames = layernames\n self.tensorlist = []\n\n defaultbutton = buttonsbg[0]\n buttonsbgarray = buttonsbg[1]\n\n plotbg, trainbg, codebg, buildbg = buttonsbg[2]\n\n toko = buttonsbg[3]\n code = buttonsbg[5]\n self.plot = buttonsbg[4]\n self.t1, self.t2, self.t3, self.t4, self.t5 = buttonsbg[6]\n\n self._drag_data = {\"x\": 0, \"y\": 0, \"item\": None}\n self.currenty = 400\n self.currentx = 20\n self.ccnt = 0\n self.dcnt = 0\n self.acnt = 0\n self.icnt = 0\n self.ocnt = 0\n self.cnt = 0\n\n self.codelines = []\n self.invgraph = [[] for i in range(20)]\n self.graph = [[] for i in range(20)]\n self.dic = [{} for i in range(20)]\n self.coonectionsdic = [[] for i in range(20)]\n self.nodes = []\n\n self.nodescnt = 0\n self.objectscnt = 0\n self.pathscnt = 0\n self.path = []\n self.buttonsarray = []\n\n self.plottry = ImageTk.PhotoImage(Image.open(\"/home/crazy/UI/modelplot.png\"))\n self.frame1 = tk.Frame(self.master, background=\"black\")\n self.frame1.place(relwidth=1, relheight=0.17, relx=0, rely=0.83)\n\n totalbuttons = 22\n\n self.currentavailablebuttons = [{} for i in range(totalbuttons)]\n\n c1 = 0\n c2 = 0\n pathlist = [\"input\", \"conv\", \"dense\", \"act\", \"output\", \"flatten\", \"add\"]\n\n for i, bpath in enumerate(pathlist):\n bg, bga = self.getwidgets(\"input\", bpath + \".png\")\n self.currentavailablebuttons[i] = {\"name\": bpath[:-4], \"bg\": bg, \"bga\": bga, \"count\": 0}\n self.buttonsarray.append(Button(self.frame1, image=buttonsbgarray[i], activebackground=\"#32CD32\"\n , relief=RAISED, borderwidth=4))\n\n self.buttonsarray[i].bind(\"<ButtonPress-1>\", lambda event, a=self.currentx, b=self.currenty,\n d=bpath, bg=bg, bga=bga: self.create_token(a, b, d, bg,\n bga))\n\n if i % 2 == 0:\n self.buttonsarray[i].grid(row=0, column=c1)\n c1 += 1\n elif i % 2 == 1:\n self.buttonsarray[i].grid(row=1, column=c2)\n c2 += 1\n\n buttonnames = [\"Separable Conv2D\",\"DW Conv2D\",\"Conv1D\" ,\"Conv3D\",\"MaxPooling2D\",\"AveragePooling2D\"\n ,\"GlobalMaxPooling2D\", \"GlobalAveragePooling2D\",\"BatchNormalization\",\"Dropout\",\"Reshape\",\"UpSampling2D\"\n ,\"LSTM layer\",\"ConvLSTM2D\",\"SpatialDropout\",\"GlobalMaxPooling1D\"]\n\n for j in range(i + 1, totalbuttons, 1):\n # print(\"button\",j,c1,c2)\n print(buttonnames[j-7])\n # self.buttonsarray.append(Button(self.frame1, image=defaultbutton, activebackground=\"#32CD32\"\n # , relief=RAISED, borderwidth=4))\n\n pixelVirtual = tk.PhotoImage(width=1, height=1)\n\n # buttonExample1 = tk.Button(app,\n # text=\"Increase\",\n # image=pixelVirtual,\n # width=100,\n # height=100,\n # compound=\"c\")\n self.buttonsarray.append(Button(self.frame1,text = buttonnames[j-7],image = pixelVirtual,compound = \"c\",\n activebackground=\"#32CD32\"\n , relief=RAISED, borderwidth=4,height = 60 , width = 60,bg = \"white\"))\n if j % 2 == 0:\n self.buttonsarray[j].grid(row=0, column=c1)\n c1 += 1\n elif j % 2 == 1:\n self.buttonsarray[j].grid(row=1, column=c2)\n c2 += 1\n\n self.b8 = Button(self.frame1, image=codebg, activebackground=\"#32CD32\", relief=RAISED, borderwidth=4)\n self.b9 = Button(self.frame1, image=trainbg, activebackground=\"#32CD32\", relief=RAISED, borderwidth=4)\n self.b11 = Button(self.frame1, image=buildbg, activebackground=\"#32CD32\", relief=RAISED, borderwidth=4)\n self.b12 = Button(self.frame1, image=plotbg, activebackground=\"#32CD32\", relief=RAISED, borderwidth=4)\n\n self.b8.bind(\"<ButtonPress-1>\", self.compilemodel)\n self.b9.bind(\"<ButtonPress-1>\", self.trainclicked)\n self.b11.bind(\"<ButtonPress-1>\", self.buildmodel)\n self.b12.bind(\"<ButtonPress-1>\", self.plotclicked)\n\n self.b8.place(rely=0, relx=0.84)\n self.b9.place(rely=0, relx=0.92)\n self.b11.place(rely=0, relx=0.68)\n self.b12.place(rely=0, relx=0.76)\n\n self.myFont = Font(family=\"clearlyu pua\", size=12)\n self.python = Frame(self.frame1, bg=\"black\", width=280, height=140)\n self.python.place(rely=0, relx=0.433, relwidth=0.245, relheight=0.95)\n entryframe = Frame(self.python, bg=\"red\", width=455, height=40)\n entryframe.grid(row=1)\n\n enterbutton = Button(entryframe, text=\"ENTER\")\n addbutton = Button(entryframe, text=\"add\")\n self.codeentry = Entry(entryframe, font=(\"Calibri 12 bold\"))\n self.codeentry.place(relx=0, rely=0, relwidth=0.9, relheight=1)\n enterbutton.place(relx=0.9, rely=0, relwidth=0.1, relheight=1)\n enterbutton.bind(\"<Button-1>\", self.insertcode)\n # addbutton.place(relx = 0.9,rely = 0,relwidth = 0.1,relheight = 1)\n # add.bind(\"<Button-1>\",add)\n\n self.scrollcanvas = Canvas(self.python, height=125, width=450, bg=\"black\")\n self.scrollcanvas.grid(row=0)\n\n self.scrollcanvasFrame = Frame(self.scrollcanvas, bg=\"black\")\n self.scrollcanvas.create_window(0, 0, window=self.scrollcanvasFrame, anchor='nw')\n\n yscrollbar = Scrollbar(self.python, orient=VERTICAL)\n yscrollbar.config(command=self.scrollcanvas.yview)\n self.scrollcanvas.config(yscrollcommand=yscrollbar.set)\n yscrollbar.grid(row=0, column=1, sticky=\"ns\")\n\n self.scrollcanvasFrame.bind(\"<Configure>\", lambda event: self.scrollcanvas.configure(\n scrollregion=self.scrollcanvas.bbox(\"all\")))\n\n self.frame7 = tk.Frame(self.master, background=\"yellow\")\n self.canvas = tk.Canvas(self.frame7, bg=\"black\")\n\n self.canvas.tag_bind(\"token\", \"<ButtonPress-1>\", self.drag_start)\n self.canvas.tag_bind(\"token\", \"<ButtonRelease-1>\", self.drag_stop)\n self.canvas.tag_bind(\"token\", \"<B1-Motion>\", self.drag)\n self.canvas.bind(\"<Shift-Button-3>\", self.clickedcanvas)\n\n self.frame7.place(relwidth=1, relheight=0.83, relx=0, rely=0.0)\n self.canvas.place(relheight=1, relwidth=1)\n\n self.toggle = Button(self.canvas, activebackground=\"#32CD32\", relief=RAISED, borderwidth=3, height=90)\n self.toggle.place(relwidth=0.03, relx=0.5, rely=0, relheight=0.03)\n # self.toggle.bind(\"<Double-Button-1>\",self.togglebg1)\n\n self.toko = Button(self.canvas, image=toko, activebackground=\"#32CD32\", relief=RAISED, borderwidth=3, height=90)\n self.toko.place(relwidth=0.05, relx=0.005, rely=0.85)\n self.toko.bind(\"<Double-Button-1>\", self.tokoclicked)\n\n self.ide = Button(self.canvas, image=code, activebackground=\"#32CD32\", relief=RAISED, borderwidth=3, height=90)\n self.ide.place(relwidth=0.04, relheight=0.1, relx=0.95, rely=0.0)\n self.ide.bind(\"<Button-1>\", self.ideclicked)\n\n self.sequence = [ImageTk.PhotoImage(img)\n for img in ImageSequence.Iterator(\n Image.open(\n bgpath + 'ai3.gif'))]\n\n self.backgroundimage1 = ImageTk.PhotoImage(Image.open(\"/mnt/DATA/UI/backgrounds/bg2.jpg\"))\n self.backgroundimage2 = ImageTk.PhotoImage(Image.open(\"/mnt/DATA/UI/backgrounds/background1.jpg\"))\n self.image = self.canvas.create_image(0,0, image=self.backgroundimage1,anchor = NW)\n self.editorflag = False\n # self.image = self.canvas.create_image(0, 0, image=self.sequence[0], anchor=NW)\n # self.animatecount = 0\n # self.animate(1)\n # self.change = False\n\n # def animate(self, counter):\n # self.canvas.itemconfig(self.image, image=self.sequence[counter])\n # self.master.after(38, lambda: self.animate((counter + 1) % len(self.sequence)))\n # self.animatecount += 1\n # if self.animatecount == 2:\n # self.startspeak()\n\n # def animatedestroy(self, counter):\n # self.master.after(1,lambda : _show('Title', 'Prompting after 5 seconds'))\n # self.canvas.itemconfig(self.image, image=self.backgroundimage1)\n\n # def togglebg1(self,event):\n # if self.change == True:\n # self.canvas.itemconfig(self.image, image=self.sequence[0])\n # self.animate(1)\n # self.change = False\n # else:\n # self.canvas.delete(self.image)\n # self.image = self.canvas.create_image(0,0, image=self.backgroundimage1,anchor = NW)\n # self.change = True\n # animatedestroy\n\n def ideclicked(self, event):\n # obj = Ide(self.canvas)\n self.editorflag = True\n self.editorobj = Editor(self.canvas)\n self.editorobj.frame.mainloop()\n self.updatecodecanvas(\"the code is saved as model.py format\")\n\n def startspeak(self):\n self.updatecodecanvas(\"Welcome to deeplearning self.graphical interface\")\n self.updatecodecanvas(\"For any queries click on the Toko Button \")\n self.updatecodecanvas(\"-----------------------------\")\n self.updatecodecanvas(\"start by adding Input layer\")\n engine.say(\"Welcome to deep learning self.graphical interface\")\n engine.say(\"For any queries click on the Toko Button\")\n engine.runAndWait()\n\n def updatecodecanvas(self, s):\n label = Label(self.scrollcanvasFrame, text=s, bg=\"black\", foreground=\"white\", font=\"Courier 12\")\n label.pack()\n self.codelines.append(label)\n self.scrollcanvas.update_idletasks()\n self.scrollcanvas.yview_moveto('1.5')\n\n def insertcode(self, event):\n s = self.codeentry.get()\n self.updatecodecanvas(s)\n self.codeentry.delete(0, 'end')\n if s == \"clear\":\n for i in range(len(self.codelines)):\n self.codelines[i].destroy()\n self.scrollcanvas.yview_moveto('0')\n\n def getwidgets(self, s, path):\n widgetsactivepath = '/mnt/DATA/UI/widgets/active/'\n widgetspath = '/mnt/DATA/UI/widgets/inactive/'\n image = Image.open(widgetspath + path)\n bg = ImageTk.PhotoImage(image)\n s = widgetsactivepath + path[:-4] + \"active\" + path[-4:]\n image = Image.open(s)\n bga = ImageTk.PhotoImage(image)\n return bg, bga\n\n def drag_start(self, event):\n self._drag_data[\"item\"] = self.canvas.find_closest(event.x, event.y)[0]\n self._drag_data[\"x\"] = event.x\n self._drag_data[\"y\"] = event.y\n\n def drag_stop(self, event):\n \"\"\"End drag of an object\"\"\"\n self._drag_data[\"item\"] = None\n self._drag_data[\"x\"] = 0\n self._drag_data[\"y\"] = 0\n # i = event.widget.find_withtag('current')[0]\n\n canvas_item_id = event.widget.find_withtag('current')[0]\n n1 = self.nodes.index(canvas_item_id)\n self.dic[n1][\"x\"] = event.x\n self.dic[n1][\"y\"] = event.y\n lines = self.coonectionsdic[n1]\n print(\"selected \", n1, \"lines ==\", lines)\n for j in range(len(lines)):\n # print(\"connectionsself.dic before\",self.coonectionsdic[:4])\n line = lines[0]\n n2 = line.get(\"nodeid\")\n lineid1 = line.get(\"lineid\")\n\n ind = [self.coonectionsdic[n2][i].get(\"nodeid\") for i in range(len(self.coonectionsdic[n2]))].index(n1)\n lineid2 = self.coonectionsdic[n2][ind][\"lineid\"]\n\n self.canvas.delete(lineid2)\n self.canvas.delete(lineid1)\n\n self.addline(n1, n2)\n self.coonectionsdic[n1].pop(0)\n self.coonectionsdic[n2].pop(ind)\n\n # print(\"connectionsself.dic after\",self.coonectionsdic[:4])\n\n def drag(self, event):\n \"\"\"Handle dragging of an object\"\"\"\n delta_x = event.x - self._drag_data[\"x\"]\n delta_y = event.y - self._drag_data[\"y\"]\n self.canvas.move(self._drag_data[\"item\"], delta_x, delta_y)\n self._drag_data[\"x\"] = event.x\n self._drag_data[\"y\"] = event.y\n\n def create_token(self, x, y, label, bg, bga):\n # print(\"button \",label,\" is pressed\")\n x = self.currentx\n y = self.currenty\n self.nodescnt += 1\n\n if label == \"conv\":\n self.updatecodecanvas(\"conv2d object is created, double-click to initialize\")\n self.ccnt += 1\n self.currentx += 160\n name = \"conv\"\n\n elif label == \"dense\":\n self.updatecodecanvas(\"dense object is created, double-click to initialize\")\n self.currentx += 80\n y = y - 50\n name = \"dense\"\n\n elif label == \"act\":\n self.updatecodecanvas(\"activation object is created, double-click to initialize\")\n self.currentx += 120\n y = y\n name = \"activation\"\n\n elif label == \"input\":\n self.updatecodecanvas(\"input object is created, double-click to initialize\")\n self.updatecodecanvas(\"start adding layers\")\n if self.icnt >= 1:\n y = self.currenty - 120 * self.icnt\n x = 20\n self.icnt += 1\n else:\n self.currentx += 120\n self.icnt += 1\n name = \"input\"\n\n elif label == \"output\":\n self.updatecodecanvas(\"output object is created, double-click to initialize\")\n y = self.currenty - 120 * self.ocnt\n x = 1800\n self.ocnt += 1\n name = \"output\"\n\n\n elif label == \"flatten\":\n self.updatecodecanvas(\"flatten object is created, double-click to initialize\")\n self.currentx += 80\n y = y - 50\n name = \"flatten\"\n\n elif label == \"add\":\n self.updatecodecanvas(\"add object is created, double-click to initialize\")\n self.currentx += 110\n name = \"add\"\n\n token = self.canvas.create_image(x, y, image=bg, anchor=NW, tags=(\"token\",), activeimage=bga)\n self.nodes.append(token)\n self.tensorlist.append(None)\n self.dic[self.cnt] = {\"x\": x, \"y\": y, \"name\": name, \"Node\": None, \"param\": [None]}\n self.canvas.tag_bind(token, '<Double-Button-1>', self.itemClicked)\n self.canvas.tag_bind(token, \"<Shift-Button-1>\", self.connect)\n self.cnt += 1\n\n def connect(self, event):\n canvas_item_id = event.widget.find_withtag('current')[0]\n try:\n self.path.index(canvas_item_id)\n # print(\"Node already added\")\n except:\n self.path.append(canvas_item_id)\n\n # print(self.path)\n\n def clickedcanvas(self, event):\n if len(self.path) > 1:\n for i in range(len(self.path) - 1):\n n1 = self.nodes.index(self.path[i])\n n2 = self.nodes.index(self.path[i + 1])\n self.graph[n1].append(n2)\n self.invgraph[n2].append(n1)\n self.addline(n1, n2)\n self.pathscnt += 1\n print(\"added path\")\n self.path = []\n print(self.path)\n if self.pathscnt == self.nodescnt - 1:\n self.updatecodecanvas(\"path is created build now\")\n\n def addline(self, n1, n2):\n x1 = self.dic[n1][\"x\"]\n y1 = self.dic[n1][\"y\"]\n x2 = self.dic[n2][\"x\"]\n y2 = self.dic[n2][\"y\"]\n lineid1 = self.canvas.create_line(x1, y1, x2, y2, fill=\"white\", width=3)\n lineid2 = self.canvas.create_line(x2, y2, x1, y1, fill=\"white\", width=3)\n self.coonectionsdic[n1].append({\"nodeid\": n2, \"lineid\": lineid1})\n self.coonectionsdic[n2].append({\"nodeid\": n1, \"lineid\": lineid2})\n\n def itemClicked(self, event):\n\n canvas_item_id = event.widget.find_withtag('current')[0]\n print('Item', canvas_item_id, 'Clicked!')\n ind = self.nodes.index(canvas_item_id)\n self.objectscnt += 1\n\n if self.dic[ind][\"name\"].startswith(\"conv\"):\n print(\"conv\")\n self.updatecodecanvas(str(canvas_item_id) + \":tensorflow.keras.layers.Conv2D(**args) is created\")\n\n ConvDialog(self.canvas, self, event.x, event.y, ind)\n dic = self.dic\n\n elif self.dic[ind][\"name\"].startswith(\"dense\"):\n print(\"dense\")\n self.updatecodecanvas(str(canvas_item_id) + \":tensorflow.keras.layers.Dense(**args) is created\")\n DenseDialog(self.canvas, self, event.x, event.y, ind)\n dic = self.dic\n\n elif self.dic[ind][\"name\"].startswith(\"input\"):\n print(\"input\")\n self.updatecodecanvas(str(canvas_item_id) + \":tensorflow.keras.layers.Input(**args) is created\")\n InputDialog(self.canvas, self, event.x, event.y, ind)\n dic = self.dic\n\n elif self.dic[ind][\"name\"].startswith(\"output\"):\n print(\"output\")\n self.updatecodecanvas(str(canvas_item_id) + \":tensorflow.keras.layers.Dense(**args) is created\")\n OutputDialog(self.canvas, self, event.x, event.y, ind)\n dic = self.dic\n\n elif self.dic[ind][\"name\"].startswith(\"add\"):\n print(\"add\")\n self.updatecodecanvas(str(canvas_item_id) + \":tensorflow.keras.layers.Add(**args) is created\")\n AddDialog(self.canvas, self, event.x, event.y, ind)\n dic = self.dic\n\n # elif self.dic[ind][\"name\"].startswith(\"act\"):\n # print(\"activation\")\n # self.updatecodecanvas(str(canvas_item_id)+\":tensorflow.keras.layers.Activation(**args) is created\")\n # actDialog(self.canvas,event.x,event.y,ind)\n\n elif self.dic[ind][\"name\"].startswith(\"flatten\"):\n print(\"flatten\")\n self.updatecodecanvas(str(canvas_item_id) + \":tensorflow.keras.layers.Flatten(**args) is created\")\n FlattenDialog(self.canvas, self, event.x, event.y, ind)\n dic = self.dic\n\n if self.objectscnt >= self.nodescnt:\n self.updatecodecanvas(\"---all objects are created.---\")\n self.updatecodecanvas(\"--- you can add paths now---\")\n self.updatecodecanvas(\"hold shift + left mouse click to add paths\")\n self.updatecodecanvas(\"hold shift + right mouse click to connect paths\")\n self.updatecodecanvas(\" \")\n\n # print(self.dic)\n\n def tokoclicked(self, event):\n obj = TokoDialog(self.canvas)\n\n def plotclicked(self, event):\n global getplotimage\n obj = ModelplotDialog(self.canvas, getplotimage())\n self.updatecodecanvas(\"plot is self.graphical representation in image format\")\n\n def codeclicked(self, event):\n # obj = ModelcodeDialog(self.canvas)\n obj = Editor(self.canvas)\n obj.frame.mainloop()\n self.updatecodecanvas(\"the code is saved as model.py format\")\n\n def summaryclicked(self):\n obj = ModelsummaryDialog(self.canvas)\n self.updatecodecanvas(\"summary is the architecture of model\")\n self.updatecodecanvas(\"built successful\")\n self.updatecodecanvas(\"you can train model now\")\n self.updatecodecanvas(\"remember to compile model first\")\n\n def trainclicked(self, event):\n obj = Train(self.canvas, [self.t1, self.t2, self.t3, self.t4, self.t5], self.model, self)\n\n def printdict(self, event):\n print(self.nodes)\n print(self.dic)\n\n def addtocode(self, node, xlist):\n name = self.dic[node][\"name\"]\n params = self.dic[node][\"param\"]\n print(\"params = \", params)\n if name.startswith(\"conv\"):\n self.updatecodecanvas(\" {} = tf.keras.layers.Conv2d(**args)(x)\")\n with open(\"model.py\", \"a\") as myfile:\n myfile.write(\n \" {} = tf.keras.layers.Conv2d(filters={},kernel_size={},strides={},padding= '{}',dilation_rate= {},activation= '{}')({})\\n\".format(\n \"x\" + str(node), params[0], params[1], params[2], params[3], params[4], params[5], xlist))\n\n elif name.startswith(\"dense\"):\n self.updatecodecanvas(\"x = tf.keras.layers.Dense(**args)(x)\")\n with open(\"model.py\", \"a\") as myfile:\n myfile.write(\" {} = tf.keras.layers.Dense(units = {},activation= '{}',use_bias= {})({})\\n\".format(\n \"x\" + str(node), params[0], params[1], params[2], xlist))\n\n elif name.startswith(\"output\"):\n self.updatecodecanvas(\"x = tf.keras.layers.Dense(**args)(x)\")\n with open(\"model.py\", \"a\") as myfile:\n myfile.write(\" {} = tf.keras.layers.Dense(units = {},activation= '{}',use_bias= {})({})\\n\".format(\n \"x\" + str(node), params[0], params[1], params[2], xlist))\n elif name.startswith(\"flatten\"):\n self.updatecodecanvas(\"x = tf.keras.layers.Flatten(**args)(x)\")\n with open(\"model.py\", \"a\") as myfile:\n myfile.write(\" {} = tf.keras.layers.Flatten()({})\\n\".format(\"x\" + str(node), xlist))\n elif name.startswith(\"act\"):\n self.updatecodecanvas(\"x = tf.keras.layers.Activation(**args)(x)\")\n with open(\"model.py\", \"a\") as myfile:\n myfile.write(\" {} = tf.keras.layers.Activation()({})\\n\".format(\"x\" + str(node), xlist))\n elif name.startswith(\"add\"):\n self.updatecodecanvas(\"x = tf.keras.layers.Add(**args)(x)\")\n with open(\"model.py\", \"a\") as myfile:\n myfile.write(\" {} = tf.keras.layers.Add(**args)({})\\n\".format(\"x\" + str(node), xlist))\n elif name.startswith(\"input\"):\n self.updatecodecanvas(\"x = tf.keras.layers.Add(**args)(x)\")\n with open(\"model.py\", \"a\") as myfile:\n myfile.write(\" {} = tf.keras.layers.Input(shape = {})\\n\".format(\"x\" + str(node), params[0]))\n\n\n def rec(self, node):\n if node == 0:\n self.tensorlist[0] = self.dic[0][\"Node\"]\n self.addtocode(node, 0)\n return self.tensorlist[0]\n else:\n lis = [self.rec(i) for i in self.invgraph[node]]\n xlist = [\"x\" + str(i) for i in self.invgraph[node]]\n if len(lis) == 1:\n self.tensorlist[node] = self.dic[node][\"Node\"](lis[0])\n self.addtocode(node, xlist[0])\n else:\n self.tensorlist[node] = self.dic[node][\"Node\"](lis)\n self.addtocode(node, xlist)\n print(self.dic[node][\"Node\"], self.dic[node][\"name\"])\n return self.tensorlist[node]\n\n def buildmodel(self, event):\n for i in range(len(self.nodes)):\n if len(self.graph[i]) == 0:\n end = i\n\n self.rec(i)\n self.model = tf.keras.models.Model(self.tensorlist[0], self.tensorlist[i])\n self.model.summary()\n tf.keras.utils.plot_model(self.model, \"/home/crazy/UI/modelplot.png\")\n with open('modelsummary.txt', 'w') as f:\n with redirect_stdout(f):\n self.model.summary()\n\n with open(\"model.py\", \"a\") as myfile:\n myfile.write(\n \" return tf.keras.models.Model(inputs = {} , outputs = {})\\n\\n\".format(\"x\" + str(0), \"x\" + str(i)))\n myfile.write(\"\\n\")\n myfile.write(\"model = mymodel()\\n\")\n myfile.write(\"model.summary()\")\n # self.editorobj.root.destroy()\n # self.editorobj = Editor(self.canvas)\n # self.editorobj.frame.mainloop()\n print(\"compilling model\")\n if self.editorflag == True:\n self.editorobj.first_open(\"model.py\")\n self.updatecodecanvas(\"the code is saved as model.py format\")\n self.summaryclicked()\n\n \n def compilemodel(self, event):\n obj = CompileDialog(self.canvas,self.model)\n self.updatecodecanvas(\"model is compileD. Start Training\")\n\nclass Mainclass:\n def __init__(self):\n # self.sroot = sroot\n\n # self.traindatagen = sroot.traingen\n # self.testdatagen = sroot.testgen\n # self.traindatagen = []\n # self.testdatagen = []\n\n # sroot.controller.root.destroy()\n\n self.window = tk.Tk()\n self.window.attributes('-zoomed', True)\n self.fullScreenState = False\n self.window.bind(\"<F11>\", self.toggleFullScreen)\n self.window.bind(\"<Escape>\", self.quitFullScreen)\n self.window.title(\"DEEP-LEARNING UI\")\n b = self.getbuttonimages()\n app = Window(b, root=self, master=self.window)\n\n self.window.mainloop()\n\n def getbuttonimages(self):\n # [\"input\",\"conv\",\"dense\",\"act\",\"output\",\"flatten\",\"add\"]\n\n default = self.buttonimage(\"later\")\n\n bg1 = self.buttonimage(\"input\")\n bg2 = self.buttonimage(\"conv\")\n bg3 = self.buttonimage(\"dense\")\n bg4 = self.buttonimage(\"act\")\n bg5 = self.buttonimage(\"output\")\n bg6 = self.buttonimage(\"flatten\")\n bg7 = self.buttonimage(\"add\")\n\n bg8 = self.buttonimage(\"embedding\")\n # bg9 = self.buttonimage(\"add\")\n # bg10 = self.buttonimage(\"add\")\n # bg11 = self.buttonimage(\"add\")\n # bg12 = self.buttonimage(\"add\")\n # bg13 = self.buttonimage(\"add\")\n # bg14 = self.buttonimage(\"add\")\n # bg15 = self.buttonimage(\"add\")\n # bg16 = self.buttonimage(\"add\")\n\n\n\n\n # fg1 = ImageTk.PhotoImage(Image.open(\"/mnt/DATA/UI/buttons/plotbutton3.png\"))\n fg1 = self.buttonimage(\"plotlarge\")\n fg2 = self.buttonimage(\"train\")\n fg3 = self.buttonimage(\"compilebuttonlarge\")\n fg4 = self.buttonimage(\"buildlarge\")\n # fg3 = ImageTk.PhotoImage(Image.open(\"/mnt/DATA/UI/buttons/codebutton3.png\"))\n # fg4 = ImageTk.PhotoImage(Image.open(\"/mnt/DATA/UI/buttons/buildbutton3.png\"))\n\n toko = self.buttonimage(\"toko\")\n code = self.buttonimage(\"code\")\n\n plot = ImageTk.PhotoImage(Image.open(\"/home/crazy/UI/modelplot.png\"))\n\n train1 = ImageTk.PhotoImage(Image.open(\"/mnt/DATA/UI/buttons/trainingbutton.png\"))\n train2 = ImageTk.PhotoImage(Image.open(\"/mnt/DATA/UI/buttons/predbutton.png\"))\n train3 = ImageTk.PhotoImage(Image.open(\"/mnt/DATA/UI/buttons/databutton.png\"))\n train4 = ImageTk.PhotoImage(Image.open(\"/mnt/DATA/UI/buttons/compilebutton1.png\"))\n train5 = ImageTk.PhotoImage(Image.open(\"/mnt/DATA/UI/buttons/databutton.png\"))\n return [default, [bg1, bg2, bg3, bg4, bg5, bg6, bg8], [fg1, fg2, fg3, fg4], toko, plot, code,\n [train1, train2, train3, train4, train5]]\n\n def buttonimage(self, s, resize=False):\n path = buttonspath +\"edited/\"+ s + \"button2.png\"\n image = Image.open(path)\n if resize == True:\n image = image.resize((200, 140), Image.ANTIALIAS)\n bg = ImageTk.PhotoImage(image)\n return bg\n\n def toggleFullScreen(self, event):\n self.fullScreenState = not self.fullScreenState\n self.window.attributes(\"-zoomed\", self.fullScreenState)\n\n def quitFullScreen(self, event):\n self.fullScreenState = False\n self.window.attributes(\"-zoomed\", self.fullScreenState)\n\n\ndef toggleFullScreen(event):\n fullScreenState = not fullScreenState\n root.attributes(\"-zoomed\", fullScreenState)\n\n\ndef quitFullScreen(event):\n fullScreenState = False\n root.attributes(\"-zoomed\", fullScreenState)\n\nfrom PIL import Image, ImageTk, ImageSequence\n# sroot = Tk()\n# sroot.minsize(height=1000, width=1000)\n# sroot.title(\"Loading.....\")\n# sroot.configure()\n# spath = \"/mnt/DATA/UI/backgrounds/\"\nMainclass()\n# sroot.mainloop()\n", "Separable Conv2D\nDW Conv2D\nConv1D\nConv3D\nMaxPooling2D\nAveragePooling2D\nGlobalMaxPooling2D\nGlobalAveragePooling2D\nBatchNormalization\nDropout\nReshape\nUpSampling2D\nLSTM layer\nConvLSTM2D\nSpatialDropout\nselected 1 lines == []\nselected 2 lines == []\nselected 3 lines == []\nselected 4 lines == []\n" ] ] ]
[ "code" ]
[ [ "code" ] ]
4a0a4d38689b2248be61ba214f5942ccb549bcca
13,001
ipynb
Jupyter Notebook
01c - Object Detection.ipynb
ketana0224/-ai-fundamentals
9663343161e19bb8cba7903fb6a60e99e628555f
[ "MIT" ]
2
2020-07-22T05:14:54.000Z
2020-11-28T11:26:08.000Z
01c - Object Detection.ipynb
ketana0224/-ai-fundamentals
9663343161e19bb8cba7903fb6a60e99e628555f
[ "MIT" ]
null
null
null
01c - Object Detection.ipynb
ketana0224/-ai-fundamentals
9663343161e19bb8cba7903fb6a60e99e628555f
[ "MIT" ]
6
2020-07-18T09:16:35.000Z
2020-11-28T12:22:15.000Z
64.681592
619
0.668026
[ [ [ "# Object Detection\n\n*Object detection* is a form of computer vision in which a machine learning model is trained to classify individual instances of objects in an image, and indicate a *bounding box* that marks its location. Youi can think of this as a progression from *image classification* (in which the model answers the question \"what is this an image of?\") to building solutions where we can ask the model \"what objects are in this image, and where are they?\".\n\n<p style='text-align:center'><img src='./images/object-detection.jpg' alt='A robot identifying fruit'/></p>\n\nFor example, a grocery store might use an object detection model to implement an automated checkout system that scans a conveyor belt using a camera, and can identify specific items without the need to place each item on the belt and scan them individually.\n\nThe **Custom Vision** cognitive service in Microsoft Azure provides a cloud-based solution for creating and publishing custom object detection models.\n\n## Create a Custom Vision resource\n\nTo use the Custom Vision service, you need an Azure resource that you can use to train a model, and a resource with which you can publish it for applications to use. You can use the same resource for each of these tasks, or you can use different resources for each to allocate costs separately provided both resources are created in the same region. The resource for either (or both) tasks can be a general **Cognitive Services** resource, or a specific **Custom Vision** resource. Use the following instructions to create a new **Custom Vision** resource (or you can use an existing resource if you have one).\n\n1. In a new browser tab, open the Azure portal at [https://portal.azure.com](https://portal.azure.com), and sign in using the Microsoft account associated with your Azure subscription.\n2. Select the **&#65291;Create a resource** button, search for *custom vision*, and create a **Custom Vision** resource with the following settings:\n - **Create options**: Both\n - **Subscription**: *Your Azure subscription*\n - **Resource group**: *Create a new resource group with a unique name*\n - **Name**: *Enter a unique name*\n - **Training location**: *Choose any available region*\n - **Training pricing tier**: F0\n - **Prediction location**: *The same as the training location*\n - **Prediction pricing tier**: F0\n\n > **Note**: If you already have an F0 custom vision service in your subscription, select **S0** for this one.\n\n3. Wait for the resource to be created.\n\n## Create a Custom Vision project\n\nTo train an object detection model, you need to create a Custom Vision project based on your trainign resource. To do this, you'll use the Custom Vision portal.\n\n1. In a new browser tab, open the Custom Vision portal at [https://customvision.ai](https://customvision.ai), and sign in using the Microsoft account associated with your Azure subscription.\n2. Create a new project with the following settings:\n - **Name**: Grocery Detection\n - **Description**: Object detection for groceries.\n - **Resource**: *The Custom Vision resource you created previously*\n - **Project Types**: Object Detection\n - **Domains**: General\n3. Wait for the project to be created and opened in the browser.\n\n## Add and tag images\n\nTo train an object detection model, you need to upload images that contain the classes you want the model to identify, and tag them to indicate bounding boxes for each object instance.\n\n1. Download and extract the training images from https://aka.ms/fruit-objects. The extracted folder contains a collection of images of fruit.\n2. In the Custom Vision portal, in your object detection project, select **Add images** and upload all of the images in the extracted folder.\n3. After the images have been uploaded, select the first one to open it.\n4. Hold the mouse over any object in the image until an automatically detected region is displayed like the image below. Then select the object, and if necessary resize the region to surround it.\n\n <p style='text-align:center'><img src='./images/object-region.jpg' alt='The default region for an object'/></p>\n\n Alternatively, you can simply drag around the object to create a region.\n\n5. When the region surrounds the object, add a new tag with the appropriate object type (*apple*, *banana*, or *orange*) as shown here:\n\n <p style='text-align:center'><img src='./images/object-tag.jpg' alt='A tagged object in an image'/></p>\n\n6. Select and tag each other object in the image, resizing the regions and adding new tags as required.\n\n <p style='text-align:center'><img src='./images/object-tags.jpg' alt='Two tagged objects in an image'/></p>\n\n7. Use the **>** link on the right to go to the next image, and tag its objects. Then just keep working through the entire image collection, tagging each apple, banana, and orange.\n\n8. When you have finished tagging the last image, close the **Image Detail** editor and on the **Training Images** page, under **Tags**, select **Tagged** to see all of your tagged images:\n\n <p style='text-align:center'><img src='./images/tagged-images.jpg' alt='Tagged images in a project'/></p>\n\n## Train and test a model\n\nNow that you've tagged the images in your project, you're ready to train a model.\n\n1. In the Custom Vision project, click **Train** to train an object detection model using the tagged images. Select the **Quick Training** option.\n2. Wait for training to complete (it might take ten minutes or so), and then review the *Precision*, *Recall*, and *mAP* performance metrics - these measure the prediction accuracy of the classification model, and should all be high.\n3. At the top right of the page, click **Quick Test**, and then in the **Image URL** box, enter `https://aka.ms/apple-orange` and view the prediction that is generated. Then close the **Quick Test** window.\n\n## Publish and consume the object detection model\n\nNow you're ready to publish your trained model and use it from a client application.\n\n1. At the top left of the **Performance** page, click **&#128504; Publish** to publish the trained model with the following settings:\n - **Model name**: detect-produce\n - **Prediction Resource**: *Your custom vision **prediction** resource*.\n2. After publishing, click the *settings* (&#9881;) icon at the top right of the **Performance** page to view the project settings. Then, under **General** (on the left), copy the **Project Id** and paste it into the code cell below replacing **YOUR_PROJECT_ID**.\n\n> (*if you used a **Cognitive Services** resource instead of creating a **Custom Vision** resource at the beginning of this exercise, you can copy its key and endpoint from the right side of the project settings, paste it into the code cell below, and run it to see the results. Otherwise, continue completing the steps below to get the key and endpoint for your Custom Vision prediction resource*).\n\n3. At the top left of the **Project Settings** page, click the *Projects Gallery* (&#128065;) icon to return to the Custom Vision portal home page, where your project is now listed.\n4. On the Custom Vision portal home page, at the top right, click the *settings* (&#9881;) icon to view the settings for your Custom Vision service. Then, under **Resources**, expand your *prediction* resource (<u>not</u> the training resource) and copy its **Key** and **Endpoint** values to the code cell below, replacing **YOUR_KEY** and **YOUR_ENDPOINT**.\n5. Run the code cell below by clicking its green <span style=\"color:green\">&#9655</span> button (at the top left of the cell) to set the variables to your project ID, key, and endpoint values.", "_____no_output_____" ] ], [ [ "project_id = 'YOUR_PROJECT_ID' # Replace with your project ID\ncv_key = 'YOUR_KEY' # Replace with your prediction resource primary key\ncv_endpoint = 'YOUR_ENDPOINT' # Replace with your prediction resource endpoint\n\nmodel_name = 'detect-produce' # this must match the model name you set when publishing your model iteration exactly (including case)!\nprint('Ready to predict using model {} in project {}'.format(model_name, project_id))", "_____no_output_____" ] ], [ [ "Client applications can use the details above to connect to and your custom vision object detection model.\n\nRun the following code cell, which uses your model to detect individual produce items in an image.\n\n> **Note**: Don't worry too much about the details of the code. It uses the Python SDK for the Custom Vision service to submit an image to your model and retrieve predictions for detected objects. Each prediction consists of a class name (*apple*, *banana*, or *orange*) and *bounding box* coordinates that indicate where in the image the predicted object has been detected. The code then uses this information to draw a labelled box around each object on the image.", "_____no_output_____" ] ], [ [ "from azure.cognitiveservices.vision.customvision.prediction import CustomVisionPredictionClient\nfrom msrest.authentication import ApiKeyCredentials\nfrom matplotlib import pyplot as plt\nfrom PIL import Image, ImageDraw, ImageFont\nimport numpy as np\nimport os\n%matplotlib inline\n\n# Load a test image and get its dimensions\ntest_img_file = os.path.join('data', 'object-detection', 'produce.jpg')\ntest_img = Image.open(test_img_file)\ntest_img_h, test_img_w, test_img_ch = np.array(test_img).shape\n\n# Get a prediction client for the object detection model\ncredentials = ApiKeyCredentials(in_headers={\"Prediction-key\": cv_key})\npredictor = CustomVisionPredictionClient(endpoint=cv_endpoint, credentials=credentials)\n\nprint('Detecting objects in {} using model {} in project {}...'.format(test_img_file, model_name, project_id))\n\n# Detect objects in the test image\nwith open(test_img_file, mode=\"rb\") as test_data:\n results = predictor.detect_image(project_id, model_name, test_data)\n\n# Create a figure to display the results\nfig = plt.figure(figsize=(8, 8))\nplt.axis('off')\n\n# Display the image with boxes around each detected object\ndraw = ImageDraw.Draw(test_img)\nlineWidth = int(np.array(test_img).shape[1]/100)\nobject_colors = {\n \"apple\": \"lightgreen\",\n \"banana\": \"yellow\",\n \"orange\": \"orange\"\n}\nfor prediction in results.predictions:\n color = 'white' # default for 'other' object tags\n if (prediction.probability*100) > 50:\n if prediction.tag_name in object_colors:\n color = object_colors[prediction.tag_name]\n left = prediction.bounding_box.left * test_img_w \n top = prediction.bounding_box.top * test_img_h \n height = prediction.bounding_box.height * test_img_h\n width = prediction.bounding_box.width * test_img_w\n points = ((left,top), (left+width,top), (left+width,top+height), (left,top+height),(left,top))\n draw.line(points, fill=color, width=lineWidth)\n plt.annotate(prediction.tag_name + \": {0:.2f}%\".format(prediction.probability * 100),(left,top), backgroundcolor=color)\nplt.imshow(test_img)\n", "_____no_output_____" ] ], [ [ "View the resulting predictions, which show the objects detected and the probability for each prediction.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
4a0a4df1529f772ea27c776d1464240c65c69c97
510,826
ipynb
Jupyter Notebook
BayesianMethodsPhysicalSciences/Example 7_2.ipynb
balarsen/pymc_learning
e4a077d492af6604a433433e64b835ce4ed0333a
[ "BSD-3-Clause" ]
null
null
null
BayesianMethodsPhysicalSciences/Example 7_2.ipynb
balarsen/pymc_learning
e4a077d492af6604a433433e64b835ce4ed0333a
[ "BSD-3-Clause" ]
null
null
null
BayesianMethodsPhysicalSciences/Example 7_2.ipynb
balarsen/pymc_learning
e4a077d492af6604a433433e64b835ce4ed0333a
[ "BSD-3-Clause" ]
1
2017-05-23T16:38:55.000Z
2017-05-23T16:38:55.000Z
2,240.464912
210,984
0.948732
[ [ [ "from pprint import pprint\n\nimport spacepy.plot as spp\nimport numpy as np\nimport pymc as mc\n\n%matplotlib inline\n", "_____no_output_____" ], [ "data = np.asarray([mc.TruncatedNormal(name='data', mu=0, tau=3**-2, a=-1, b=np.inf).value for v in range(300)])\nspp.plt.hist(data, 20)", "_____no_output_____" ], [ "xcent = mc.Uniform('xcent', -10, 10)\nspread = 3\nx = mc.TruncatedNormal('x', xcent, spread**-2, -1, np.inf, observed=True, value=data)", "_____no_output_____" ], [ "model = mc.MCMC((xcent, spread, x))", "_____no_output_____" ], [ "model.sample(50000, burn=100, burn_till_tuned=True, thin=20)\n", " [-----------------100%-----------------] 54900 of 54900 complete in 8.0 secPlotting xcent\n\nxcent:\n \n\tMean SD MC Error 95% HPD interval\n\t------------------------------------------------------------------\n\t-0.277 0.269 0.004 [-0.787 0.251]\n\t\n\t\n\tPosterior quantiles:\n\t\n\t2.5 25 50 75 97.5\n\t |---------------|===============|===============|---------------|\n\t-0.805 -0.457 -0.279 -0.089 0.239\n\t\nNone\n" ], [ "mc.Matplot.plot(model)\npprint(model.summary())", "Plotting xcent\n\nxcent:\n \n\tMean SD MC Error 95% HPD interval\n\t------------------------------------------------------------------\n\t-0.277 0.269 0.004 [-0.787 0.251]\n\t\n\t\n\tPosterior quantiles:\n\t\n\t2.5 25 50 75 97.5\n\t |---------------|===============|===============|---------------|\n\t-0.805 -0.457 -0.279 -0.089 0.239\n\t\nNone\n" ], [ "bin, hist, _ = spp.plt.hist(data, 20, normed=True)", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code" ] ]
4a0a59bcc3830573c6bd8fc8b690fb96770158db
224,690
ipynb
Jupyter Notebook
notebooks/example-led-positions.ipynb
zack-insitro/qpc-algorithms
95270d350779150f09e78e0f95bfaed7a4c2bbf4
[ "BSD-3-Clause" ]
5
2020-02-03T14:25:01.000Z
2021-08-09T12:48:11.000Z
notebooks/example-led-positions.ipynb
zack-insitro/qpc-algorithms
95270d350779150f09e78e0f95bfaed7a4c2bbf4
[ "BSD-3-Clause" ]
null
null
null
notebooks/example-led-positions.ipynb
zack-insitro/qpc-algorithms
95270d350779150f09e78e0f95bfaed7a4c2bbf4
[ "BSD-3-Clause" ]
1
2020-02-03T14:27:16.000Z
2020-02-03T14:27:16.000Z
237.515856
186,380
0.879648
[ [ [ "%matplotlib notebook\n%load_ext autoreload\n%autoreload 2\n\nimport numpy as np\nfrom comptic import ledarray\nimport matplotlib.pyplot as plt", "_____no_output_____" ] ], [ [ "## Determine which LED Arrays are Available", "_____no_output_____" ] ], [ [ "ledarray.getAvailableLedArrays()", "_____no_output_____" ] ], [ [ "## Access LED Positions of Quasi-Dome", "_____no_output_____" ] ], [ [ "device_name = 'quasi-dome'\n\n# Get positions in x,y,z format\npositions_cartesian = ledarray.getPositionsCart(device_name)\n\n# Get positions in na_x, na_y format\npositions_na = ledarray.getPositionsNa(device_name)\n\n# Get board indicies\npositions_boards = ledarray.getBoardIndicies(device_name)\n\n# Get all information\npositions = ledarray.getPositions(device_name)\n\n# Show board Indicies\nplt.figure(figsize=(10,4))\nplt.subplot(121)\nplt.title('Board Indicies')\nplt.scatter(np.asarray(positions_na)[:,0], np.asarray(positions_na)[:,1], c=positions_boards)\nplt.xlabel('$NA_x$')\nplt.ylabel('$NA_y$')\nplt.tight_layout()\nplt.colorbar()\n\nplt.subplot(122)\nplt.title('LED Indicies')\nplt.scatter(np.asarray(positions_na)[:,0], np.asarray(positions_na)[:,1], c=np.asarray(positions)[:,0])\nplt.xlabel('$NA_x$')\nplt.ylabel('$NA_y$')\nplt.tight_layout()\nplt.colorbar()", "_____no_output_____" ] ], [ [ "# Generate New LED Positions", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
4a0a618ca1d6273ab0a990507387345429cd2275
65,543
ipynb
Jupyter Notebook
classifier/SK_classifiers.ipynb
izconcept/LyricsToGenre
61a0affa10404dbbd8e361c7fa6402091f58b911
[ "Apache-2.0" ]
null
null
null
classifier/SK_classifiers.ipynb
izconcept/LyricsToGenre
61a0affa10404dbbd8e361c7fa6402091f58b911
[ "Apache-2.0" ]
3
2021-03-31T19:04:27.000Z
2022-03-02T14:56:59.000Z
classifier/SK_classifiers.ipynb
izconcept/LyricsToGenre
61a0affa10404dbbd8e361c7fa6402091f58b911
[ "Apache-2.0" ]
null
null
null
118.522604
15,824
0.850861
[ [ [ "# Classifier\n\nClassifiers used to classify a song genre given its lyrics", "_____no_output_____" ], [ "## Loading and Processing Dataset", "_____no_output_____" ] ], [ [ "import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.model_selection import GridSearchCV\n\nfilename = '../data/dataset.csv'\n\ndf = pd.read_csv(filename, header=None, names=[\"artist\", \"song\", \"genre\", \"tokens\"])\n\ndef to_list(x):\n return x[1:-1].split(',')\n\ndf['tokens'] = df['tokens'].apply(to_list)", "_____no_output_____" ], [ "from ast import literal_eval\nfrom sklearn.feature_extraction.text import TfidfVectorizer\n\ndata = df.values\n\ndef unison_shuffled_copies(a, b):\n assert a.shape[0] == b.shape[0]\n p = np.random.permutation(a.shape[0])\n return a[p], b[p]\n\ndef dummy_fun(x):\n return x\n\ntfidf = TfidfVectorizer(\n analyzer='word',\n tokenizer=dummy_fun,\n preprocessor=dummy_fun,\n token_pattern=None) \n\nX = tfidf.fit_transform(data[:,3])\nY = data[:, 2]\n\nX, Y = unison_shuffled_copies(X, Y)\n\nX_train = X[:4800]\nX_valid = X[4800:5500]\nX_test = X[5500:]\n\nY_train = Y[:4800]\nY_valid = Y[4800:5500]\nY_test = Y[5500:]", "_____no_output_____" ] ], [ [ "## Naive Bayes", "_____no_output_____" ] ], [ [ "from sklearn.naive_bayes import MultinomialNB\n\nalpha_params = [0, 0.2, 0.6, 1.0, 2.0, 5.0, 10.0]\n\nbest_alpha, best_score = alpha_params[0], 0\nscores = []\nfor alpha in alpha_params:\n nb_model = MultinomialNB(alpha=alpha).fit(X_train, Y_train)\n \n predicted = nb_model.predict(X_valid)\n score = accuracy_score(predicted, Y_valid)\n if score > best_score: \n best_score = score\n best_alpha = alpha\n scores.append(score)\n print(f\"Alpha: {alpha}, Validation Accuracy: {score}\")", "/Users/IzKevin/anaconda3/lib/python3.6/site-packages/sklearn/naive_bayes.py:472: UserWarning: alpha too small will result in numeric errors, setting alpha = 1.0e-10\n 'setting alpha = %.1e' % _ALPHA_MIN)\n" ], [ "plt.plot(alpha_params, scores)\nplt.ylabel('Accuracy')\nplt.title('Multinomial NB: Alpha & Accuracy')\nplt.xlabel('Alpha')\nplt.savefig('nb.png')\nplt.show()\n\nnb_model = MultinomialNB(alpha=best_alpha).fit(X_train, Y_train)\npredicted = nb_model.predict(X_test)\nscore = accuracy_score(predicted, Y_test)\nprint(f\"Naive Bayes Test Accuracy: {score}\")", "_____no_output_____" ] ], [ [ "## Logistic Regression", "_____no_output_____" ] ], [ [ "from sklearn.linear_model import LogisticRegression\n\nc_params = [0.1, 0.2, 0.4, 0.7, 1.0, 2.0, 3.5, 5.0, 10.0, 20.0]\n\nbest_c, best_score = c_params[0], 0\nscores = []\nfor c in c_params:\n lr_model = LogisticRegression(C = c).fit(X_train, Y_train)\n \n predicted = lr_model.predict(X_valid)\n score = accuracy_score(predicted, Y_valid)\n if score > best_score: \n best_score = score\n best_c = c\n scores.append(score)\n print(f\"C: {c}, Validation Accuracy: {score}\")\n", "C: 0.1, Validation Accuracy: 0.6114285714285714\nC: 0.2, Validation Accuracy: 0.6528571428571428\nC: 0.4, Validation Accuracy: 0.6828571428571428\nC: 0.7, Validation Accuracy: 0.6957142857142857\nC: 1.0, Validation Accuracy: 0.7157142857142857\nC: 2.0, Validation Accuracy: 0.7157142857142857\nC: 3.5, Validation Accuracy: 0.72\nC: 5.0, Validation Accuracy: 0.7214285714285714\nC: 10.0, Validation Accuracy: 0.7271428571428571\nC: 20.0, Validation Accuracy: 0.72\n" ], [ "plt.plot(c_params, scores)\nplt.ylabel('Accuracy')\nplt.title('Logistic Regression: Regularization (C) & Accuracy')\nplt.xlabel('C')\nplt.savefig('lr.png')\nplt.show()\n\nnb_model = LogisticRegression(C=best_c).fit(X_train, Y_train)\npredicted = nb_model.predict(X_test)\nscore = accuracy_score(predicted, Y_test)\nprint(f\"Logistic Regression Test Accuracy: {score}\")", "_____no_output_____" ] ], [ [ "## Support Vector Machine", "_____no_output_____" ] ], [ [ "from sklearn.svm import SVC\n\nc_params = [0.1, 0.5, 1.0, 1.5, 2.0, 2.5, 5.0, 10.0]\n\nbest_c, best_score = c_params[0], 0\nscores = []\nfor c in c_params:\n svc = SVC(kernel='linear', C=c).fit(X_train, Y_train)\n \n predicted = svc.predict(X_valid)\n score = accuracy_score(predicted, Y_valid)\n if score > best_score: \n best_score = score\n best_c = c\n scores.append(score)\n print(f\"C: {c}, Validation Accuracy: {score}\")", "C: 0.1, Validation Accuracy: 0.5971428571428572\nC: 0.5, Validation Accuracy: 0.6971428571428572\nC: 1.0, Validation Accuracy: 0.7085714285714285\nC: 1.5, Validation Accuracy: 0.7142857142857143\nC: 2.0, Validation Accuracy: 0.7285714285714285\nC: 2.5, Validation Accuracy: 0.7085714285714285\nC: 5.0, Validation Accuracy: 0.6871428571428572\nC: 10.0, Validation Accuracy: 0.6785714285714286\n" ], [ "plt.plot(c_params, scores)\nplt.ylabel('Accuracy')\nplt.title('SVM: Penalty (C) & Accuracy')\nplt.xlabel('C')\nplt.savefig('svm.png')\nplt.show()\n\nnb_model = LogisticRegression(C=best_c).fit(X_train, Y_train)\npredicted = nb_model.predict(X_test)\nscore = accuracy_score(predicted, Y_test)\nprint(f\"SVM Test Accuracy: {score}\")", "_____no_output_____" ] ], [ [ "## Random Forests", "_____no_output_____" ] ], [ [ "from sklearn.ensemble import RandomForestClassifier\n\nparameters = [{\"n_estimators\": [10, 20, 40, 60], \"max_depth\": [5, 10, 20, 35, 60], \"min_samples_split\": [2, 4, 8]}]\n\nclf = GridSearchCV(RandomForestClassifier(), parameters, cv=5)\nclf.fit(X_train, Y_train)\n\nprint(\"Best parameters set found on development set:\")\nprint()\nprint(clf.best_params_)\nprint()\nprint(\"Grid scores on development set:\")\nprint()\nmeans = clf.cv_results_['mean_test_score']\nstds = clf.cv_results_['std_test_score']\nfor mean, std, params in zip(means, stds, clf.cv_results_['params']):\n print(\"%0.3f (+/-%0.03f) for %r\" % (mean, std * 2, params))", "Best parameters set found on development set:\n\n{'max_depth': 60, 'min_samples_split': 4, 'n_estimators': 60}\n\nGrid scores on development set:\n\n0.461 (+/-0.045) for {'max_depth': 5, 'min_samples_split': 2, 'n_estimators': 10}\n0.468 (+/-0.031) for {'max_depth': 5, 'min_samples_split': 2, 'n_estimators': 20}\n0.471 (+/-0.030) for {'max_depth': 5, 'min_samples_split': 2, 'n_estimators': 40}\n0.490 (+/-0.029) for {'max_depth': 5, 'min_samples_split': 2, 'n_estimators': 60}\n0.461 (+/-0.026) for {'max_depth': 5, 'min_samples_split': 4, 'n_estimators': 10}\n0.474 (+/-0.013) for {'max_depth': 5, 'min_samples_split': 4, 'n_estimators': 20}\n0.482 (+/-0.025) for {'max_depth': 5, 'min_samples_split': 4, 'n_estimators': 40}\n0.487 (+/-0.011) for {'max_depth': 5, 'min_samples_split': 4, 'n_estimators': 60}\n0.458 (+/-0.034) for {'max_depth': 5, 'min_samples_split': 8, 'n_estimators': 10}\n0.465 (+/-0.032) for {'max_depth': 5, 'min_samples_split': 8, 'n_estimators': 20}\n0.477 (+/-0.020) for {'max_depth': 5, 'min_samples_split': 8, 'n_estimators': 40}\n0.488 (+/-0.012) for {'max_depth': 5, 'min_samples_split': 8, 'n_estimators': 60}\n0.518 (+/-0.023) for {'max_depth': 10, 'min_samples_split': 2, 'n_estimators': 10}\n0.527 (+/-0.025) for {'max_depth': 10, 'min_samples_split': 2, 'n_estimators': 20}\n0.533 (+/-0.029) for {'max_depth': 10, 'min_samples_split': 2, 'n_estimators': 40}\n0.543 (+/-0.030) for {'max_depth': 10, 'min_samples_split': 2, 'n_estimators': 60}\n0.514 (+/-0.021) for {'max_depth': 10, 'min_samples_split': 4, 'n_estimators': 10}\n0.517 (+/-0.016) for {'max_depth': 10, 'min_samples_split': 4, 'n_estimators': 20}\n0.534 (+/-0.019) for {'max_depth': 10, 'min_samples_split': 4, 'n_estimators': 40}\n0.536 (+/-0.017) for {'max_depth': 10, 'min_samples_split': 4, 'n_estimators': 60}\n0.508 (+/-0.029) for {'max_depth': 10, 'min_samples_split': 8, 'n_estimators': 10}\n0.534 (+/-0.024) for {'max_depth': 10, 'min_samples_split': 8, 'n_estimators': 20}\n0.539 (+/-0.035) for {'max_depth': 10, 'min_samples_split': 8, 'n_estimators': 40}\n0.539 (+/-0.018) for {'max_depth': 10, 'min_samples_split': 8, 'n_estimators': 60}\n0.585 (+/-0.017) for {'max_depth': 20, 'min_samples_split': 2, 'n_estimators': 10}\n0.595 (+/-0.022) for {'max_depth': 20, 'min_samples_split': 2, 'n_estimators': 20}\n0.609 (+/-0.011) for {'max_depth': 20, 'min_samples_split': 2, 'n_estimators': 40}\n0.617 (+/-0.012) for {'max_depth': 20, 'min_samples_split': 2, 'n_estimators': 60}\n0.573 (+/-0.023) for {'max_depth': 20, 'min_samples_split': 4, 'n_estimators': 10}\n0.598 (+/-0.032) for {'max_depth': 20, 'min_samples_split': 4, 'n_estimators': 20}\n0.613 (+/-0.031) for {'max_depth': 20, 'min_samples_split': 4, 'n_estimators': 40}\n0.614 (+/-0.018) for {'max_depth': 20, 'min_samples_split': 4, 'n_estimators': 60}\n0.574 (+/-0.027) for {'max_depth': 20, 'min_samples_split': 8, 'n_estimators': 10}\n0.593 (+/-0.029) for {'max_depth': 20, 'min_samples_split': 8, 'n_estimators': 20}\n0.603 (+/-0.034) for {'max_depth': 20, 'min_samples_split': 8, 'n_estimators': 40}\n0.606 (+/-0.024) for {'max_depth': 20, 'min_samples_split': 8, 'n_estimators': 60}\n0.617 (+/-0.015) for {'max_depth': 35, 'min_samples_split': 2, 'n_estimators': 10}\n0.648 (+/-0.025) for {'max_depth': 35, 'min_samples_split': 2, 'n_estimators': 20}\n0.663 (+/-0.033) for {'max_depth': 35, 'min_samples_split': 2, 'n_estimators': 40}\n0.669 (+/-0.019) for {'max_depth': 35, 'min_samples_split': 2, 'n_estimators': 60}\n0.611 (+/-0.043) for {'max_depth': 35, 'min_samples_split': 4, 'n_estimators': 10}\n0.649 (+/-0.016) for {'max_depth': 35, 'min_samples_split': 4, 'n_estimators': 20}\n0.660 (+/-0.020) for {'max_depth': 35, 'min_samples_split': 4, 'n_estimators': 40}\n0.665 (+/-0.015) for {'max_depth': 35, 'min_samples_split': 4, 'n_estimators': 60}\n0.615 (+/-0.040) for {'max_depth': 35, 'min_samples_split': 8, 'n_estimators': 10}\n0.642 (+/-0.036) for {'max_depth': 35, 'min_samples_split': 8, 'n_estimators': 20}\n0.660 (+/-0.013) for {'max_depth': 35, 'min_samples_split': 8, 'n_estimators': 40}\n0.669 (+/-0.007) for {'max_depth': 35, 'min_samples_split': 8, 'n_estimators': 60}\n0.631 (+/-0.019) for {'max_depth': 60, 'min_samples_split': 2, 'n_estimators': 10}\n0.661 (+/-0.025) for {'max_depth': 60, 'min_samples_split': 2, 'n_estimators': 20}\n0.679 (+/-0.027) for {'max_depth': 60, 'min_samples_split': 2, 'n_estimators': 40}\n0.692 (+/-0.020) for {'max_depth': 60, 'min_samples_split': 2, 'n_estimators': 60}\n0.641 (+/-0.023) for {'max_depth': 60, 'min_samples_split': 4, 'n_estimators': 10}\n0.674 (+/-0.016) for {'max_depth': 60, 'min_samples_split': 4, 'n_estimators': 20}\n0.682 (+/-0.020) for {'max_depth': 60, 'min_samples_split': 4, 'n_estimators': 40}\n0.697 (+/-0.026) for {'max_depth': 60, 'min_samples_split': 4, 'n_estimators': 60}\n0.639 (+/-0.032) for {'max_depth': 60, 'min_samples_split': 8, 'n_estimators': 10}\n0.665 (+/-0.020) for {'max_depth': 60, 'min_samples_split': 8, 'n_estimators': 20}\n0.687 (+/-0.025) for {'max_depth': 60, 'min_samples_split': 8, 'n_estimators': 40}\n0.697 (+/-0.022) for {'max_depth': 60, 'min_samples_split': 8, 'n_estimators': 60}\n" ], [ "from sklearn.ensemble import RandomForestClassifier\nclf = RandomForestClassifier(max_depth = 60, n_estimators= 60, min_samples_split = 4).fit(X_train, Y_train)\n\npredicted = clf.predict(X_test)\nscore = accuracy_score(predicted, Y_test)\nprint(f\"SVM Test Accuracy: {score}\")", "SVM Test Accuracy: 0.7047496790757382\n" ] ], [ [ "# Kaggle Dataset", "_____no_output_____" ] ], [ [ "from numpy import genfromtxt\nkaggle_data = genfromtxt('clean_data.csv', delimiter=',', dtype=None)", "/Users/IzKevin/anaconda3/lib/python3.6/site-packages/ipykernel_launcher.py:2: VisibleDeprecationWarning: Reading unicode strings without specifying the encoding argument is deprecated. Set the encoding, use None for the system default.\n \n" ], [ "from sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.feature_extraction.text import TfidfTransformer\n\nY = kaggle_data[:,0]\n\ncount_vect = CountVectorizer()\nX = count_vect.fit_transform(kaggle_data[:,1])\n\ntfidf_transformer = TfidfTransformer()\nX = tfidf_transformer.fit_transform(X)\n\nX_train = X[:250000]\nY_train = Y[:250000]\n\nX_test = X[250000:]\nY_test = Y[250000:]", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ] ]
4a0a630988d1e598990c678d28eb1728f15778eb
2,095
ipynb
Jupyter Notebook
Octubre19.ipynb
MoisesAcostaNava/daa_2021_1
c796a8888ecbd04ce004d80757a2cce56388165e
[ "MIT" ]
null
null
null
Octubre19.ipynb
MoisesAcostaNava/daa_2021_1
c796a8888ecbd04ce004d80757a2cce56388165e
[ "MIT" ]
null
null
null
Octubre19.ipynb
MoisesAcostaNava/daa_2021_1
c796a8888ecbd04ce004d80757a2cce56388165e
[ "MIT" ]
null
null
null
25.54878
235
0.401432
[ [ [ "<a href=\"https://colab.research.google.com/github/MoisesAcostaNava/daa_2021_1/blob/master/Octubre19.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ] ], [ [ "a2d = [[3,2,1],\n [6,4,8],\n [7,4,2]]\nn = 3\nprint(a2d)\n\ntotal = 0 #1\nprint(\"Nivel 1\")\nfor ren in range(n):\n sumaRenglon = 0\n print(\"Nivel 2\")\n for col in range(n):\n sumaRenglon += a2d[ren][col]\n total += a2d[ren][col]\n print(\"Nivel 3\")\n\nprint(total)", "[[3, 2, 1], [6, 4, 8], [7, 4, 2]]\nNivel 1\nNivel 2\nNivel 3\nNivel 3\nNivel 3\nNivel 2\nNivel 3\nNivel 3\nNivel 3\nNivel 2\nNivel 3\nNivel 3\nNivel 3\n37\n" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code" ] ]
4a0a67d95da458e73086b957a1ae48226f4e8dfa
19,530
ipynb
Jupyter Notebook
REST_API/notebooks/comparative_validation.ipynb
PDBeurope/PDBe_Programming
a2a5be13e94eb44365e2db495a2812b26b3ebe54
[ "Apache-2.0" ]
10
2015-03-18T14:06:03.000Z
2021-05-10T10:51:43.000Z
REST_API/notebooks/comparative_validation.ipynb
PDBeurope/PDBe_Programming
a2a5be13e94eb44365e2db495a2812b26b3ebe54
[ "Apache-2.0" ]
1
2018-07-12T15:43:27.000Z
2018-07-12T15:43:27.000Z
REST_API/notebooks/comparative_validation.ipynb
PDBeurope/PDBe_Programming
a2a5be13e94eb44365e2db495a2812b26b3ebe54
[ "Apache-2.0" ]
8
2015-01-21T14:28:25.000Z
2020-11-03T21:12:53.000Z
33.556701
358
0.535279
[ [ [ "empty" ] ] ]
[ "empty" ]
[ [ "empty" ] ]
4a0a6b9c7820fb2de96c40a65e41316cc4337b53
530,755
ipynb
Jupyter Notebook
1. Load and Visualize Data.ipynb
parksurk/P1_Facial_Keypoints
78ee8be73a4059d7597acecd2f9c024941cacd84
[ "MIT" ]
null
null
null
1. Load and Visualize Data.ipynb
parksurk/P1_Facial_Keypoints
78ee8be73a4059d7597acecd2f9c024941cacd84
[ "MIT" ]
null
null
null
1. Load and Visualize Data.ipynb
parksurk/P1_Facial_Keypoints
78ee8be73a4059d7597acecd2f9c024941cacd84
[ "MIT" ]
null
null
null
777.093704
170,464
0.948613
[ [ [ "# Facial Keypoint Detection\n \nThis project will be all about defining and training a convolutional neural network to perform facial keypoint detection, and using computer vision techniques to transform images of faces. The first step in any challenge like this will be to load and visualize the data you'll be working with. \n\nLet's take a look at some examples of images and corresponding facial keypoints.\n\n<img src='images/key_pts_example.png' width=50% height=50%/>\n\nFacial keypoints (also called facial landmarks) are the small magenta dots shown on each of the faces in the image above. In each training and test image, there is a single face and **68 keypoints, with coordinates (x, y), for that face**. These keypoints mark important areas of the face: the eyes, corners of the mouth, the nose, etc. These keypoints are relevant for a variety of tasks, such as face filters, emotion recognition, pose recognition, and so on. Here they are, numbered, and you can see that specific ranges of points match different portions of the face.\n\n<img src='images/landmarks_numbered.jpg' width=30% height=30%/>\n\n---", "_____no_output_____" ], [ "## Load and Visualize Data\n\nThe first step in working with any dataset is to become familiar with your data; you'll need to load in the images of faces and their keypoints and visualize them! This set of image data has been extracted from the [YouTube Faces Dataset](https://www.cs.tau.ac.il/~wolf/ytfaces/), which includes videos of people in YouTube videos. These videos have been fed through some processing steps and turned into sets of image frames containing one face and the associated keypoints.\n\n#### Training and Testing Data\n\nThis facial keypoints dataset consists of 5770 color images. All of these images are separated into either a training or a test set of data.\n\n* 3462 of these images are training images, for you to use as you create a model to predict keypoints.\n* 2308 are test images, which will be used to test the accuracy of your model.\n\nThe information about the images and keypoints in this dataset are summarized in CSV files, which we can read in using `pandas`. Let's read the training CSV and get the annotations in an (N, 2) array where N is the number of keypoints and 2 is the dimension of the keypoint coordinates (x, y).\n\n---", "_____no_output_____" ], [ "**** Additional for using cloud(Ignore if your jupyter is in on-prems.)\n\nFirst, before we do anything, we have to load in our image data. This data is stored in a zip file and in the below cell, we access it by it's URL and unzip the data in a /data/ directory that is separate from the workspace home directory.", "_____no_output_____" ] ], [ [ "# -- DO NOT CHANGE THIS CELL -- #\n!mkdir /data\n!wget -P /data/ https://s3.amazonaws.com/video.udacity-data.com/topher/2018/May/5aea1b91_train-test-data/train-test-data.zip\n!unzip -n /data/train-test-data.zip -d /data", "_____no_output_____" ], [ "# import the required libraries\nimport glob\nimport os\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\n\nimport cv2", "_____no_output_____" ], [ "key_pts_frame = pd.read_csv('data/training_frames_keypoints.csv')\n\nn = 0\nimage_name = key_pts_frame.iloc[n, 0]\nkey_pts = key_pts_frame.iloc[n, 1:].as_matrix()\nkey_pts = key_pts.astype('float').reshape(-1, 2)\n\nprint('Image name: ', image_name)\nprint('Landmarks shape: ', key_pts.shape)\nprint('First 4 key pts: {}'.format(key_pts[:4]))", "Image name: Luis_Fonsi_21.jpg\nLandmarks shape: (68, 2)\nFirst 4 key pts: [[ 45. 98.]\n [ 47. 106.]\n [ 49. 110.]\n [ 53. 119.]]\n" ], [ "# print out some stats about the data\nprint('Number of images: ', key_pts_frame.shape[0])", "Number of images: 3462\n" ] ], [ [ "## Look at some images\n\nBelow, is a function `show_keypoints` that takes in an image and keypoints and displays them. As you look at this data, **note that these images are not all of the same size**, and neither are the faces! To eventually train a neural network on these images, we'll need to standardize their shape.", "_____no_output_____" ] ], [ [ "def show_keypoints(image, key_pts):\n \"\"\"Show image with keypoints\"\"\"\n plt.imshow(image)\n plt.scatter(key_pts[:, 0], key_pts[:, 1], s=20, marker='.', c='m')\n", "_____no_output_____" ], [ "# Display a few different types of images by changing the index n\n\n# select an image by index in our data frame\nn = 0\nimage_name = key_pts_frame.iloc[n, 0]\nkey_pts = key_pts_frame.iloc[n, 1:].as_matrix()\nkey_pts = key_pts.astype('float').reshape(-1, 2)\n\nplt.figure(figsize=(5, 5))\nshow_keypoints(mpimg.imread(os.path.join('data/training/', image_name)), key_pts)\nplt.show()", "_____no_output_____" ] ], [ [ "## Dataset class and Transformations\n\nTo prepare our data for training, we'll be using PyTorch's Dataset class. Much of this this code is a modified version of what can be found in the [PyTorch data loading tutorial](http://pytorch.org/tutorials/beginner/data_loading_tutorial.html).\n\n#### Dataset class\n\n``torch.utils.data.Dataset`` is an abstract class representing a\ndataset. This class will allow us to load batches of image/keypoint data, and uniformly apply transformations to our data, such as rescaling and normalizing images for training a neural network.\n\n\nYour custom dataset should inherit ``Dataset`` and override the following\nmethods:\n\n- ``__len__`` so that ``len(dataset)`` returns the size of the dataset.\n- ``__getitem__`` to support the indexing such that ``dataset[i]`` can\n be used to get the i-th sample of image/keypoint data.\n\nLet's create a dataset class for our face keypoints dataset. We will\nread the CSV file in ``__init__`` but leave the reading of images to\n``__getitem__``. This is memory efficient because all the images are not\nstored in the memory at once but read as required.\n\nA sample of our dataset will be a dictionary\n``{'image': image, 'keypoints': key_pts}``. Our dataset will take an\noptional argument ``transform`` so that any required processing can be\napplied on the sample. We will see the usefulness of ``transform`` in the\nnext section.\n", "_____no_output_____" ] ], [ [ "from torch.utils.data import Dataset, DataLoader\n\nclass FacialKeypointsDataset(Dataset):\n \"\"\"Face Landmarks dataset.\"\"\"\n\n def __init__(self, csv_file, root_dir, transform=None):\n \"\"\"\n Args:\n csv_file (string): Path to the csv file with annotations.\n root_dir (string): Directory with all the images.\n transform (callable, optional): Optional transform to be applied\n on a sample.\n \"\"\"\n self.key_pts_frame = pd.read_csv(csv_file)\n self.root_dir = root_dir\n self.transform = transform\n\n def __len__(self):\n return len(self.key_pts_frame)\n\n def __getitem__(self, idx):\n image_name = os.path.join(self.root_dir,\n self.key_pts_frame.iloc[idx, 0])\n \n image = mpimg.imread(image_name)\n \n # if image has an alpha color channel, get rid of it\n if(image.shape[2] == 4):\n image = image[:,:,0:3]\n \n key_pts = self.key_pts_frame.iloc[idx, 1:].as_matrix()\n key_pts = key_pts.astype('float').reshape(-1, 2)\n sample = {'image': image, 'keypoints': key_pts}\n\n if self.transform:\n sample = self.transform(sample)\n\n return sample", "_____no_output_____" ] ], [ [ "Now that we've defined this class, let's instantiate the dataset and display some images.", "_____no_output_____" ] ], [ [ "# Construct the dataset\nface_dataset = FacialKeypointsDataset(csv_file='data/training_frames_keypoints.csv',\n root_dir='data/training/')\n\n# print some stats about the dataset\nprint('Length of dataset: ', len(face_dataset))", "Length of dataset: 3462\n" ], [ "# Display a few of the images from the dataset\nnum_to_display = 3\n\nfor i in range(num_to_display):\n \n # define the size of images\n fig = plt.figure(figsize=(20,10))\n \n # randomly select a sample\n rand_i = np.random.randint(0, len(face_dataset))\n sample = face_dataset[rand_i]\n\n # print the shape of the image and keypoints\n print(i, sample['image'].shape, sample['keypoints'].shape)\n\n ax = plt.subplot(1, num_to_display, i + 1)\n ax.set_title('Sample #{}'.format(i))\n \n # Using the same display function, defined earlier\n show_keypoints(sample['image'], sample['keypoints'])\n", "0 (99, 109, 3) (68, 2)\n1 (270, 285, 3) (68, 2)\n2 (275, 254, 3) (68, 2)\n" ] ], [ [ "## Transforms\n\nNow, the images above are not of the same size, and neural networks often expect images that are standardized; a fixed size, with a normalized range for color ranges and coordinates, and (for PyTorch) converted from numpy lists and arrays to Tensors.\n\nTherefore, we will need to write some pre-processing code.\nLet's create four transforms:\n\n- ``Normalize``: to convert a color image to grayscale values with a range of [0,1] and normalize the keypoints to be in a range of about [-1, 1]\n- ``Rescale``: to rescale an image to a desired size.\n- ``RandomCrop``: to crop an image randomly.\n- ``ToTensor``: to convert numpy images to torch images.\n\n\nWe will write them as callable classes instead of simple functions so\nthat parameters of the transform need not be passed everytime it's\ncalled. For this, we just need to implement ``__call__`` method and \n(if we require parameters to be passed in), the ``__init__`` method. \nWe can then use a transform like this:\n\n tx = Transform(params)\n transformed_sample = tx(sample)\n\nObserve below how these transforms are generally applied to both the image and its keypoints.\n\n", "_____no_output_____" ] ], [ [ "import torch\nfrom torchvision import transforms, utils\n# tranforms\n\nclass Normalize(object):\n \"\"\"Convert a color image to grayscale and normalize the color range to [0,1].\"\"\" \n\n def __call__(self, sample):\n image, key_pts = sample['image'], sample['keypoints']\n \n image_copy = np.copy(image)\n key_pts_copy = np.copy(key_pts)\n\n # convert image to grayscale\n image_copy = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)\n \n # scale color range from [0, 255] to [0, 1]\n image_copy= image_copy/255.0\n \n # scale keypoints to be centered around 0 with a range of [-1, 1]\n # mean = 100, sqrt = 50, so, pts should be (pts - 100)/50\n key_pts_copy = (key_pts_copy - 100)/50.0\n\n\n return {'image': image_copy, 'keypoints': key_pts_copy}\n\n\nclass Rescale(object):\n \"\"\"Rescale the image in a sample to a given size.\n\n Args:\n output_size (tuple or int): Desired output size. If tuple, output is\n matched to output_size. If int, smaller of image edges is matched\n to output_size keeping aspect ratio the same.\n \"\"\"\n\n def __init__(self, output_size):\n assert isinstance(output_size, (int, tuple))\n self.output_size = output_size\n\n def __call__(self, sample):\n image, key_pts = sample['image'], sample['keypoints']\n\n h, w = image.shape[:2]\n if isinstance(self.output_size, int):\n if h > w:\n new_h, new_w = self.output_size * h / w, self.output_size\n else:\n new_h, new_w = self.output_size, self.output_size * w / h\n else:\n new_h, new_w = self.output_size\n\n new_h, new_w = int(new_h), int(new_w)\n\n img = cv2.resize(image, (new_w, new_h))\n \n # scale the pts, too\n key_pts = key_pts * [new_w / w, new_h / h]\n\n return {'image': img, 'keypoints': key_pts}\n\n\nclass RandomCrop(object):\n \"\"\"Crop randomly the image in a sample.\n\n Args:\n output_size (tuple or int): Desired output size. If int, square crop\n is made.\n \"\"\"\n\n def __init__(self, output_size):\n assert isinstance(output_size, (int, tuple))\n if isinstance(output_size, int):\n self.output_size = (output_size, output_size)\n else:\n assert len(output_size) == 2\n self.output_size = output_size\n\n def __call__(self, sample):\n image, key_pts = sample['image'], sample['keypoints']\n\n h, w = image.shape[:2]\n new_h, new_w = self.output_size\n\n top = np.random.randint(0, h - new_h)\n left = np.random.randint(0, w - new_w)\n\n image = image[top: top + new_h,\n left: left + new_w]\n\n key_pts = key_pts - [left, top]\n\n return {'image': image, 'keypoints': key_pts}\n\n\nclass ToTensor(object):\n \"\"\"Convert ndarrays in sample to Tensors.\"\"\"\n\n def __call__(self, sample):\n image, key_pts = sample['image'], sample['keypoints']\n \n # if image has no grayscale color channel, add one\n if(len(image.shape) == 2):\n # add that third color dim\n image = image.reshape(image.shape[0], image.shape[1], 1)\n \n # swap color axis because\n # numpy image: H x W x C\n # torch image: C X H X W\n image = image.transpose((2, 0, 1))\n \n return {'image': torch.from_numpy(image),\n 'keypoints': torch.from_numpy(key_pts)}", "_____no_output_____" ] ], [ [ "## Test out the transforms\n\nLet's test these transforms out to make sure they behave as expected. As you look at each transform, note that, in this case, **order does matter**. For example, you cannot crop a image using a value smaller than the original image (and the orginal images vary in size!), but, if you first rescale the original image, you can then crop it to any size smaller than the rescaled size.", "_____no_output_____" ] ], [ [ "# test out some of these transforms\nrescale = Rescale(100)\ncrop = RandomCrop(50)\ncomposed = transforms.Compose([Rescale(250),\n RandomCrop(224)])\n\n# apply the transforms to a sample image\ntest_num = 500\nsample = face_dataset[test_num]\n\nfig = plt.figure()\nfor i, tx in enumerate([rescale, crop, composed]):\n transformed_sample = tx(sample)\n\n ax = plt.subplot(1, 3, i + 1)\n plt.tight_layout()\n ax.set_title(type(tx).__name__)\n show_keypoints(transformed_sample['image'], transformed_sample['keypoints'])\n\nplt.show()", "_____no_output_____" ] ], [ [ "## Create the transformed dataset\n\nApply the transforms in order to get grayscale images of the same shape. Verify that your transform works by printing out the shape of the resulting data (printing out a few examples should show you a consistent tensor size).", "_____no_output_____" ] ], [ [ "# define the data tranform\n# order matters! i.e. rescaling should come before a smaller crop\ndata_transform = transforms.Compose([Rescale(250),\n RandomCrop(224),\n Normalize(),\n ToTensor()])\n\n# create the transformed dataset\ntransformed_dataset = FacialKeypointsDataset(csv_file='data/training_frames_keypoints.csv',\n root_dir='data/training/',\n transform=data_transform)\n", "_____no_output_____" ], [ "# print some stats about the transformed data\nprint('Number of images: ', len(transformed_dataset))\n\n# make sure the sample tensors are the expected size\nfor i in range(5):\n sample = transformed_dataset[i]\n print(i, sample['image'].size(), sample['keypoints'].size())\n", "Number of images: 3462\n0 torch.Size([1, 224, 224]) torch.Size([68, 2])\n1 torch.Size([1, 224, 224]) torch.Size([68, 2])\n2 torch.Size([1, 224, 224]) torch.Size([68, 2])\n3 torch.Size([1, 224, 224]) torch.Size([68, 2])\n4 torch.Size([1, 224, 224]) torch.Size([68, 2])\n" ] ], [ [ "## Data Iteration and Batching\n\nRight now, we are iterating over this data using a ``for`` loop, but we are missing out on a lot of PyTorch's dataset capabilities, specifically the abilities to:\n\n- Batch the data\n- Shuffle the data\n- Load the data in parallel using ``multiprocessing`` workers.\n\n``torch.utils.data.DataLoader`` is an iterator which provides all these\nfeatures, and we'll see this in use in the *next* notebook, Notebook 2, when we load data in batches to train a neural network!\n\n---\n\n", "_____no_output_____" ], [ "## Ready to Train!\n\nNow that you've seen how to load and transform our data, you're ready to build a neural network to train on this data.\n\nIn the next notebook, you'll be tasked with creating a CNN for facial keypoint detection.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ] ]
4a0a71fdfed44b7e6a32da9d2590f4aa383a3c2b
83,147
ipynb
Jupyter Notebook
report/ProgrammaticReport-eng.ipynb
vtikha/assistive-rehab
95137cd3a4dac6db23f7a5c595dd2ff40ad189f3
[ "BSD-3-Clause" ]
null
null
null
report/ProgrammaticReport-eng.ipynb
vtikha/assistive-rehab
95137cd3a4dac6db23f7a5c595dd2ff40ad189f3
[ "BSD-3-Clause" ]
null
null
null
report/ProgrammaticReport-eng.ipynb
vtikha/assistive-rehab
95137cd3a4dac6db23f7a5c595dd2ff40ad189f3
[ "BSD-3-Clause" ]
null
null
null
42.099747
154
0.398102
[ [ [ "import nbformat as nbf\nimport textwrap", "_____no_output_____" ], [ "nb = nbf.v4.new_notebook()", "_____no_output_____" ], [ "#this creates a button to toggle to remove code in html\nsource_1 = textwrap.dedent(\"\"\"\nfrom IPython.display import HTML\n\nHTML('''<script>\ncode_show=true; \nfunction code_toggle() {\n if (code_show){\n $('div.input').hide();\n } else {\n $('div.input').show();\n }\n code_show = !code_show\n} \n$( document ).ready(code_toggle);\n</script>\n<form action=\"javascript:code_toggle()\"><input type=\"submit\" value=\"Click here to toggle on/off the raw code.\"></form>''')\"\"\")\ncode_cell = nbf.v4.new_code_cell(source=source_1)\nnb.cells.append(code_cell)", "_____no_output_____" ], [ "#import libraries\nsource_1 = textwrap.dedent(\"\"\"\\\n#import libraries\nimport warnings \nwarnings.filterwarnings(\"ignore\",category=FutureWarning)\nwarnings.filterwarnings(\"ignore\", message=\"numpy.dtype size changed\")\nimport scipy.io as spio\nimport scipy.signal\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom collections import namedtuple\nimport math \nimport re \nimport pandas as pd\nimport os\nimport glob\nfrom os.path import expanduser\nimport datetime\nimport statistics\nfrom plotly import __version__\nfrom plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot\nimport plotly.graph_objs as go\ninit_notebook_mode(connected=True)\n\"\"\")\ncode_cell = nbf.v4.new_code_cell(source=source_1)\nnb.cells.append(code_cell)", "_____no_output_____" ], [ "#define functions\nsource_1 = textwrap.dedent(\"\"\"\\\ndef color_negative_red(val):\n color = 'red' if val > 110 else 'black'\n return 'color: %s' % color\n\"\"\")\ncode_cell = nbf.v4.new_code_cell(source=source_1)\nnb.cells.append(code_cell)\n\nsource_1 = textwrap.dedent(\"\"\"\\\nclass Keypoint:\n tag = \"\"\n parent = ['']\n child = ['']\n point = None\n \n def __init__(self,tag=None,parent=None,child=None,point=None):\n if tag is not None: \n self.tag = tag\n if parent is not None:\n self.parent = parent\n if child is not None:\n self.child = child\n if point is not None:\n self.point = point\n\"\"\")\ncode_cell = nbf.v4.new_code_cell(source=source_1)\nnb.cells.append(code_cell)\n\nsource_1 = textwrap.dedent(\"\"\"\\\nclass Skeleton:\n keypoints = [Keypoint() for i in range(17)]\n tag2id = {\n \"shoulderCenter\" : 0,\n \"head\" : 1,\n \"shoulderLeft\" : 2,\n \"elbowLeft\" : 3,\n \"handLeft\" : 4,\n \"shoulderRight\" : 5,\n \"elbowRight\" : 6,\n \"handRight\" : 7,\n \"hipCenter\" : 8,\n \"hipLeft\" : 9,\n \"kneeLeft\" : 10,\n \"ankleLeft\" : 11,\n \"footLeft\" : 12,\n \"hipRight\" : 13,\n \"kneeRight\" : 14,\n \"ankleRight\" : 15,\n \"footRight\" : 16,\n }\n keypoints[tag2id[\"shoulderCenter\"]] = Keypoint(\"shoulderCenter\",[''],['head','shoulderLeft','shoulderRight','hipCenter'])\n keypoints[tag2id[\"head\"]] = Keypoint(\"head\",['shoulderCenter'],[''])\n keypoints[tag2id[\"shoulderLeft\"]] = Keypoint(\"shoulderLeft\",['shoulderCenter'],['elbowLeft'])\n keypoints[tag2id[\"elbowLeft\"]] = Keypoint(\"elbowLeft\",['shoulderLeft'],['handLeft'])\n keypoints[tag2id[\"handLeft\"]] = Keypoint(\"handLeft\",['elbowLeft'],[''])\n keypoints[tag2id[\"shoulderRight\"]] = Keypoint(\"shoulderRight\",['shoulderCenter'],['elbowRight'])\n keypoints[tag2id[\"elbowRight\"]] = Keypoint(\"elbowRight\",['shoulderRight'],['handRight'])\n keypoints[tag2id[\"handRight\"]] = Keypoint(\"handRight\",['elbowRight'],[''])\n keypoints[tag2id[\"hipCenter\"]] = Keypoint(\"hipCenter\",['shoulderCenter'],['hipLeft','hipRight'])\n keypoints[tag2id[\"hipLeft\"]] = Keypoint(\"hipLeft\",['shoulderCenter'],['kneeLeft'])\n keypoints[tag2id[\"kneeLeft\"]] = Keypoint(\"kneeLeft\",['hipLeft'],['ankleLeft'])\n keypoints[tag2id[\"ankleLeft\"]] = Keypoint(\"ankleLeft\",['kneeLeft'],['footLeft'])\n keypoints[tag2id[\"footLeft\"]] = Keypoint(\"footLeft\",['ankleLeft'],[''])\n keypoints[tag2id[\"hipRight\"]] = Keypoint(\"hipRight\",['shoulderCenter'],['kneeRight'])\n keypoints[tag2id[\"kneeRight\"]] = Keypoint(\"kneeRight\",['hipRight'],['ankleRight'])\n keypoints[tag2id[\"ankleRight\"]] = Keypoint(\"ankleRight\",['kneeRight'],['footRight'])\n keypoints[tag2id[\"footRight\"]] = Keypoint(\"footRight\",['ankleRight'],[''])\n \n def __init__(self,keyp_map=None):\n if keyp_map is not None:\n for i in range(len(keyp_map)):\n tag = keyp_map.keys()[i]\n self.keypoints[self.tag2id[tag]].point = keyp_map[tag] \n \n def getKeypoint(self,keyp_tag):\n return self.keypoints[self.tag2id[keyp_tag]].point\n \n def getChild(self,keyp_tag):\n return self.keypoints[self.tag2id[keyp_tag]].child\n \n def getParent(self,keyp_tag):\n return self.keypoints[self.tag2id[keyp_tag]].parent\n \n def getTransformation(self):\n sagittal = None\n coronal = None\n transverse = None\n T = np.eye(4,4)\n if self.getKeypoint(\"shoulderLeft\") is not None:\n if self.getKeypoint(\"shoulderRight\") is not None:\n sagittal = self.getKeypoint(\"shoulderLeft\")[0]-self.getKeypoint(\"shoulderRight\")[0]\n sagittal = sagittal/np.linalg.norm(sagittal)\n if self.getKeypoint(\"shoulderCenter\") is not None:\n if self.getKeypoint(\"hipLeft\") is not None:\n if self.getKeypoint(\"hipRight\") is not None:\n transverse = self.getKeypoint(\"shoulderCenter\")[0]-0.5*(self.getKeypoint(\"hipLeft\")[0]+self.getKeypoint(\"hipRight\")[0])\n transverse = transverse/np.linalg.norm(transverse)\n if self.getKeypoint(\"shoulderCenter\") is not None:\n pSC = self.getKeypoint(\"shoulderCenter\")[0]\n\n if sagittal is not None:\n if coronal is not None:\n coronal = np.cross(sagittal,transverse)\n T[0,0]=coronal[0]\n T[1,0]=coronal[1]\n T[2,0]=coronal[2]\n T[0,1]=sagittal[0]\n T[1,1]=sagittal[1]\n T[2,1]=sagittal[2]\n T[0,2]=transverse[0]\n T[1,2]=transverse[1]\n T[2,2]=transverse[2]\n T[0,3]=pSC[0]\n T[1,3]=pSC[1]\n T[2,3]=pSC[2]\n T[3,3]=1\n return T\n \n def show(self):\n for i in range(len(self.keypoints)):\n k = self.keypoints[i]\n print \"keypoint[\", k.tag, \"]\", \"=\", k.point\n\"\"\")\ncode_cell = nbf.v4.new_code_cell(source=source_1)\nnb.cells.append(code_cell)", "_____no_output_____" ], [ "source_1 = textwrap.dedent(\"\"\"\\\nclass Exercise:\n name = \"\"\n typee = \"\"\n metrics = []\n \nclass Tug(Exercise):\n name = \"tug\"\n typee = \"test\"\n metrics = [\"ROM_0\",\"ROM_1\",\"ROM_2\",\"ROM_3\",\"ROM_4\",\"ROM_5\",\"step_0\"]\n result = []\n month_res = {\n 0: [],\n 1: [],\n 2: [],\n 3: [],\n 4: [],\n 5: [],\n 6: [],\n 7: [],\n 8: [],\n 9: [],\n 10: [],\n 11: []\n }\n \n def __init__(self,month,result):\n self.result = result\n self.month_res[month] = result\n \n def getResult(self,month):\n return self.month_res[month]\n \nclass Abduction(Exercise):\n name = \"abduction\"\n typee = \"rehabilitation\"\n metrics = [\"ROM_0\"] \n result = []\n month_res = {\n 0: [],\n 1: [],\n 2: [],\n 3: [],\n 4: [],\n 5: [],\n 6: [],\n 7: [],\n 8: [],\n 9: [],\n 10: [],\n 11: []\n }\n def __init__(self,name,monthi,result):\n self.name = name\n self.result = result\n self.month_res[monthi] = result\n \n def getResult(self,month):\n return self.month_res[month]\n \nclass Internal_Rotation(Exercise):\n name = \"internal_rotation\"\n typee = \"rehabilitation\"\n metrics = [\"ROM_0\"] \n result = []\n month_res = {\n 0: [],\n 1: [],\n 2: [],\n 3: [],\n 4: [],\n 5: [],\n 6: [],\n 7: [],\n 8: [],\n 9: [],\n 10: [],\n 11: []\n }\n def __init__(self,name,monthi,result):\n self.name = name\n self.result = result\n self.month_res[monthi] = result\n \n def getResult(self,month):\n return self.month_res[month]\n \nclass External_Rotation(Exercise):\n name = \"external_rotation\"\n typee = \"rehabilitation\"\n metrics = [\"ROM_0\"] \n result = []\n month_res = {\n 0: [],\n 1: [],\n 2: [],\n 3: [],\n 4: [],\n 5: [],\n 6: [],\n 7: [],\n 8: [],\n 9: [],\n 10: [],\n 11: []\n }\n def __init__(self,name,monthi,result):\n self.name = name\n self.result = result\n self.month_res[monthi] = result\n \n def getResult(self,month):\n return self.month_res[month]\n \nclass Reaching(Exercise):\n name = \"reaching\"\n typee = \"rehabilitation\"\n metrics = [\"EP_0\"] \n result = []\n month_res = {\n 0: [],\n 1: [],\n 2: [],\n 3: [],\n 4: [],\n 5: [],\n 6: [],\n 7: [],\n 8: [],\n 9: [],\n 10: [],\n 11: []\n }\n def __init__(self,name,monthi,result):\n self.name = name\n self.result = result\n self.month_res[monthi] = result\n \n def getResult(self,month):\n return self.month_res[month]\n\n\n\"\"\")\ncode_cell = nbf.v4.new_code_cell(source=source_1)\nnb.cells.append(code_cell)", "_____no_output_____" ], [ "source_1 = textwrap.dedent(\"\"\"\\\nclass Metric:\n name = ''\n \n def __init__(self,name):\n self.name = name\n\nclass Rom(Metric):\n name = \"ROM\"\n tagjoint = \"\"\n refjoint = \"\"\n refdir = []\n tagplane = \"\"\n def __init__(self,tagjoint,refjoint,refdir,tagplane):\n self.tagjoint = tagjoint\n self.refjoint = refjoint\n self.refdir = refdir\n self.tagplane = tagplane\n \n def compute(self,skeleton): \n #joint ref and child\n tj = skeleton.getKeypoint(self.tagjoint)\n tagchild = skeleton.getChild(self.tagjoint)[0]\n cj = skeleton.getKeypoint(tagchild)\n \n xrj = []\n yrj = []\n zrj = []\n if self.refjoint != \"\":\n rj = skeleton.getKeypoint(self.refjoint)\n xrj = rj[:,0]\n yrj = rj[:,1]\n zrj = rj[:,2]\n \n #compute metric\n x=tj[:,0]\n y=tj[:,1]\n z=tj[:,2]\n\n xchild=cj[:,0]\n ychild=cj[:,1]\n zchild=cj[:,2]\n\n #plane over which we want to evaluate the metric\n plane = np.zeros(3)\n if tagplane == \"coronal\":\n plane[0] = 1.0\n if tagplane == \"sagittal\":\n plane[1] = 1.0\n if tagplane == \"transverse\":\n plane[2] = 1.0\n\n #project v1 on the right plane\n invT = np.linalg.inv(skeleton.getTransformation())\n cosRom = [] \n for i in range(len(x)):\n temp_ref = np.array([x[i],y[i],z[i],1])\n temp_child = np.array([xchild[i],ychild[i],zchild[i],1])\n\n transf_ref = np.inner(invT,temp_ref) \n transf_child = np.inner(invT,temp_child) \n vprocess = transf_child-transf_ref\n vprocess = np.delete(vprocess,3)\n\n dist = np.dot(vprocess,np.transpose(plane)) \n vprocess = vprocess-dist*plane\n\n n1 = np.linalg.norm(vprocess)\n if(n1>0):\n vprocess = vprocess/n1 \n \n if len(xrj)>0:\n temp_refjoint = np.array([xrj[i],yrj[i],zrj[i],1])\n transf_refjoint = np.inner(invT,temp_refjoint)\n vecref = transf_ref - transf_refjoint\n ref = np.delete(vecref,3)\n else: \n n2 = np.linalg.norm(self.refdir)\n if(n2>0):\n self.refdir = self.refdir/n2\n ref = self.refdir\n \n dotprod = np.dot(vprocess,np.transpose(ref))\n cosRom.append(dotprod)\n\n \n rom_value = np.arccos(cosRom)\n result = rom_value *(180/math.pi)\n return result\n \n \nclass Step(Metric):\n name = \"step\"\n num = []\n den = []\n tstart = 0.0\n tend = 0.0\n steplen = []\n nsteps = 0\n cadence = 0.0\n speed = 0.0\n ex_time = 0.0\n filtered_distfeet = []\n strikes = []\n def __init__(self,num,den,tstart,tend):\n self.num = num\n self.den = den\n self.tstart = tstart\n self.tend = tend\n\n def compute(self,skeleton):\n alj = skeleton.getKeypoint(\"ankleLeft\")\n arj = skeleton.getKeypoint(\"ankleRight\")\n sagittal = None\n if skeleton.getKeypoint(\"shoulderLeft\") is not None:\n if skeleton.getKeypoint(\"shoulderRight\") is not None:\n sagittal = skeleton.getKeypoint(\"shoulderLeft\")[0]-skeleton.getKeypoint(\"shoulderRight\")[0]\n sagittal = sagittal/np.linalg.norm(sagittal)\n distfeet = []\n for i in range(len(alj)):\n v = alj[i,:]-arj[i,:]\n dist = np.dot(v,np.transpose(sagittal)) \n v = v-dist*sagittal\n distfeet.append(np.linalg.norm(v))\n self.filtered_distfeet = scipy.signal.filtfilt(self.num,self.den,distfeet)\n self.strikes,_ = scipy.signal.find_peaks(self.filtered_distfeet,height=0.05)\n filtered_distfeet_np = np.array(self.filtered_distfeet)\n slen = filtered_distfeet_np[self.strikes]\n self.steplen = statistics.mean(slen)\n self.nsteps = len(self.strikes)\n self.cadence = self.nsteps/(self.tend-self.tstart)\n self.speed = self.steplen*self.cadence\n self.ex_time = self.tend-self.tstart\n \nclass EndPoint(Metric):\n name = \"EP\"\n tagjoint = \"\"\n refdir = []\n tagplane = \"\"\n target = []\n trajectories = []\n tstart = 0.0\n tend = 0.0\n speed = 0.0\n ex_time = 0.0\n def __init__(self,tagjoint,refdir,tagplane,target,tstart,tend):\n self.tagjoint = tagjoint\n self.refdir = refdir\n self.tagplane = tagplane\n self.target = target\n self.tstart = tstart\n self.tend = tend\n \n def compute(self,skeleton):\n self.ex_time = self.tend-self.tstart\n tj = skeleton.getKeypoint(self.tagjoint)\n x = tj[:,0]\n y = tj[:,1]\n z = tj[:,2]\n\n plane = np.zeros(3)\n if tagplane == \"coronal\":\n plane[0] = 1.0\n if tagplane == \"sagittal\":\n plane[1] = 1.0\n if tagplane == \"transverse\":\n plane[2] = 1.0\n invT = np.linalg.inv(skeleton.getTransformation())\n self.trajectories = np.zeros([len(x),3])\n for i in range(len(x)):\n temp_jnt = np.array([x[i],y[i],z[i],1]) \n transf_jnt = np.inner(invT,temp_jnt) \n v = np.delete(transf_jnt,3)\n dist = np.dot(v,np.transpose(plane)) \n v = v-dist*plane\n self.trajectories[i,0]=v[0]\n self.trajectories[i,1]=v[1]\n self.trajectories[i,2]=v[2]\n \n vel = np.zeros([len(x),3])\n vel[:,0] = np.gradient(self.trajectories[:,0])/self.ex_time\n vel[:,1] = np.gradient(self.trajectories[:,1])/self.ex_time\n vel[:,2] = np.gradient(self.trajectories[:,2])/self.ex_time\n \n self.speed = 0.0\n for i in range(len(x)):\n self.speed = self.speed + np.linalg.norm([vel[i,0],vel[i,1],vel[i,2]])\n self.speed = self.speed/len(x)\n\"\"\")\ncode_cell = nbf.v4.new_code_cell(source=source_1)\nnb.cells.append(code_cell)", "_____no_output_____" ], [ "source_1 = textwrap.dedent(\"\"\"\\\ndef loadmat(filename):\n '''\n this function should be called instead of direct spio.loadmat\n as it cures the problem of not properly recovering python dictionaries\n from mat files. It calls the function check keys to cure all entries\n which are still mat-objects\n '''\n data = spio.loadmat(filename, struct_as_record=False, squeeze_me=True)\n return _check_keys(data)\n\ndef _check_keys(dict):\n '''\n checks if entries in dictionary are mat-objects. If yes\n todict is called to change them to nested dictionaries\n '''\n for key in dict:\n if isinstance(dict[key], spio.matlab.mio5_params.mat_struct):\n dict[key] = _todict(dict[key])\n return dict \n\ndef _todict(matobj):\n '''\n A recursive function which constructs from matobjects nested dictionaries\n '''\n dict = {}\n for strg in matobj._fieldnames:\n elem = matobj.__dict__[strg]\n if isinstance(elem, spio.matlab.mio5_params.mat_struct):\n dict[strg] = _todict(elem)\n else:\n dict[strg] = elem\n return dict\n\"\"\")\ncode_cell = nbf.v4.new_code_cell(source=source_1)\nnb.cells.append(code_cell)", "_____no_output_____" ], [ "#print personal data\ntext = \"\"\"\n# Personal data \"\"\"\nmarkdown_cell = nbf.v4.new_markdown_cell(text)\nnb.cells.append(markdown_cell)\n\nsource_1 = textwrap.dedent(\"\"\" \n#load file \nhome = expanduser(\"~\")\npth = home + '/.local/share/yarp/contexts/motionAnalyzer'\nfiles = glob.glob(os.path.join(pth, '*.mat'))\nlastfile = max(files, key=os.path.getctime)\nprint lastfile\n\n#print personal data\ni = [pos for pos, char in enumerate(lastfile) if char == \"-\"]\ni1 = i[-3]\ni2 = i[-2]\nname = lastfile[i1+1:i2]\nsurname = \"\"\nage = \"\"\n\npersonaldata = []\npersonaldata.append(name)\npersonaldata.append(surname)\npersonaldata.append(age) \ntable = pd.DataFrame(personaldata) \ntable.rename(index={0:\"Name\",1:\"Surname\",2:\"Age\"}, columns={0:\"Patient\"}, inplace=True)\ndisplay(table) \"\"\")\ncode_cell = nbf.v4.new_code_cell(source=source_1)\nnb.cells.append(code_cell)", "_____no_output_____" ], [ "#we load all the files with the same user name\nsource_1 = textwrap.dedent(\"\"\" \ndata = []\nctime = []\nfilename = []\ntagex = []\nfiles.sort(key=os.path.getctime)\nfor fi in files:\n i = [pos for pos, char in enumerate(fi) if char == \"-\"]\n i1 = i[-3]\n i2 = i[-2]\n i3 = i[-1]\n namei = fi[i1+1:i2]\n if namei == name:\n filename.append(fi)\n data.append(loadmat(fi)) #data.append(scipy.io.loadmat(fi))\n tagex.append(fi[i2+1:i3])\n ctime.append(os.path.getctime(fi)) \"\"\")\ncode_cell = nbf.v4.new_code_cell(source=source_1)\nnb.cells.append(code_cell)", "_____no_output_____" ], [ "#define keypoints\nsource_1 = textwrap.dedent(\"\"\"\\\ntime = []\nmonth = []\nexercises = []\nex_names = []\n#count how many exercise of the same type were performed at that month\ncountexmonth = {\n \"tug\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"abduction_left\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"internal_rotation_left\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"external_rotation_left\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"reaching_left\" : [0,0,0,0,0,0,0,0,0,0,0,0]\n}\n\nfor i in range(len(data)):\n\n datai = data[i]\n time.append(datai['Time_samples'])\n monthi = datetime.date.fromtimestamp(ctime[i]).month-1\n month.append(monthi)\n shoulderCenter = datai['Keypoints']['shoulderCenter']\n head = datai['Keypoints']['head']\n shoulderLeft = datai['Keypoints']['shoulderLeft']\n shoulderRight = datai['Keypoints']['shoulderRight']\n elbowLeft = datai['Keypoints']['elbowLeft']\n handLeft = datai['Keypoints']['handLeft']\n elbowRight = datai['Keypoints']['elbowRight']\n handRight = datai['Keypoints']['handRight']\n hipLeft = datai['Keypoints']['hipLeft']\n hipRight = datai['Keypoints']['hipRight']\n ankleLeft = datai['Keypoints']['ankleLeft']\n ankleRight = datai['Keypoints']['ankleRight']\n kneeLeft = datai['Keypoints']['kneeLeft']\n kneeRight = datai['Keypoints']['kneeRight']\n footLeft = datai['Keypoints']['footLeft']\n footRight = datai['Keypoints']['footRight']\n hipCenter = datai['Keypoints']['hipCenter']\n \n key_pam = {\n \"shoulderCenter\" : shoulderCenter,\n \"head\" : head,\n \"shoulderLeft\" : shoulderLeft,\n \"shoulderRight\" : shoulderRight,\n \"elbowLeft\" : elbowLeft,\n \"handLeft\" : handLeft,\n \"elbowRight\" : elbowRight,\n \"handRight\" : handRight,\n \"hipLeft\" : hipLeft,\n \"hipRight\" : hipRight,\n \"ankleLeft\" : ankleLeft,\n \"ankleRight\" : ankleRight,\n \"kneeLeft\" : kneeLeft,\n \"kneeRight\" : kneeRight,\n \"footLeft\" : footLeft,\n \"footRight\" : footRight,\n \"hipCenter\" : hipCenter\n }\n s=Skeleton(key_pam)\n #s.show()\n \n exname = datai[\"Exercise\"][\"name\"]\n exname = re.sub(r'[^\\w]','',exname)\n ex_names.append(exname)\n result_singleexercise = []\n allmet = datai[\"Exercise\"][\"metrics\"]\n metrics = allmet.keys()\n for j in range(len(metrics)):\n metname = metrics[j]\n if \"ROM\" in metname:\n tagjoint = allmet[metname][\"tag_joint\"]\n tagjoint = re.sub(r'[^\\w]', '',tagjoint)\n refjoint = allmet[metname][\"ref_joint\"]\n refjoint = re.sub(r'[^\\w]', '',refjoint)\n if type(refjoint) is np.ndarray:\n refjoint = \"\"\n refdir = allmet[metname][\"ref_dir\"]\n tagplane = allmet[metname][\"tag_plane\"]\n tagplane = re.sub(r'[^\\w]', '',tagplane)\n rom = Rom(tagjoint,refjoint,refdir,tagplane)\n result_singleexercise.append((rom,rom.compute(s)))\n\n if \"step\" in metname:\n num = allmet[metname][\"num\"]\n den = allmet[metname][\"den\"]\n tstart = allmet[metname][\"tstart\"]\n tend = allmet[metname][\"tend\"]\n step = Step(num,den,tstart,tend)\n step.compute(s)\n stepmet = [step.steplen,step.nsteps,step.cadence,step.speed,step.ex_time,\n step.filtered_distfeet,step.strikes]\n result_singleexercise.append((step,stepmet))\n\n if \"EP\" in metname:\n tagjoint = allmet[metname][\"tag_joint\"]\n tagjoint = re.sub(r'[^\\w]', '',tagjoint)\n refdir = allmet[metname][\"ref_dir\"]\n tagplane = allmet[metname][\"tag_plane\"]\n tagplane = re.sub(r'[^\\w]', '',tagplane)\n target = allmet[metname][\"target\"]\n tstart = allmet[metname][\"tstart\"]\n tend = allmet[metname][\"tend\"]\n ep = EndPoint(tagjoint,refdir,tagplane,target,tstart,tend)\n ep.compute(s)\n result_singleexercise.append((ep,ep.trajectories))\n\n if exname == \"tug\":\n ex = Tug(monthi,result_singleexercise)\n if \"abduction\" in exname:\n ex = Abduction(exname,monthi,result_singleexercise)\n if \"internal_rotation\" in exname:\n ex = Internal_Rotation(exname,monthi,result_singleexercise)\n if \"external_rotation\" in exname:\n ex = External_Rotation(exname,monthi,result_singleexercise)\n if \"reaching\" in exname:\n ex = Reaching(exname,monthi,result_singleexercise)\n\n countexmonth[exname][monthi] = 1 + countexmonth[exname][monthi]\n \n exercises.append(ex) \n \"\"\")\ncode_cell = nbf.v4.new_code_cell(source=source_1)\nnb.cells.append(code_cell)", "_____no_output_____" ], [ "#print information about the performed movement and the evaluated metric\ntext = \"\"\" \n# Daily session report\nThe patient did the following exercise: \"\"\"\nmarkdown_cell = nbf.v4.new_markdown_cell(text)\nnb.cells.append(markdown_cell)\n\nsource_1 = textwrap.dedent(\"\"\" \nprint exname.encode('ascii') \"\"\")\ncode_cell = nbf.v4.new_code_cell(source=source_1)\nnb.cells.append(code_cell)\n\ntext = \"\"\" \non: \"\"\"\nmarkdown_cell = nbf.v4.new_markdown_cell(text)\nnb.cells.append(markdown_cell)\n\nsource_1 = textwrap.dedent(\"\"\" \nnow = datetime.datetime.now()\nprint now \"\"\")\ncode_cell = nbf.v4.new_code_cell(source=source_1)\nnb.cells.append(code_cell)", "_____no_output_____" ], [ "#plot the metrics for each session\ntext = \"\"\" \nThe following shows the metric trend during the exercise:\"\"\"\nmarkdown_cell = nbf.v4.new_markdown_cell(text)\nnb.cells.append(markdown_cell)\n\nsource_1 = textwrap.dedent(\"\"\"\\\nlastsess_time = time[-1]\nlastsess_result = exercises[-1].result\nlastsess_res_step = []\n\n%matplotlib inline\n%matplotlib inline\nfor i in range(len(lastsess_result)):\n lastsess_met,lastsess_resi = lastsess_result[i]\n lastsess_metname = lastsess_met.name\n ################\n # ROM #\n ################\n if lastsess_metname == \"ROM\":\n lastsess_metjoint = lastsess_met.tagjoint\n trace1 = go.Scatter(\n x=lastsess_time,y=lastsess_resi,\n mode='lines',\n line=dict(\n color='blue',\n width=3\n ),\n name='Real trend'\n )\n data = [trace1]\n layout = dict(\n width=750,\n height=600,\n autosize=False,\n title='Range of Motion '+lastsess_metjoint,\n font=dict(family='Courier New, monospace', size=22, color='black'),\n xaxis=dict(\n title='time [s]',\n titlefont=dict(\n family='Courier New, monospace',\n size=18,\n color='#7f7f7f'\n )\n ),\n yaxis=dict(\n title='ROM [degrees]',\n titlefont=dict(\n family='Courier New, monospace',\n size=18,\n color='#7f7f7f'\n )\n )\n )\n fig = dict(data=data, layout=layout)\n iplot(fig)\n \n ################\n # STEP #\n ################\n if lastsess_metname == \"step\":\n dist=lastsess_resi[5]\n strikes=lastsess_resi[6]\n trace1 = go.Scatter(\n x=lastsess_time,y=dist,\n mode='lines',\n line=dict(\n color='blue',\n width=3\n ),\n name='Feet distance'\n )\n trace2 = go.Scatter(\n x=lastsess_time[strikes],y=dist[strikes],\n mode='markers',\n marker=dict(\n color='red',\n size=10\n ),\n name='Heel strikes'\n )\n data = [trace1,trace2]\n layout = dict(\n width=750,\n height=600,\n autosize=False,\n title='Feet distance',\n font=dict(family='Courier New, monospace', size=22, color='black'),\n xaxis=dict(\n title='time [s]',\n titlefont=dict(\n family='Courier New, monospace',\n size=18,\n color='#7f7f7f'\n )\n ),\n yaxis=dict(\n title='dist [m]',\n titlefont=dict(\n family='Courier New, monospace',\n size=18,\n color='#7f7f7f'\n )\n )\n )\n fig = dict(data=data, layout=layout)\n iplot(fig)\n \n lastsess_res_step.append(lastsess_resi)\n tablestep = pd.DataFrame(lastsess_res_step[0][0:4])\n tablestep.rename(index={0:\"Step length [m]\",1:\"Number of steps\",2:\"Cadence [steps/s]\",\n 3:\"Speed [m/s]\",4:\"Execution time [s]\"},\n columns={0:\"Gait analysis\"}, inplace=True)\n display(tablestep)\n \n ################\n # EP #\n ################\n if lastsess_metname == \"EP\":\n target = lastsess_met.target\n trace1 = go.Scatter3d(\n x=lastsess_resi[:,0], y=lastsess_resi[:,1], z=lastsess_resi[:,2],\n mode = 'lines',\n line=dict(\n color='blue',\n width=3\n ),\n name = 'Trajectories'\n )\n trace2 = go.Scatter3d(\n x=[target[0]], y=[target[1]], z=[target[2]],\n mode = 'markers',\n marker=dict(\n color='red',\n size=5\n ),\n name = 'Target to reach'\n )\n data = [trace1, trace2] \n layout = dict(\n margin=dict(\n l=0,\n r=0,\n b=0\n ),\n title='End-point trajectories',\n font=dict(family='Courier New, monospace', size=22, color='black'),\n scene=dict(\n xaxis=dict(\n title='x [cm]',\n titlefont=dict(\n family='Courier New, monospace',\n size=18,\n color='#7f7f7f'\n ),\n tickfont=dict(\n family='Courier New, monospace',\n size=14,\n color='#7f7f7f'\n ),\n gridcolor='rgb(255, 255, 255)',\n zerolinecolor='rgb(255, 255, 255)',\n showbackground=True,\n backgroundcolor='rgb(230, 230,230)'\n ),\n yaxis=dict(\n title='y [cm]',\n titlefont=dict(\n family='Courier New, monospace',\n size=18,\n color='#7f7f7f'\n ),\n tickfont=dict(\n family='Courier New, monospace',\n size=14,\n color='#7f7f7f'\n ),\n gridcolor='rgb(255, 255, 255)',\n zerolinecolor='rgb(255, 255, 255)',\n showbackground=True,\n backgroundcolor='rgb(230, 230,230)'\n ),\n zaxis=dict(\n title='z [cm]',\n titlefont=dict(\n family='Courier New, monospace',\n size=18,\n color='#7f7f7f'\n ),\n tickfont=dict(\n family='Courier New, monospace',\n size=14,\n color='#7f7f7f'\n ),\n gridcolor='rgb(255, 255, 255)',\n zerolinecolor='rgb(255, 255, 255)',\n showbackground=True,\n backgroundcolor='rgb(230, 230,230)'\n ),\n camera=dict(\n up=dict(\n x=0,\n y=0,\n z=1\n ),\n eye=dict(\n x=-1.7428,\n y=1.0707,\n z=0.7100,\n )\n ),\n aspectratio = dict( x=1, y=1, z=0.7 ),\n aspectmode = 'manual'\n ),\n )\n fig = dict(data=data, layout=layout)\n iplot(fig)\n \"\"\")\n\ncode_cell = nbf.v4.new_code_cell(source=source_1)\nnb.cells.append(code_cell)", "_____no_output_____" ], [ "source_1 = textwrap.dedent(\"\"\"\\\nif exname == 'tug':\n \n table_tug = pd.DataFrame([['Normal mobility'],['Good mobility'],['Gait aids'],['Falling risk']],\n index=['< 10 s','< 20 s','< 30 s','>= 30 s'],\n columns=['TUG Table'])\n display(table_tug)\n \n time_score = lastsess_res_step[0][4]\n print \"The test has been done in\",round(time_score,2),\"s\"\n if time_score < 10:\n evaluation = 'Normal mobility'\n print \"The evaluation is \\033[1;30;42m\",evaluation\n elif time_score < 20:\n evaluation = 'Good mobility, no need for gait aids'\n print \"The evaluation is \\033[1;30;42m\",evaluation\n elif time_score < 30:\n evaluation = 'Need for gait aids'\n print \"The evaluation is \\033[1;30;43m\",evaluation\n elif time_score >= 30:\n evaluation = 'Falling risk'\n print \"The evaluation is \\033[1;30;41m\",evaluation\n \"\"\")\n\ncode_cell = nbf.v4.new_code_cell(source=source_1)\nnb.cells.append(code_cell)", "_____no_output_____" ], [ "#report about patient's improvements\ntext = \"\"\" \n# Patient progress\"\"\"\nmarkdown_cell = nbf.v4.new_markdown_cell(text)\nnb.cells.append(markdown_cell)\n\ntext = \"\"\" \nThe exercises performed by the patient during the months under analysis are grouped as following:\"\"\"\nmarkdown_cell = nbf.v4.new_markdown_cell(text)\nnb.cells.append(markdown_cell)\n\nsource_1 = textwrap.dedent(\"\"\"\\\nlabels = [\"reaching_left\",\"abduction_left\",\"internal-rotation_left\",\"external-rotation_left\",\"timed-up-and-go\"]\nvalues = [tagex.count(\"reaching_left\"), tagex.count(\"abduction_left\"), tagex.count(\"internal_rotation_left\"), \n tagex.count(\"external_rotation_left\"), tagex.count(\"tug\")]\ncolors = ['#FEBFB3', '#E1396C', '#96D38C', '#D0F9B1']\n\ntrace = go.Pie(labels=labels, values=values,\n #hoverinfo='label+percent', textinfo='value', \n textfont=dict(size=20),\n marker=dict(colors=colors, \n line=dict(color='#000000', width=2)),\n hoverinfo=\"label+percent+value\",\n hole=0.3\n )\nlayout = go.Layout(\n title=\"Performed exercises\",\n)\ndata = [trace]\nfig = go.Figure(data=data,layout=layout)\niplot(fig) \"\"\")\n\ncode_cell = nbf.v4.new_code_cell(source=source_1)\nnb.cells.append(code_cell)\n\ntext = \"\"\" \nThe trends of the patient metrics, grouped by month, are shown here: \"\"\"\nmarkdown_cell = nbf.v4.new_markdown_cell(text)\nnb.cells.append(markdown_cell)\n\nsource_1 = textwrap.dedent(\"\"\"\\\nkeyp2rommax = {\n \"shoulderCenter\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"head\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"shoulderLeft\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"elbowLeft\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"handLeft\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"shoulderRight\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"elbowRight\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"handRight\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"hipCenter\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"hipLeft\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"kneeLeft\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"ankleLeft\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"footLeft\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"hipRight\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"kneeRight\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"ankleRight\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"footRight\" : [0,0,0,0,0,0,0,0,0,0,0,0]\n}\nkeyp2rommin = {\n \"shoulderCenter\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"head\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"shoulderLeft\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"elbowLeft\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"handLeft\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"shoulderRight\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"elbowRight\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"handRight\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"hipCenter\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"hipLeft\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"kneeLeft\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"ankleLeft\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"footLeft\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"hipRight\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"kneeRight\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"ankleRight\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"footRight\" : [0,0,0,0,0,0,0,0,0,0,0,0]\n}\ncountrommonth = {\n \"shoulderCenter\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"head\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"shoulderLeft\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"elbowLeft\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"handLeft\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"shoulderRight\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"elbowRight\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"handRight\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"hipCenter\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"hipLeft\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"kneeLeft\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"ankleLeft\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"footLeft\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"hipRight\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"kneeRight\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"ankleRight\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"footRight\" : [0,0,0,0,0,0,0,0,0,0,0,0]\n}\nkeyp2rommax_avg = {\n \"shoulderCenter\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"head\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"shoulderLeft\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"elbowLeft\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"handLeft\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"shoulderRight\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"elbowRight\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"handRight\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"hipCenter\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"hipLeft\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"kneeLeft\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"ankleLeft\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"footLeft\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"hipRight\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"kneeRight\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"ankleRight\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"footRight\" : [0,0,0,0,0,0,0,0,0,0,0,0]\n}\nkeyp2rommin_avg = {\n \"shoulderCenter\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"head\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"shoulderLeft\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"elbowLeft\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"handLeft\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"shoulderRight\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"elbowRight\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"handRight\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"hipCenter\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"hipLeft\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"kneeLeft\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"ankleLeft\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"footLeft\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"hipRight\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"kneeRight\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"ankleRight\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"footRight\" : [0,0,0,0,0,0,0,0,0,0,0,0]\n}\n\nstepmonth = {\n \"steplen\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"numsteps\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"cadence\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"speed\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"time\" : [0,0,0,0,0,0,0,0,0,0,0,0]\n}\ncountstepmonth = [0,0,0,0,0,0,0,0,0,0,0,0]\n\nendpointmonth = {\n \"time\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"speed\" : [0,0,0,0,0,0,0,0,0,0,0,0]\n}\ncountendpointmonth = [0,0,0,0,0,0,0,0,0,0,0,0]\n\nfor i in range(len(exercises)):\n exnamei = exercises[i].name\n for monthi in range(12):\n if countexmonth[exnamei][monthi] != 0:\n res_exi = exercises[i].getResult(monthi)\n for m in range(len(res_exi)): \n single_metric,result_single_metric = res_exi[m]\n single_metric_name = single_metric.name\n if single_metric_name == \"ROM\":\n maxromj = max(result_single_metric)\n minromj = min(result_single_metric)\n tagjoint = single_metric.tagjoint\n keyp2rommax[tagjoint][monthi] = maxromj + keyp2rommax[tagjoint][monthi]\n keyp2rommin[tagjoint][monthi] = minromj + keyp2rommin[tagjoint][monthi]\n countrommonth[tagjoint][monthi] = 1 + countrommonth[tagjoint][monthi] \n\n if single_metric_name == \"step\":\n stepmonth[\"steplen\"][monthi] = single_metric.steplen + stepmonth[\"steplen\"][monthi]\n stepmonth[\"numsteps\"][monthi] = single_metric.nsteps + stepmonth[\"numsteps\"][monthi]\n stepmonth[\"cadence\"][monthi] = single_metric.cadence + stepmonth[\"cadence\"][monthi]\n stepmonth[\"speed\"][monthi] = single_metric.speed + stepmonth[\"speed\"][monthi]\n stepmonth[\"time\"][monthi] = single_metric.ex_time + stepmonth[\"time\"][monthi]\n countstepmonth[monthi] = 1 + countstepmonth[monthi]\n \n if single_metric_name == \"EP\":\n endpointmonth[\"time\"][monthi] = single_metric.ex_time + endpointmonth[\"time\"][monthi]\n endpointmonth[\"speed\"][monthi] = single_metric.speed + endpointmonth[\"speed\"][monthi]\n countendpointmonth[monthi] = 1 + countendpointmonth[monthi]\n \n \"\"\")\n\ncode_cell = nbf.v4.new_code_cell(source=source_1)\nnb.cells.append(code_cell)", "_____no_output_____" ], [ "source_1 = textwrap.dedent(\"\"\"\\\ncounted_exmonth = {\n \"tug\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"abduction_left\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"internal_rotation_left\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"external_rotation_left\" : [0,0,0,0,0,0,0,0,0,0,0,0],\n \"reaching_left\" : [0,0,0,0,0,0,0,0,0,0,0,0]\n}\nfor i in range(len(exercises)):\n exnamei = exercises[i].name\n \n for monthi in range(12): \n if countexmonth[exnamei][monthi] != 0:\n if counted_exmonth[exnamei][monthi] < 1: \n res_exi = exercises[i].getResult(monthi)\n for m in range(len(res_exi)): \n single_metric,result_single_metric = res_exi[m]\n single_metric_name = single_metric.name\n\n if single_metric_name == \"ROM\":\n tagjoint = single_metric.tagjoint\n if countrommonth[tagjoint][monthi] != 0:\n keyp2rommax_avg[tagjoint][monthi] = keyp2rommax[tagjoint][monthi]/countrommonth[tagjoint][monthi]\n keyp2rommin_avg[tagjoint][monthi] = keyp2rommin[tagjoint][monthi]/countrommonth[tagjoint][monthi]\n \n \n if single_metric_name == \"step\":\n if countstepmonth[monthi] != 0:\n stepmonth[\"steplen\"][monthi] = stepmonth[\"steplen\"][monthi]/countstepmonth[monthi]\n stepmonth[\"numsteps\"][monthi] = stepmonth[\"numsteps\"][monthi]/countstepmonth[monthi]\n stepmonth[\"cadence\"][monthi] = stepmonth[\"cadence\"][monthi]/countstepmonth[monthi]\n stepmonth[\"speed\"][monthi] = stepmonth[\"speed\"][monthi]/countstepmonth[monthi]\n stepmonth[\"time\"][monthi] = stepmonth[\"time\"][monthi]/countstepmonth[monthi] \n \n if single_metric_name == \"EP\":\n if countendpointmonth[monthi] != 0:\n endpointmonth[\"time\"][monthi] = endpointmonth[\"time\"][monthi]/countendpointmonth[monthi]\n endpointmonth[\"speed\"][monthi] = endpointmonth[\"speed\"][monthi]/countendpointmonth[monthi]\n\n counted_exmonth[exnamei][monthi] = 1\n \n \"\"\")\n\ncode_cell = nbf.v4.new_code_cell(source=source_1)\nnb.cells.append(code_cell)", "_____no_output_____" ], [ "source_1 = textwrap.dedent(\"\"\"\\\ntitle = \"Results for Timed Up and Go\"\nmsg1 = HTML('<font size=5><b>'+title+'</b></font>')\nmsg2 = HTML('<font size=5,font color=gray,font >'+title+'</font>')\nif sum(counted_exmonth['tug'])>0:\n display(msg1);\nelse:\n display(msg2); \"\"\")\n\ncode_cell = nbf.v4.new_code_cell(source=source_1)\nnb.cells.append(code_cell)", "_____no_output_____" ], [ "source_1 = textwrap.dedent(\"\"\"\\\nallmonths = [1,2,3,4,5,6,7,8,9,10,11,12]\ncounted_ex = {\n \"tug\" : 0,\n \"abduction_left\" : 0,\n \"internal_rotation_left\" : 0,\n \"external_rotation_left\" : 0,\n \"reaching_left\" : 0\n}\nfor i in range(len(exercises)):\n exnamei = exercises[i].name\n res_exi = exercises[i].result\n if counted_ex[exnamei] < 1:\n\n #############################\n # Results for TUG #\n #############################\n if exnamei == \"tug\":\n counted_ex[exnamei] = 1\n step_month_table = pd.DataFrame.from_dict(stepmonth,orient='index',\n columns=['Jan','Feb','Mar','Apr','May','Jun',\n 'Jul','Aug','Sep','Oct','Nov','Dec'])\n step_month_table.index = [\"Number steps\",\"Speed [m/s]\",\"Step length [m]\",\n \"Cadence [steps/s]\",\"Execution time [s]\"]\n display(step_month_table)\n\n for m in range(len(res_exi)): \n single_metric,result_single_metric = res_exi[m]\n if single_metric.name == \"ROM\":\n tagjoint = single_metric.tagjoint\n\n if np.sum(keyp2rommax_avg[tagjoint]) > 0.0:\n trace1 = go.Bar(\n x=allmonths, \n y=keyp2rommax_avg[tagjoint],\n name='Maximum value reached',\n marker=dict(\n color='rgb(0,0,255)'\n )\n )\n trace2 = go.Bar(\n x=allmonths, \n y=keyp2rommin_avg[tagjoint],\n name='Minimum value reached',\n marker=dict(\n color='rgb(255,0,0)'\n )\n )\n layout = go.Layout(\n title='Range of Motion Parameters',\n font=dict(family='Courier New, monospace', size=18, color='black'),\n xaxis=dict(\n title='Month',\n titlefont=dict(\n family='Courier New, monospace',\n size=18,\n color='#7f7f7f'\n ),\n tickfont=dict(\n family='Courier New, monospace',\n size=14,\n color='#7f7f7f'\n )\n ),\n yaxis=dict(\n title='ROM ' + tagjoint + ' [degrees]',\n titlefont=dict(\n family='Courier New, monospace',\n size=18,\n color='#7f7f7f'\n ),\n tickfont=dict(\n family='Courier New, monospace',\n size=14,\n color='#7f7f7f'\n )\n ),\n legend=dict(\n bgcolor='rgba(255, 255, 255, 0)',\n bordercolor='rgba(255, 255, 255, 0)'\n ),\n barmode='group',\n bargap=0.1,\n bargroupgap=0.0\n )\n data=[trace1,trace2]\n fig = go.Figure(data=data, layout=layout)\n iplot(fig) \"\"\")\n\ncode_cell = nbf.v4.new_code_cell(source=source_1)\nnb.cells.append(code_cell)", "_____no_output_____" ], [ "source_1 = textwrap.dedent(\"\"\"\\\ntitle = \"Results for Abduction\"\nmsg1 = HTML('<font size=5><b>'+title+'</b></font>')\nmsg2 = HTML('<font size=5,font color=gray>'+title+'</font>')\nif sum(counted_exmonth['abduction_left'])>0:\n display(msg1);\nelse:\n display(msg2); \"\"\")\n\ncode_cell = nbf.v4.new_code_cell(source=source_1)\nnb.cells.append(code_cell)", "_____no_output_____" ], [ "source_1 = textwrap.dedent(\"\"\"\\\nfor i in range(len(exercises)):\n exnamei = exercises[i].name\n res_exi = exercises[i].result\n if counted_ex[exnamei] < 1:\n \n ###################################\n # Results for Abduction #\n ###################################\n if \"abduction\" in exnamei:\n counted_ex[exnamei] = 1 \n\n for m in range(len(res_exi)): \n single_metric,result_single_metric = res_exi[m]\n if single_metric.name == \"ROM\":\n tagjoint = single_metric.tagjoint\n\n if np.sum(keyp2rommax_avg[tagjoint]) > 0.0:\n trace1 = go.Bar(\n x=allmonths, \n y=keyp2rommax_avg[tagjoint],\n name='Maximum value reached',\n marker=dict(\n color='rgb(0,0,255)'\n )\n )\n trace2 = go.Bar(\n x=allmonths, \n y=keyp2rommin_avg[tagjoint],\n name='Minimum value reached',\n marker=dict(\n color='rgb(255,0,0)'\n )\n )\n layout = go.Layout(\n title='Range of Motion Parameters',\n font=dict(family='Courier New, monospace', size=18, color='black'),\n xaxis=dict(\n title='Month',\n titlefont=dict(\n family='Courier New, monospace',\n size=18,\n color='#7f7f7f'\n ),\n tickfont=dict(\n family='Courier New, monospace',\n size=14,\n color='#7f7f7f'\n )\n ),\n yaxis=dict(\n title='ROM ' + tagjoint + ' [degrees]',\n titlefont=dict(\n family='Courier New, monospace',\n size=18,\n color='#7f7f7f'\n ),\n tickfont=dict(\n family='Courier New, monospace',\n size=14,\n color='#7f7f7f'\n )\n ),\n legend=dict(\n bgcolor='rgba(255, 255, 255, 0)',\n bordercolor='rgba(255, 255, 255, 0)'\n ),\n barmode='group',\n bargap=0.1,\n bargroupgap=0.0\n )\n data=[trace1,trace2]\n fig = go.Figure(data=data, layout=layout)\n iplot(fig) \"\"\")\n\ncode_cell = nbf.v4.new_code_cell(source=source_1)\nnb.cells.append(code_cell)", "_____no_output_____" ], [ "source_1 = textwrap.dedent(\"\"\"\\\ntitle = \"Results for Internal Rotation\"\nmsg1 = HTML('<font size=5><b>'+title+'</b></font>')\nmsg2 = HTML('<font size=5,font color=gray>'+title+'</font>')\nif sum(counted_exmonth['internal_rotation_left'])>0:\n display(msg1);\nelse:\n display(msg2); \"\"\")\n\ncode_cell = nbf.v4.new_code_cell(source=source_1)\nnb.cells.append(code_cell)", "_____no_output_____" ], [ "source_1 = textwrap.dedent(\"\"\"\\\nfor i in range(len(exercises)):\n exnamei = exercises[i].name\n res_exi = exercises[i].result\n if counted_ex[exnamei] < 1:\n \n ###################################\n # Results for Internal #\n ###################################\n if \"internal_rotation\" in exnamei:\n counted_ex[exnamei] = 1 \n\n for m in range(len(res_exi)): \n single_metric,result_single_metric = res_exi[m]\n if single_metric.name == \"ROM\":\n tagjoint = single_metric.tagjoint\n\n if np.sum(keyp2rommax_avg[tagjoint]) > 0.0:\n trace1 = go.Bar(\n x=allmonths, \n y=keyp2rommax_avg[tagjoint],\n name='Maximum value reached',\n marker=dict(\n color='rgb(0,0,255)'\n )\n )\n trace2 = go.Bar(\n x=allmonths, \n y=keyp2rommin_avg[tagjoint],\n name='Minimum value reached',\n marker=dict(\n color='rgb(255,0,0)'\n )\n )\n layout = go.Layout(\n title='Range of Motion Parameters',\n font=dict(family='Courier New, monospace', size=18, color='black'),\n xaxis=dict(\n title='Month',\n titlefont=dict(\n family='Courier New, monospace',\n size=18,\n color='#7f7f7f'\n ),\n tickfont=dict(\n family='Courier New, monospace',\n size=14,\n color='#7f7f7f'\n )\n ),\n yaxis=dict(\n title='ROM ' + tagjoint + ' [degrees]',\n titlefont=dict(\n family='Courier New, monospace',\n size=18,\n color='#7f7f7f'\n ),\n tickfont=dict(\n family='Courier New, monospace',\n size=14,\n color='#7f7f7f'\n )\n ),\n legend=dict(\n bgcolor='rgba(255, 255, 255, 0)',\n bordercolor='rgba(255, 255, 255, 0)'\n ),\n barmode='group',\n bargap=0.1,\n bargroupgap=0.0\n )\n data=[trace1,trace2]\n fig = go.Figure(data=data, layout=layout)\n iplot(fig) \"\"\")\n\ncode_cell = nbf.v4.new_code_cell(source=source_1)\nnb.cells.append(code_cell)", "_____no_output_____" ], [ "source_1 = textwrap.dedent(\"\"\"\\\ntitle = \"Results for External Rotation\"\nmsg1 = HTML('<font size=5><b>'+title+'</b></font>')\nmsg2 = HTML('<font size=5,font color=gray>'+title+'</font>')\nif sum(counted_exmonth['external_rotation_left'])>0:\n display(msg1);\nelse:\n display(msg2); \"\"\")\n\ncode_cell = nbf.v4.new_code_cell(source=source_1)\nnb.cells.append(code_cell)", "_____no_output_____" ], [ "source_1 = textwrap.dedent(\"\"\"\\\nfor i in range(len(exercises)):\n exnamei = exercises[i].name\n res_exi = exercises[i].result\n if counted_ex[exnamei] < 1:\n \n ###################################\n # Results for External #\n ###################################\n if \"external_rotation\" in exnamei:\n counted_ex[exnamei] = 1 \n\n for m in range(len(res_exi)): \n single_metric,result_single_metric = res_exi[m]\n if single_metric.name == \"ROM\":\n tagjoint = single_metric.tagjoint\n\n if np.sum(keyp2rommax_avg[tagjoint]) > 0.0:\n trace1 = go.Bar(\n x=allmonths, \n y=keyp2rommax_avg[tagjoint],\n name='Maximum value reached',\n marker=dict(\n color='rgb(0,0,255)'\n )\n )\n trace2 = go.Bar(\n x=allmonths, \n y=keyp2rommin_avg[tagjoint],\n name='Minimum value reached',\n marker=dict(\n color='rgb(255,0,0)'\n )\n )\n layout = go.Layout(\n title='Range of Motion Parameters',\n font=dict(family='Courier New, monospace', size=18, color='black'),\n xaxis=dict(\n title='Month',\n titlefont=dict(\n family='Courier New, monospace',\n size=18,\n color='#7f7f7f'\n ),\n tickfont=dict(\n family='Courier New, monospace',\n size=14,\n color='#7f7f7f'\n )\n ),\n yaxis=dict(\n title='ROM ' + tagjoint + ' [degrees]',\n titlefont=dict(\n family='Courier New, monospace',\n size=18,\n color='#7f7f7f'\n ),\n tickfont=dict(\n family='Courier New, monospace',\n size=14,\n color='#7f7f7f'\n )\n ),\n legend=dict(\n bgcolor='rgba(255, 255, 255, 0)',\n bordercolor='rgba(255, 255, 255, 0)'\n ),\n barmode='group',\n bargap=0.1,\n bargroupgap=0.0\n )\n data=[trace1,trace2]\n fig = go.Figure(data=data, layout=layout)\n iplot(fig) \"\"\")\n\ncode_cell = nbf.v4.new_code_cell(source=source_1)\nnb.cells.append(code_cell)", "_____no_output_____" ], [ "source_1 = textwrap.dedent(\"\"\"\\\ntitle = \"Results for Reaching\"\nmsg1 = HTML('<font size=5><b>'+title+'</b></font>')\nmsg2 = HTML('<font size=5,font color=gray>'+title+'</font>')\nif sum(counted_exmonth['reaching_left'])>0:\n display(msg1);\nelse:\n display(msg2); \"\"\")\n\ncode_cell = nbf.v4.new_code_cell(source=source_1)\nnb.cells.append(code_cell)", "_____no_output_____" ], [ "source_1 = textwrap.dedent(\"\"\"\\\nfor i in range(len(exercises)):\n exnamei = exercises[i].name\n res_exi = exercises[i].result\n if counted_ex[exnamei] < 1:\n \n ###################################\n # Results for Reaching #\n ###################################\n if \"reaching\" in exnamei:\n counted_ex[exnamei] = 1 \n\n for m in range(len(res_exi)): \n single_metric,result_single_metric = res_exi[m]\n if single_metric.name == \"EP\":\n trace1 = go.Bar(\n x=allmonths, \n y=endpointmonth[\"time\"],\n name='Time',\n marker=dict(\n color='rgb(0,0,255)'\n )\n )\n layout = go.Layout(\n title='Reaching parameters',\n font=dict(family='Courier New, monospace', size=18, color='black'),\n xaxis=dict(\n title='Month',\n titlefont=dict(\n family='Courier New, monospace',\n size=18,\n color='#7f7f7f'\n ),\n tickfont=dict(\n family='Courier New, monospace',\n size=14,\n color='#7f7f7f'\n )\n ),\n yaxis=dict(\n title='Execution time [s]',\n titlefont=dict(\n family='Courier New, monospace',\n size=18,\n color='#7f7f7f'\n ),\n tickfont=dict(\n family='Courier New, monospace',\n size=14,\n color='#7f7f7f'\n )\n ),\n legend=dict(\n bgcolor='rgba(255, 255, 255, 0)',\n bordercolor='rgba(255, 255, 255, 0)'\n ),\n barmode='group',\n bargap=0.1,\n bargroupgap=0.0\n )\n data=[trace1]\n fig = go.Figure(data=data, layout=layout)\n iplot(fig) \n \n trace1 = go.Bar(\n x=allmonths, \n y=endpointmonth[\"speed\"],\n name='Speed',\n marker=dict(\n color='rgb(0,0,255)'\n )\n )\n layout = go.Layout(\n font=dict(family='Courier New, monospace', size=18, color='black'),\n xaxis=dict(\n title='Month',\n titlefont=dict(\n family='Courier New, monospace',\n size=18,\n color='#7f7f7f'\n ),\n tickfont=dict(\n family='Courier New, monospace',\n size=14,\n color='#7f7f7f'\n )\n ),\n yaxis=dict(\n title='Speed [m/s]',\n titlefont=dict(\n family='Courier New, monospace',\n size=18,\n color='#7f7f7f'\n ),\n tickfont=dict(\n family='Courier New, monospace',\n size=14,\n color='#7f7f7f'\n )\n ),\n legend=dict(\n bgcolor='rgba(255, 255, 255, 0)',\n bordercolor='rgba(255, 255, 255, 0)'\n ),\n barmode='group',\n bargap=0.1,\n bargroupgap=0.0\n )\n data=[trace1]\n fig = go.Figure(data=data, layout=layout)\n iplot(fig) \"\"\")\n\ncode_cell = nbf.v4.new_code_cell(source=source_1)\nnb.cells.append(code_cell)", "_____no_output_____" ], [ "nbf.write(nb, 'report-eng.ipynb')", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
4a0a757a175b58adcc1e6140d95914597e9cb56e
53,496
ipynb
Jupyter Notebook
python-api-examples/guide/static.ipynb
kozo2/projects
2b161b2956d90712f746d2cca4892e559a7e4fb8
[ "Apache-2.0" ]
44
2020-07-07T13:35:51.000Z
2022-03-25T21:45:43.000Z
python-api-examples/guide/static.ipynb
kozo2/projects
2b161b2956d90712f746d2cca4892e559a7e4fb8
[ "Apache-2.0" ]
20
2020-10-15T01:33:28.000Z
2022-03-18T14:43:16.000Z
python-api-examples/guide/static.ipynb
kozo2/projects
2b161b2956d90712f746d2cca4892e559a7e4fb8
[ "Apache-2.0" ]
4
2021-10-17T09:21:05.000Z
2022-02-06T22:38:50.000Z
30.378194
411
0.531329
[ [ [ "# Essential: Static file management with SourceLoader\n\nData pipelines usually interact with external systems such as SQL databases. Using relative paths to find such files is error-prone as the path to the file depends on the file loading it, on the other hand, absolute paths are to restrictive, the path will only work in your current environment but will break others. Combining `Env` with `SourceLoader` provides a clean approach for managing static files.", "_____no_output_____" ] ], [ [ "from pathlib import Path\n\nimport pandas as pd\nfrom sklearn import datasets\nfrom IPython.display import display, Markdown\n\nfrom ploomber import DAG, SourceLoader, with_env\nfrom ploomber.tasks import PythonCallable, NotebookRunner, SQLUpload, SQLScript\nfrom ploomber.products import File, SQLiteRelation\nfrom ploomber.clients import SQLAlchemyClient\nfrom ploomber.executors import Serial", "_____no_output_____" ], [ "# initialize a temporary directory\nimport tempfile\nimport os\ntmp_dir = Path(tempfile.mkdtemp())\ntmp_dir_static = tmp_dir / 'static'\ntmp_dir_static.mkdir()\nos.chdir(str(tmp_dir))", "_____no_output_____" ], [ "report_py = \"\"\"\n# static/report.py\n\n# +\n# This file is in jupytext light format\nimport seaborn as sns\nimport pandas as pd\n# -\n\n# + tags=['parameters']\n# papermill will add the parameters below this cell\nupstream = None\nproduct = None\n# -\n\n# +\npath = upstream['raw']\ndf = pd.read_parquet(path)\n# -\n\n# ## AGE distribution\n\n# +\n_ = sns.distplot(df.AGE)\n# -\n\n# ## Price distribution\n\n# +\n_ = sns.distplot(df.price)\n# -\n\"\"\"\n\nclean_table_sql = \"\"\"\n-- static/clean_table.sql\n\nDROP TABLE IF EXISTS {{product}};\n\nCREATE TABLE {{product}}\nAS SELECT * FROM {{upstream[\"raw_table\"]}}\nWHERE AGE < 100\n\"\"\"\n\nenv_yaml = \"\"\"\n_module: '{{here}}'\n\npath:\n data: '{{here}}/data/'\n static: '{{here}}/static/'\n\"\"\"\n\n(tmp_dir_static / 'report.py').write_text(report_py)\n(tmp_dir_static / 'clean_table.sql').write_text(clean_table_sql)\n(tmp_dir / 'env.yaml').write_text(env_yaml)\n\ndef display_file(file, syntax):\n s = \"\"\"\n```{}\n{}\n```\n\"\"\".format(syntax, file)\n return display(Markdown(s))", "_____no_output_____" ] ], [ [ "Our working environment has an `env.yaml` file with a `static/` folder holding a SQL and a Python script.", "_____no_output_____" ] ], [ [ "! tree $tmp_dir", "\u001b[01;34m/var/folders/3h/_lvh_w_x5g30rrjzb_xnn2j80000gq/T/tmpf8svp9hx\u001b[00m\n├── env.yaml\n└── \u001b[01;34mstatic\u001b[00m\n ├── clean_table.sql\n └── report.py\n\n1 directory, 3 files\n" ] ], [ [ "### Content of `env.yaml`", "_____no_output_____" ] ], [ [ "display_file(env_yaml, 'yaml')", "_____no_output_____" ] ], [ [ "### Content of `static/report.py`", "_____no_output_____" ] ], [ [ "display_file(report_py, 'python')", "_____no_output_____" ] ], [ [ "### Content of `static/create_table.sql`", "_____no_output_____" ] ], [ [ "display_file(clean_table_sql, 'sql')", "_____no_output_____" ] ], [ [ "### Pipeline declaration", "_____no_output_____" ] ], [ [ "def _get_data(product):\n data = datasets.load_boston()\n df = pd.DataFrame(data.data)\n df.columns = data.feature_names\n df['price'] = data.target\n df.to_parquet(str(product))\n\n\n@with_env\ndef make(env):\n # NOTE: passing the executor parameter is only required for testing purposes, can be removed\n dag = DAG(executor=Serial(build_in_subprocess=False))\n\n client = SQLAlchemyClient('sqlite:///my_db.db')\n dag.clients[SQLUpload] = client\n dag.clients[SQLiteRelation] = client\n dag.clients[SQLScript] = client\n\n # initialize SourceLoader in our static directory\n loader = SourceLoader(path=env.path.static)\n\n get_data = PythonCallable(_get_data,\n product=File(tmp_dir / 'raw.parquet'),\n dag=dag,\n name='raw')\n\n # if we do not pass a name, the filename will be used as default\n report = NotebookRunner(loader['report.py'],\n product=File(tmp_dir / 'report.html'),\n dag=dag,\n kernelspec_name='python3')\n\n raw_table = SQLUpload(source='{{upstream[\"raw\"]}}',\n product=SQLiteRelation(('raw', 'table')),\n dag=dag,\n name='raw_table')\n\n # same here, no need to pass a name\n clean_table = SQLScript(loader['clean_table.sql'],\n product=SQLiteRelation(('clean', 'table')),\n dag=dag)\n\n get_data >> report\n get_data >> raw_table >> clean_table\n \n return dag\n\n\ndag = make()", "_____no_output_____" ] ], [ [ "### Pipeline status", "_____no_output_____" ] ], [ [ "# Using SourceLoader automatically adds 'Location' column which points to the the source code location\ndag.status()", "_____no_output_____" ], [ "dag.build()", "_____no_output_____" ] ], [ [ "## Advanced jinja2 features\n\n`SourceLoader` initializes a proper jinja2 environment, so you can use features such as [macros](https://jinja.palletsprojects.com/en/2.11.x/templates/#macros), this is very useful to maximize SQL code reusability.", "_____no_output_____" ] ], [ [ "import shutil\nshutil.rmtree(str(tmp_dir))", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ] ]
4a0a7b4e33ec32eab411b10dbfb41c6629e1ca6e
5,787
ipynb
Jupyter Notebook
notebooks/.ipynb_checkpoints/Simulation-checkpoint.ipynb
XQBai/CCNMF
dd328cf1991b8b7177274bf9f0a9d5d1ba69e011
[ "MIT" ]
10
2020-02-10T16:20:13.000Z
2021-12-09T01:55:27.000Z
notebooks/.ipynb_checkpoints/Simulation-checkpoint.ipynb
XQBai/CCNMF
dd328cf1991b8b7177274bf9f0a9d5d1ba69e011
[ "MIT" ]
1
2022-03-03T04:02:00.000Z
2022-03-04T05:16:05.000Z
notebooks/.ipynb_checkpoints/Simulation-checkpoint.ipynb
XQBai/CCNMF
dd328cf1991b8b7177274bf9f0a9d5d1ba69e011
[ "MIT" ]
1
2021-04-24T22:55:40.000Z
2021-04-24T22:55:40.000Z
29.227273
450
0.577501
[ [ [ "## Simulation Procedures", "_____no_output_____" ], [ "## The progress of simulation\n\nWe simulate paired scDNA and RNA data following the procedure as illustrated in supplement (Figure S1). The simulation principle is to coherently generate scRNA and scDNA data from the same ground truth genetic copy number and clonality while also allowing adding sequencing platform specific noises.", "_____no_output_____" ] ], [ [ "import pandas as pd\nimport sys\nsys.path.append('~/CCNMF/SimulationCode/')", "_____no_output_____" ], [ "# The Simulation.py (module) is restored in '~/simulationCode'\nimport Simulation as st", "_____no_output_____" ] ], [ [ "Specifically, we estimated the transition probabilty matrix as follows: we downloaded the [TCGA](https://www.cancer.gov/about-nci/organization/ccg/research/structural-genomics/tcga) genetic copy number difference GCN data from [cBioPortal](https://www.cbioportal.org/) with 171 triple-negative breast cancer basal samples on paired bulk RNA-seq and DNA-seq data. The below Probmatrix's cloumns are copy number from 1 to 5 as well as the rows. ", "_____no_output_____" ] ], [ [ "ProbMatrix = [[0.42, 0.5, 0.08, 0, 0], \n [0.02, 0.52, 0.46, 0, 0],\n [0, 0, 0.5, 0.5, 0], \n [0, 0, 0.01, 0.4, 0.59], \n [0, 0, 0, 0.01, 0.99]]", "_____no_output_____" ] ], [ [ " The various configurations for simulated data. The details of each parameter are shown as the annotation. ", "_____no_output_____" ] ], [ [ "Paramaters = {'Ncluster' : [3], # The number of clusters, 2 or 3\n 'Topology' : ['linear'], # The clonal structure of simulated data: 'linear' or 'bifurcate'\n 'C1Percent' : [0.5, 0.5], # The each cluster percentage if the data has 2 clusters\n 'C2Percent':[0.2, 0.4, 0.4], # The each cluster percentage if the data has 3 clusters\n 'Percentage' : [0.1, 0.2, 0.3, 0.4, 0.5], # The simulated copy number fraction in each cluster on various cases\n 'Outlier': [0.5], # The simulated outlier percentages in each cluster on various cases \n 'Dropout': [0.5]} # The simulated dropout percentages in each cluster on various cases", "_____no_output_____" ] ], [ [ "Simulate the Genetic Copy file for the pecific clone structure, nGenes is the number of genes, nCells is the number \nof cells", "_____no_output_____" ] ], [ [ "Configure = st.GeneticCN(Paramaters, nGenes = 200, nCells = 100)", "_____no_output_____" ] ], [ [ "We simulate the scDNA data based on their associated clonal copy number profiles and transition probability matrix.", "_____no_output_____" ] ], [ [ "DNAmatrix = st.Simulate_DNA(ProbMatrix, Configure)", "_____no_output_____" ] ], [ [ "Simulate the scRNA data based on their associated clonal copy number profiles. ", "_____no_output_____" ] ], [ [ "RNAmatrix = st.Simulate_RNA(Configure)", "_____no_output_____" ] ], [ [ "The above procedures are how to simulate the various copy number fractions in each cluster for linear structure with 3 \nclusters when the default of outlier percentange and dropout percentange are 0.5. \nMeanwhile, if we need to simulate other configuration such as bifurcate structure with 3 clusters for various dropout percentages.\nit is best to give the default of \"Percentage\" and \"Dropout\". Such as:\nParamaters = {'Ncluster' : [3], 'Topology' : ['bifurcate'], 'C1Percent' : [0.5, 0.5], 'C2Percent':[0.2, 0.4, 0.4], 'Percentage' : [0.5], 'Outlier': [0.5], 'Dropout': [0.1, 0.2, 0.3, 0.4, 0.5]} ", "_____no_output_____" ], [ "Finally, save each pair datasets as '.csv' file. ", "_____no_output_____" ] ], [ [ "DNA1 = DNAmatrix[1]\nRNA1 = RNAmatrix[1]\nDNA1 = pd.DataFrame(DNA1)\nRNA1 = pd.DataFrame(RNA1)\nDNA1.to_csv('DNA1.csv', index = 0)\nRNA1.to_csv('RNA1.csv', index = 0)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ] ]
4a0a7e749fe4cb19c01e99f3ccd207bb581cfb28
15,026
ipynb
Jupyter Notebook
testingModel.ipynb
thehappeninghomo/CapstoneProject_Sonali-Kushwaha
5e72ac38eb3626996233960666798c1785f86112
[ "MIT" ]
null
null
null
testingModel.ipynb
thehappeninghomo/CapstoneProject_Sonali-Kushwaha
5e72ac38eb3626996233960666798c1785f86112
[ "MIT" ]
null
null
null
testingModel.ipynb
thehappeninghomo/CapstoneProject_Sonali-Kushwaha
5e72ac38eb3626996233960666798c1785f86112
[ "MIT" ]
null
null
null
98.855263
11,409
0.867097
[ [ [ "# Evaluate the model taking image input from MS-Paint", "_____no_output_____" ], [ "### e.g. IMAGE NAME: something.png ", "_____no_output_____" ] ], [ [ "# Importing some needed modules\r\nimport tensorflow as tf \r\nfrom tensorflow.keras.models import load_model\r\nimport matplotlib.pyplot as plt", "_____no_output_____" ], [ "# Loading our trained \"HAMARA_PYARA_MODEL\"\r\nmodel = tf.keras.models.load_model('HAMARA_PYARA_MODEL.keras')", "_____no_output_____" ], [ "# In case you want to change the input image, It's ADVISABLE to change input image name from both testModel.py and this cell.\r\n\r\n# Importing needed modules\r\nimport cv2 \r\nimport tensorflow as tf \r\nimport numpy as np\r\n\r\n# Reading image\r\nmyImage = cv2.imread('something.png') # CHANGE IMAGE NAME HERE\r\n# Converting image into gray from RGB\r\nconvertedImage = cv2.cvtColor(myImage, cv2.COLOR_BGR2GRAY)\r\n\r\n# Preparing it for kernel operation\r\n# Resizing and adjusting pixels of the image\r\nresizedImage = cv2.resize(convertedImage, (28,28), interpolation = cv2.INTER_AREA)\r\n# Scaling from 0 to 1\r\nnewImage = tf.keras.utils.normalize(resizedImage, axis = 1)\r\n\r\n# Kernal operation of CNN layer \r\nIMG_SIZE = 28\r\nnewImage = np.array(newImage).reshape(-1, IMG_SIZE, IMG_SIZE, 1) ", "_____no_output_____" ], [ "# Getting to know how the input image looks like(Not from any of test sets)\r\nplt.imshow(myImage)", "_____no_output_____" ], [ "# Predicting from image input outside MNIST test sets\r\nprediction = model.predict(newImage)\r\npredictImage = np.argmax(prediction)\r\nprint(predictImage)", "7\n" ] ], [ [ "THANK YOU FOR BEARING OVER-EXPLANATORY ME :)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ] ]
4a0a8352f94e465065cd326b268a11305dcee904
70,086
ipynb
Jupyter Notebook
ASPCAP_Normalization.ipynb
henrysky/astroNN_spectra_paper_figures
b77c89a3d2540df37b836662399d4eaba9464cfd
[ "MIT" ]
1
2020-04-01T15:27:34.000Z
2020-04-01T15:27:34.000Z
ASPCAP_Normalization.ipynb
henrysky/astroNN_spectra_paper_figures
b77c89a3d2540df37b836662399d4eaba9464cfd
[ "MIT" ]
2
2018-04-19T18:39:14.000Z
2018-10-10T18:03:45.000Z
ASPCAP_Normalization.ipynb
henrysky/astroNN_spectra_paper_figures
b77c89a3d2540df37b836662399d4eaba9464cfd
[ "MIT" ]
null
null
null
57.166395
343
0.635876
[ [ [ "## Compile a training set using ASPCAP normalization", "_____no_output_____" ] ], [ [ "from utils_h5 import H5Compiler\nfrom astropy.io import fits\nimport numpy as np\n\n# To create a astroNN compiler instance\ncompiler_aspcap_train = H5Compiler()\ncompiler_aspcap_train.teff_low = 4000 # Effective Temperature Upper\ncompiler_aspcap_train.teff_high = 5500 # Effective Temperature Lower\ncompiler_aspcap_train.vscattercut = 1 # Velocity Scattering Upper\ncompiler_aspcap_train.starflagcut = True # STARFLAG == 0\ncompiler_aspcap_train.aspcapflagcut = True # ASPCAPFALG == 0\ncompiler_aspcap_train.ironlow = -10000. # [Fe/H] Lower\ncompiler_aspcap_train.continuum = False # use aspcap normalization\ncompiler_aspcap_train.SNR_low = 200 # SNR Lower\ncompiler_aspcap_train.SNR_high = 99999 # SNR Upper\n\ncompiler_aspcap_train.filename = 'aspcap_norm_train'\n\n# To compile a .h5 datasets, use .compile() method\ncompiler_aspcap_train.compile()", "dr is not provided, using default dr=14\nE:\\sdss_mirror\\dr14/apogee/spectro/redux/r8/stars/l31c/l31c.2/allStar-l31c.2.fits was found!\nLoading allStar DR14 catalog\nTotal Combined Spectra after filtering: 33407\nCompleted 1 of 33407, 0.14s elapsed\nCompleted 101 of 33407, 0.75s elapsed\nCompleted 201 of 33407, 1.40s elapsed\nCompleted 301 of 33407, 2.10s elapsed\nCompleted 401 of 33407, 2.82s elapsed\nCompleted 501 of 33407, 3.57s elapsed\nCompleted 601 of 33407, 4.31s elapsed\nCompleted 701 of 33407, 5.05s elapsed\nCompleted 801 of 33407, 5.82s elapsed\nCompleted 901 of 33407, 6.55s elapsed\nCompleted 1001 of 33407, 7.31s elapsed\nCompleted 1101 of 33407, 8.04s elapsed\nCompleted 1201 of 33407, 8.76s elapsed\nCompleted 1301 of 33407, 9.43s elapsed\nCompleted 1401 of 33407, 10.01s elapsed\nCompleted 1501 of 33407, 10.78s elapsed\nCompleted 1601 of 33407, 11.60s elapsed\nCompleted 1701 of 33407, 12.41s elapsed\nCompleted 1801 of 33407, 13.19s elapsed\nCompleted 1901 of 33407, 13.99s elapsed\nCompleted 2001 of 33407, 14.81s elapsed\nCompleted 2101 of 33407, 15.66s elapsed\nCompleted 2201 of 33407, 16.48s elapsed\nCompleted 2301 of 33407, 17.28s elapsed\nCompleted 2401 of 33407, 18.12s elapsed\nCompleted 2501 of 33407, 18.96s elapsed\nCompleted 2601 of 33407, 19.79s elapsed\nCompleted 2701 of 33407, 20.62s elapsed\nCompleted 2801 of 33407, 21.43s elapsed\nCompleted 2901 of 33407, 22.26s elapsed\nCompleted 3001 of 33407, 23.10s elapsed\nCompleted 3101 of 33407, 23.96s elapsed\nCompleted 3201 of 33407, 24.81s elapsed\nCompleted 3301 of 33407, 25.66s elapsed\nCompleted 3401 of 33407, 26.52s elapsed\nCompleted 3501 of 33407, 27.33s elapsed\nCompleted 3601 of 33407, 28.15s elapsed\nCompleted 3701 of 33407, 28.98s elapsed\nCompleted 3801 of 33407, 29.82s elapsed\nCompleted 3901 of 33407, 30.69s elapsed\nCompleted 4001 of 33407, 31.57s elapsed\nCompleted 4101 of 33407, 32.41s elapsed\nCompleted 4201 of 33407, 33.27s elapsed\nCompleted 4301 of 33407, 34.10s elapsed\nCompleted 4401 of 33407, 34.94s elapsed\nCompleted 4501 of 33407, 35.77s elapsed\nCompleted 4601 of 33407, 36.58s elapsed\nCompleted 4701 of 33407, 37.40s elapsed\nCompleted 4801 of 33407, 38.24s elapsed\nCompleted 4901 of 33407, 39.05s elapsed\nCompleted 5001 of 33407, 39.90s elapsed\nCompleted 5101 of 33407, 40.72s elapsed\nCompleted 5201 of 33407, 41.53s elapsed\nCompleted 5301 of 33407, 42.33s elapsed\nCompleted 5401 of 33407, 43.13s elapsed\nCompleted 5501 of 33407, 43.96s elapsed\nCompleted 5601 of 33407, 44.79s elapsed\nCompleted 5701 of 33407, 45.63s elapsed\nCompleted 5801 of 33407, 46.46s elapsed\nCompleted 5901 of 33407, 47.30s elapsed\nCompleted 6001 of 33407, 48.13s elapsed\nCompleted 6101 of 33407, 48.98s elapsed\nCompleted 6201 of 33407, 49.82s elapsed\nCompleted 6301 of 33407, 50.65s elapsed\nCompleted 6401 of 33407, 51.49s elapsed\nCompleted 6501 of 33407, 52.33s elapsed\nCompleted 6601 of 33407, 53.17s elapsed\nCompleted 6701 of 33407, 54.01s elapsed\nCompleted 6801 of 33407, 54.86s elapsed\nCompleted 6901 of 33407, 55.70s elapsed\nCompleted 7001 of 33407, 56.57s elapsed\nCompleted 7101 of 33407, 57.41s elapsed\nCompleted 7201 of 33407, 58.24s elapsed\nCompleted 7301 of 33407, 59.07s elapsed\nCompleted 7401 of 33407, 59.90s elapsed\nCompleted 7501 of 33407, 60.74s elapsed\nCompleted 7601 of 33407, 61.59s elapsed\nCompleted 7701 of 33407, 62.43s elapsed\nCompleted 7801 of 33407, 63.30s elapsed\nCompleted 7901 of 33407, 64.16s elapsed\nCompleted 8001 of 33407, 65.00s elapsed\nCompleted 8101 of 33407, 65.83s elapsed\nCompleted 8201 of 33407, 66.68s elapsed\nCompleted 8301 of 33407, 67.52s elapsed\nCompleted 8401 of 33407, 68.35s elapsed\nCompleted 8501 of 33407, 69.21s elapsed\nCompleted 8601 of 33407, 70.07s elapsed\nCompleted 8701 of 33407, 70.93s elapsed\nCompleted 8801 of 33407, 71.81s elapsed\nCompleted 8901 of 33407, 72.70s elapsed\nCompleted 9001 of 33407, 73.60s elapsed\nCompleted 9101 of 33407, 74.52s elapsed\nCompleted 9201 of 33407, 75.40s elapsed\nCompleted 9301 of 33407, 76.38s elapsed\nCompleted 9401 of 33407, 77.29s elapsed\nCompleted 9501 of 33407, 78.13s elapsed\nCompleted 9601 of 33407, 78.99s elapsed\nCompleted 9701 of 33407, 79.87s elapsed\nCompleted 9801 of 33407, 80.76s elapsed\nCompleted 9901 of 33407, 81.66s elapsed\nCompleted 10001 of 33407, 82.55s elapsed\nCompleted 10101 of 33407, 83.40s elapsed\nCompleted 10201 of 33407, 84.23s elapsed\nCompleted 10301 of 33407, 85.08s elapsed\nCompleted 10401 of 33407, 85.96s elapsed\nCompleted 10501 of 33407, 86.83s elapsed\nCompleted 10601 of 33407, 87.73s elapsed\nCompleted 10701 of 33407, 88.64s elapsed\nCompleted 10801 of 33407, 89.52s elapsed\nCompleted 10901 of 33407, 90.41s elapsed\nCompleted 11001 of 33407, 91.30s elapsed\nCompleted 11101 of 33407, 92.20s elapsed\nCompleted 11201 of 33407, 93.06s elapsed\nCompleted 11301 of 33407, 94.01s elapsed\nCompleted 11401 of 33407, 94.88s elapsed\nCompleted 11501 of 33407, 95.76s elapsed\nCompleted 11601 of 33407, 96.65s elapsed\nCompleted 11701 of 33407, 97.51s elapsed\nCompleted 11801 of 33407, 98.36s elapsed\nCompleted 11901 of 33407, 99.22s elapsed\nCompleted 12001 of 33407, 100.06s elapsed\nCompleted 12101 of 33407, 100.94s elapsed\nCompleted 12201 of 33407, 101.77s elapsed\nCompleted 12301 of 33407, 102.60s elapsed\nCompleted 12401 of 33407, 103.41s elapsed\nCompleted 12501 of 33407, 104.24s elapsed\nCompleted 12601 of 33407, 105.01s elapsed\nCompleted 12701 of 33407, 105.80s elapsed\nCompleted 12801 of 33407, 106.57s elapsed\nCompleted 12901 of 33407, 107.38s elapsed\nCompleted 13001 of 33407, 108.25s elapsed\nCompleted 13101 of 33407, 109.38s elapsed\nCompleted 13201 of 33407, 110.30s elapsed\nCompleted 13301 of 33407, 111.15s elapsed\nCompleted 13401 of 33407, 112.04s elapsed\nCompleted 13501 of 33407, 113.04s elapsed\nCompleted 13601 of 33407, 114.06s elapsed\nCompleted 13701 of 33407, 115.30s elapsed\nCompleted 13801 of 33407, 116.34s elapsed\nCompleted 13901 of 33407, 117.17s elapsed\nCompleted 14001 of 33407, 118.02s elapsed\nCompleted 14101 of 33407, 118.87s elapsed\nCompleted 14201 of 33407, 119.80s elapsed\nCompleted 14301 of 33407, 120.60s elapsed\nCompleted 14401 of 33407, 121.46s elapsed\nCompleted 14501 of 33407, 122.31s elapsed\nCompleted 14601 of 33407, 123.18s elapsed\nCompleted 14701 of 33407, 124.03s elapsed\nCompleted 14801 of 33407, 124.86s elapsed\nCompleted 14901 of 33407, 125.65s elapsed\nCompleted 15001 of 33407, 126.46s elapsed\nCompleted 15101 of 33407, 127.25s elapsed\nCompleted 15201 of 33407, 128.06s elapsed\nCompleted 15301 of 33407, 128.84s elapsed\nCompleted 15401 of 33407, 129.61s elapsed\nCompleted 15501 of 33407, 130.42s elapsed\nCompleted 15601 of 33407, 131.21s elapsed\nCompleted 15701 of 33407, 132.04s elapsed\nCompleted 15801 of 33407, 132.86s elapsed\nCompleted 15901 of 33407, 133.63s elapsed\nCompleted 16001 of 33407, 134.42s elapsed\nCompleted 16101 of 33407, 135.25s elapsed\nCompleted 16201 of 33407, 136.07s elapsed\nCompleted 16301 of 33407, 136.86s elapsed\nCompleted 16401 of 33407, 137.65s elapsed\nCompleted 16501 of 33407, 138.49s elapsed\nCompleted 16601 of 33407, 139.29s elapsed\nCompleted 16701 of 33407, 140.19s elapsed\nCompleted 16801 of 33407, 141.32s elapsed\nCompleted 16901 of 33407, 142.28s elapsed\nCompleted 17001 of 33407, 143.14s elapsed\nCompleted 17101 of 33407, 143.93s elapsed\nCompleted 17201 of 33407, 144.72s elapsed\nCompleted 17301 of 33407, 145.53s elapsed\nCompleted 17401 of 33407, 146.32s elapsed\nCompleted 17501 of 33407, 147.11s elapsed\nCompleted 17601 of 33407, 147.89s elapsed\nCompleted 17701 of 33407, 148.68s elapsed\nCompleted 17801 of 33407, 149.48s elapsed\nCompleted 17901 of 33407, 150.31s elapsed\nCompleted 18001 of 33407, 151.10s elapsed\nCompleted 18101 of 33407, 151.89s elapsed\nCompleted 18201 of 33407, 152.67s elapsed\nCompleted 18301 of 33407, 153.45s elapsed\nCompleted 18401 of 33407, 154.26s elapsed\nCompleted 18501 of 33407, 155.04s elapsed\nCompleted 18601 of 33407, 155.82s elapsed\nCompleted 18701 of 33407, 156.61s elapsed\nCompleted 18801 of 33407, 157.40s elapsed\nCompleted 18901 of 33407, 158.19s elapsed\nCompleted 19001 of 33407, 167.84s elapsed\nCompleted 19101 of 33407, 171.47s elapsed\nCompleted 19201 of 33407, 175.99s elapsed\nCompleted 19301 of 33407, 181.41s elapsed\nCompleted 19401 of 33407, 185.08s elapsed\nCompleted 19501 of 33407, 190.10s elapsed\nCompleted 19601 of 33407, 191.82s elapsed\nCompleted 19701 of 33407, 196.30s elapsed\nCompleted 19801 of 33407, 205.40s elapsed\nCompleted 19901 of 33407, 208.91s elapsed\nCompleted 20001 of 33407, 211.85s elapsed\nCompleted 20101 of 33407, 215.57s elapsed\nCompleted 20201 of 33407, 219.98s elapsed\nCompleted 20301 of 33407, 223.49s elapsed\nCompleted 20401 of 33407, 229.57s elapsed\nCompleted 20501 of 33407, 230.43s elapsed\nCompleted 20601 of 33407, 233.97s elapsed\nCompleted 20701 of 33407, 238.39s elapsed\nCompleted 20801 of 33407, 244.33s elapsed\nCompleted 20901 of 33407, 246.36s elapsed\nCompleted 21001 of 33407, 251.66s elapsed\nCompleted 21101 of 33407, 254.22s elapsed\nCompleted 21201 of 33407, 259.54s elapsed\nCompleted 21301 of 33407, 266.29s elapsed\nCompleted 21401 of 33407, 268.83s elapsed\nCompleted 21501 of 33407, 272.33s elapsed\nCompleted 21601 of 33407, 273.99s elapsed\nCompleted 21701 of 33407, 280.19s elapsed\nCompleted 21801 of 33407, 282.17s elapsed\nCompleted 21901 of 33407, 284.94s elapsed\nCompleted 22001 of 33407, 289.09s elapsed\nCompleted 22101 of 33407, 292.89s elapsed\nCompleted 22201 of 33407, 297.69s elapsed\nCompleted 22301 of 33407, 303.95s elapsed\nCompleted 22401 of 33407, 307.77s elapsed\nCompleted 22501 of 33407, 312.20s elapsed\nCompleted 22601 of 33407, 313.97s elapsed\nCompleted 22701 of 33407, 318.28s elapsed\nCompleted 22801 of 33407, 323.44s elapsed\nCompleted 22901 of 33407, 328.16s elapsed\nCompleted 23001 of 33407, 330.08s elapsed\nCompleted 23101 of 33407, 331.87s elapsed\nCompleted 23201 of 33407, 335.48s elapsed\nCompleted 23301 of 33407, 338.16s elapsed\nCompleted 23401 of 33407, 340.12s elapsed\nCompleted 23501 of 33407, 342.86s elapsed\nCompleted 23601 of 33407, 348.99s elapsed\nCompleted 23701 of 33407, 350.94s elapsed\nCompleted 23801 of 33407, 354.43s elapsed\nCompleted 23901 of 33407, 358.91s elapsed\nCompleted 24001 of 33407, 366.09s elapsed\nCompleted 24101 of 33407, 367.84s elapsed\nCompleted 24201 of 33407, 370.34s elapsed\nCompleted 24301 of 33407, 372.88s elapsed\nCompleted 24401 of 33407, 377.29s elapsed\nCompleted 24501 of 33407, 382.28s elapsed\nCompleted 24601 of 33407, 387.52s elapsed\nCompleted 24701 of 33407, 396.16s elapsed\nCompleted 24801 of 33407, 400.28s elapsed\nCompleted 24901 of 33407, 409.90s elapsed\nCompleted 25001 of 33407, 419.85s elapsed\nCompleted 25101 of 33407, 426.70s elapsed\nCompleted 25201 of 33407, 434.43s elapsed\nCompleted 25301 of 33407, 440.29s elapsed\nCompleted 25401 of 33407, 448.34s elapsed\nCompleted 25501 of 33407, 451.51s elapsed\nCompleted 25601 of 33407, 455.30s elapsed\nCompleted 25701 of 33407, 457.88s elapsed\nCompleted 25801 of 33407, 462.16s elapsed\nCompleted 25901 of 33407, 465.59s elapsed\nCompleted 26001 of 33407, 466.39s elapsed\nCompleted 26101 of 33407, 468.14s elapsed\nCompleted 26201 of 33407, 469.02s elapsed\nCompleted 26301 of 33407, 470.78s elapsed\nCompleted 26401 of 33407, 471.67s elapsed\nCompleted 26501 of 33407, 474.64s elapsed\nCompleted 26601 of 33407, 475.57s elapsed\nCompleted 26701 of 33407, 479.09s elapsed\nCompleted 26801 of 33407, 481.63s elapsed\nCompleted 26901 of 33407, 483.27s elapsed\nCompleted 27001 of 33407, 484.14s elapsed\nCompleted 27101 of 33407, 487.71s elapsed\nCompleted 27201 of 33407, 488.54s elapsed\nCompleted 27301 of 33407, 490.27s elapsed\nCompleted 27401 of 33407, 491.11s elapsed\nCompleted 27501 of 33407, 492.79s elapsed\nCompleted 27601 of 33407, 497.20s elapsed\nCompleted 27701 of 33407, 498.09s elapsed\nCompleted 27801 of 33407, 499.79s elapsed\nCompleted 27901 of 33407, 500.66s elapsed\nCompleted 28001 of 33407, 501.51s elapsed\nCompleted 28101 of 33407, 503.44s elapsed\nCompleted 28201 of 33407, 504.30s elapsed\nCompleted 28301 of 33407, 505.15s elapsed\nCompleted 28401 of 33407, 507.76s elapsed\nCompleted 28501 of 33407, 509.54s elapsed\nCompleted 28601 of 33407, 510.43s elapsed\nCompleted 28701 of 33407, 512.17s elapsed\nCompleted 28801 of 33407, 514.82s elapsed\nCompleted 28901 of 33407, 516.81s elapsed\nCompleted 29001 of 33407, 518.52s elapsed\nCompleted 29101 of 33407, 519.37s elapsed\nCompleted 29201 of 33407, 521.39s elapsed\nCompleted 29301 of 33407, 522.28s elapsed\nCompleted 29401 of 33407, 524.04s elapsed\nCompleted 29501 of 33407, 524.94s elapsed\nCompleted 29601 of 33407, 526.94s elapsed\nCompleted 29701 of 33407, 528.87s elapsed\nCompleted 29801 of 33407, 529.83s elapsed\nCompleted 29901 of 33407, 531.71s elapsed\nCompleted 30001 of 33407, 533.87s elapsed\nCompleted 30101 of 33407, 535.58s elapsed\nCompleted 30201 of 33407, 536.49s elapsed\nCompleted 30301 of 33407, 537.39s elapsed\nCompleted 30401 of 33407, 539.15s elapsed\nCompleted 30501 of 33407, 540.87s elapsed\nCompleted 30601 of 33407, 543.57s elapsed\nCompleted 30701 of 33407, 547.08s elapsed\nCompleted 30801 of 33407, 551.67s elapsed\nCompleted 30901 of 33407, 554.11s elapsed\nCompleted 31001 of 33407, 557.74s elapsed\nCompleted 31101 of 33407, 561.22s elapsed\nCompleted 31201 of 33407, 566.37s elapsed\nCompleted 31301 of 33407, 567.25s elapsed\nCompleted 31401 of 33407, 569.86s elapsed\nCompleted 31501 of 33407, 573.67s elapsed\nCompleted 31601 of 33407, 577.76s elapsed\nCompleted 31701 of 33407, 582.85s elapsed\nCompleted 31801 of 33407, 583.80s elapsed\nCompleted 31901 of 33407, 585.65s elapsed\nCompleted 32001 of 33407, 588.60s elapsed\nCompleted 32101 of 33407, 594.27s elapsed\nCompleted 32201 of 33407, 597.04s elapsed\nCompleted 32301 of 33407, 597.88s elapsed\nCompleted 32401 of 33407, 602.16s elapsed\nCompleted 32501 of 33407, 604.03s elapsed\nCompleted 32601 of 33407, 608.20s elapsed\nCompleted 32701 of 33407, 612.17s elapsed\nCompleted 32801 of 33407, 614.75s elapsed\nCompleted 32901 of 33407, 617.11s elapsed\nCompleted 33001 of 33407, 619.69s elapsed\nCompleted 33101 of 33407, 622.30s elapsed\nCompleted 33201 of 33407, 623.88s elapsed\nCompleted 33301 of 33407, 624.73s elapsed\nCompleted 33401 of 33407, 625.59s elapsed\nThis is Gaia DR2 - APOGEE DR14 matched parallax, RA DEC in J2000, parallax in mas\nPlease be advised that astroNN fakemag is parallax(mas) * 10 ** (0.2 * mag)\nCreating aspcap_norm_train.h5\nSuccessfully created aspcap_norm_train.h5 in D:\\University\\AST425\\astroNN_spectra_paper_figures\n" ] ], [ [ "## Compile a testing set using ASPCAP normalization", "_____no_output_____" ] ], [ [ "from utils_h5 import H5Compiler\nfrom astropy.io import fits\nimport numpy as np\n\n# To create a astroNN compiler instance\ncompiler_aspcap_test = H5Compiler()\ncompiler_aspcap_test.teff_low = 4000 # Effective Temperature Upper\ncompiler_aspcap_test.teff_high = 5500 # Effective Temperature Lower\ncompiler_aspcap_test.vscattercut = 1 # Velocity Scattering Upper\ncompiler_aspcap_test.starflagcut = True # STARFLAG == 0\ncompiler_aspcap_test.aspcapflagcut = True # ASPCAPFALG == 0\ncompiler_aspcap_test.ironlow = -10000. # [Fe/H] Lower\ncompiler_aspcap_test.continuum = False # use aspcap normalization\ncompiler_aspcap_test.SNR_low = 100 # SNR Lower\ncompiler_aspcap_test.SNR_high = 200 # SNR Upper\n\ncompiler_aspcap_test.filename = 'aspcap_norm_test'\n\n# To compile a .h5 datasets, use .compile() method\ncompiler_aspcap_test.compile()", "dr is not provided, using default dr=14\nE:\\sdss_mirror\\dr14/apogee/spectro/redux/r8/stars/l31c/l31c.2/allStar-l31c.2.fits was found!\nLoading allStar DR14 catalog\nTotal Combined Spectra after filtering: 28692\nCompleted 1 of 28692, 0.16s elapsed\nCompleted 101 of 28692, 0.97s elapsed\nCompleted 201 of 28692, 1.83s elapsed\nCompleted 301 of 28692, 2.70s elapsed\nCompleted 401 of 28692, 3.61s elapsed\nCompleted 501 of 28692, 4.52s elapsed\nCompleted 601 of 28692, 5.41s elapsed\nCompleted 701 of 28692, 6.33s elapsed\nCompleted 801 of 28692, 7.25s elapsed\nCompleted 901 of 28692, 8.13s elapsed\nCompleted 1001 of 28692, 9.04s elapsed\nCompleted 1101 of 28692, 9.94s elapsed\nCompleted 1201 of 28692, 10.70s elapsed\nCompleted 1301 of 28692, 11.47s elapsed\nCompleted 1401 of 28692, 12.24s elapsed\nCompleted 1501 of 28692, 12.98s elapsed\nCompleted 1601 of 28692, 13.74s elapsed\nCompleted 1701 of 28692, 14.51s elapsed\nCompleted 1801 of 28692, 15.30s elapsed\nCompleted 1901 of 28692, 16.11s elapsed\nCompleted 2001 of 28692, 16.90s elapsed\nCompleted 2101 of 28692, 17.69s elapsed\nCompleted 2201 of 28692, 18.56s elapsed\nCompleted 2301 of 28692, 19.43s elapsed\nCompleted 2401 of 28692, 20.29s elapsed\nCompleted 2501 of 28692, 21.12s elapsed\nCompleted 2601 of 28692, 21.95s elapsed\nCompleted 2701 of 28692, 22.77s elapsed\nCompleted 2801 of 28692, 23.62s elapsed\nCompleted 2901 of 28692, 24.48s elapsed\nCompleted 3001 of 28692, 25.34s elapsed\nCompleted 3101 of 28692, 26.22s elapsed\nCompleted 3201 of 28692, 27.06s elapsed\nCompleted 3301 of 28692, 27.90s elapsed\nCompleted 3401 of 28692, 28.70s elapsed\nCompleted 3501 of 28692, 29.58s elapsed\nCompleted 3601 of 28692, 30.41s elapsed\nCompleted 3701 of 28692, 31.26s elapsed\nCompleted 3801 of 28692, 32.12s elapsed\nCompleted 3901 of 28692, 32.97s elapsed\nCompleted 4001 of 28692, 33.84s elapsed\nCompleted 4101 of 28692, 34.72s elapsed\nCompleted 4201 of 28692, 35.53s elapsed\nCompleted 4301 of 28692, 36.37s elapsed\nCompleted 4401 of 28692, 37.24s elapsed\nCompleted 4501 of 28692, 38.12s elapsed\nCompleted 4601 of 28692, 38.96s elapsed\nCompleted 4701 of 28692, 39.82s elapsed\nCompleted 4801 of 28692, 40.62s elapsed\nCompleted 4901 of 28692, 41.46s elapsed\nCompleted 5001 of 28692, 42.33s elapsed\nCompleted 5101 of 28692, 43.21s elapsed\nCompleted 5201 of 28692, 44.11s elapsed\nCompleted 5301 of 28692, 44.96s elapsed\nCompleted 5401 of 28692, 45.78s elapsed\nCompleted 5501 of 28692, 46.61s elapsed\nCompleted 5601 of 28692, 47.50s elapsed\nCompleted 5701 of 28692, 48.36s elapsed\nCompleted 5801 of 28692, 49.23s elapsed\nCompleted 5901 of 28692, 50.10s elapsed\nCompleted 6001 of 28692, 50.92s elapsed\nCompleted 6101 of 28692, 53.75s elapsed\nCompleted 6201 of 28692, 54.56s elapsed\nCompleted 6301 of 28692, 55.38s elapsed\nCompleted 6401 of 28692, 56.22s elapsed\nCompleted 6501 of 28692, 57.10s elapsed\nCompleted 6601 of 28692, 57.94s elapsed\nCompleted 6701 of 28692, 58.75s elapsed\nCompleted 6801 of 28692, 59.59s elapsed\nCompleted 6901 of 28692, 60.44s elapsed\nCompleted 7001 of 28692, 61.26s elapsed\nCompleted 7101 of 28692, 62.12s elapsed\nCompleted 7201 of 28692, 63.01s elapsed\nCompleted 7301 of 28692, 63.86s elapsed\nCompleted 7401 of 28692, 64.69s elapsed\nCompleted 7501 of 28692, 65.51s elapsed\nCompleted 7601 of 28692, 66.37s elapsed\nCompleted 7701 of 28692, 67.20s elapsed\nCompleted 7801 of 28692, 68.03s elapsed\nCompleted 7901 of 28692, 68.86s elapsed\nCompleted 8001 of 28692, 69.70s elapsed\nCompleted 8101 of 28692, 70.55s elapsed\nCompleted 8201 of 28692, 71.40s elapsed\nCompleted 8301 of 28692, 72.23s elapsed\nCompleted 8401 of 28692, 73.02s elapsed\nCompleted 8501 of 28692, 73.85s elapsed\nCompleted 8601 of 28692, 74.72s elapsed\nCompleted 8701 of 28692, 75.56s elapsed\nCompleted 8801 of 28692, 76.43s elapsed\nCompleted 8901 of 28692, 77.32s elapsed\nCompleted 9001 of 28692, 78.18s elapsed\nCompleted 9101 of 28692, 79.04s elapsed\nCompleted 9201 of 28692, 79.93s elapsed\nCompleted 9301 of 28692, 80.79s elapsed\nCompleted 9401 of 28692, 81.65s elapsed\nCompleted 9501 of 28692, 82.52s elapsed\nCompleted 9601 of 28692, 83.37s elapsed\nCompleted 9701 of 28692, 84.20s elapsed\nCompleted 9801 of 28692, 85.02s elapsed\nCompleted 9901 of 28692, 85.82s elapsed\nCompleted 10001 of 28692, 86.62s elapsed\nCompleted 10101 of 28692, 87.43s elapsed\nCompleted 10201 of 28692, 88.25s elapsed\nCompleted 10301 of 28692, 89.07s elapsed\nCompleted 10401 of 28692, 89.92s elapsed\nCompleted 10501 of 28692, 90.74s elapsed\nCompleted 10601 of 28692, 91.55s elapsed\nCompleted 10701 of 28692, 92.37s elapsed\nCompleted 10801 of 28692, 93.21s elapsed\nCompleted 10901 of 28692, 94.05s elapsed\nCompleted 11001 of 28692, 94.83s elapsed\nCompleted 11101 of 28692, 95.63s elapsed\nCompleted 11201 of 28692, 96.48s elapsed\nCompleted 11301 of 28692, 97.27s elapsed\nCompleted 11401 of 28692, 98.04s elapsed\nCompleted 11501 of 28692, 98.82s elapsed\nCompleted 11601 of 28692, 99.60s elapsed\nCompleted 11701 of 28692, 100.40s elapsed\nCompleted 11801 of 28692, 101.17s elapsed\nCompleted 11901 of 28692, 101.91s elapsed\nCompleted 12001 of 28692, 102.66s elapsed\nCompleted 12101 of 28692, 103.41s elapsed\nCompleted 12201 of 28692, 104.15s elapsed\nCompleted 12301 of 28692, 104.94s elapsed\nCompleted 12401 of 28692, 105.68s elapsed\nCompleted 12501 of 28692, 106.41s elapsed\nCompleted 12601 of 28692, 107.17s elapsed\nCompleted 12701 of 28692, 107.92s elapsed\nCompleted 12801 of 28692, 108.69s elapsed\nCompleted 12901 of 28692, 109.47s elapsed\nCompleted 13001 of 28692, 110.26s elapsed\nCompleted 13101 of 28692, 111.07s elapsed\nCompleted 13201 of 28692, 111.91s elapsed\nCompleted 13301 of 28692, 112.74s elapsed\nCompleted 13401 of 28692, 113.51s elapsed\nCompleted 13501 of 28692, 114.26s elapsed\nCompleted 13601 of 28692, 115.02s elapsed\nCompleted 13701 of 28692, 117.52s elapsed\nCompleted 13801 of 28692, 118.27s elapsed\nCompleted 13901 of 28692, 119.04s elapsed\nCompleted 14001 of 28692, 119.79s elapsed\nCompleted 14101 of 28692, 121.41s elapsed\nCompleted 14201 of 28692, 122.14s elapsed\nCompleted 14301 of 28692, 122.91s elapsed\nCompleted 14401 of 28692, 123.66s elapsed\nCompleted 14501 of 28692, 124.41s elapsed\nCompleted 14601 of 28692, 125.17s elapsed\nCompleted 14701 of 28692, 125.91s elapsed\nCompleted 14801 of 28692, 128.74s elapsed\nCompleted 14901 of 28692, 129.48s elapsed\nCompleted 15001 of 28692, 130.24s elapsed\nCompleted 15101 of 28692, 131.03s elapsed\nCompleted 15201 of 28692, 131.82s elapsed\nCompleted 15301 of 28692, 133.50s elapsed\nCompleted 15401 of 28692, 135.24s elapsed\nCompleted 15501 of 28692, 135.97s elapsed\nCompleted 15601 of 28692, 137.59s elapsed\nCompleted 15701 of 28692, 138.36s elapsed\nCompleted 15801 of 28692, 139.16s elapsed\nCompleted 15901 of 28692, 140.80s elapsed\nCompleted 16001 of 28692, 141.58s elapsed\nCompleted 16101 of 28692, 142.35s elapsed\nCompleted 16201 of 28692, 143.13s elapsed\nCompleted 16301 of 28692, 143.88s elapsed\nCompleted 16401 of 28692, 144.62s elapsed\nCompleted 16501 of 28692, 146.47s elapsed\nCompleted 16601 of 28692, 147.23s elapsed\nCompleted 16701 of 28692, 148.01s elapsed\nCompleted 16801 of 28692, 148.87s elapsed\nCompleted 16901 of 28692, 149.68s elapsed\nCompleted 17001 of 28692, 150.47s elapsed\nCompleted 17101 of 28692, 151.25s elapsed\nCompleted 17201 of 28692, 152.03s elapsed\nCompleted 17301 of 28692, 152.84s elapsed\nCompleted 17401 of 28692, 155.58s elapsed\nCompleted 17501 of 28692, 156.46s elapsed\nCompleted 17601 of 28692, 157.38s elapsed\nCompleted 17701 of 28692, 158.24s elapsed\nCompleted 17801 of 28692, 159.17s elapsed\nCompleted 17901 of 28692, 160.03s elapsed\nCompleted 18001 of 28692, 160.87s elapsed\nCompleted 18101 of 28692, 161.73s elapsed\nCompleted 18201 of 28692, 162.74s elapsed\nCompleted 18301 of 28692, 163.64s elapsed\nCompleted 18401 of 28692, 164.57s elapsed\nCompleted 18501 of 28692, 165.42s elapsed\nCompleted 18601 of 28692, 166.24s elapsed\nCompleted 18701 of 28692, 167.02s elapsed\nCompleted 18801 of 28692, 167.78s elapsed\nCompleted 18901 of 28692, 168.55s elapsed\nCompleted 19001 of 28692, 169.39s elapsed\nCompleted 19101 of 28692, 170.21s elapsed\nCompleted 19201 of 28692, 171.03s elapsed\nCompleted 19301 of 28692, 171.88s elapsed\nCompleted 19401 of 28692, 172.66s elapsed\nCompleted 19501 of 28692, 173.47s elapsed\nCompleted 19601 of 28692, 174.33s elapsed\nCompleted 19701 of 28692, 176.04s elapsed\nCompleted 19801 of 28692, 176.89s elapsed\nCompleted 19901 of 28692, 177.70s elapsed\nCompleted 20001 of 28692, 179.44s elapsed\nCompleted 20101 of 28692, 180.27s elapsed\nCompleted 20201 of 28692, 181.15s elapsed\nCompleted 20301 of 28692, 182.00s elapsed\nCompleted 20401 of 28692, 183.72s elapsed\nCompleted 20501 of 28692, 184.58s elapsed\nCompleted 20601 of 28692, 185.41s elapsed\nCompleted 20701 of 28692, 186.27s elapsed\nCompleted 20801 of 28692, 187.11s elapsed\nCompleted 20901 of 28692, 187.99s elapsed\nCompleted 21001 of 28692, 188.81s elapsed\nCompleted 21101 of 28692, 189.68s elapsed\nCompleted 21201 of 28692, 190.57s elapsed\nCompleted 21301 of 28692, 191.41s elapsed\nCompleted 21401 of 28692, 192.27s elapsed\nCompleted 21501 of 28692, 193.13s elapsed\nCompleted 21601 of 28692, 193.96s elapsed\nCompleted 21701 of 28692, 194.76s elapsed\nCompleted 21801 of 28692, 195.61s elapsed\nCompleted 21901 of 28692, 196.47s elapsed\nCompleted 22001 of 28692, 197.34s elapsed\nCompleted 22101 of 28692, 198.17s elapsed\nCompleted 22201 of 28692, 199.09s elapsed\nCompleted 22301 of 28692, 199.92s elapsed\nCompleted 22401 of 28692, 200.75s elapsed\nCompleted 22501 of 28692, 201.63s elapsed\nCompleted 22601 of 28692, 202.44s elapsed\nCompleted 22701 of 28692, 203.29s elapsed\nCompleted 22801 of 28692, 204.13s elapsed\nCompleted 22901 of 28692, 204.97s elapsed\nCompleted 23001 of 28692, 205.86s elapsed\nCompleted 23101 of 28692, 206.72s elapsed\nCompleted 23201 of 28692, 207.55s elapsed\nCompleted 23301 of 28692, 208.36s elapsed\nCompleted 23401 of 28692, 209.22s elapsed\nCompleted 23501 of 28692, 210.11s elapsed\nCompleted 23601 of 28692, 210.96s elapsed\nCompleted 23701 of 28692, 211.83s elapsed\nCompleted 23801 of 28692, 212.69s elapsed\nCompleted 23901 of 28692, 213.54s elapsed\nCompleted 24001 of 28692, 214.38s elapsed\nCompleted 24101 of 28692, 215.24s elapsed\nCompleted 24201 of 28692, 216.08s elapsed\nCompleted 24301 of 28692, 216.93s elapsed\nCompleted 24401 of 28692, 217.80s elapsed\nCompleted 24501 of 28692, 218.68s elapsed\nCompleted 24601 of 28692, 219.60s elapsed\nCompleted 24701 of 28692, 220.48s elapsed\nCompleted 24801 of 28692, 221.40s elapsed\nCompleted 24901 of 28692, 222.30s elapsed\nCompleted 25001 of 28692, 223.20s elapsed\nCompleted 25101 of 28692, 224.16s elapsed\nCompleted 25201 of 28692, 225.12s elapsed\nCompleted 25301 of 28692, 226.05s elapsed\nCompleted 25401 of 28692, 226.95s elapsed\nCompleted 25501 of 28692, 227.85s elapsed\nCompleted 25601 of 28692, 228.75s elapsed\nCompleted 25701 of 28692, 229.61s elapsed\nCompleted 25801 of 28692, 230.58s elapsed\nCompleted 25901 of 28692, 231.43s elapsed\nCompleted 26001 of 28692, 232.35s elapsed\nCompleted 26101 of 28692, 233.15s elapsed\nCompleted 26201 of 28692, 233.96s elapsed\nCompleted 26301 of 28692, 234.77s elapsed\nCompleted 26401 of 28692, 235.55s elapsed\nCompleted 26501 of 28692, 236.37s elapsed\nCompleted 26601 of 28692, 237.16s elapsed\nCompleted 26701 of 28692, 237.99s elapsed\nCompleted 26801 of 28692, 238.89s elapsed\nCompleted 26901 of 28692, 239.76s elapsed\nCompleted 27001 of 28692, 240.65s elapsed\nCompleted 27101 of 28692, 241.55s elapsed\nCompleted 27201 of 28692, 242.43s elapsed\nCompleted 27301 of 28692, 243.27s elapsed\nCompleted 27401 of 28692, 244.15s elapsed\nCompleted 27501 of 28692, 245.04s elapsed\nCompleted 27601 of 28692, 245.91s elapsed\nCompleted 27701 of 28692, 246.77s elapsed\nCompleted 27801 of 28692, 247.60s elapsed\nCompleted 27901 of 28692, 248.42s elapsed\nCompleted 28001 of 28692, 249.24s elapsed\nCompleted 28101 of 28692, 250.09s elapsed\nCompleted 28201 of 28692, 250.92s elapsed\nCompleted 28301 of 28692, 251.71s elapsed\nCompleted 28401 of 28692, 252.48s elapsed\nCompleted 28501 of 28692, 253.37s elapsed\nCompleted 28601 of 28692, 254.18s elapsed\nThis is Gaia DR2 - APOGEE DR14 matched parallax, RA DEC in J2000, parallax in mas\nPlease be advised that astroNN fakemag is parallax(mas) * 10 ** (0.2 * mag)\nCreating aspcap_norm_test.h5\nSuccessfully created aspcap_norm_test.h5 in D:\\University\\AST425\\astroNN_spectra_paper_figures\n" ] ], [ [ "## Train a NN with ASPCAP normalization", "_____no_output_____" ] ], [ [ "import numpy as np\n\nfrom utils_h5 import H5Loader\nfrom astroNN.models import ApogeeBCNNCensored\n\nloader = H5Loader('aspcap_norm_train') # continuum normalized dataset\nloader.load_err = True\nloader.target = ['teff', 'logg', 'C', 'C1', 'N', 'O', 'Na', 'Mg', 'Al', 'Si', 'P', 'S', 'K',\n 'Ca', 'Ti', 'Ti2', 'V', 'Cr', 'Mn', 'Fe','Co', 'Ni']\nx, y, x_err, y_err = loader.load()\n\nbcnn = ApogeeBCNNCensored()\nbcnn.num_hidden = [192, 64, 32, 16, 2] # default model size used in the paper\nbcnn.max_epochs = 60 # default max epochs used in the paper\nbcnn.autosave = True\nbcnn.folder_name = 'aspcapStar_BCNNCensored'\n\nbcnn.train(x, y, labels_err=y_err)", "Using TensorFlow backend.\n" ] ], [ [ "## Test the NN with ASPCAP normalization", "_____no_output_____" ] ], [ [ "import numpy as np\nimport pandas as pd\nfrom astropy.stats import mad_std as mad\n\nfrom utils_h5 import H5Loader\nfrom astroNN.models import ApogeeBCNNCensored, load_folder\n\nloader = H5Loader('aspcap_norm_test') # continuum normalized dataset\nloader.load_err = True\nloader.target = ['teff', 'logg', 'C', 'C1', 'N', 'O', 'Na', 'Mg', 'Al', 'Si', 'P', 'S', 'K',\n 'Ca', 'Ti', 'Ti2', 'V', 'Cr', 'Mn', 'Fe','Co', 'Ni']\nx, y, x_err, y_err = loader.load()\n\nbcnn = load_folder('aspcapStar_BCNNCensored')\n\npred, pred_error = bcnn.test(x, y)\n\nresidue = (pred - y)\n\nbias = np.ma.median(np.ma.array(residue, mask=[y == -9999.]), axis=0)\nscatter = mad(np.ma.array(residue, mask=[y == -9999.]), axis=0)\n\nd = {'Name': bcnn.targetname, 'Bias': [f'{bias_single:.{3}f}' for bias_single in bias], 'Scatter': [f'{scatter_single:.{3}f}' for scatter_single in scatter]}\ndf = pd.DataFrame(data=d)\ndf", "========================================================\nLoaded astroNN model, model type: Bayesian Convolutional Neural Network -> ApogeeBCNNCensored\n========================================================\nStarting Dropout Variational Inference\nCompleted Dropout Variational Inference with 100 forward passes, 109.53s elapsed\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
4a0a9a1594595891188f5f905aa08d18f1103fec
693,244
ipynb
Jupyter Notebook
doc/SPySort Documentation Updated.ipynb
mgraupe/SPySort
da0f1710bd7dfe0881e1ded18052e868f151aec9
[ "BSD-3-Clause" ]
null
null
null
doc/SPySort Documentation Updated.ipynb
mgraupe/SPySort
da0f1710bd7dfe0881e1ded18052e868f151aec9
[ "BSD-3-Clause" ]
null
null
null
doc/SPySort Documentation Updated.ipynb
mgraupe/SPySort
da0f1710bd7dfe0881e1ded18052e868f151aec9
[ "BSD-3-Clause" ]
null
null
null
1,305.544256
175,428
0.944555
[ [ [ "## What is SPySort?\n\nSPySort is a spike sorting package written entirely in Python. It takes advantage of Numpy, Scipy, Matplotlib, Pandas and Scikit-learn. Below, you can find a brief how-to-use tutorial.", "_____no_output_____" ], [ "### Load the data\nTo begin with, we have to load our raw data. This can be done either by using the **import_data** module of SPySort or by using a custom loading function. In the case where the user would like to use the SPySort's methods to load its data he or she has to take into account the fact that the raw data must be in plain binary format. SPySort does not yet support reading other formats such as HDF5. Here we examine the case where the user decides to use the SPySort's methods. In the demonstration case below we have already the data available on our machine. If you would like to get the data you can use the following commands before performing any further analysis.", "_____no_output_____" ], [ "#### Download the data", "_____no_output_____" ] ], [ [ "import os\nfrom urllib import urlretrieve\nimport matplotlib.pyplot as plt\n%matplotlib inline \n\ndata_names = ['Locust_' + str(i) + '.dat.gz' for i in range(1, 5)]\ndata_src = ['http://xtof.disque.math.cnrs.fr/data/'+ n for n in data_names]\n\n[urlretrieve(data_src[i], data_names[i]) for i in range(4)] \n\n[os.system('gunzip ' + n) for n in data_names]\n\ndata_files_names = ['Locust_' + str(i) + '.dat' for i in range(1, 5)]", "_____no_output_____" ] ], [ [ "#### Load the data\nOnce we have downloaded the data, we load them using the module **import_data**. This module provides the method **read_data(filenames, frequency)**, which loads all the raw data. This method takes as input the filenames and the sampling frequency. \n\nAt a next level, we can print the five numbers for each row (recording channel) using the method **five_numbers()**. The first column contains the minimal value; the second, the first quartile; the third, the median; the fourth, the third quartile; the fifth, the maximal value. Using these five numbers we can ensure that our data are proper for any further statistical analysis. Moreover, we check if some processing like a division by the standard deviation (SD) has been applied on our raw data by calling the method **checkStdDiv()**. Finally, we can obtain the size of the digitization set by calling the method **discreteStepAmpl()**.", "_____no_output_____" ] ], [ [ "import numpy as np\nfrom spysort.ReadData import import_data\n\n# Data analysis parameter\nfreq = 1.5e4 # Sampling frequency\nwin = np.array([1., 1., 1., 1., 1.])/5. # Boxcar filter\n\n# read_data instance\nr_data = import_data.read_data(data_files_names, freq) # Read raw data\n\nprint r_data.fiveNumbers() # Prints the five numbers\n\nprint r_data.checkStdDiv() # Check if our data have been divided by std\n\nprint r_data.discretStepAmpl() # Print the discretization step amplitude ", "[array([ -9.074, -0.371, -0.029, 0.326, 10.626]), array([ -8.229, -0.45 , -0.036, 0.396, 11.742]), array([-6.89 , -0.53 , -0.042, 0.469, 9.849]), array([ -7.347, -0.492, -0.04 , 0.431, 10.564])]\n[0.99999833333194166, 0.99999833333193622, 0.99999833333194788, 0.99999833333174282]\n[0.0067098450784115471, 0.0091945001879327748, 0.011888432902217971, 0.0096140421286605715]\n" ] ], [ [ "### Preprossecing the data\nOnce we have loaded the raw data and we have check that the data range (maximum - minimum) is similar (close to 20) on the four recording sites and the inter-quartiles ranges are also similar in previously described five-numbers statistics, we can proceed to the renormalization of our data.\n\nThe renormalization can be done by calling the method **renormalization()** of the **import_data** module.\nAs one can notice in the following code snippet, the attribute timeseries is not of dimension one. Indeed, the **timeseries** atribute contains the renormalized data in its first dimension and theis corresponding timestamps in the second dimension. Finally, we can plot the renormalized raw data in order to visually inspect our data. \n\nThe goal of the renormalization is to scale the raw data such that the noise SD is approximately 1. Since it is not straightforward to obtain a noise SD on data where both signal (i.e., spikes) and noise are present, we use this robust type of statistic for the SD. ", "_____no_output_____" ] ], [ [ "# Data normalization using MAD\nr_data.timeseries[0] = r_data.renormalization()\n\nr_data.plotData(r_data.data[0:300]) # Plot normalized data", "_____no_output_____" ] ], [ [ "Now, we have renormalized our data, but how we know that MAD does its job? In order to know if MAD indeed works, we can compute the Q-Q plots of the whole traces normalized with the MAD and normalized with the \"classical\" SD. This is implemented in SPySort's **chechMad()** method.", "_____no_output_____" ] ], [ [ "r_data.checkMad()", "_____no_output_____" ] ], [ [ "### Detect peaks\nAfter the normalization of the raw data, we apply a threshold method in spite of detecting peaks (possible spike events) in our raw data. Before, detect any peaks we filter the data slightly using a \"box\" filter of length 3. This means that the data points of the original trace are going to be replaced by the average of themselves with their four nearest neighbors. We will then scale the filtered traces such that the MAD is one on each recording site and keep only the parts of the signal which are above a threshold. The threshold is an argument and can be set by the user easily. \n\nThe peak detection can be done by creating a **spike_detection** instance and then calling the methods **filtering(threshold, window)** and **peaks(filtered_data, minimalDist, notZero, kind)**. The method **filtering()** takes as arguments a threshold value and the filtering window. The method **peaks()** takes as input arguments the filtered data, the minimal distance between two successive peaks, the smallest value above which the absolute value of the derivative is considered null and the sort of detection method. There are two choices for the detection method. The first one is the aggregate, where \nthe data of all channels are summed up and then the detection is performed on the \naggregated data. The second one is the classical method, where a peak detection is performed\non each signal separatelly. ", "_____no_output_____" ] ], [ [ "from spysort.Events import spikes\n\n# Create a spike_detection instance\ns = spikes.spike_detection(r_data.timeseries)\n\n# Filter the data using a boxcar window filter of length 3 and a threshold value 4\nfiltered = s.filtering(4.0, win)\n\n# Detect peaks over the filtered data\nsp0 = s.peaks(filtered, kind='aggregate')", "_____no_output_____" ] ], [ [ "### Split the data\nDepending on the nature of our raw data we can accelerate the spike sorting method by splitting our data into two or more sets. In the present example we split the data into two subsets and early and a later one. In sp0E (early), the number of detected events is: 908. On the other hand in sp0L (late), the number of detected events is: 887. Then we can plot our new filtered data sets and our detected peaks calling the methods **plotFilteredData(data, filteredData, threshold)** and **plotPeaks(data, positions)**, respectively.\n\n", "_____no_output_____" ] ], [ [ "# We split our peak positions into two subsets (left and right)\nsp0E = sp0[sp0 <= r_data.data_len/2.]\nsp0L = sp0[sp0 > r_data.data_len/2.]\n\ns.plotFilteredData(s.data, filtered, 4.) # Plot the data\ns.plotPeaks(s.data, sp0E) # Plot the peaks of the left subset", "_____no_output_____" ] ], [ [ "### Making cuts\n\nAfter detecting our spikes, we must make our cuts in order to create our events' sample. The obvious question we must first address is: How long should our cuts be? The pragmatic way to get an answer is:\n \n + Make longer cuts, like 50 sampling points on both sides of the detected event's time.\n \n + Compute robust estimates of the \"central\" event (with the median) and of the dispersion of the\n sample around this central event (with the MAD).\n \n + Plot the two together and check when does the MAD trace reach the background noise level (at 1\n since we have normalized the data).\n \n + Having the central event allows us to see if it outlasts significantly the region where the MAD \n is above the background noise level.\n \nClearly cutting beyond the time at which the MAD hits back the noise level should not bring any useful information as far a classifying the spikes is concerned. In this context, we use the method **mkEvents()** in order to build all the events and then we plot the MAD and the Median using the mehtod **plotMadMedia()**.", "_____no_output_____" ] ], [ [ "from spysort.Events import events\n\nevts = events.build_events(r_data.data, sp0E, win, before=14, after=30)\nevtsE = evts.mkEvents(otherPos=True, x=np.asarray(r_data.data) ,pos=sp0E, before=50, after=50) # Make spike events\n\nevts.plotMadMedian(evtsE) # Plot mad and median of the events", "_____no_output_____" ] ], [ [ "### Events\n\nOnce we are satisfied with our spike detection, at least in a provisory way, and that we have decided on the length of our cuts, we proceed by making cuts around the detected events using the **mkEvents()** method once again. \n\n### Noise\n\nGetting an estimate of the noise statistical properties is an essential ingredient to build respectable goodness of fit tests. In our approach \"noise events\" are essentially anything that is not an \"event\".\n\nWe could think that keeping a cut length on each side would be enough. That would indeed be the case if all events were starting from and returning to zero within a cut. But this is not the case with the cuts parameters we chose previously (that will become clear soon). You might wonder why we chose so short a cut length then. Simply to avoid having to deal with too many superposed events which are the really bothering events for anyone wanting to do proper sorting. To obtain our noise events we are going to use the method\n**mkNoise()**.", "_____no_output_____" ] ], [ [ "evtsE = evts.mkEvents() # Make spike events\nnoise = evts.mkNoise() # Make noise events\n\nevts.plotEvents(evtsE) # Plot events", "_____no_output_____" ] ], [ [ "### Getting \"clean\" events\n\nOur spike sorting has two main stages, the first one consist in estimating a model and the second one consists in using this model to classify the data. Our model is going to be built out of reasonably \"clean\" events. Here by clean we mean events which are not due to a nearly simultaneous firing of two or more neurons; and simultaneity is defined on the time scale of one of our cuts. When the model will be subsequently used to classify data, events are going to decomposed into their (putative) constituent when they are not \"clean\", that is, superposition are going to be looked and accounted for.\n\nIn order to eliminate the most obvious superpositions we are going to use a rather brute force approach, looking at the sides of the central peak of our median event and checking if individual events are not too large there, that is do not exhibit extra peaks. We first define a function doing this job:", "_____no_output_____" ], [ "### Dimension reduction", "_____no_output_____" ] ], [ [ "from spysort.Events import clusters\n\n# Create a clusters instance\nc = clusters.pca_clustering(r_data.timeseries[0], sp0E, win, thr=8, before=14, after=30)\n\nprint c.pcaVariance(10) # Print the variance of the PCs\n\nc.plotMeanPca() # Plot the mean +- PC\nc.plotPcaProjections() # Plot the projections of the PCs on the data", "[(0, -576.61794224907885), (1, -276.53159175880285), (2, -186.62984905302847), (3, -127.10551508861568), (4, -90.385106529223435), (5, -57.906325031919664), (6, -35.429504876530245), (7, -20.610159843611314), (8, -7.3309326071264422), (9, 1.2184518646396327)]\n" ] ], [ [ "### Clustering", "_____no_output_____" ] ], [ [ "CSize = 10 # Cluster size\n\nkmeans_clusters = c.KMeans(CSize) # K-means clustering\n\n# gmmClusters = c.GMM(10, 'diag') # GMM clustering\n\nc.plotClusters(kmeans_clusters) # Plot the clusters", "_____no_output_____" ] ], [ [ "### Spike \"peeling\"", "_____no_output_____" ] ], [ [ "from spysort.Events import alignment\n\n#(data, positions, goodEvts, clusters, CSize, win=[],\n# before=14, after=30, thr=3)\n\nalign = alignment.align_events(r_data.data,sp0E,c.goodEvts,kmeans_clusters,CSize,win=win)\n\n\ncenters = {\"Cluster \" + str(i): align.mk_center_dictionary(sp0E[c.goodEvts][np.array(kmeans_clusters) == i])\n for i in range(CSize)}\n# c10b\n# Apply it to every detected event\n# Warning do it like this\nround0 = [align.classify_and_align_evt(sp0[i], centers) for i in range(len(sp0))]\n\nprint(len([x[1] for x in round0 if x[0] == '?']))\n\n# Apply it\npred0 = align.predict_data(round0, centers)\ndata1 = np.array(r_data.timeseries[0]) - pred0\n\ndata_filtered = np.apply_along_axis(lambda x: np.convolve(x, np.array([1, 1, 1])/3.), 1, data1)\ndata_filtered = (data_filtered.transpose() / np.apply_along_axis(mad, 1, data_filtered)).transpose()\ndata_filtered[data_filtered < 4.] = 0\nprint data_filtered[0, :].shape\n\nsp1 = s.peaks(data_filtered[0, :], kind='simple')\nprint(len(sp1))\n\nround1 = [align.classify_and_align_evt(sp1[i], centers, otherData=True, \n x=data1) for i in range(len(sp1))]\n\nprint(len([x[1] for x in round1 if x[0] == '?']))\n\npred1 = align.predict_data(round1, centers)\ndata2 = data1 - pred1", "33\n" ], [ "dir(alignment)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ] ]
4a0a9bfdda7e1f51a43e77179a8ade14bafa2557
17,418
ipynb
Jupyter Notebook
summer-2018-model/notebooks-max/assign_job_ids_to_persons.ipynb
lmwang9527/ual_model_workspace
cdbab19cfaf2cb4d0f9cfbdaf890607a107308cd
[ "BSD-3-Clause" ]
1
2019-02-20T00:10:49.000Z
2019-02-20T00:10:49.000Z
summer-2018-model/notebooks-max/assign_job_ids_to_persons.ipynb
lmwang9527/ual_model_workspace
cdbab19cfaf2cb4d0f9cfbdaf890607a107308cd
[ "BSD-3-Clause" ]
1
2019-02-06T00:50:20.000Z
2019-02-06T00:50:20.000Z
summer-2018-model/notebooks-max/assign_job_ids_to_persons.ipynb
lmwang9527/ual_model_workspace
cdbab19cfaf2cb4d0f9cfbdaf890607a107308cd
[ "BSD-3-Clause" ]
1
2019-02-20T00:22:40.000Z
2019-02-20T00:22:40.000Z
42.796069
6,152
0.67258
[ [ [ "import os; os.chdir('../')\nfrom tqdm import tqdm", "_____no_output_____" ], [ "import pandas as pd\nimport numpy as np\nfrom sklearn.neighbors import BallTree\n%matplotlib inline", "_____no_output_____" ], [ "from urbansim_templates import modelmanager as mm\nfrom urbansim_templates.models import MNLDiscreteChoiceStep\nfrom urbansim.utils import misc\nfrom scripts import datasources, models\nimport orca", "_____no_output_____" ] ], [ [ "### Load data", "_____no_output_____" ] ], [ [ "chts_persons = pd.read_csv('/home/mgardner/data/chts-orig/data/Deliv_PER.csv', low_memory=False)", "_____no_output_____" ], [ "chts_persons_lookup = pd.read_csv('/home/mgardner/data/chts-orig/data/LookUp_PER.csv')", "_____no_output_____" ], [ "chts_persons = pd.merge(\n chts_persons.set_index(['SAMPN','PERNO']),\n chts_persons_lookup.set_index(['SAMPN','PERNO']),\n left_index=True, right_index=True,\n suffixes=('_persons', '_lookup')).reset_index()", "_____no_output_____" ], [ "chts_homes = pd.read_csv('/home/mgardner/data/chts-orig/data/LookUp_Home.csv')", "_____no_output_____" ], [ "chts_persons = pd.merge(chts_persons, chts_homes, on='SAMPN')", "_____no_output_____" ], [ "# SF Bay Area only!\nchts_persons = chts_persons[chts_persons['HCTFIP'].isin([1, 13, 41, 55, 75, 81, 85, 95, 97])].reset_index()", "_____no_output_____" ], [ "jobs = pd.read_csv('/home/mgardner/data/jobs_w_occup.csv')", "_____no_output_____" ], [ "buildings = pd.read_hdf('./data/bayarea_ual.h5', 'buildings')", "_____no_output_____" ], [ "parcels = pd.read_hdf('./data/bayarea_ual.h5', 'parcels')", "_____no_output_____" ] ], [ [ "### Get job coords", "_____no_output_____" ] ], [ [ "buildings = pd.merge(buildings, parcels[['x', 'y']], left_on='parcel_id', right_index=True)\n\njobs = pd.merge(jobs, buildings[['x', 'y']], left_on='building_id', right_index=True)\njobs.rename(columns={'x': 'lng', 'y': 'lat'}, inplace=True)", "_____no_output_____" ] ], [ [ "### Assign jobs a node ID", "_____no_output_____" ] ], [ [ "# load the network nodes\nnodes = pd.read_csv('~/data/bay_area_full_strongly_nodes.csv')\nnodes = nodes.set_index('osmid')\nassert nodes.index.is_unique", "_____no_output_____" ], [ "# haversine requires data in form of [lat, lng] and inputs/outputs in units of radians\nnodes_rad = np.deg2rad(nodes[['y', 'x']])\npersons_rad = np.deg2rad(chts_persons[['WYCORD_lookup', 'WXCORD_lookup']])\njobs_rad = np.deg2rad(jobs[['lng', 'lat']])", "_____no_output_____" ], [ "# build the tree for fast nearest-neighbor search\ntree = BallTree(nodes_rad, metric='haversine')", "_____no_output_____" ], [ "# query the tree for nearest node to each home\nidx = tree.query(jobs_rad, return_distance=False)\njobs['node_id'] = nodes.iloc[idx[:,0]].index", "_____no_output_____" ], [ "jobs.to_csv('/home/mgardner/data/jobs_w_occup_and_node.csv', index=False)", "_____no_output_____" ] ], [ [ "### Assign CHTS persons a job ID", "_____no_output_____" ] ], [ [ "dists = []\nno_job_info = []\nno_work_coords = []\n\n# new columnd in CHTS persons to store job_id\nchts_persons.loc[:, 'job_id'] = None\n\n# prepare jobs table\njobs.loc[:, 'taken'] = False\njobs.loc[:, 'x'] = jobs_rad['lng']\njobs.loc[:, 'y'] = jobs_rad['lat']\n\nfor i, person in tqdm(chts_persons.iterrows(), total=len(chts_persons)):\n \n # only assign a job ID for employed persons with a fixed work location\n if (person['EMPLY'] == 1) & (person['WLOC'] == 1):\n \n # skip person if no CHTS industry or occupation\n if (person['INDUS'] > 96) & (person['OCCUP'] > 96):\n no_job_info.append(i)\n continue\n \n # skip person if no work location\n elif pd.isnull(person[['WYCORD_lookup', 'WXCORD_lookup']]).any():\n no_work_coords.append(i)\n continue\n \n # if CHTS industry is unknown, match jobs based on occupation only\n elif person['INDUS'] > 96:\n potential_jobs = jobs[\n (jobs['occupation_id'] == person['OCCUP']) &\n (jobs['taken'] == False)]\n \n # if occupation is unknown, match jobs based on industry only\n elif person['OCCUP'] > 96:\n potential_jobs = jobs[\n (jobs['naics'] == person['INDUS']) &\n (jobs['taken'] == False)]\n \n elif (person['INDUS'] < 97) & (person['OCCUP'] < 97):\n \n # define potential jobs based on industry and occupation\n potential_jobs = jobs[\n (jobs['naics'] == person['INDUS']) &\n (jobs['occupation_id'] == person['OCCUP']) &\n (jobs['taken'] == False)]\n \n # if no such jobs exist, define jobs by industry\n if len(potential_jobs) == 0:\n potential_jobs = jobs[\n (jobs['naics'] == person['INDUS']) &\n (jobs['taken'] == False)]\n \n # if no such jobs exist, define jobs by occupation\n if len(potential_jobs) == 0:\n potential_jobs = jobs[\n (jobs['occupation_id'] == person['OCCUP']) &\n (jobs['taken'] == False)]\n \n # otherwise, continue\n if len(potential_jobs) == 0:\n continue\n \n # build the tree of potential jobs for fast nearest-neighbor search\n tree = BallTree(potential_jobs[['y','x']], metric='haversine')\n \n # query the tree for nearest job to each workplace\n dist, idx = tree.query(persons_rad.iloc[i].values.reshape(1,-1), return_distance=True)\n \n # save results\n job = potential_jobs.iloc[idx[0][0]]\n dists.append(dist[0][0])\n chts_persons.loc[i, 'job_id'] = job['job_id']\n jobs.loc[jobs['job_id'] == job['job_id'], 'taken'] = True \n", "100%|██████████| 24030/24030 [24:09<00:00, 16.57it/s]\n" ], [ "chts_persons.to_csv('./data/chts_persons_with_job_id.csv', index=False)", "_____no_output_____" ], [ "# convert dists from radians to kilometers\ndists = [dist * 6371 for dist in dists]", "_____no_output_____" ], [ "pd.Series(dists).plot(kind='hist', bins=20000, xlim=(0, 20), normed=True)", "_____no_output_____" ], [ "print('Assigned job IDs to {0}% of workers with a fixed work location.'.format(\n np.round(chts_persons.job_id.count() / len(\n chts_persons[(chts_persons['EMPLY'] == 1) & (chts_persons['WLOC'] == 1)]) * 100, 1)))\nprint('{0}% had no industry/occupation info.'.format(\n np.round(len(no_job_info) / len(\n chts_persons[(chts_persons['EMPLY'] == 1) & (chts_persons['WLOC'] == 1)]) * 100, 1)))\nprint('{0}% had no work coordinates.'.format(\n np.round(len(no_work_coords) / len(\n chts_persons[(chts_persons['EMPLY'] == 1) & (chts_persons['WLOC'] == 1)]) * 100, 1)))", "Assigned job IDs to 98.1% of workers with a fixed work location.\n1.8% had no industry/occupation info.\n0.0% had no work coordinates.\n" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ] ]
4a0aad54b62f9d9c3203b157d37281c36994536c
890,994
ipynb
Jupyter Notebook
Unsupervised Learning in R.ipynb
VictorOmondi1997/Unsupervised-Learning-in-R
e0a4198015f0cd7de19f104af3f43323551fcbf7
[ "MIT" ]
null
null
null
Unsupervised Learning in R.ipynb
VictorOmondi1997/Unsupervised-Learning-in-R
e0a4198015f0cd7de19f104af3f43323551fcbf7
[ "MIT" ]
null
null
null
Unsupervised Learning in R.ipynb
VictorOmondi1997/Unsupervised-Learning-in-R
e0a4198015f0cd7de19f104af3f43323551fcbf7
[ "MIT" ]
null
null
null
161.587595
117,110
0.855747
[ [ [ "# Unsupervised Learning in R\n\n> clustering and dimensionality reduction in R from a machine learning perspective\n\n- author: Victor Omondi\n- toc: true\n- comments: true\n- categories: [unsupervised-learning, machine-learning, r]\n- image: images/ield.png", "_____no_output_____" ], [ "# Overview\n\nMany times in machine learning, the goal is to find patterns in data without trying to make predictions. This is called unsupervised learning. One common use case of unsupervised learning is grouping consumers based on demographics and purchasing history to deploy targeted marketing campaigns. Another example is wanting to describe the unmeasured factors that most influence crime differences between cities. We will cover basic introduction to clustering and dimensionality reduction in R from a machine learning perspective, so that we can get from data to insights as quickly as possible.\n", "_____no_output_____" ], [ "# Libraries", "_____no_output_____" ] ], [ [ "library(readr)\nlibrary(ggplot2)\nlibrary(dplyr)", "Warning message:\n\"package 'readr' was built under R version 3.6.3\"Warning message:\n\"package 'dplyr' was built under R version 3.6.3\"\nAttaching package: 'dplyr'\n\nThe following objects are masked from 'package:stats':\n\n filter, lag\n\nThe following objects are masked from 'package:base':\n\n intersect, setdiff, setequal, union\n\n" ] ], [ [ "# Unsupervised learning in R\n\nThe k-means algorithm is one common approach to clustering. We will explore how the algorithm works under the hood, implement k-means clustering in R, visualize and interpret the results, and select the number of clusters when it's not known ahead of time. We'll have applied k-means clustering to a fun \"real-world\" dataset!", "_____no_output_____" ], [ "### Types of machine learning\n- Unsupervised learning\n - Finding structure in unlabeled data\n- Supervised learning\n - Making predictions based on labeled data\n - Predictions like regression or classication\n- Reinforcement learning", "_____no_output_____" ], [ "### Unsupervised learning - clustering\n- Finding homogeneous subgroups within larger group \n- _People have features such as income, education attainment, and gender_\n", "_____no_output_____" ], [ "### Unsupervised learning - dimensionality reduction\n- Finding homogeneous subgroups within larger group\n - Clustering\n- Finding patterns in the features of the data\n - Dimensionality reduction\n - Find patterns in the features of the data\n - Visualization of high dimensional data\n - Pre-processing before supervised learning\n", "_____no_output_____" ], [ "### Challenges and benefits\n- No single goal of analysis\n- Requires more creativity\n- Much more unlabeled data available than cleanly labeled data\n", "_____no_output_____" ], [ "## Introduction to k-means clustering\n\n### k-means clustering algorithm\n- Breaks observations into pre-dened number of clusters\n\n### k-means in R\n\n- One observation per row, one feature per column\n- k-means has a random component\n- Run algorithm multiple times to improve odds of the best model\n", "_____no_output_____" ] ], [ [ "x <- as.matrix(x_df <- read_csv(\"datasets/x.csv\"))\nclass(x)", "Parsed with column specification:\ncols(\n V1 = col_double(),\n V2 = col_double()\n)\n" ], [ "head(x)", "_____no_output_____" ] ], [ [ "### k-means clustering\n\nWe have created some two-dimensional data and stored it in a variable called `x`.", "_____no_output_____" ] ], [ [ "x_df %>%\n ggplot(aes(x=V1, y=V2)) +\n geom_point()", "_____no_output_____" ] ], [ [ "The scatter plot on the above is a visual representation of the data.\n\nWe will create a k-means model of the `x` data using 3 clusters, then to look at the structure of the resulting model using the `summary()` function.", "_____no_output_____" ] ], [ [ "# Create the k-means model: km.out\nkm.out_x <- kmeans(x, centers=3, nstart=20)\n\n# Inspect the result\nsummary(km.out_x)", "_____no_output_____" ] ], [ [ "### Results of kmeans()\n\nThe `kmeans()` function produces several outputs. One is the output of modeling, the cluster membership. We will access the `cluster` component directly. This is useful anytime we need the cluster membership for each observation of the data used to build the clustering model. This cluster membership might be used to help communicate the results of k-means modeling.\n\n`k-means` models also have a print method to give a human friendly output of basic modeling results. This is available by using `print()` or simply typing the name of the model.", "_____no_output_____" ] ], [ [ "# Print the cluster membership component of the model\nkm.out_x$cluster\n\n", "_____no_output_____" ], [ "# Print the km.out object\nkm.out_x", "_____no_output_____" ] ], [ [ "### Visualizing and interpreting results of kmeans()\n\nOne of the more intuitive ways to interpret the results of k-means models is by plotting the data as a scatter plot and using color to label the samples' cluster membership. We will use the standard `plot()` function to accomplish this.\n\nTo create a scatter plot, we can pass data with two features (i.e. columns) to `plot()` with an extra argument `col = km.out$cluster`, which sets the color of each point in the scatter plot according to its cluster membership.", "_____no_output_____" ] ], [ [ "# Scatter plot of x\nplot(x, main=\"k-means with 3 clusters\", col=km.out_x$cluster, xlab=\"\", ylab=\"\")", "_____no_output_____" ] ], [ [ "## How k-means works and practical matters\n\n### Objectives\n- Explain how k-means algorithm is implemented visually\n- **Model selection**: determining number of clusters\n\n### Model selection\n- Recall k-means has a random component\n- Best outcome is based on total within cluster sum of squares:\n - For each cluster\n - For each observation in the cluster\n - Determine squared distance from observation to cluster center\n - Sum all of them together\n- Running algorithm multiple times helps find the global minimum total within cluster sum of squares", "_____no_output_____" ], [ "### Handling random algorithms\n\n`kmeans()` randomly initializes the centers of clusters. This random initialization can result in assigning observations to different cluster labels. Also, the random initialization can result in finding different local minima for the k-means algorithm. we will demonstrate both results.\n\nAt the top of each plot, the measure of model quality—total within cluster sum of squares error—will be plotted. Look for the model(s) with the lowest error to find models with the better model results.\n\nBecause `kmeans()` initializes observations to random clusters, it is important to set the random number generator seed for reproducibility.", "_____no_output_____" ] ], [ [ "# Set up 2 x 3 plotting grid\npar(mfrow = c(2, 3))\n\n# Set seed\nset.seed(1)\n\nfor(i in 1:6) {\n # Run kmeans() on x with three clusters and one start\n km.out <- kmeans(x, centers=3, nstart=1)\n \n # Plot clusters\n plot(x, col = km.out$cluster, \n main = km.out$tot.withinss, \n xlab = \"\", ylab = \"\")\n}", "_____no_output_____" ] ], [ [ "Because of the random initialization of the k-means algorithm, there's quite some variation in cluster assignments among the six models.", "_____no_output_____" ], [ "### Selecting number of clusters\n\nThe k-means algorithm assumes the number of clusters as part of the input. If you know the number of clusters in advance (e.g. due to certain business constraints) this makes setting the number of clusters easy. However, if you do not know the number of clusters and need to determine it, you will need to run the algorithm multiple times, each time with a different number of clusters. From this, we can observe how a measure of model quality changes with the number of clusters.\n\nWe will run `kmeans()` multiple times to see how model quality changes as the number of clusters changes. Plots displaying this information help to determine the number of clusters and are often referred to as scree plots.\n\nThe ideal plot will have an elbow where the quality measure improves more slowly as the number of clusters increases. This indicates that the quality of the model is no longer improving substantially as the model complexity (i.e. number of clusters) increases. In other words, the elbow indicates the number of clusters inherent in the data.", "_____no_output_____" ] ], [ [ "# Initialize total within sum of squares error: wss\nwss <- 0\n\n# For 1 to 15 cluster centers\nfor (i in 1:15) {\n km.out <- kmeans(x, centers = i, nstart=20)\n # Save total within sum of squares to wss variable\n wss[i] <- km.out$tot.withinss\n}\n\n# Plot total within sum of squares vs. number of clusters\nplot(1:15, wss, type = \"b\", \n xlab = \"Number of Clusters\", \n ylab = \"Within groups sum of squares\")\n\n", "_____no_output_____" ], [ "# Set k equal to the number of clusters corresponding to the elbow location\nk <- 2", "_____no_output_____" ] ], [ [ "Looking at the scree plot, it looks like there are inherently 2 or 3 clusters in the data.", "_____no_output_____" ], [ "## Introduction to the Pokemon data\n", "_____no_output_____" ] ], [ [ "pokemon <- read_csv(\"datasets//Pokemon.csv\")\nhead(pokemon)", "Parsed with column specification:\ncols(\n Number = col_double(),\n Name = col_character(),\n Type1 = col_character(),\n Type2 = col_character(),\n Total = col_double(),\n HitPoints = col_double(),\n Attack = col_double(),\n Defense = col_double(),\n SpecialAttack = col_double(),\n SpecialDefense = col_double(),\n Speed = col_double(),\n Generation = col_double(),\n Legendary = col_logical()\n)\n" ] ], [ [ "### Data challenges\n- Selecting the variables to cluster upon\n- Scaling the data\n- Determining the number of clusters\n - Often no clean \"elbow\" in scree plot\n - This will be a core part. \n- Visualize the results for interpretation\n", "_____no_output_____" ], [ "### Practical matters: working with real data\n\nDealing with real data is often more challenging than dealing with synthetic data. Synthetic data helps with learning new concepts and techniques, but we will deal with data that is closer to the type of real data we might find in the professional or academic pursuits.\n\nThe first challenge with the Pokemon data is that there is no pre-determined number of clusters. We will determine the appropriate number of clusters, keeping in mind that in real data the elbow in the scree plot might be less of a sharp elbow than in synthetic data. We'll use our judgement on making the determination of the number of clusters.\n\nWe'll be plotting the outcomes of the clustering on two dimensions, or features, of the data.\n\nAn additional note: We'll utilize the `iter.max` argument to `kmeans()`. `kmeans()` is an iterative algorithm, repeating over and over until some stopping criterion is reached. The default number of iterations for `kmeans()` is 10, which is not enough for the algorithm to converge and reach its stopping criterion, so we'll set the number of iterations to 50 to overcome this issue. ", "_____no_output_____" ] ], [ [ "head(pokemon <- pokemon %>%\n select(HitPoints:Speed))", "_____no_output_____" ], [ "# Initialize total within sum of squares error: wss\nwss <- 0\n\n# Look over 1 to 15 possible clusters\nfor (i in 1:15) {\n # Fit the model: km.out\n km.out <- kmeans(pokemon, centers = i, nstart = 20, iter.max = 50)\n # Save the within cluster sum of squares\n wss[i] <- km.out$tot.withinss\n}\n\n# Produce a scree plot\nplot(1:15, wss, type = \"b\", \n xlab = \"Number of Clusters\", \n ylab = \"Within groups sum of squares\")\n\n", "_____no_output_____" ], [ "# Select number of clusters\nk <- 2\n\n# Build model with k clusters: km.out\nkm.out <- kmeans(pokemon, centers = 2, nstart = 20, iter.max = 50)\n\n# View the resulting model\nkm.out\n\n", "_____no_output_____" ], [ "# Plot of Defense vs. Speed by cluster membership\nplot(pokemon[, c(\"Defense\", \"Speed\")],\n col = km.out$cluster,\n main = paste(\"k-means clustering of Pokemon with\", k, \"clusters\"),\n xlab = \"Defense\", ylab = \"Speed\")", "_____no_output_____" ] ], [ [ "## Review of k-means clustering\n\n### Chapter review\n- Unsupervised vs. supervised learning\n- How to create k-means cluster model in R\n- How k-means algorithm works\n- Model selection\n- Application to \"real\" (and hopefully fun) dataset\n", "_____no_output_____" ], [ "# Hierarchical clustering\n\nHierarchical clustering is another popular method for clustering. We will go over how it works, how to use it, and how it compares to k-means clustering.\n\n", "_____no_output_____" ], [ "## Introduction to hierarchical clustering\n\n### Hierarchical clustering\n- Number of clusters is not known ahead of time\n- Two kinds: bottom-up and top-down, we will focus on bottom-up\n\n### Hierarchical clustering in R", "_____no_output_____" ] ], [ [ "dist_matrix <- dist(x)\nhclust(dist_matrix)", "_____no_output_____" ], [ "head(x <- as.matrix(x_df <- read_csv(\"datasets//x2.csv\")))", "Parsed with column specification:\ncols(\n V1 = col_double(),\n V2 = col_double()\n)\n" ], [ "class(x)", "_____no_output_____" ] ], [ [ "### Hierarchical clustering with results\n\nWe will create hierarchical clustering model using the `hclust()` function.", "_____no_output_____" ] ], [ [ "# Create hierarchical clustering model: hclust.out\nhclust.out <- hclust(dist(x))\n\n# Inspect the result\nsummary(hclust.out)", "_____no_output_____" ] ], [ [ "## Selecting number of clusters\n\n### Dendrogram\n- Tree shaped structure used to interpret hierarchical clustering models", "_____no_output_____" ] ], [ [ "plot(hclust.out)\nabline(h=6, col=\"red\")\nabline(h=3.5, col=\"red\")\nabline(h=4.5, col=\"red\")\nabline(h=6.9, col=\"red\")\nabline(h=9, col=\"red\")", "_____no_output_____" ] ], [ [ "If you cut the tree at a height of 6.9, you're left with 3 branches representing 3 distinct clusters.", "_____no_output_____" ], [ "### Tree \"cutting\" in R\n\n`cutree()` is the R function that cuts a hierarchical model. The `h` and `k` arguments to `cutree()` allow you to cut the tree based on a certain height `h` or a certain number of clusters `k`.", "_____no_output_____" ] ], [ [ "cutree(hclust.out, h=6)", "_____no_output_____" ], [ "cutree(hclust.out, k=2)", "_____no_output_____" ], [ "# Cut by height\ncutree(hclust.out, h=7)\n\n", "_____no_output_____" ], [ "# Cut by number of clusters\ncutree(hclust.out, k=3)", "_____no_output_____" ] ], [ [ "The output of each `cutree()` call represents the cluster assignments for each observation in the original dataset", "_____no_output_____" ], [ "## Clustering linkage and practical matters\n\n### Linking clusters in hierarchical clustering\n- How is distance between clusters determined? Rules?\n- Four methods to determine which cluster should be linked\n - **Complete**: pairwise similarity between all observations in cluster 1 and cluster 2, and uses ***largest of similarities***\n - **Single**: same as above but uses ***smallest of similarities***\n - **Average**: same as above but uses ***average of similarities***\n - **Centroid**: finds centroid of cluster 1 and centroid of cluster 2, and uses ***similarity between two centroids***\n", "_____no_output_____" ], [ "### Linkage in R", "_____no_output_____" ] ], [ [ "hclust.complete <- hclust(dist(x), method = \"complete\")\nhclust.average <- hclust(dist(x), method = \"average\")\nhclust.single <- hclust(dist(x), method = \"single\")\n\nplot(hclust.complete, main=\"Complete\")", "_____no_output_____" ], [ "plot(hclust.average, main=\"Average\")", "_____no_output_____" ], [ "plot(hclust.single, main=\"Single\")", "_____no_output_____" ] ], [ [ "Whether you want balanced or unbalanced trees for hierarchical clustering model depends on the context of the problem you're trying to solve. Balanced trees are essential if you want an even number of observations assigned to each cluster. On the other hand, if you want to detect outliers, for example, an unbalanced tree is more desirable because pruning an unbalanced tree can result in most observations assigned to one cluster and only a few observations assigned to other clusters.", "_____no_output_____" ], [ "### Practical matters\n- Data on different scales can cause undesirable results in clustering methods\n- Solution is to scale data so that features have same mean and standard deviation\n - Subtract mean of a feature from all observations\n - Divide each feature by the standard deviation of the feature\n - Normalized features have a mean of zero and a standard deviation of one\n", "_____no_output_____" ] ], [ [ "colMeans(x)", "_____no_output_____" ], [ "apply(x, 2, sd)", "_____no_output_____" ], [ "scaled_x <- scale(x)\ncolMeans(scaled_x)", "_____no_output_____" ], [ "apply(scaled_x, 2, sd)", "_____no_output_____" ] ], [ [ "### Linkage methods\n\nWe will produce hierarchical clustering models using different linkages and plot the dendrogram for each, observing the overall structure of the trees.", "_____no_output_____" ], [ "### Practical matters: scaling\n\nClustering real data may require scaling the features if they have different distributions. We will go back to working with \"real\" data, the `pokemon` dataset. We will observe the distribution (mean and standard deviation) of each feature, scale the data accordingly, then produce a hierarchical clustering model using the complete linkage method.\n\n", "_____no_output_____" ] ], [ [ "# View column means\ncolMeans(pokemon)\n\n", "_____no_output_____" ], [ "# View column standard deviations\napply(pokemon, 2, sd)\n\n", "_____no_output_____" ], [ "# Scale the data\npokemon.scaled = scale(pokemon)\n\n# Create hierarchical clustering model: hclust.pokemon\nhclust.pokemon <- hclust(dist(pokemon.scaled), method=\"complete\")", "_____no_output_____" ] ], [ [ "### Comparing kmeans() and hclust()\n\nComparing k-means and hierarchical clustering, we'll see the two methods produce different cluster memberships. This is because the two algorithms make different assumptions about how the data is generated. In a more advanced course, we could choose to use one model over another based on the quality of the models' assumptions, but for now, it's enough to observe that they are different.\n\nWe will have compare results from the two models on the pokemon dataset to see how they differ.", "_____no_output_____" ] ], [ [ "# Apply cutree() to hclust.pokemon: cut.pokemon\ncut.pokemon<- cutree(hclust.pokemon, k=3)\n\n# Compare methods\ntable(km.out$cluster, cut.pokemon)", "_____no_output_____" ] ], [ [ "# Dimensionality reduction with PCA\n\nPrincipal component analysis, or PCA, is a common approach to dimensionality reduction. We'll explore exactly what PCA does, visualize the results of PCA with biplots and scree plots, and deal with practical issues such as centering and scaling the data before performing PCA.", "_____no_output_____" ], [ "## Introduction to PCA\n\n### Two methods of clustering\n- Two methods of clustering - finding groups of homogeneous items\n- Next up, dimensionality reduction\n - Find structure in features\n - Aid in visualization\n", "_____no_output_____" ], [ "### Dimensionality reduction\n- A popular method is principal component analysis (PCA)\n- Three goals when finding lower dimensional representation of features:\n - Find linear combination of variables to create principal components\n - Maintain most variance in the data\n - Principal components are uncorrelated (i.e. orthogonal to each other)\n", "_____no_output_____" ] ], [ [ "head(iris)", "_____no_output_____" ] ], [ [ "### PCA in R\n", "_____no_output_____" ] ], [ [ "summary(\n pr.iris <- prcomp(x=iris[-5], scale=F, center=T)\n)", "_____no_output_____" ] ], [ [ "### PCA using prcomp()\nWe will create PCA model and observe the diagnostic results.\n\nWe have loaded the Pokemon data, which has four dimensions, and placed it in a variable called `pokemon`. We'll create a PCA model of the data, then to inspect the resulting model using the `summary()` function.", "_____no_output_____" ] ], [ [ "# Perform scaled PCA: pr.out\npr.out <- prcomp(pokemon, scale=T)\n\n# Inspect model output\nsummary(pr.out)", "_____no_output_____" ] ], [ [ "The first 3 principal components describe around 77% of the variance.", "_____no_output_____" ], [ "### Additional results of PCA\nPCA models in R produce additional diagnostic and output components:\n\n- `center`: the column means used to center to the data, or `FALSE` if the data weren't centered\n- `scale`: the column standard deviations used to scale the data, or `FALSE` if the data weren't scaled\n- `rotation`: the directions of the principal component vectors in terms of the original features/variables. This information allows you to define new data in terms of the original principal components\n- `x`: the value of each observation in the original dataset projected to the principal components\nYou can access these the same as other model components. For example, use `pr.out$rotation` to access the rotation component", "_____no_output_____" ] ], [ [ "head(pr.out$x)", "_____no_output_____" ], [ "pr.out$center", "_____no_output_____" ], [ "pr.out$scale", "_____no_output_____" ] ], [ [ "## Visualizing and interpreting PCA results\n\n### Biplots in R", "_____no_output_____" ] ], [ [ "biplot(pr.iris)", "_____no_output_____" ] ], [ [ "Petal.Width and Petal.Length are correlated in the original dataset.", "_____no_output_____" ], [ "### Scree plots in R", "_____no_output_____" ] ], [ [ "# Getting proportion of variance for a scree plot\npr.var <- pr.iris$sdev^2\npve <- pr.var/sum(pr.var)\n# Plot variance explained for each principal component\nplot(pve, main=\"variance explained for each principal component\", \n xlab=\"Principal component\", ylab=\"Proportion of Variance Explained\", ylim=c(0,1), type=\"b\")", "_____no_output_____" ] ], [ [ "### Interpreting biplots (1)\n\nThe `biplot()` function plots both the principal components loadings and the mapping of the observations to their first two principal component values. We will do interpretation of the `biplot()` visualization.\n\nUsing the `biplot()` of the `pr.out` model, which two original variables have approximately the same loadings in the first two principal components?", "_____no_output_____" ] ], [ [ "biplot(pr.out)", "_____no_output_____" ] ], [ [ "`Attack` and `HitPoints` have approximately the same loadings in the first two principal components", "_____no_output_____" ], [ "### Variance explained\n\nThe second common plot type for understanding PCA models is a scree plot. A scree plot shows the variance explained as the number of principal components increases. Sometimes the cumulative variance explained is plotted as well.\n\nWe will prepare data from the `pr.out` modelfor use in a scree plot. Preparing the data for plotting is required because there is not a built-in function in R to create this type of plot.", "_____no_output_____" ] ], [ [ "# Variability of each principal component: pr.var\npr.var <- pr.out$sdev^2\n\n# Variance explained by each principal component: pve\npve <-pr.var / sum(pr.var)", "_____no_output_____" ] ], [ [ "### Visualize variance explained\n\nNow we will create a scree plot showing the proportion of variance explained by each principal component, as well as the cumulative proportion of variance explained.\n\nThese plots can help to determine the number of principal components to retain. One way to determine the number of principal components to retain is by looking for an elbow in the scree plot showing that as the number of principal components increases, the rate at which variance is explained decreases substantially. In the absence of a clear elbow, we can use the scree plot as a guide for setting a threshold.", "_____no_output_____" ] ], [ [ "# Plot variance explained for each principal component\nplot(pve, xlab = \"Principal Component\",\n ylab = \"Proportion of Variance Explained\",\n ylim = c(0, 1), type = \"b\")\n\n", "_____no_output_____" ], [ "# Plot cumulative proportion of variance explained\nplot(cumsum(pve), xlab = \"Principal Component\",\n ylab = \"Cumulative Proportion of Variance Explained\",\n ylim = c(0, 1), type = \"b\")", "_____no_output_____" ] ], [ [ "when the number of principal components is equal to the number of original features in the data, the cumulative proportion of variance explained is 1.", "_____no_output_____" ], [ "### Practical issues with PCA\n\n- Scaling the data\n- Missing values:\n - Drop observations with missing values\n - Impute / estimate missing values\n- Categorical data:\n - Do not use categorical data features\n - Encode categorical features as numbers\n", "_____no_output_____" ], [ "### mtcars dataset", "_____no_output_____" ] ], [ [ "head(mtcars)", "_____no_output_____" ] ], [ [ "### Scaling", "_____no_output_____" ] ], [ [ "# Means and standard deviations vary a lot\nround(colMeans(mtcars), 2)", "_____no_output_____" ], [ "round(apply(mtcars, 2, sd), 2)", "_____no_output_____" ], [ "biplot(prcomp(mtcars, center=T, scale=F))", "_____no_output_____" ], [ "biplot(prcomp(mtcars, scale=T, center=T))", "_____no_output_____" ] ], [ [ "### Practical issues: scaling\n\nScaling data before doing PCA changes the results of the PCA modeling. Here, we will perform PCA with and without scaling, then visualize the results using biplots.\n\nSometimes scaling is appropriate when the variances of the variables are substantially different. This is commonly the case when variables have different units of measurement, for example, degrees Fahrenheit (temperature) and miles (distance). Making the decision to use scaling is an important step in performing a principal component analysis.", "_____no_output_____" ] ], [ [ "head(pokemon <- read_csv(\"datasets//Pokemon.csv\"))", "Parsed with column specification:\ncols(\n Number = col_double(),\n Name = col_character(),\n Type1 = col_character(),\n Type2 = col_character(),\n Total = col_double(),\n HitPoints = col_double(),\n Attack = col_double(),\n Defense = col_double(),\n SpecialAttack = col_double(),\n SpecialDefense = col_double(),\n Speed = col_double(),\n Generation = col_double(),\n Legendary = col_logical()\n)\n" ], [ "head(pokemon <- pokemon%>%\n select(Total, HitPoints, Attack, Defense, Speed))", "_____no_output_____" ], [ "# Mean of each variable\ncolMeans(pokemon)", "_____no_output_____" ], [ "# Standard deviation of each variable\napply(pokemon, 2, sd)", "_____no_output_____" ], [ "# PCA model with scaling: pr.with.scaling\npr.with.scaling <- prcomp(pokemon, center=T, scale=T)\n\n# PCA model without scaling: pr.without.scaling\npr.without.scaling <- prcomp(pokemon, center=T, scale=F)\n\n# Create biplots of both for comparison\nbiplot(pr.with.scaling)", "_____no_output_____" ], [ "biplot(pr.without.scaling)", "_____no_output_____" ] ], [ [ "The new Total column contains much more variation, on average, than the other four columns, so it has a disproportionate effect on the PCA model when scaling is not performed. After scaling the data, there's a much more even distribution of the loading vectors.", "_____no_output_____" ], [ "# Exploring Wisconsin breast cancer data\n\n## Introduction to the case study\n\n- Human breast mass data:\n - Ten features measured of each cell nuclei\n - Summary information is provided for each group of cells\n - Includes diagnosis: benign (not cancerous) and malignant (cancerous)", "_____no_output_____" ], [ "### Analysis\n- Download data and prepare data for modeling\n- Exploratory data analysis (# observations, # features, etc.)\n- Perform PCA and interpret results\n- Complete two types of clusteringUnderstand and compare the two types\n- Combine PCA and clustering\n", "_____no_output_____" ], [ "### Preparing the data", "_____no_output_____" ] ], [ [ "url <- \"datasets//WisconsinCancer.csv\"\n\n# Download the data: wisc.df\nwisc.df <- read.csv(url)\n\n# Convert the features of the data: wisc.data\nwisc.data <- as.matrix(wisc.df[3:32])\n\n# Set the row names of wisc.data\nrow.names(wisc.data) <- wisc.df$id\n\n# Create diagnosis vector\ndiagnosis <- as.numeric(wisc.df$diagnosis == \"M\")", "_____no_output_____" ] ], [ [ "### Exploratory data analysis\n\n- How many observations are in this dataset?", "_____no_output_____" ] ], [ [ "dim(wisc.data)", "_____no_output_____" ], [ "names(wisc.df)", "_____no_output_____" ] ], [ [ "### Performing PCA\nThe next step is to perform PCA on wisc.data.\n\nit's important to check if the data need to be scaled before performing PCA. Two common reasons for scaling data:\n\n- The input variables use different units of measurement.\n- The input variables have significantly different variances.", "_____no_output_____" ] ], [ [ "# Check column means and standard deviations\ncolMeans(wisc.data)", "_____no_output_____" ], [ "apply(wisc.data, 2, sd)", "_____no_output_____" ], [ "# Execute PCA, scaling if appropriate: wisc.pr\nwisc.pr <- prcomp(wisc.data, center=T, scale=T)\n\n# Look at summary of results\nsummary(wisc.pr)", "_____no_output_____" ] ], [ [ "### Interpreting PCA results\nNow we'll use some visualizations to better understand the PCA model. \n", "_____no_output_____" ] ], [ [ "# Create a biplot of wisc.pr\nbiplot(wisc.pr)", "_____no_output_____" ], [ "# Scatter plot observations by components 1 and 2\nplot(wisc.pr$x[, c(1, 2)], col = (diagnosis + 1), \n xlab = \"PC1\", ylab = \"PC2\")", "_____no_output_____" ], [ "# Repeat for components 1 and 3\nplot(wisc.pr$x[, c(1,3)], col = (diagnosis + 1), \n xlab = \"PC1\", ylab = \"PC3\")\n\n", "_____no_output_____" ], [ "# Do additional data exploration of your choosing below (optional)\nplot(wisc.pr$x[, c(2,3)], col = (diagnosis + 1), \n xlab = \"PC2\", ylab = \"PC3\")\n", "_____no_output_____" ] ], [ [ "Because principal component 2 explains more variance in the original data than principal component 3, you can see that the first plot has a cleaner cut separating the two subgroups.", "_____no_output_____" ], [ "### Variance explained\n\nWe will produce scree plots showing the proportion of variance explained as the number of principal components increases. The data from PCA must be prepared for these plots, as there is not a built-in function in R to create them directly from the PCA model.\n", "_____no_output_____" ] ], [ [ "# Set up 1 x 2 plotting grid\npar(mfrow = c(1, 2))\n\n# Calculate variability of each component\npr.var <- wisc.pr$sdev^2\n\n# Variance explained by each principal component: pve\npve <- pr.var/sum(pr.var)\n\n# Plot variance explained for each principal component\nplot(pve, xlab = \"Principal Component\", \n ylab = \"Proportion of Variance Explained\", \n ylim = c(0, 1), type = \"b\")", "_____no_output_____" ], [ "# Plot cumulative proportion of variance explained\nplot(cumsum(pve), xlab = \"Principal Component\", \n ylab = \"Cumulative Proportion of Variance Explained\", \n ylim = c(0, 1), type = \"b\")", "_____no_output_____" ] ], [ [ "### Next steps\n- Complete hierarchical clustering\n- Complete k-means clustering\n- Combine PCA and clustering\n- Contrast results of hierarchical clustering with diagnosis\n- Compare hierarchical and k-means clustering results\n- PCA as a pre-processing step for clustering\n", "_____no_output_____" ], [ "### Hierarchical clustering of case data\n\nWe will do hierarchical clustering of the observations. This type of clustering does not assume in advance the number of natural groups that exist in the data.\n\nAs part of the preparation for hierarchical clustering, distance between all pairs of observations are computed. Furthermore, there are different ways to link clusters together, with single, complete, and average being the most common linkage methods.", "_____no_output_____" ] ], [ [ "# Scale the wisc.data data: data.scaled\ndata.scaled <- scale(wisc.data)\n\n# Calculate the (Euclidean) distances: data.dist\ndata.dist <- dist(data.scaled)\n\n# Create a hierarchical clustering model: wisc.hclust\nwisc.hclust <- hclust(data.dist, method=\"complete\")", "_____no_output_____" ] ], [ [ "### Results of hierarchical clustering", "_____no_output_____" ] ], [ [ "plot(wisc.hclust)", "_____no_output_____" ] ], [ [ "### Selecting number of clusters\n\nWe will compare the outputs from your hierarchical clustering model to the actual diagnoses. Normally when performing unsupervised learning like this, a target variable isn't available. We do have it with this dataset, however, so it can be used to check the performance of the clustering model.\n\nWhen performing supervised learning—that is, when we're trying to predict some target variable of interest and that target variable is available in the original data—using clustering to create new features may or may not improve the performance of the final model.", "_____no_output_____" ] ], [ [ "# Cut tree so that it has 4 clusters: wisc.hclust.clusters\nwisc.hclust.clusters <- cutree(wisc.hclust, k=4)\n\n# Compare cluster membership to actual diagnoses\ntable(wisc.hclust.clusters, diagnosis)", "_____no_output_____" ] ], [ [ "Four clusters were picked after some exploration. Before moving on, we may want to explore how different numbers of clusters affect the ability of the hierarchical clustering to separate the different diagnoses", "_____no_output_____" ], [ "### k-means clustering and comparing results\n\nThere are two main types of clustering: hierarchical and k-means.\n\nWe will create a k-means clustering model on the Wisconsin breast cancer data and compare the results to the actual diagnoses and the results of your hierarchical clustering model.", "_____no_output_____" ] ], [ [ "# Create a k-means model on wisc.data: wisc.km\nwisc.km <- kmeans(scale(wisc.data), centers=2, nstart=20)\n\n# Compare k-means to actual diagnoses\ntable(wisc.km$cluster, diagnosis)", "_____no_output_____" ], [ "# Compare k-means to hierarchical clustering\ntable(wisc.km$cluster, wisc.hclust.clusters)", "_____no_output_____" ] ], [ [ "Looking at the second table you generated, it looks like clusters 1, 2, and 4 from the hierarchical clustering model can be interpreted as the cluster 1 equivalent from the k-means algorithm, and cluster 3 can be interpreted as the cluster 2 equivalent.", "_____no_output_____" ], [ "### Clustering on PCA results\n\nWe will put together several steps used earlier and, in doing so, we will experience some of the creativity that is typical in unsupervised learning.\n\nThe PCA model required significantly fewer features to describe 80% and 95% of the variability of the data. In addition to normalizing data and potentially avoiding overfitting, PCA also uncorrelates the variables, sometimes improving the performance of other modeling techniques.\n\nLet's see if PCA improves or degrades the performance of hierarchical clustering.", "_____no_output_____" ] ], [ [ "# Create a hierarchical clustering model: wisc.pr.hclust\nwisc.pr.hclust <- hclust(dist(wisc.pr$x[, 1:7]), method = \"complete\")\n\n# Cut model into 4 clusters: wisc.pr.hclust.clusters\nwisc.pr.hclust.clusters <- cutree(wisc.pr.hclust, k=4)\n\n# Compare to actual diagnoses\ntable(wisc.pr.hclust.clusters, diagnosis)", "_____no_output_____" ], [ "table(wisc.hclust.clusters, diagnosis)", "_____no_output_____" ], [ "# Compare to k-means and hierarchical\ntable(wisc.km$cluster, diagnosis)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ] ]
4a0aafac6a7951b2ba9f41bd82b577c1fc7b1418
49,881
ipynb
Jupyter Notebook
Merida/Summarizer/Summarization_Files/Abstractive_summarization/Semantic_Text_Summarization.ipynb
rahulmadanraju/Semantic-Search-Engine
b0be4b9cdee2362be6c7ac97865c2588a7acdc15
[ "MIT" ]
2
2020-06-03T11:26:56.000Z
2020-07-23T11:23:32.000Z
Merida/Summarizer/Summarization_Files/Abstractive_summarization/Semantic_Text_Summarization.ipynb
rahulmadanraju/Semantic-Search-Engine
b0be4b9cdee2362be6c7ac97865c2588a7acdc15
[ "MIT" ]
null
null
null
Merida/Summarizer/Summarization_Files/Abstractive_summarization/Semantic_Text_Summarization.ipynb
rahulmadanraju/Semantic-Search-Engine
b0be4b9cdee2362be6c7ac97865c2588a7acdc15
[ "MIT" ]
null
null
null
54.935022
826
0.590566
[ [ [ "# Semantic Text Summarization\nHere we are using the semantic method to understand the text and also keep up the standards of the extractive summarization. The task is implemnted using the various pre-defined models such **BERT, BART, T5, XLNet and GPT2** for summarizing the articles. It is also comapared with a classical method i.e. **summarzation based on word frequencies**.\n", "_____no_output_____" ] ], [ [ "## installation\n!pip install transformers --upgrade\n!pip install bert-extractive-summarizer\n!pip install neuralcoref\n!python -m spacy download en_core_web_md", "Requirement already up-to-date: transformers in /usr/local/lib/python3.6/dist-packages (2.8.0)\nRequirement already satisfied, skipping upgrade: numpy in /usr/local/lib/python3.6/dist-packages (from transformers) (1.18.3)\nRequirement already satisfied, skipping upgrade: filelock in /usr/local/lib/python3.6/dist-packages (from transformers) (3.0.12)\nRequirement already satisfied, skipping upgrade: dataclasses; python_version < \"3.7\" in /usr/local/lib/python3.6/dist-packages (from transformers) (0.7)\nRequirement already satisfied, skipping upgrade: boto3 in /usr/local/lib/python3.6/dist-packages (from transformers) (1.12.46)\nRequirement already satisfied, skipping upgrade: tqdm>=4.27 in /usr/local/lib/python3.6/dist-packages (from transformers) (4.38.0)\nRequirement already satisfied, skipping upgrade: regex!=2019.12.17 in /usr/local/lib/python3.6/dist-packages (from transformers) (2019.12.20)\nRequirement already satisfied, skipping upgrade: sacremoses in /usr/local/lib/python3.6/dist-packages (from transformers) (0.0.41)\nRequirement already satisfied, skipping upgrade: tokenizers==0.5.2 in /usr/local/lib/python3.6/dist-packages (from transformers) (0.5.2)\nRequirement already satisfied, skipping upgrade: requests in /usr/local/lib/python3.6/dist-packages (from transformers) (2.21.0)\nRequirement already satisfied, skipping upgrade: sentencepiece in /usr/local/lib/python3.6/dist-packages (from transformers) (0.1.86)\nRequirement already satisfied, skipping upgrade: jmespath<1.0.0,>=0.7.1 in /usr/local/lib/python3.6/dist-packages (from boto3->transformers) (0.9.5)\nRequirement already satisfied, skipping upgrade: botocore<1.16.0,>=1.15.46 in /usr/local/lib/python3.6/dist-packages (from boto3->transformers) (1.15.46)\nRequirement already satisfied, skipping upgrade: s3transfer<0.4.0,>=0.3.0 in /usr/local/lib/python3.6/dist-packages (from boto3->transformers) (0.3.3)\nRequirement already satisfied, skipping upgrade: click in /usr/local/lib/python3.6/dist-packages (from sacremoses->transformers) (7.1.1)\nRequirement already satisfied, skipping upgrade: joblib in /usr/local/lib/python3.6/dist-packages (from sacremoses->transformers) (0.14.1)\nRequirement already satisfied, skipping upgrade: six in /usr/local/lib/python3.6/dist-packages (from sacremoses->transformers) (1.12.0)\nRequirement already satisfied, skipping upgrade: certifi>=2017.4.17 in /usr/local/lib/python3.6/dist-packages (from requests->transformers) (2020.4.5.1)\nRequirement already satisfied, skipping upgrade: urllib3<1.25,>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from requests->transformers) (1.24.3)\nRequirement already satisfied, skipping upgrade: idna<2.9,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests->transformers) (2.8)\nRequirement already satisfied, skipping upgrade: chardet<3.1.0,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests->transformers) (3.0.4)\nRequirement already satisfied, skipping upgrade: python-dateutil<3.0.0,>=2.1 in /usr/local/lib/python3.6/dist-packages (from botocore<1.16.0,>=1.15.46->boto3->transformers) (2.8.1)\nRequirement already satisfied, skipping upgrade: docutils<0.16,>=0.10 in /usr/local/lib/python3.6/dist-packages (from botocore<1.16.0,>=1.15.46->boto3->transformers) (0.15.2)\nRequirement already satisfied: bert-extractive-summarizer in /usr/local/lib/python3.6/dist-packages (0.4.2)\nRequirement already satisfied: scikit-learn in /usr/local/lib/python3.6/dist-packages (from bert-extractive-summarizer) (0.22.2.post1)\nRequirement already satisfied: transformers in /usr/local/lib/python3.6/dist-packages (from bert-extractive-summarizer) (2.8.0)\nRequirement already satisfied: spacy in /usr/local/lib/python3.6/dist-packages (from bert-extractive-summarizer) (2.2.4)\nRequirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.6/dist-packages (from scikit-learn->bert-extractive-summarizer) (0.14.1)\nRequirement already satisfied: scipy>=0.17.0 in /usr/local/lib/python3.6/dist-packages (from scikit-learn->bert-extractive-summarizer) (1.4.1)\nRequirement already satisfied: numpy>=1.11.0 in /usr/local/lib/python3.6/dist-packages (from scikit-learn->bert-extractive-summarizer) (1.18.3)\nRequirement already satisfied: sacremoses in /usr/local/lib/python3.6/dist-packages (from transformers->bert-extractive-summarizer) (0.0.41)\nRequirement already satisfied: dataclasses; python_version < \"3.7\" in /usr/local/lib/python3.6/dist-packages (from transformers->bert-extractive-summarizer) (0.7)\nRequirement already satisfied: boto3 in /usr/local/lib/python3.6/dist-packages (from transformers->bert-extractive-summarizer) (1.12.46)\nRequirement already satisfied: filelock in /usr/local/lib/python3.6/dist-packages (from transformers->bert-extractive-summarizer) (3.0.12)\nRequirement already satisfied: sentencepiece in /usr/local/lib/python3.6/dist-packages (from transformers->bert-extractive-summarizer) (0.1.86)\nRequirement already satisfied: tqdm>=4.27 in /usr/local/lib/python3.6/dist-packages (from transformers->bert-extractive-summarizer) (4.38.0)\nRequirement already satisfied: requests in /usr/local/lib/python3.6/dist-packages (from transformers->bert-extractive-summarizer) (2.21.0)\nRequirement already satisfied: tokenizers==0.5.2 in /usr/local/lib/python3.6/dist-packages (from transformers->bert-extractive-summarizer) (0.5.2)\nRequirement already satisfied: regex!=2019.12.17 in /usr/local/lib/python3.6/dist-packages (from transformers->bert-extractive-summarizer) (2019.12.20)\nRequirement already satisfied: catalogue<1.1.0,>=0.0.7 in /usr/local/lib/python3.6/dist-packages (from spacy->bert-extractive-summarizer) (1.0.0)\nRequirement already satisfied: blis<0.5.0,>=0.4.0 in /usr/local/lib/python3.6/dist-packages (from spacy->bert-extractive-summarizer) (0.4.1)\nRequirement already satisfied: plac<1.2.0,>=0.9.6 in /usr/local/lib/python3.6/dist-packages (from spacy->bert-extractive-summarizer) (1.1.3)\nRequirement already satisfied: murmurhash<1.1.0,>=0.28.0 in /usr/local/lib/python3.6/dist-packages (from spacy->bert-extractive-summarizer) (1.0.2)\nRequirement already satisfied: thinc==7.4.0 in /usr/local/lib/python3.6/dist-packages (from spacy->bert-extractive-summarizer) (7.4.0)\nRequirement already satisfied: wasabi<1.1.0,>=0.4.0 in /usr/local/lib/python3.6/dist-packages (from spacy->bert-extractive-summarizer) (0.6.0)\nRequirement already satisfied: setuptools in /usr/local/lib/python3.6/dist-packages (from spacy->bert-extractive-summarizer) (46.1.3)\nRequirement already satisfied: preshed<3.1.0,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from spacy->bert-extractive-summarizer) (3.0.2)\nRequirement already satisfied: srsly<1.1.0,>=1.0.2 in /usr/local/lib/python3.6/dist-packages (from spacy->bert-extractive-summarizer) (1.0.2)\nRequirement already satisfied: cymem<2.1.0,>=2.0.2 in /usr/local/lib/python3.6/dist-packages (from spacy->bert-extractive-summarizer) (2.0.3)\nRequirement already satisfied: click in /usr/local/lib/python3.6/dist-packages (from sacremoses->transformers->bert-extractive-summarizer) (7.1.1)\nRequirement already satisfied: six in /usr/local/lib/python3.6/dist-packages (from sacremoses->transformers->bert-extractive-summarizer) (1.12.0)\nRequirement already satisfied: s3transfer<0.4.0,>=0.3.0 in /usr/local/lib/python3.6/dist-packages (from boto3->transformers->bert-extractive-summarizer) (0.3.3)\nRequirement already satisfied: botocore<1.16.0,>=1.15.46 in /usr/local/lib/python3.6/dist-packages (from boto3->transformers->bert-extractive-summarizer) (1.15.46)\nRequirement already satisfied: jmespath<1.0.0,>=0.7.1 in /usr/local/lib/python3.6/dist-packages (from boto3->transformers->bert-extractive-summarizer) (0.9.5)\nRequirement already satisfied: idna<2.9,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests->transformers->bert-extractive-summarizer) (2.8)\nRequirement already satisfied: chardet<3.1.0,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests->transformers->bert-extractive-summarizer) (3.0.4)\nRequirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.6/dist-packages (from requests->transformers->bert-extractive-summarizer) (2020.4.5.1)\nRequirement already satisfied: urllib3<1.25,>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from requests->transformers->bert-extractive-summarizer) (1.24.3)\nRequirement already satisfied: importlib-metadata>=0.20; python_version < \"3.8\" in /usr/local/lib/python3.6/dist-packages (from catalogue<1.1.0,>=0.0.7->spacy->bert-extractive-summarizer) (1.6.0)\nRequirement already satisfied: docutils<0.16,>=0.10 in /usr/local/lib/python3.6/dist-packages (from botocore<1.16.0,>=1.15.46->boto3->transformers->bert-extractive-summarizer) (0.15.2)\nRequirement already satisfied: python-dateutil<3.0.0,>=2.1 in /usr/local/lib/python3.6/dist-packages (from botocore<1.16.0,>=1.15.46->boto3->transformers->bert-extractive-summarizer) (2.8.1)\nRequirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.6/dist-packages (from importlib-metadata>=0.20; python_version < \"3.8\"->catalogue<1.1.0,>=0.0.7->spacy->bert-extractive-summarizer) (3.1.0)\nRequirement already satisfied: neuralcoref in /usr/local/lib/python3.6/dist-packages (4.0)\nRequirement already satisfied: boto3 in /usr/local/lib/python3.6/dist-packages (from neuralcoref) (1.12.46)\nRequirement already satisfied: numpy>=1.15.0 in /usr/local/lib/python3.6/dist-packages (from neuralcoref) (1.18.3)\nRequirement already satisfied: requests<3.0.0,>=2.13.0 in /usr/local/lib/python3.6/dist-packages (from neuralcoref) (2.21.0)\nRequirement already satisfied: spacy>=2.1.0 in /usr/local/lib/python3.6/dist-packages (from neuralcoref) (2.2.4)\nRequirement already satisfied: s3transfer<0.4.0,>=0.3.0 in /usr/local/lib/python3.6/dist-packages (from boto3->neuralcoref) (0.3.3)\nRequirement already satisfied: botocore<1.16.0,>=1.15.46 in /usr/local/lib/python3.6/dist-packages (from boto3->neuralcoref) (1.15.46)\nRequirement already satisfied: jmespath<1.0.0,>=0.7.1 in /usr/local/lib/python3.6/dist-packages (from boto3->neuralcoref) (0.9.5)\nRequirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.6/dist-packages (from requests<3.0.0,>=2.13.0->neuralcoref) (2020.4.5.1)\nRequirement already satisfied: chardet<3.1.0,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests<3.0.0,>=2.13.0->neuralcoref) (3.0.4)\nRequirement already satisfied: urllib3<1.25,>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from requests<3.0.0,>=2.13.0->neuralcoref) (1.24.3)\nRequirement already satisfied: idna<2.9,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests<3.0.0,>=2.13.0->neuralcoref) (2.8)\nRequirement already satisfied: wasabi<1.1.0,>=0.4.0 in /usr/local/lib/python3.6/dist-packages (from spacy>=2.1.0->neuralcoref) (0.6.0)\nRequirement already satisfied: thinc==7.4.0 in /usr/local/lib/python3.6/dist-packages (from spacy>=2.1.0->neuralcoref) (7.4.0)\nRequirement already satisfied: blis<0.5.0,>=0.4.0 in /usr/local/lib/python3.6/dist-packages (from spacy>=2.1.0->neuralcoref) (0.4.1)\nRequirement already satisfied: setuptools in /usr/local/lib/python3.6/dist-packages (from spacy>=2.1.0->neuralcoref) (46.1.3)\nRequirement already satisfied: srsly<1.1.0,>=1.0.2 in /usr/local/lib/python3.6/dist-packages (from spacy>=2.1.0->neuralcoref) (1.0.2)\nRequirement already satisfied: tqdm<5.0.0,>=4.38.0 in /usr/local/lib/python3.6/dist-packages (from spacy>=2.1.0->neuralcoref) (4.38.0)\nRequirement already satisfied: plac<1.2.0,>=0.9.6 in /usr/local/lib/python3.6/dist-packages (from spacy>=2.1.0->neuralcoref) (1.1.3)\nRequirement already satisfied: preshed<3.1.0,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from spacy>=2.1.0->neuralcoref) (3.0.2)\nRequirement already satisfied: murmurhash<1.1.0,>=0.28.0 in /usr/local/lib/python3.6/dist-packages (from spacy>=2.1.0->neuralcoref) (1.0.2)\nRequirement already satisfied: cymem<2.1.0,>=2.0.2 in /usr/local/lib/python3.6/dist-packages (from spacy>=2.1.0->neuralcoref) (2.0.3)\nRequirement already satisfied: catalogue<1.1.0,>=0.0.7 in /usr/local/lib/python3.6/dist-packages (from spacy>=2.1.0->neuralcoref) (1.0.0)\nRequirement already satisfied: python-dateutil<3.0.0,>=2.1 in /usr/local/lib/python3.6/dist-packages (from botocore<1.16.0,>=1.15.46->boto3->neuralcoref) (2.8.1)\nRequirement already satisfied: docutils<0.16,>=0.10 in /usr/local/lib/python3.6/dist-packages (from botocore<1.16.0,>=1.15.46->boto3->neuralcoref) (0.15.2)\nRequirement already satisfied: importlib-metadata>=0.20; python_version < \"3.8\" in /usr/local/lib/python3.6/dist-packages (from catalogue<1.1.0,>=0.0.7->spacy>=2.1.0->neuralcoref) (1.6.0)\nRequirement already satisfied: six>=1.5 in /usr/local/lib/python3.6/dist-packages (from python-dateutil<3.0.0,>=2.1->botocore<1.16.0,>=1.15.46->boto3->neuralcoref) (1.12.0)\nRequirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.6/dist-packages (from importlib-metadata>=0.20; python_version < \"3.8\"->catalogue<1.1.0,>=0.0.7->spacy>=2.1.0->neuralcoref) (3.1.0)\nRequirement already satisfied: en_core_web_md==2.2.5 from https://github.com/explosion/spacy-models/releases/download/en_core_web_md-2.2.5/en_core_web_md-2.2.5.tar.gz#egg=en_core_web_md==2.2.5 in /usr/local/lib/python3.6/dist-packages (2.2.5)\nRequirement already satisfied: spacy>=2.2.2 in /usr/local/lib/python3.6/dist-packages (from en_core_web_md==2.2.5) (2.2.4)\nRequirement already satisfied: preshed<3.1.0,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from spacy>=2.2.2->en_core_web_md==2.2.5) (3.0.2)\nRequirement already satisfied: setuptools in /usr/local/lib/python3.6/dist-packages (from spacy>=2.2.2->en_core_web_md==2.2.5) (46.1.3)\nRequirement already satisfied: blis<0.5.0,>=0.4.0 in /usr/local/lib/python3.6/dist-packages (from spacy>=2.2.2->en_core_web_md==2.2.5) (0.4.1)\nRequirement already satisfied: cymem<2.1.0,>=2.0.2 in /usr/local/lib/python3.6/dist-packages (from spacy>=2.2.2->en_core_web_md==2.2.5) (2.0.3)\nRequirement already satisfied: numpy>=1.15.0 in /usr/local/lib/python3.6/dist-packages (from spacy>=2.2.2->en_core_web_md==2.2.5) (1.18.3)\nRequirement already satisfied: requests<3.0.0,>=2.13.0 in /usr/local/lib/python3.6/dist-packages (from spacy>=2.2.2->en_core_web_md==2.2.5) (2.21.0)\nRequirement already satisfied: tqdm<5.0.0,>=4.38.0 in /usr/local/lib/python3.6/dist-packages (from spacy>=2.2.2->en_core_web_md==2.2.5) (4.38.0)\nRequirement already satisfied: plac<1.2.0,>=0.9.6 in /usr/local/lib/python3.6/dist-packages (from spacy>=2.2.2->en_core_web_md==2.2.5) (1.1.3)\nRequirement already satisfied: catalogue<1.1.0,>=0.0.7 in /usr/local/lib/python3.6/dist-packages (from spacy>=2.2.2->en_core_web_md==2.2.5) (1.0.0)\nRequirement already satisfied: thinc==7.4.0 in /usr/local/lib/python3.6/dist-packages (from spacy>=2.2.2->en_core_web_md==2.2.5) (7.4.0)\nRequirement already satisfied: wasabi<1.1.0,>=0.4.0 in /usr/local/lib/python3.6/dist-packages (from spacy>=2.2.2->en_core_web_md==2.2.5) (0.6.0)\nRequirement already satisfied: srsly<1.1.0,>=1.0.2 in /usr/local/lib/python3.6/dist-packages (from spacy>=2.2.2->en_core_web_md==2.2.5) (1.0.2)\nRequirement already satisfied: murmurhash<1.1.0,>=0.28.0 in /usr/local/lib/python3.6/dist-packages (from spacy>=2.2.2->en_core_web_md==2.2.5) (1.0.2)\nRequirement already satisfied: idna<2.9,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests<3.0.0,>=2.13.0->spacy>=2.2.2->en_core_web_md==2.2.5) (2.8)\nRequirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.6/dist-packages (from requests<3.0.0,>=2.13.0->spacy>=2.2.2->en_core_web_md==2.2.5) (2020.4.5.1)\nRequirement already satisfied: urllib3<1.25,>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from requests<3.0.0,>=2.13.0->spacy>=2.2.2->en_core_web_md==2.2.5) (1.24.3)\nRequirement already satisfied: chardet<3.1.0,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests<3.0.0,>=2.13.0->spacy>=2.2.2->en_core_web_md==2.2.5) (3.0.4)\nRequirement already satisfied: importlib-metadata>=0.20; python_version < \"3.8\" in /usr/local/lib/python3.6/dist-packages (from catalogue<1.1.0,>=0.0.7->spacy>=2.2.2->en_core_web_md==2.2.5) (1.6.0)\nRequirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.6/dist-packages (from importlib-metadata>=0.20; python_version < \"3.8\"->catalogue<1.1.0,>=0.0.7->spacy>=2.2.2->en_core_web_md==2.2.5) (3.1.0)\n\u001b[38;5;2m✔ Download and installation successful\u001b[0m\nYou can now load the model via spacy.load('en_core_web_md')\n" ], [ "from transformers import pipeline\nfrom summarizer import Summarizer, TransformerSummarizer\n\nimport pprint\n\npp = pprint.PrettyPrinter(indent=14)", "_____no_output_____" ], [ "## documentation for summarizer: https://huggingface.co/transformers/main_classes/pipelines.html#summarizationpipeline\n# summarize with BART\nsummarizer_bart = pipeline(task='summarization', model=\"bart-large-cnn\")\n\n#summarize with BERT\nsummarizer_bert = Summarizer()\n\n# summarize with T5\nsummarizer_t5 = pipeline(task='summarization', model=\"t5-large\") # options: ‘t5-small’, ‘t5-base’, ‘t5-large’, ‘t5-3b’, ‘t5-11b’\n#for T5 you can chose the size of the model. Everything above t5-base is very slow, even on GPU or TPU.\n\n# summarize with XLNet\nsummarizer_xlnet = TransformerSummarizer(transformer_type=\"XLNet\",transformer_model_key=\"xlnet-base-cased\")\n\n# summarize with GPT2\nsummarizer_gpt2 = TransformerSummarizer(transformer_type=\"GPT2\",transformer_model_key=\"gpt2-medium\")", "WARNING:transformers.modelcard:Couldn't reach server at 'https://s3.amazonaws.com/models.huggingface.co/bert/facebook/bart-large-cnn/modelcard.json' to download model card file.\nWARNING:transformers.modelcard:Creating an empty model card.\n" ], [ "data = '''\nFor the actual assembly of an module, the Material list of a complete module is displayed in order to make the necessary materials physically available. Also CAD model of the assembly and 2-D construction models can be viewed or printed out in order to be able to later on\nto carry out individual steps.\nNecessary steps: The material list, 3D model and 2D drawings of a complete assembly must be available.\n'''", "_____no_output_____" ], [ "# Bart for Text - Summarization\nprint('Bart for Text - Summarization')\nsummary_bart = summarizer_bart(data, min_length=10, max_length=40) # change min_ and max_length for different output\npp.pprint(summary_bart[0]['summary_text'])\n\n# BERT for Text - Summarization\nprint('\\n BERT for Text - Summarization')\nsummary_bert = summarizer_bert(data, min_length=60)\nfull = ''.join(summary_bert)\npp.pprint(full)\n\n# XLNet for Text - Summarization\nprint('\\n XLNet for Text - Summarization')\nsummary_xlnet = summarizer_xlnet(data, min_length=60)\nfull = ''.join(summary_xlnet)\npp.pprint(full)\n\n# GPT2 for Text - Summarization\nprint('\\n GPT2 for Text - Summarization')\nsummary_gpt2 = summarizer_gpt2(data, min_length=60, ratio = 0.1)\nfull = ''.join(summary_gpt2)\npp.pprint(full)\n\n# T5 for Text - Summarization\nprint('\\n T5 for Text - Summarization')\nsummary_t5 = summarizer_t5(data, min_length=10) # change min_ and max_length for different output\npp.pprint(summary_t5[0]['summary_text'])", "Bart for Text - Summarization\n('Necessary steps: The material list, 3D model and 2D drawings of a complete '\n 'assembly must be available.')\n\n BERT for Text - Summarization\n('For the actual assembly of an module, the Material list of a complete module '\n 'is displayed in order to make the necessary materials physically available. '\n 'Necessary steps: The material list, 3D model and 2D drawings of a complete '\n 'assembly must be available.')\n\n XLNet for Text - Summarization\n" ], [ "# a review on another data\ndata = '''\nIn the production of SMC (Sheet Moulding Compound), the maturing of the semi-finished product (resin+glass fibre) is of decisive importance. \nThe associated thickening of the material determines the viscosity and thus the quality of the end product. \nPossible defects due to short maturing and soft semi-finished products are lack of fibre transport, while too long maturing and hard semi-finished products result in incompletely filled components. \nBy adjusting the press parameters such as closing force, closing speed, mould temperature etc., the fluctuations in thickening can normally be compensated. \nBy measuring the flowability/viscosity of the material or by measuring additional parameters during the manufacturing process, the ideal process window for the production of SMC is to be controlled even better.\n'''", "_____no_output_____" ], [ "# Bart for Text - Summarization\nprint('Bart for Text - Summarization')\nsummary_bart = summarizer_bart(data, min_length=10, max_length=40) # change min_ and max_length for different output\npp.pprint(summary_bart[0]['summary_text'])\n\n# BERT for Text - Summarization\nprint('\\n BERT for Text - Summarization')\nsummary_bert = summarizer_bert(data, min_length=60)\nfull = ''.join(summary_bert)\npp.pprint(full)\n\n# XLNet for Text - Summarization\nprint('\\n XLNet for Text - Summarization')\nsummary_xlnet = summarizer_xlnet(data, min_length=60)\nfull = ''.join(summary_xlnet)\npp.pprint(full)\n\n# GPT2 for Text - Summarization\nprint('\\n GPT2 for Text - Summarization')\nsummary_gpt2 = summarizer_gpt2(data, min_length=60)\nfull = ''.join(summary_gpt2)\npp.pprint(full)\n\n# T5 for Text - Summarization\nprint('\\n T5 for Text - Summarization')\nsummary_t5 = summarizer_t5(data, min_length=10) # change min_ and max_length for different output\npp.pprint(summary_t5[0]['summary_text'])", "Bart for Text - Summarization\n('The maturing of the semi-finished product is of decisive importance. The '\n 'associated thickening of the material determines the viscosity and thus the '\n 'quality of the end product.')\n\n BERT for Text - Summarization\n('In the production of SMC (Sheet Moulding Compound), the maturing of the '\n 'semi-finished product (resin+glass fibre) is of decisive importance. The '\n 'associated thickening of the material determines the viscosity and thus the '\n 'quality of the end product.')\n\n XLNet for Text - Summarization\n('In the production of SMC (Sheet Moulding Compound), the maturing of the '\n 'semi-finished product (resin+glass fibre) is of decisive importance.')\n\n GPT2 for Text - Summarization\n" ], [ "# Text - Summarization using word frequencies\n# importing libraries\n\nimport nltk\nnltk.download('stopwords')\nnltk.download('punkt')\nfrom nltk.corpus import stopwords\nfrom nltk.stem import PorterStemmer\nfrom nltk.tokenize import word_tokenize, sent_tokenize\nimport bs4 as BeautifulSoup\nimport urllib.request \n\n#fetching the content from the URL\nfetched_data = urllib.request.urlopen('https://en.wikipedia.org/wiki/20th_century')\n\narticle_read = fetched_data.read()\n\n#parsing the URL content and storing in a variable\narticle_parsed = BeautifulSoup.BeautifulSoup(article_read,'html.parser')\n\n#returning <p> tags\nparagraphs = article_parsed.find_all('p')\n\narticle_content = ''' \nIn the production of SMC (Sheet Moulding Compound), the maturing of the semi-finished product (resin+glass fibre) is of decisive importance. The associated thickening of the material determines the viscosity and thus the quality of the end product. Possible defects due to short maturing and soft semi-finished products are lack of fibre transport, while too long maturing and hard semi-finished products result in incompletely filled components. By adjusting the press parameters such as closing force, closing speed, mould temperature etc., the fluctuations in thickening can normally be compensated. By measuring the flowability/viscosity of the material or by measuring additional parameters during the manufacturing process, the ideal process window for the production of SMC is to be controlled even better.\n'''\n\n#looping through the paragraphs and adding them to the variable\n#for p in paragraphs: \n# article_content += p.text\n\n#print(article_content)\n\n\ndef _create_dictionary_table(text_string) -> dict:\n \n #removing stop words\n stop_words = set(stopwords.words(\"english\"))\n \n words = word_tokenize(text_string)\n \n #reducing words to their root form\n stem = PorterStemmer()\n \n #creating dictionary for the word frequency table\n frequency_table = dict()\n for wd in words:\n wd = stem.stem(wd)\n if wd in stop_words:\n continue\n if wd in frequency_table:\n frequency_table[wd] += 1\n else:\n frequency_table[wd] = 1\n\n return frequency_table\n\n\ndef _calculate_sentence_scores(sentences, frequency_table) -> dict: \n\n #algorithm for scoring a sentence by its words\n sentence_weight = dict()\n\n for sentence in sentences:\n sentence_wordcount = (len(word_tokenize(sentence)))\n sentence_wordcount_without_stop_words = 0\n for word_weight in frequency_table:\n if word_weight in sentence.lower():\n sentence_wordcount_without_stop_words += 1\n if sentence[:7] in sentence_weight:\n sentence_weight[sentence[:7]] += frequency_table[word_weight]\n else:\n sentence_weight[sentence[:7]] = frequency_table[word_weight]\n\n sentence_weight[sentence[:7]] = sentence_weight[sentence[:7]] / sentence_wordcount_without_stop_words\n\n \n\n return sentence_weight\n\ndef _calculate_average_score(sentence_weight) -> int:\n \n #calculating the average score for the sentences\n sum_values = 0\n for entry in sentence_weight:\n sum_values += sentence_weight[entry]\n\n #getting sentence average value from source text\n average_score = (sum_values / len(sentence_weight))\n\n return average_score\n\ndef _get_article_summary(sentences, sentence_weight, threshold):\n sentence_counter = 0\n article_summary = ''\n\n for sentence in sentences:\n if sentence[:7] in sentence_weight and sentence_weight[sentence[:7]] >= (threshold):\n article_summary += \" \" + sentence\n sentence_counter += 1\n\n return article_summary\n\ndef _run_article_summary(article):\n \n #creating a dictionary for the word frequency table\n frequency_table = _create_dictionary_table(article)\n\n #tokenizing the sentences\n sentences = sent_tokenize(article)\n\n #algorithm for scoring a sentence by its words\n sentence_scores = _calculate_sentence_scores(sentences, frequency_table)\n\n #getting the threshold\n threshold = _calculate_average_score(sentence_scores)\n\n #producing the summary\n article_summary = _get_article_summary(sentences, sentence_scores, 1.1 * threshold)\n\n return article_summary\n\nif __name__ == '__main__':\n summary_results = _run_article_summary(article_content)\n print(summary_results)", "[nltk_data] Downloading package stopwords to /root/nltk_data...\n[nltk_data] Package stopwords is already up-to-date!\n[nltk_data] Downloading package punkt to /root/nltk_data...\n[nltk_data] Package punkt is already up-to-date!\n \nIn the production of SMC (Sheet Moulding Compound), the maturing of the semi-finished product (resin+glass fibre) is of decisive importance.\n" ], [ "# Text - Summarization using GenSim\n\nfrom gensim.summarization.summarizer import summarize\nprint(summarize(data))", "By measuring the flowability/viscosity of the material or by measuring additional parameters during the manufacturing process, the ideal process window for the production of SMC is to be controlled even better.\n" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
4a0ab9f01ebeb91227e409d0720eb22f5683e8fd
199,733
ipynb
Jupyter Notebook
case_study1/code/DS7333CaseStudy1.ipynb
lijjumathew/MSDS-QTW
282f7b81dffe158cbfdc65c3caa34db16f8e7d6b
[ "MIT" ]
null
null
null
case_study1/code/DS7333CaseStudy1.ipynb
lijjumathew/MSDS-QTW
282f7b81dffe158cbfdc65c3caa34db16f8e7d6b
[ "MIT" ]
null
null
null
case_study1/code/DS7333CaseStudy1.ipynb
lijjumathew/MSDS-QTW
282f7b81dffe158cbfdc65c3caa34db16f8e7d6b
[ "MIT" ]
null
null
null
40.464546
6,180
0.426179
[ [ [ "## Case Study 1 DS7333 ", "_____no_output_____" ] ], [ [ "import sys\nprint(sys.path)", "['/Users/lijjumathew/Code/SMU/MSDS-QTW/case_study1/code', '/Users/lijjumathew/opt/anaconda3/lib/python38.zip', '/Users/lijjumathew/opt/anaconda3/lib/python3.8', '/Users/lijjumathew/opt/anaconda3/lib/python3.8/lib-dynload', '', '/Users/lijjumathew/.local/lib/python3.8/site-packages', '/Users/lijjumathew/opt/anaconda3/lib/python3.8/site-packages', '/Users/lijjumathew/opt/anaconda3/lib/python3.8/site-packages/aeosa', '/Users/lijjumathew/opt/anaconda3/lib/python3.8/site-packages/locket-0.2.1-py3.8.egg', '/Users/lijjumathew/opt/anaconda3/lib/python3.8/site-packages/IPython/extensions', '/Users/lijjumathew/.ipython']\n" ] ], [ [ "## Business Understanding", "_____no_output_____" ], [ "The objective behind this case study is to build a linear regression modeling using L1 (LASSO) or L2 (Ridge) regularization to predict the cirtical temperature. The team was given two files which contain the data and from this data we must attempt to predict the cirtical temperature. \n\nOur overall goals are to predict critical temperature and to describe which variable carries the most importance.", "_____no_output_____" ], [ "## Data Evaluation/ Engineering ", "_____no_output_____" ] ], [ [ "#First we'll import all our necessary libraries and add addtional ones as needed as the project grows\nimport pandas as pd\nimport numpy as np\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.metrics import mean_squared_error, r2_score, mean_absolute_error\nfrom ml_metrics import rmse\nimport matplotlib.pyplot as plt\nfrom sklearn import datasets\nfrom pandas_profiling import ProfileReport\nfrom sklearn.preprocessing import StandardScaler, normalize\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn import linear_model\nfrom sklearn.linear_model import Ridge\nfrom sklearn import preprocessing\nimport statsmodels.api as sm\nfrom statsmodels.stats.outliers_influence import variance_inflation_factor\nfrom matplotlib import pyplot", "_____no_output_____" ], [ "#Next we'll bring in our data\ndat1 = pd.read_csv(\"/Users/lijjumathew/Code/SMU/MSDS-QTW/case_study1/data/unique_m.csv\")\ndat2 = pd.read_csv(\"/Users/lijjumathew/Code/SMU/MSDS-QTW/case_study1/data/train.csv\")\n\n#Drop critical temp\ndat1.drop(['critical_temp'], axis=1)\n\n#Merge the data\nframes = [dat1,dat2]\nresult = pd.concat(frames)\n", "_____no_output_____" ], [ "#Drop material\ndel result['material']", "_____no_output_____" ], [ "result.info()", "<class 'pandas.core.frame.DataFrame'>\nInt64Index: 42526 entries, 0 to 21262\nColumns: 168 entries, H to wtd_std_Valence\ndtypes: float64(168)\nmemory usage: 54.8 MB\n" ], [ "result.describe()", "_____no_output_____" ], [ "pd.set_option('display.max_rows', None)\n#Check out the data, start to make some decisions on columns and missing data\n#Compute percentages of each columns missing data\npercent_missing = result.isnull().sum()/len(result)\n#Put percents into dfReduced\nmissing_value_result = pd.DataFrame({'column_name': result.columns,\n'percent_missing': percent_missing})\n#Sort it and show the results\nmissing_value_result.sort_values('percent_missing', inplace=True)\nmissing_value_result.round(6)", "_____no_output_____" ] ], [ [ "Based on the analysis above, we are lucky and have no missing values to impute/handle. Additionally, we will check for NaN's in the combined dataframe.", "_____no_output_____" ] ], [ [ "result.isnull().values.any()\n", "_____no_output_____" ], [ "result= result.fillna(0)", "_____no_output_____" ] ], [ [ "This line handles filling the NaN's with 0's.", "_____no_output_____" ] ], [ [ "print(len(result))\nresult.drop_duplicates(keep = False, inplace = True)\nprint(len(result))", "42526\n42395\n" ] ], [ [ "In a seperate check for duplicate entries- we can see that we have no duplicates.", "_____no_output_____" ], [ "In the cell below we will examine the data for multicollinearity, and remove variables above a threshold of 1000. ", "_____no_output_____" ] ], [ [ "vif_info = pd.DataFrame()\nvif_info['VIF'] = [variance_inflation_factor(result.values, i) for i in range(result.shape[1])]\nvif_info['Column'] = result.columns\nvif_info.sort_values('VIF', ascending=False)", "/Users/lijjumathew/opt/anaconda3/lib/python3.8/site-packages/statsmodels/regression/linear_model.py:1687: RuntimeWarning: invalid value encountered in double_scalars\n return 1 - self.ssr/self.uncentered_tss\n" ], [ "result.describe()", "_____no_output_____" ], [ "del result['wtd_mean_fie']\ndel result['wtd_gmean_fie']\ndel result['mean_fie']\ndel result['gmean_fie']\ndel result['wtd_mean_atomic_radius']\ndel result['wtd_gmean_atomic_radius']\ndel result['mean_atomic_radius']\ndel result['entropy_fie']\ndel result['gmean_atomic_radius']\ndel result['wtd_gmean_Valence']\ndel result['mean_Valence']\ndel result['gmean_Valence']\ndel result['entropy_Valence']\ndel result['wtd_gmean_atomic_mass']\ndel result['mean_atomic_mass']\ndel result['wtd_entropy_atomic_radius']\ndel result['gmean_atomic_mass']\ndel result['wtd_entropy_Valence']\ndel result['entropy_atomic_mass']\ndel result['std_atomic_radius']\ndel result['std_fie']\ndel result['wtd_std_fie']\ndel result['wtd_std_atomic_radius']\ndel result['wtd_mean_ElectronAffinity']\ndel result['std_ThermalConductivity']\ndel result['wtd_entropy_fie']\ndel result['range_fie']\ndel result['wtd_entropy_atomic_mass']\ndel result['range_ThermalConductivity']\ndel result['entropy_Density']\ndel result['wtd_mean_FusionHeat']", "_____no_output_____" ] ], [ [ "Based on the results above- this data is ready for analysis. It is free of duplicates, NaN's, and missing values. \n\n\nWith those items stated- we should also discuss that we are soely interested in our outcome variable ", "_____no_output_____" ], [ "### EDA", "_____no_output_____" ], [ "The purpose of the plot above was to investigate the distribution of values of our outcome variable. Based on this histogram we can see that the data is heavily right skewed. This may be worth log-transforming to fit our normality assumption.", "_____no_output_____" ], [ "## Modeling Preparations", "_____no_output_____" ], [ "The following evaluation metrics will be used for the regression task. -Mean Absolute Error (MAE) -Root Mean Squared Error (RMSE) -Mean Absolute Percentage Error (MAPE) and R^2\n\nMean absolute error is being used because it is an intuitive metric that simply looks at the absolute difference between the data and the models preditions. This metric is a good first pass at evaluating a models performance, its simple and quick. The mean absolute error however, does not indicate under/over performance in the model. The residuals all contribute proportionally, so larger errors will contribute significantally to the model. A small MAE is a good indicator of good prediction and a large MAE indicates the model may need more work. MAE of 0 is ideal, but not really possible. The MAE is farily robust to outliers since it uses the absolute value. For this model a lower MAE is \"better.\" This metric is appropriate since we are concerned with the models ability to predict critical temperatures.\n\nRoot mean squared error is the standard deviation of the residuals (commonly known as prediction errrors). We use these rediuals to see how far from the line the points are. RMSE is a good metric to tell us how concentrated the data is around the line of best fit. The nice and differentiating part of RMSE is that they can be positive or negative as the predicted value under or over the estimates of the actual value unlike the MAE and MAPE which use the absolute value. Additionally we can use the RMSE as a good measure of the spread of the y values about the predicted y values.\n\nMean absolute percentage error is being used as the percentage equivalent of MAE. Similarily to the MAE, MAPE measures how far our model's predictions are off from their corresponding outputs on average. MAPE is pretty easy to interpret because of its use of percentages. As a downside, MAPE is undefined for data where we have 0 values. The MAPE can also grow very large if the values themselves are small, and as a final note MAPE is biased towards predictions that are systematically less than actual values. We will use MAPE as a more interpretable MAE.\nWe will interpret the MAPE in terms of percentages, as an example the MAPE will state, \"our model's predictions are on average xx% off from the actual value.\" This metric is appropriate since we are concerned with the model's ability to predict critical temperatures, furthermore the addition of percentage will further our ability to interpret the model's performance.\n\nFinally R2 or the coefficient of determination will be used and is the proportion of the variation in the dependent variable that is predictable from the independent variable. This isn't the best metric, but it is quite easy to interpret as it lives in a 0-100% scale. \n", "_____no_output_____" ], [ "## Model Building & Evaluations", "_____no_output_____" ], [ "### Start with Linear Regression Model", "_____no_output_____" ] ], [ [ "# Lets scale the data\nx = result.values #returns a numpy array\nmin_max_scaler = preprocessing.MinMaxScaler()\nx_scaled = min_max_scaler.fit_transform(x)\nresult = pd.DataFrame(x_scaled)", "_____no_output_____" ], [ "# Create training and testing sets (cross-validation not needed)\ntrain_set = result.sample(frac=0.8, random_state=100)\ntest_set = result.loc[:, result.columns != 'critical_temp']\nprint(train_set.shape[0])\nprint(test_set.shape[0])\n", "33916\n42395\n" ], [ "# Get the training and testing row indices for later use\ntrain_index = train_set.index.values.astype(int)\ntest_index = test_set.index.values.astype(int)", "_____no_output_____" ], [ "# Converting the training and testing datasets back to matrix-formats\nX_train = train_set.iloc[:, :].values # returns the data; excluding the target\nY_train = train_set.iloc[:, -1].values # returns the target-only\nX_test = test_set.iloc[:, :].values # \"\"\nY_test = test_set.iloc[:, -1].values # \"", "_____no_output_____" ], [ "# Fit a linear regression to the training data\nreg = LinearRegression(normalize=True).fit(X_train, Y_train)\nprint(reg.score(X_train, Y_train))\nprint(reg.coef_)\nprint(reg.intercept_)\nprint(reg.get_params())", "1.0\n[-2.56168830e-15 -1.29753328e-01 3.62804994e-15 5.79491537e-15\n -1.19653111e-14 1.49070049e-15 2.69939419e-16 -6.16112409e-16\n -5.09691421e-16 1.15379089e-02 -1.23742808e-15 1.29864769e-15\n -9.38401615e-16 3.97717377e-15 -2.84928882e-16 1.05676764e-15\n -1.52213820e-16 -2.71618986e-03 -5.14571876e-16 1.88200913e-15\n 7.83896690e-16 1.74419824e-16 -8.31368066e-17 -3.81989039e-16\n -1.77761326e-15 -5.41772685e-16 -1.75577567e-15 -2.81162646e-16\n 5.23114385e-16 5.00513024e-15 1.55072678e-15 2.14180953e-15\n -5.49035753e-16 -1.09077902e-15 1.10086438e-15 -6.34344655e-04\n -9.88782303e-16 -1.02632930e-15 -1.46867939e-16 4.48699573e-16\n -1.86323289e-15 2.94939183e-15 1.93343846e-15 -3.48135695e-15\n -2.41298374e-15 -5.25164649e-17 -3.52985888e-15 2.83867313e-15\n 3.05184273e-15 2.44101536e-15 -2.30055073e-15 -2.17192326e-16\n -9.34820576e-17 -3.81304212e-05 -5.55749713e-16 -1.63610750e-15\n 8.49205088e-16 -8.92676187e-16 3.86798354e-15 -2.11127277e-16\n -2.12326712e-04 -2.88703130e-15 2.04008023e-15 1.07821991e-15\n -3.59655476e-15 -6.93631903e-16 -2.47056659e-16 1.66809890e-15\n -7.94444064e-16 -6.41994595e-15 3.71885996e-16 -1.66921493e-14\n 4.64631876e-15 -4.78281180e-15 5.04015902e-15 -3.32467237e-15\n -5.60707739e-15 -9.49373474e-16 3.02570436e-15 1.33893397e-15\n 9.00501895e-16 -1.85394850e-15 3.29254494e-16 4.17711863e-05\n 3.49348918e-06 -1.63379253e-05 1.07312462e-16 5.81979535e-16\n -2.74616593e-16 -1.22190283e-15 -3.61105390e-16 7.17093186e-16\n 9.21202133e-16 -6.06819106e-16 -1.42283741e-15 -1.27712901e-16\n 2.04162682e-16 7.70752745e-16 -8.36088089e-16 -9.25574799e-16\n 2.14825330e-15 -9.73883007e-17 -2.21881106e-16 -6.65226498e-17\n 3.42223353e-16 -7.49446300e-16 -2.92506066e-15 9.33552379e-16\n 1.72127485e-15 3.09501078e-16 -1.48465435e-16 -8.58384041e-16\n -2.45196825e-16 1.51609034e-15 3.07864139e-16 2.14610982e-15\n -6.27320382e-16 -1.09462056e-15 1.87220672e-16 9.76020640e-16\n -7.47254532e-16 5.48306970e-16 5.54083757e-16 -4.89641048e-17\n 2.13486335e-16 1.62696167e-15 5.68936651e-16 -1.83290257e-15\n -3.81542426e-16 4.36867989e-16 -1.14074980e-15 3.25970475e-16\n -1.03333873e-15 1.04055509e-15 6.05006836e-16 8.38287771e-16\n 1.00000000e+00]\n-8.326672684688674e-17\n{'copy_X': True, 'fit_intercept': True, 'n_jobs': None, 'normalize': True}\n" ], [ "# Find the variable with the largest \"normalized\" coefficient value\nprint('The positive(max) coef-value is {}'.format(max(reg.coef_))) # Positive Max\n#print('The abs(max) coef-value is {}'.format(max(reg.coef_, key=abs))) # ABS Max\nmax_var = max(reg.coef_) # Positive Max\n#max_var = max(reg.coef_, key=abs) # ABS Max\nvar_index = reg.coef_.tolist().index(max_var)\nprint('The variable associated with this coef-value is {}'.format(result.columns[var_index]))", "The positive(max) coef-value is 0.9999999999999997\nThe variable associated with this coef-value is 136\n" ], [ "importance = reg.coef_\n# summarize feature importance\nfor i,v in enumerate(importance):\n\tprint('Feature: %0d, Score: %.5f' % (i,v))\n# plot feature importance\npyplot.bar([x for x in range(len(importance))], importance)\npyplot.show()", "Feature: 0, Score: -0.00000\nFeature: 1, Score: -0.12975\nFeature: 2, Score: 0.00000\nFeature: 3, Score: 0.00000\nFeature: 4, Score: -0.00000\nFeature: 5, Score: 0.00000\nFeature: 6, Score: 0.00000\nFeature: 7, Score: -0.00000\nFeature: 8, Score: -0.00000\nFeature: 9, Score: 0.01154\nFeature: 10, Score: -0.00000\nFeature: 11, Score: 0.00000\nFeature: 12, Score: -0.00000\nFeature: 13, Score: 0.00000\nFeature: 14, Score: -0.00000\nFeature: 15, Score: 0.00000\nFeature: 16, Score: -0.00000\nFeature: 17, Score: -0.00272\nFeature: 18, Score: -0.00000\nFeature: 19, Score: 0.00000\nFeature: 20, Score: 0.00000\nFeature: 21, Score: 0.00000\nFeature: 22, Score: -0.00000\nFeature: 23, Score: -0.00000\nFeature: 24, Score: -0.00000\nFeature: 25, Score: -0.00000\nFeature: 26, Score: -0.00000\nFeature: 27, Score: -0.00000\nFeature: 28, Score: 0.00000\nFeature: 29, Score: 0.00000\nFeature: 30, Score: 0.00000\nFeature: 31, Score: 0.00000\nFeature: 32, Score: -0.00000\nFeature: 33, Score: -0.00000\nFeature: 34, Score: 0.00000\nFeature: 35, Score: -0.00063\nFeature: 36, Score: -0.00000\nFeature: 37, Score: -0.00000\nFeature: 38, Score: -0.00000\nFeature: 39, Score: 0.00000\nFeature: 40, Score: -0.00000\nFeature: 41, Score: 0.00000\nFeature: 42, Score: 0.00000\nFeature: 43, Score: -0.00000\nFeature: 44, Score: -0.00000\nFeature: 45, Score: -0.00000\nFeature: 46, Score: -0.00000\nFeature: 47, Score: 0.00000\nFeature: 48, Score: 0.00000\nFeature: 49, Score: 0.00000\nFeature: 50, Score: -0.00000\nFeature: 51, Score: -0.00000\nFeature: 52, Score: -0.00000\nFeature: 53, Score: -0.00004\nFeature: 54, Score: -0.00000\nFeature: 55, Score: -0.00000\nFeature: 56, Score: 0.00000\nFeature: 57, Score: -0.00000\nFeature: 58, Score: 0.00000\nFeature: 59, Score: -0.00000\nFeature: 60, Score: -0.00021\nFeature: 61, Score: -0.00000\nFeature: 62, Score: 0.00000\nFeature: 63, Score: 0.00000\nFeature: 64, Score: -0.00000\nFeature: 65, Score: -0.00000\nFeature: 66, Score: -0.00000\nFeature: 67, Score: 0.00000\nFeature: 68, Score: -0.00000\nFeature: 69, Score: -0.00000\nFeature: 70, Score: 0.00000\nFeature: 71, Score: -0.00000\nFeature: 72, Score: 0.00000\nFeature: 73, Score: -0.00000\nFeature: 74, Score: 0.00000\nFeature: 75, Score: -0.00000\nFeature: 76, Score: -0.00000\nFeature: 77, Score: -0.00000\nFeature: 78, Score: 0.00000\nFeature: 79, Score: 0.00000\nFeature: 80, Score: 0.00000\nFeature: 81, Score: -0.00000\nFeature: 82, Score: 0.00000\nFeature: 83, Score: 0.00004\nFeature: 84, Score: 0.00000\nFeature: 85, Score: -0.00002\nFeature: 86, Score: 0.00000\nFeature: 87, Score: 0.00000\nFeature: 88, Score: -0.00000\nFeature: 89, Score: -0.00000\nFeature: 90, Score: -0.00000\nFeature: 91, Score: 0.00000\nFeature: 92, Score: 0.00000\nFeature: 93, Score: -0.00000\nFeature: 94, Score: -0.00000\nFeature: 95, Score: -0.00000\nFeature: 96, Score: 0.00000\nFeature: 97, Score: 0.00000\nFeature: 98, Score: -0.00000\nFeature: 99, Score: -0.00000\nFeature: 100, Score: 0.00000\nFeature: 101, Score: -0.00000\nFeature: 102, Score: -0.00000\nFeature: 103, Score: -0.00000\nFeature: 104, Score: 0.00000\nFeature: 105, Score: -0.00000\nFeature: 106, Score: -0.00000\nFeature: 107, Score: 0.00000\nFeature: 108, Score: 0.00000\nFeature: 109, Score: 0.00000\nFeature: 110, Score: -0.00000\nFeature: 111, Score: -0.00000\nFeature: 112, Score: -0.00000\nFeature: 113, Score: 0.00000\nFeature: 114, Score: 0.00000\nFeature: 115, Score: 0.00000\nFeature: 116, Score: -0.00000\nFeature: 117, Score: -0.00000\nFeature: 118, Score: 0.00000\nFeature: 119, Score: 0.00000\nFeature: 120, Score: -0.00000\nFeature: 121, Score: 0.00000\nFeature: 122, Score: 0.00000\nFeature: 123, Score: -0.00000\nFeature: 124, Score: 0.00000\nFeature: 125, Score: 0.00000\nFeature: 126, Score: 0.00000\nFeature: 127, Score: -0.00000\nFeature: 128, Score: -0.00000\nFeature: 129, Score: 0.00000\nFeature: 130, Score: -0.00000\nFeature: 131, Score: 0.00000\nFeature: 132, Score: -0.00000\nFeature: 133, Score: 0.00000\nFeature: 134, Score: 0.00000\nFeature: 135, Score: 0.00000\nFeature: 136, Score: 1.00000\n" ], [ "Y_pred = reg.predict(X_test)\n\norig_mae = mean_absolute_error(Y_test,Y_pred)\norig_mse = mean_squared_error(Y_test,Y_pred)\norig_rmse_val = rmse(Y_test,Y_pred)\norig_r2 = r2_score(Y_test,Y_pred)\nprint(\"MAE: %.30f\"%orig_mae)\nprint(\"MSE: %.30f\"%orig_mse)\nprint(\"RMSE: %.30f\"%orig_rmse_val)\nprint(\"R2: %.30f\"%orig_r2)", "MAE: 0.000000000000000244982312115320\nMSE: 0.000000000000000000000000000000\nRMSE: 0.000000000000000390242982433187\nR2: 1.000000000000000000000000000000\n" ], [ "Y_pred_tr = reg.predict(X_train)\n\norig_mae_tr = mean_absolute_error(Y_train,Y_pred_tr)\norig_mse_tr = mean_squared_error(Y_train,Y_pred_tr)\norig_rmse_val_tr = rmse(Y_train,Y_pred_tr)\norig_r2_tr = r2_score(Y_train,Y_pred_tr)\nprint(\"MAE: %.30f\"%orig_mae_tr)\nprint(\"MSE: %.30f\"%orig_mse_tr)\nprint(\"RMSE: %.30f\"%orig_rmse_val_tr)\nprint(\"R2: %.30f\"%orig_r2_tr)", "MAE: 0.000000000000000244045931896735\nMSE: 0.000000000000000000000000000000\nRMSE: 0.000000000000000380937086387870\nR2: 1.000000000000000000000000000000\n" ], [ "res_frame = pd.DataFrame({'data':'original',\n 'imputation':'none',\n 'mae': orig_mae, \n 'mse': orig_mse, \n 'rmse':orig_rmse_val, \n 'R2':orig_r2,\n 'mae_diff':np.nan,\n 'mse_diff':np.nan,\n 'rmse_diff':np.nan,\n 'R2_diff':np.nan}, index=[0])", "_____no_output_____" ], [ "res_frame", "_____no_output_____" ] ], [ [ "## LASSO Regularization ", "_____no_output_____" ] ], [ [ "l1_mod = linear_model.Lasso(alpha=0.001, normalize=True).fit(X_train, Y_train)\nprint(l1_mod.score(X_train, Y_train))\nprint(l1_mod.coef_)\nprint(l1_mod.intercept_)\nprint(l1_mod.get_params())", "0.0\n[-0. 0. -0. -0. -0. -0. -0. -0. -0. 0. -0. -0. -0. -0. -0. -0. -0. 0.\n -0. -0. -0. -0. -0. -0. -0. -0. -0. -0. -0. -0. -0. -0. -0. -0. -0. 0.\n -0. -0. -0. -0. -0. -0. -0. -0. -0. -0. -0. -0. -0. -0. -0. -0. -0. 0.\n -0. -0. -0. -0. -0. -0. 0. -0. -0. -0. -0. -0. -0. -0. -0. -0. -0. -0.\n -0. -0. -0. -0. -0. -0. -0. -0. -0. -0. -0. 0. 0. 0. -0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n0.11261187177580305\n{'alpha': 0.001, 'copy_X': True, 'fit_intercept': True, 'max_iter': 1000, 'normalize': True, 'positive': False, 'precompute': False, 'random_state': None, 'selection': 'cyclic', 'tol': 0.0001, 'warm_start': False}\n" ], [ "Y_pred2 = l1_mod.predict(X_test)\n\norig_mae2 = mean_absolute_error(Y_test,Y_pred2)\norig_mse2 = mean_squared_error(Y_test,Y_pred2)\norig_rmse_val2 = rmse(Y_test,Y_pred2)\norig_r22 = r2_score(Y_test,Y_pred2)\nprint(\"MAE: %.5f\"%orig_mae2)\nprint(\"MSE: %.5f\"%orig_mse2)\nprint(\"RMSE: %.5f\"%orig_rmse_val2)\nprint(\"R2: %.5f\"%orig_r22)", "MAE: 0.12489\nMSE: 0.02417\nRMSE: 0.15548\nR2: -0.00001\n" ], [ "Y_pred2_tr = l1_mod.predict(X_train)\n\norig_mae2_tr = mean_absolute_error(Y_train,Y_pred2_tr)\norig_mse2_tr = mean_squared_error(Y_train,Y_pred2_tr)\norig_rmse_val2_tr = rmse(Y_train,Y_pred2_tr)\norig_r22_tr = r2_score(Y_train,Y_pred2_tr)\nprint(\"MAE: %.5f\"%orig_mae2_tr)\nprint(\"MSE: %.5f\"%orig_mse2_tr)\nprint(\"RMSE: %.5f\"%orig_rmse_val2_tr)\nprint(\"R2: %.5f\"%orig_r22_tr)", "MAE: 0.12496\nMSE: 0.02421\nRMSE: 0.15559\nR2: 0.00000\n" ], [ "# Find the variable with the largest \"normalized\" coefficient value\nprint('The positive(max) coef-value is {}'.format(max(l1_mod.coef_))) # Positive Max\n#print('The abs(max) coef-value is {}'.format(max(l1_mod.coef_, key=abs))) # ABS Max\nmax_var = max(l1_mod.coef_) # Positive Max\n#max_var = max(reg.coef_, key=abs) # ABS Max\nvar_index = l1_mod.coef_.tolist().index(max_var)\nprint('The variable associated with this coef-value is {}'.format(result.columns[var_index]))", "The positive(max) coef-value is -0.0\nThe variable associated with this coef-value is 0\n" ], [ "importance = l1_mod.coef_\n# summarize feature importance\nfor i,v in enumerate(importance):\n\tprint('Feature: %0d, Score: %.5f' % (i,v))\n# plot feature importance\npyplot.bar([x for x in range(len(importance))], importance)\npyplot.show()", "Feature: 0, Score: -0.00000\nFeature: 1, Score: 0.00000\nFeature: 2, Score: -0.00000\nFeature: 3, Score: -0.00000\nFeature: 4, Score: -0.00000\nFeature: 5, Score: -0.00000\nFeature: 6, Score: -0.00000\nFeature: 7, Score: -0.00000\nFeature: 8, Score: -0.00000\nFeature: 9, Score: 0.00000\nFeature: 10, Score: -0.00000\nFeature: 11, Score: -0.00000\nFeature: 12, Score: -0.00000\nFeature: 13, Score: -0.00000\nFeature: 14, Score: -0.00000\nFeature: 15, Score: -0.00000\nFeature: 16, Score: -0.00000\nFeature: 17, Score: 0.00000\nFeature: 18, Score: -0.00000\nFeature: 19, Score: -0.00000\nFeature: 20, Score: -0.00000\nFeature: 21, Score: -0.00000\nFeature: 22, Score: -0.00000\nFeature: 23, Score: -0.00000\nFeature: 24, Score: -0.00000\nFeature: 25, Score: -0.00000\nFeature: 26, Score: -0.00000\nFeature: 27, Score: -0.00000\nFeature: 28, Score: -0.00000\nFeature: 29, Score: -0.00000\nFeature: 30, Score: -0.00000\nFeature: 31, Score: -0.00000\nFeature: 32, Score: -0.00000\nFeature: 33, Score: -0.00000\nFeature: 34, Score: -0.00000\nFeature: 35, Score: 0.00000\nFeature: 36, Score: -0.00000\nFeature: 37, Score: -0.00000\nFeature: 38, Score: -0.00000\nFeature: 39, Score: -0.00000\nFeature: 40, Score: -0.00000\nFeature: 41, Score: -0.00000\nFeature: 42, Score: -0.00000\nFeature: 43, Score: -0.00000\nFeature: 44, Score: -0.00000\nFeature: 45, Score: -0.00000\nFeature: 46, Score: -0.00000\nFeature: 47, Score: -0.00000\nFeature: 48, Score: -0.00000\nFeature: 49, Score: -0.00000\nFeature: 50, Score: -0.00000\nFeature: 51, Score: -0.00000\nFeature: 52, Score: -0.00000\nFeature: 53, Score: 0.00000\nFeature: 54, Score: -0.00000\nFeature: 55, Score: -0.00000\nFeature: 56, Score: -0.00000\nFeature: 57, Score: -0.00000\nFeature: 58, Score: -0.00000\nFeature: 59, Score: -0.00000\nFeature: 60, Score: 0.00000\nFeature: 61, Score: -0.00000\nFeature: 62, Score: -0.00000\nFeature: 63, Score: -0.00000\nFeature: 64, Score: -0.00000\nFeature: 65, Score: -0.00000\nFeature: 66, Score: -0.00000\nFeature: 67, Score: -0.00000\nFeature: 68, Score: -0.00000\nFeature: 69, Score: -0.00000\nFeature: 70, Score: -0.00000\nFeature: 71, Score: -0.00000\nFeature: 72, Score: -0.00000\nFeature: 73, Score: -0.00000\nFeature: 74, Score: -0.00000\nFeature: 75, Score: -0.00000\nFeature: 76, Score: -0.00000\nFeature: 77, Score: -0.00000\nFeature: 78, Score: -0.00000\nFeature: 79, Score: -0.00000\nFeature: 80, Score: -0.00000\nFeature: 81, Score: -0.00000\nFeature: 82, Score: -0.00000\nFeature: 83, Score: 0.00000\nFeature: 84, Score: 0.00000\nFeature: 85, Score: 0.00000\nFeature: 86, Score: -0.00000\nFeature: 87, Score: 0.00000\nFeature: 88, Score: 0.00000\nFeature: 89, Score: 0.00000\nFeature: 90, Score: 0.00000\nFeature: 91, Score: 0.00000\nFeature: 92, Score: 0.00000\nFeature: 93, Score: 0.00000\nFeature: 94, Score: 0.00000\nFeature: 95, Score: 0.00000\nFeature: 96, Score: 0.00000\nFeature: 97, Score: 0.00000\nFeature: 98, Score: 0.00000\nFeature: 99, Score: 0.00000\nFeature: 100, Score: 0.00000\nFeature: 101, Score: 0.00000\nFeature: 102, Score: 0.00000\nFeature: 103, Score: 0.00000\nFeature: 104, Score: 0.00000\nFeature: 105, Score: 0.00000\nFeature: 106, Score: 0.00000\nFeature: 107, Score: 0.00000\nFeature: 108, Score: 0.00000\nFeature: 109, Score: 0.00000\nFeature: 110, Score: 0.00000\nFeature: 111, Score: 0.00000\nFeature: 112, Score: 0.00000\nFeature: 113, Score: 0.00000\nFeature: 114, Score: 0.00000\nFeature: 115, Score: 0.00000\nFeature: 116, Score: 0.00000\nFeature: 117, Score: 0.00000\nFeature: 118, Score: 0.00000\nFeature: 119, Score: 0.00000\nFeature: 120, Score: 0.00000\nFeature: 121, Score: 0.00000\nFeature: 122, Score: 0.00000\nFeature: 123, Score: 0.00000\nFeature: 124, Score: 0.00000\nFeature: 125, Score: 0.00000\nFeature: 126, Score: 0.00000\nFeature: 127, Score: 0.00000\nFeature: 128, Score: 0.00000\nFeature: 129, Score: 0.00000\nFeature: 130, Score: 0.00000\nFeature: 131, Score: 0.00000\nFeature: 132, Score: 0.00000\nFeature: 133, Score: 0.00000\nFeature: 134, Score: 0.00000\nFeature: 135, Score: 0.00000\nFeature: 136, Score: 0.00000\n" ], [ "res_frame2 = pd.DataFrame({'data':'lasso',\n 'imputation':'none',\n 'mae': orig_mae2, \n 'mse': orig_mse2, \n 'rmse':orig_rmse_val2, \n 'R2':orig_r22,\n 'mae_diff':orig_mae2-orig_mae,\n 'mse_diff':orig_mse2-orig_mse,\n 'rmse_diff':orig_rmse_val2-orig_rmse_val,\n 'R2_diff':orig_r22-orig_r2}, index=[0])", "_____no_output_____" ], [ "res_frame = pd.concat([res_frame, res_frame2])\nres_frame", "_____no_output_____" ] ], [ [ "## Ridge Regularization", "_____no_output_____" ] ], [ [ "l2_mod = Ridge(alpha=1.0, normalize=True).fit(X_train, Y_train)\nprint(l2_mod.score(X_train, Y_train))\nprint(l2_mod.coef_)\nprint(l2_mod.intercept_)\nprint(l2_mod.get_params())", "0.8971461621794701\n[-6.83620615e-03 0.00000000e+00 -5.57662158e-03 -6.33991141e-03\n -3.35777264e-02 -3.04976800e-03 -3.02982234e-02 2.02123805e-04\n -1.87658848e-03 0.00000000e+00 -7.42342998e-03 -8.18448184e-03\n -2.44027237e-02 -1.50770297e-02 -6.74760084e-03 -9.49339175e-03\n -4.10919762e-03 0.00000000e+00 -5.76611434e-03 1.29011362e-02\n -4.23702829e-03 -4.49205445e-03 -3.58214260e-03 -6.30084105e-03\n -2.48126639e-03 -1.90478085e-02 -8.14305908e-03 -1.17213524e-02\n 1.13520138e-02 -4.92662057e-03 -5.28643935e-03 -1.08097812e-02\n -3.87440936e-03 -9.82002645e-03 -7.82270911e-03 0.00000000e+00\n -3.44629678e-03 8.63703503e-04 -1.89683443e-03 -3.04593841e-03\n -4.24380882e-03 -6.49859677e-03 -1.12423310e-02 -2.69863829e-02\n -7.42014402e-03 -5.43984185e-03 -5.62360172e-03 -6.50117257e-03\n -1.83620632e-02 -1.16821614e-02 -5.68998238e-03 -1.69737227e-02\n -4.18539507e-03 0.00000000e+00 -3.30344230e-03 1.27849492e-02\n -1.08344215e-02 -1.25618668e-02 -8.75888463e-03 -7.52180403e-03\n 0.00000000e+00 -9.85896020e-03 -4.72139962e-03 -1.62781491e-03\n -3.99861691e-03 -3.07363943e-03 -4.49382426e-03 -2.81791009e-03\n -3.52885196e-03 3.86780574e-04 -5.78054799e-03 -4.33223350e-02\n -4.69489099e-03 -3.31538516e-02 -6.31656667e-03 -9.10802580e-03\n -9.01375150e-03 -4.99354076e-03 -4.21060551e-03 9.07586855e-03\n 2.88261536e-03 -1.36620414e-02 -1.59908075e-03 0.00000000e+00\n 0.00000000e+00 0.00000000e+00 -3.10671277e-02 3.82331403e-03\n 1.25016093e-02 4.40204110e-03 1.80629298e-02 6.73005869e-03\n 1.52965506e-02 -2.09178757e-02 5.53618472e-03 -1.41788027e-03\n -1.28548865e-02 -6.12133183e-03 1.30161672e-02 -7.70046748e-03\n 8.24046691e-03 9.07484639e-03 5.63308840e-03 5.77913851e-03\n 1.22079394e-02 1.45569775e-02 2.88465743e-02 3.16282455e-02\n -5.18431692e-03 5.96822905e-03 2.18610926e-02 1.88162977e-02\n -5.28435796e-03 2.14237739e-02 3.62810939e-02 -5.56290626e-03\n -1.23086041e-02 7.90642650e-03 2.48338806e-03 5.99581591e-03\n 4.19225599e-03 1.12222172e-02 8.39298774e-03 2.25463880e-02\n -1.41635614e-02 -1.55235377e-02 2.65434471e-04 2.79263925e-02\n 1.24088069e-02 4.00809152e-02 -3.49273040e-02 -1.57379600e-02\n 2.21620878e-02 9.99255359e-02 2.31553435e-02 1.29974026e-01\n 2.09117723e-01]\n0.009071946816265913\n{'alpha': 1.0, 'copy_X': True, 'fit_intercept': True, 'max_iter': None, 'normalize': True, 'random_state': None, 'solver': 'auto', 'tol': 0.001}\n" ], [ "Y_pred3 = l2_mod.predict(X_test)\n\norig_mae3 = mean_absolute_error(Y_test,Y_pred3)\norig_mse3 = mean_squared_error(Y_test,Y_pred3)\norig_rmse_val3 = rmse(Y_test,Y_pred3)\norig_r23 = r2_score(Y_test,Y_pred3)\nprint(\"MAE: %.5f\"%orig_mae3)\nprint(\"MSE: %.5f\"%orig_mse3)\nprint(\"RMSE: %.5f\"%orig_rmse_val3)\nprint(\"R2: %.5f\"%orig_r23)", "MAE: 0.03033\nMSE: 0.00249\nRMSE: 0.04994\nR2: 0.89682\n" ], [ "Y_pred3_tr = l2_mod.predict(X_train)\n\norig_mae3_tr = mean_absolute_error(Y_train,Y_pred3_tr)\norig_mse3_tr = mean_squared_error(Y_train,Y_pred3_tr)\norig_rmse_val3_tr = rmse(Y_train,Y_pred3_tr)\norig_r23_tr = r2_score(Y_train,Y_pred3_tr)\nprint(\"MAE: %.5f\"%orig_mae3_tr)\nprint(\"MSE: %.5f\"%orig_mse3_tr)\nprint(\"RMSE: %.5f\"%orig_rmse_val3_tr)\nprint(\"R2: %.5f\"%orig_r23_tr)", "MAE: 0.03034\nMSE: 0.00249\nRMSE: 0.04990\nR2: 0.89715\n" ], [ "# Find the variable with the largest \"normalized\" coefficient value\nprint('The positive(max) coef-value is {}'.format(max(l2_mod.coef_))) # Positive Max\nprint('The abs(max) coef-value is {}'.format(max(l2_mod.coef_, key=abs))) # ABS Max\nmax_var = max(l2_mod.coef_) # Positive Max\n#max_var = max(reg.coef_, key=abs) # ABS Max\nvar_index = l2_mod.coef_.tolist().index(max_var)\nprint('The variable associated with this coef-value is {}'.format(result.columns[4]))", "The positive(max) coef-value is 0.20911772335927986\nThe abs(max) coef-value is 0.20911772335927986\nThe variable associated with this coef-value is 4\n" ], [ "importance = l2_mod.coef_\n# summarize feature importance\nfor i,v in enumerate(importance):\n\tprint('Feature: %0d, Score: %.5f' % (i,v))\n# plot feature importance\npyplot.bar([x for x in range(len(importance))], importance)\npyplot.show()", "Feature: 0, Score: -0.00684\nFeature: 1, Score: 0.00000\nFeature: 2, Score: -0.00558\nFeature: 3, Score: -0.00634\nFeature: 4, Score: -0.03358\nFeature: 5, Score: -0.00305\nFeature: 6, Score: -0.03030\nFeature: 7, Score: 0.00020\nFeature: 8, Score: -0.00188\nFeature: 9, Score: 0.00000\nFeature: 10, Score: -0.00742\nFeature: 11, Score: -0.00818\nFeature: 12, Score: -0.02440\nFeature: 13, Score: -0.01508\nFeature: 14, Score: -0.00675\nFeature: 15, Score: -0.00949\nFeature: 16, Score: -0.00411\nFeature: 17, Score: 0.00000\nFeature: 18, Score: -0.00577\nFeature: 19, Score: 0.01290\nFeature: 20, Score: -0.00424\nFeature: 21, Score: -0.00449\nFeature: 22, Score: -0.00358\nFeature: 23, Score: -0.00630\nFeature: 24, Score: -0.00248\nFeature: 25, Score: -0.01905\nFeature: 26, Score: -0.00814\nFeature: 27, Score: -0.01172\nFeature: 28, Score: 0.01135\nFeature: 29, Score: -0.00493\nFeature: 30, Score: -0.00529\nFeature: 31, Score: -0.01081\nFeature: 32, Score: -0.00387\nFeature: 33, Score: -0.00982\nFeature: 34, Score: -0.00782\nFeature: 35, Score: 0.00000\nFeature: 36, Score: -0.00345\nFeature: 37, Score: 0.00086\nFeature: 38, Score: -0.00190\nFeature: 39, Score: -0.00305\nFeature: 40, Score: -0.00424\nFeature: 41, Score: -0.00650\nFeature: 42, Score: -0.01124\nFeature: 43, Score: -0.02699\nFeature: 44, Score: -0.00742\nFeature: 45, Score: -0.00544\nFeature: 46, Score: -0.00562\nFeature: 47, Score: -0.00650\nFeature: 48, Score: -0.01836\nFeature: 49, Score: -0.01168\nFeature: 50, Score: -0.00569\nFeature: 51, Score: -0.01697\nFeature: 52, Score: -0.00419\nFeature: 53, Score: 0.00000\nFeature: 54, Score: -0.00330\nFeature: 55, Score: 0.01278\nFeature: 56, Score: -0.01083\nFeature: 57, Score: -0.01256\nFeature: 58, Score: -0.00876\nFeature: 59, Score: -0.00752\nFeature: 60, Score: 0.00000\nFeature: 61, Score: -0.00986\nFeature: 62, Score: -0.00472\nFeature: 63, Score: -0.00163\nFeature: 64, Score: -0.00400\nFeature: 65, Score: -0.00307\nFeature: 66, Score: -0.00449\nFeature: 67, Score: -0.00282\nFeature: 68, Score: -0.00353\nFeature: 69, Score: 0.00039\nFeature: 70, Score: -0.00578\nFeature: 71, Score: -0.04332\nFeature: 72, Score: -0.00469\nFeature: 73, Score: -0.03315\nFeature: 74, Score: -0.00632\nFeature: 75, Score: -0.00911\nFeature: 76, Score: -0.00901\nFeature: 77, Score: -0.00499\nFeature: 78, Score: -0.00421\nFeature: 79, Score: 0.00908\nFeature: 80, Score: 0.00288\nFeature: 81, Score: -0.01366\nFeature: 82, Score: -0.00160\nFeature: 83, Score: 0.00000\nFeature: 84, Score: 0.00000\nFeature: 85, Score: 0.00000\nFeature: 86, Score: -0.03107\nFeature: 87, Score: 0.00382\nFeature: 88, Score: 0.01250\nFeature: 89, Score: 0.00440\nFeature: 90, Score: 0.01806\nFeature: 91, Score: 0.00673\nFeature: 92, Score: 0.01530\nFeature: 93, Score: -0.02092\nFeature: 94, Score: 0.00554\nFeature: 95, Score: -0.00142\nFeature: 96, Score: -0.01285\nFeature: 97, Score: -0.00612\nFeature: 98, Score: 0.01302\nFeature: 99, Score: -0.00770\nFeature: 100, Score: 0.00824\nFeature: 101, Score: 0.00907\nFeature: 102, Score: 0.00563\nFeature: 103, Score: 0.00578\nFeature: 104, Score: 0.01221\nFeature: 105, Score: 0.01456\nFeature: 106, Score: 0.02885\nFeature: 107, Score: 0.03163\nFeature: 108, Score: -0.00518\nFeature: 109, Score: 0.00597\nFeature: 110, Score: 0.02186\nFeature: 111, Score: 0.01882\nFeature: 112, Score: -0.00528\nFeature: 113, Score: 0.02142\nFeature: 114, Score: 0.03628\nFeature: 115, Score: -0.00556\nFeature: 116, Score: -0.01231\nFeature: 117, Score: 0.00791\nFeature: 118, Score: 0.00248\nFeature: 119, Score: 0.00600\nFeature: 120, Score: 0.00419\nFeature: 121, Score: 0.01122\nFeature: 122, Score: 0.00839\nFeature: 123, Score: 0.02255\nFeature: 124, Score: -0.01416\nFeature: 125, Score: -0.01552\nFeature: 126, Score: 0.00027\nFeature: 127, Score: 0.02793\nFeature: 128, Score: 0.01241\nFeature: 129, Score: 0.04008\nFeature: 130, Score: -0.03493\nFeature: 131, Score: -0.01574\nFeature: 132, Score: 0.02216\nFeature: 133, Score: 0.09993\nFeature: 134, Score: 0.02316\nFeature: 135, Score: 0.12997\nFeature: 136, Score: 0.20912\n" ], [ "res_frame3 = pd.DataFrame({'data':'ridge',\n 'imputation':'none',\n 'mae': orig_mae3, \n 'mse': orig_mse3, \n 'rmse':orig_rmse_val3, \n 'R2':orig_r23,\n 'mae_diff':orig_mae3-orig_mae,\n 'mse_diff':orig_mse3-orig_mse,\n 'rmse_diff':orig_rmse_val3-orig_rmse_val,\n 'R2_diff':orig_r23-orig_r2}, index=[0])", "_____no_output_____" ], [ "res_frame = pd.concat([res_frame, res_frame3])\nres_frame", "_____no_output_____" ], [ "result.describe()", "_____no_output_____" ] ], [ [ "## Model Interpretability & Explainability", "_____no_output_____" ], [ "## Case Conclusions", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ] ]
4a0abaafa351982a10f7ef073b187ad487691253
15,681
ipynb
Jupyter Notebook
python_extras/data_model.ipynb
AnnaMilov/programming-for-data-science
2c6363f41733d3fff0d7886741b8960fe982c855
[ "MIT" ]
null
null
null
python_extras/data_model.ipynb
AnnaMilov/programming-for-data-science
2c6363f41733d3fff0d7886741b8960fe982c855
[ "MIT" ]
2
2021-08-18T06:49:03.000Z
2021-08-19T10:54:02.000Z
python_extras/data_model.ipynb
AnnaMilov/programming-for-data-science
2c6363f41733d3fff0d7886741b8960fe982c855
[ "MIT" ]
4
2021-08-17T13:57:27.000Z
2021-08-18T14:33:31.000Z
24.199074
237
0.518589
[ [ [ "# Python Data Model", "_____no_output_____" ], [ "Most of the content of this book has been extracted from the book \"Fluent Python\" by Luciano Ramalho (O'Reilly, 2015)\nhttp://shop.oreilly.com/product/0636920032519.do", "_____no_output_____" ], [ ">One of the best qualities of Python is its consistency. \n>After working with Python for a while, you are able to start making informed, correct guesses about features that are new to you.", "_____no_output_____" ], [ "However, if you learned another object-oriented language before Python, you may have found it strange to use `len(collection)` instead of `collection.len()`. \n\nThis apparent oddity is the tip of an iceberg that, when properly understood, is the key to everything we call **Pythonic**. \n\n>The iceberg is called the **Python data model**, and it describes the API that you can use to make your own objects play well with the most idiomatic language features.", "_____no_output_____" ], [ "> You can think of the data model as a description of Python as a framework. It formalises the interfaces of the building blocks of the language itself, such as sequences, iterators, functions, classes, context managers, and so on.", "_____no_output_____" ], [ "While coding with any framework, you spend a lot of time implementing methods that are called by the framework. The same happens when you leverage the Python data model. \n\nThe Python interpreter invokes **special methods** to perform basic object operations, often triggered by **special syntax**. \n\nThe special method names are always written with leading and trailing double underscores (i.e., `__getitem__`).\n\nFor example, the syntax `obj[key]` is supported by the `__getitem__` special method. \n\nIn order to evaluate `my_collection[key]`, the interpreter calls `my_collection.__getitem__(key)`.\n\nThe special method names allow your objects to implement, support, and interact with basic language constructs such as:\n\n- Iteration\n- Collections\n- Attribute access\n- Operator overloading\n- Function and method invocation\n- Object creation and destruction\n- String representation and formatting\n- Managed contexts (i.e., with blocks)", "_____no_output_____" ], [ "## A Pythonic Card Deck", "_____no_output_____" ] ], [ [ "import collections\n\nCard = collections.namedtuple('Card', ['rank', 'suit'])\n\nclass FrenchDeck:\n ranks = [str(n) for n in range(2, 11)] + list('JQKA')\n suits = 'spades diamonds clubs hearts'.split()\n\n def __init__(self):\n self._cards = [Card(rank, suit) for suit in self.suits\n for rank in self.ranks]\n\n def __len__(self):\n return len(self._cards)\n\n def __getitem__(self, position):\n return self._cards[position]", "_____no_output_____" ] ], [ [ "The first thing to note is the use of `collections.namedtuple` to construct a simple class to represent individual cards. \n\nSince Python 2.6, `namedtuple` can be used to build classes of objects that are just bundles of attributes with no custom methods, like a database record. \n\nIn the example, we use it to provide a nice representation for the cards in the deck:", "_____no_output_____" ] ], [ [ "beer_card = Card('7', 'diamonds')\nbeer_card", "_____no_output_____" ] ], [ [ "But the point of this example is the `FrenchDeck` class. \n\nIt’s short, but it packs a punch. \n\n##### Length of a Deck\n\nFirst, like any standard Python collection, a deck responds to the `len()` function by returning the number of cards in it:", "_____no_output_____" ] ], [ [ "deck = FrenchDeck()\nlen(deck)", "_____no_output_____" ] ], [ [ "##### Reading Specific Cards", "_____no_output_____" ], [ "Reading specific cards from the deck say, the first or the last— should be as easy as `deck[0]` or `deck[-1]`, and this is what the `__getitem__` method provides:", "_____no_output_____" ] ], [ [ "deck[0]", "_____no_output_____" ], [ "deck[-1]", "_____no_output_____" ] ], [ [ "##### Picking Random Card\n\nShould we create a method to pick a random card? **No need**. \n\nPython already has a function to get a random item from a sequence: `random.choice`. We can just use it on a deck instance:", "_____no_output_____" ] ], [ [ "from random import choice\nchoice(deck)", "_____no_output_____" ], [ "choice(deck)", "_____no_output_____" ], [ "choice(deck)", "_____no_output_____" ] ], [ [ "### First Impressions:\n\nWe’ve just seen two advantages of using special methods to leverage the Python data model:\n\n- The users of your classes don’t have to memorize arbitrary method names for standard operations \n(“How to get the number of items? Is it .size(), .length(), or what?”).\n\n- It’s easier to benefit from the rich Python standard library and avoid reinventing the wheel, like the `random.choice` function.", "_____no_output_____" ], [ "**... but it gets better ...**\n\nBecause our `__getitem__` delegates to the `[]` operator of `self._cards`, our deck automatically supports **slicing**. \n\nHere’s how we look at the top three cards from a brand new deck, and then pick just the aces by starting on index 12 and skipping 13 cards at a time:\n\n", "_____no_output_____" ] ], [ [ "deck[:3]", "_____no_output_____" ], [ "deck[12::13]", "_____no_output_____" ] ], [ [ "Just by implementing the `__getitem__` special method, our deck is also **iterable**:\n", "_____no_output_____" ] ], [ [ "for card in deck:\n print(card)", "Card(rank='2', suit='spades')\nCard(rank='3', suit='spades')\nCard(rank='4', suit='spades')\nCard(rank='5', suit='spades')\nCard(rank='6', suit='spades')\nCard(rank='7', suit='spades')\nCard(rank='8', suit='spades')\nCard(rank='9', suit='spades')\nCard(rank='10', suit='spades')\nCard(rank='J', suit='spades')\nCard(rank='Q', suit='spades')\nCard(rank='K', suit='spades')\nCard(rank='A', suit='spades')\nCard(rank='2', suit='diamonds')\nCard(rank='3', suit='diamonds')\nCard(rank='4', suit='diamonds')\nCard(rank='5', suit='diamonds')\nCard(rank='6', suit='diamonds')\nCard(rank='7', suit='diamonds')\nCard(rank='8', suit='diamonds')\nCard(rank='9', suit='diamonds')\nCard(rank='10', suit='diamonds')\nCard(rank='J', suit='diamonds')\nCard(rank='Q', suit='diamonds')\nCard(rank='K', suit='diamonds')\nCard(rank='A', suit='diamonds')\nCard(rank='2', suit='clubs')\nCard(rank='3', suit='clubs')\nCard(rank='4', suit='clubs')\nCard(rank='5', suit='clubs')\nCard(rank='6', suit='clubs')\nCard(rank='7', suit='clubs')\nCard(rank='8', suit='clubs')\nCard(rank='9', suit='clubs')\nCard(rank='10', suit='clubs')\nCard(rank='J', suit='clubs')\nCard(rank='Q', suit='clubs')\nCard(rank='K', suit='clubs')\nCard(rank='A', suit='clubs')\nCard(rank='2', suit='hearts')\nCard(rank='3', suit='hearts')\nCard(rank='4', suit='hearts')\nCard(rank='5', suit='hearts')\nCard(rank='6', suit='hearts')\nCard(rank='7', suit='hearts')\nCard(rank='8', suit='hearts')\nCard(rank='9', suit='hearts')\nCard(rank='10', suit='hearts')\nCard(rank='J', suit='hearts')\nCard(rank='Q', suit='hearts')\nCard(rank='K', suit='hearts')\nCard(rank='A', suit='hearts')\n" ] ], [ [ "... also in **reverse order**:\n\n```python \nfor card in reversed(deck):\n print(card)\n \n...\n```", "_____no_output_____" ], [ "## To know more...\n\nTo have a more complete overview of the Magic (_dunder_) methods, please have a look at the [Extra - Magic Methods and Operator Overloading](Extra - Magic Methods and Operator Overloading.ipynb) notebook.", "_____no_output_____" ], [ "---\n\n## Exercise: Emulating Numeric Types", "_____no_output_____" ], [ "```python \nfrom math import hypot\n\nclass Vector:\n\n def __init__(self, x=0, y=0):\n self.x = x\n self.y = y\n\n def __repr__(self):\n return 'Vector(%r, %r)' % (self.x, self.y)\n\n def __abs__(self):\n return hypot(self.x, self.y)\n\n def __bool__(self):\n return bool(abs(self))\n\n def __add__(self, other):\n x = self.x + other.x\n y = self.y + other.y\n return Vector(x, y)\n\n def __mul__(self, scalar):\n return Vector(self.x * scalar, self.y * scalar)\n```", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ] ]
4a0b084dc26805b83ac364ccfad6fdc4daf28e15
45,442
ipynb
Jupyter Notebook
PySpark DataFrame SQL Basics.ipynb
tvelichkovt/PySpark-DataFrame
1a70dbc59b5fe8098db21aae680dfdcc3232e728
[ "Apache-2.0" ]
null
null
null
PySpark DataFrame SQL Basics.ipynb
tvelichkovt/PySpark-DataFrame
1a70dbc59b5fe8098db21aae680dfdcc3232e728
[ "Apache-2.0" ]
null
null
null
PySpark DataFrame SQL Basics.ipynb
tvelichkovt/PySpark-DataFrame
1a70dbc59b5fe8098db21aae680dfdcc3232e728
[ "Apache-2.0" ]
null
null
null
57.303909
7,053
0.485058
[ [ [ "<a href=\"https://colab.research.google.com/github/tvelichkovt/PySpark-DataFrame/blob/main/PySpark%20DataFrame%20SQL%20Basics.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ] ], [ [ "!apt-get install openjdk-8-jdk-headless -qq > /dev/null\n!wget -q http://archive.apache.org/dist/spark/spark-3.1.1/spark-3.1.1-bin-hadoop3.2.tgz\n!tar xf spark-3.1.1-bin-hadoop3.2.tgz\n!pip install -q findspark", "_____no_output_____" ], [ "import os\nos.environ[\"JAVA_HOME\"] = \"/usr/lib/jvm/java-8-openjdk-amd64\"\nos.environ[\"SPARK_HOME\"] = \"/content/spark-3.1.1-bin-hadoop3.2\"", "_____no_output_____" ], [ "import findspark\nfindspark.init()\nfrom pyspark.sql import SparkSession\nspark = SparkSession.builder.master(\"local[*]\").getOrCreate()\nspark.conf.set(\"spark.sql.repl.eagerEval.enabled\", True) # Property used to format output tables better\nspark", "_____no_output_____" ], [ "# Load the csv into a dataframe\nfrom google.colab import files\n\n# Download the dataset from here (https://raw.githubusercontent.com/datasciencedojo/datasets/master/titanic.csv) and keep it somewhere on your computer. Load the dataset into your Colab directory from your local system:\nfiles.upload()\ndf = spark.read.csv(\"titanic.csv\", header=True, inferSchema=True)", "_____no_output_____" ], [ "!ls", "sample_data\t\t spark-3.1.1-bin-hadoop3.2.tgz\nspark-3.1.1-bin-hadoop3.2 titanic.csv\n" ], [ "display(df)", "_____no_output_____" ], [ "df.show(2)", "+-----------+--------+------+--------------------+------+----+-----+-----+---------+-------+-----+--------+\n|PassengerId|Survived|Pclass| Name| Sex| Age|SibSp|Parch| Ticket| Fare|Cabin|Embarked|\n+-----------+--------+------+--------------------+------+----+-----+-----+---------+-------+-----+--------+\n| 1| 0| 3|Braund, Mr. Owen ...| male|22.0| 1| 0|A/5 21171| 7.25| null| S|\n| 2| 1| 1|Cumings, Mrs. Joh...|female|38.0| 1| 0| PC 17599|71.2833| C85| C|\n+-----------+--------+------+--------------------+------+----+-----+-----+---------+-------+-----+--------+\nonly showing top 2 rows\n\n" ], [ "df.limit(2)", "_____no_output_____" ], [ "type(df)", "_____no_output_____" ], [ "df.printSchema()", "root\n |-- PassengerId: integer (nullable = true)\n |-- Survived: integer (nullable = true)\n |-- Pclass: integer (nullable = true)\n |-- Name: string (nullable = true)\n |-- Sex: string (nullable = true)\n |-- Age: double (nullable = true)\n |-- SibSp: integer (nullable = true)\n |-- Parch: integer (nullable = true)\n |-- Ticket: string (nullable = true)\n |-- Fare: double (nullable = true)\n |-- Cabin: string (nullable = true)\n |-- Embarked: string (nullable = true)\n\n" ], [ "df.select('PassengerId', 'Survived').limit(5)", "_____no_output_____" ], [ "# Females with age more than 25yrs who survived and not from 1st class ordered by theor ticket price ascending\n\ndf.where((df.Age > 25) & (df.Survived == 1) & (df.Sex != \"male\") & (df.Pclass != 1)).orderBy(df.Fare).limit(5)", "_____no_output_____" ], [ "# Average price of the tickets\n\ndf.agg({'Fare':'avg'})", "_____no_output_____" ], [ "df.groupBy('Pclass').agg({'Fare':'avg'}).orderBy('Pclass', ascending=False)", "_____no_output_____" ], [ "df.filter(df.Age > 25).agg({'Fare':'avg'})", "_____no_output_____" ], [ "from pyspark.sql.types import IntegerType\nfrom pyspark.sql.functions import udf\n\ndef round_float_down(x):\n return int(x)\n\nround_float_down_udf = udf(round_float_down, IntegerType())\n\ndf.select('PassengerId', 'Fare', round_float_down_udf('Fare').alias('Fare Rounded Down')).limit(5)", "_____no_output_____" ], [ "df.createOrReplaceTempView(\"Titanic\")", "_____no_output_____" ], [ "spark.sql('select * from Titanic')", "_____no_output_____" ], [ "spark.sql(' select count(*) Survived_Women_3rdClass from Titanic where Sex=\"female\" and Survived=1 and Pclass=3 ') ", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
4a0b0d44e6b782875aa24660d2610b30ff6b66b7
845,899
ipynb
Jupyter Notebook
pylondinium/notebooks/xcpp.ipynb
jtpio/quantstack-talks
092f93ddb9901cb614f428e13a0b1b1e3ffcc0ec
[ "BSD-3-Clause" ]
82
2017-04-14T20:18:55.000Z
2021-12-25T23:38:52.000Z
pylondinium/notebooks/xcpp.ipynb
jtpio/quantstack-talks
092f93ddb9901cb614f428e13a0b1b1e3ffcc0ec
[ "BSD-3-Clause" ]
3
2017-04-07T18:37:21.000Z
2020-07-11T09:37:53.000Z
pylondinium/notebooks/xcpp.ipynb
jtpio/quantstack-talks
092f93ddb9901cb614f428e13a0b1b1e3ffcc0ec
[ "BSD-3-Clause" ]
59
2017-04-07T11:16:56.000Z
2022-03-25T14:48:55.000Z
1,123.371846
684,434
0.944631
[ [ [ "empty" ] ] ]
[ "empty" ]
[ [ "empty" ] ]
4a0b0f1fc80c0b4bdd294c8c0976f6f29c0dcbec
104,881
ipynb
Jupyter Notebook
module1-decision-trees/LS_DS_411B_ipywidgets_Decision_Trees.ipynb
brit228/DS-Unit-4-Sprint-1-Tree-Ensembles
f753c90eb815f47de392b9cbcd64a11310f7c073
[ "MIT" ]
null
null
null
module1-decision-trees/LS_DS_411B_ipywidgets_Decision_Trees.ipynb
brit228/DS-Unit-4-Sprint-1-Tree-Ensembles
f753c90eb815f47de392b9cbcd64a11310f7c073
[ "MIT" ]
null
null
null
module1-decision-trees/LS_DS_411B_ipywidgets_Decision_Trees.ipynb
brit228/DS-Unit-4-Sprint-1-Tree-Ensembles
f753c90eb815f47de392b9cbcd64a11310f7c073
[ "MIT" ]
null
null
null
357.955631
59,928
0.938416
[ [ [ "_Lambda School Data Science — Tree Ensembles_ \n\n# Decision Trees — with ipywidgets!", "_____no_output_____" ], [ "### Notebook requirements\n- [ipywidgets](https://ipywidgets.readthedocs.io/en/stable/examples/Using%20Interact.html): works in Jupyter but [doesn't work on Google Colab](https://github.com/googlecolab/colabtools/issues/60#issuecomment-462529981)\n- [mlxtend.plotting.plot_decision_regions](http://rasbt.github.io/mlxtend/user_guide/plotting/plot_decision_regions/): `pip install mlxtend`", "_____no_output_____" ], [ "## Regressing a wave", "_____no_output_____" ] ], [ [ "import matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\n\n# Example from http://scikit-learn.org/stable/auto_examples/tree/plot_tree_regression.html\ndef make_data():\n import numpy as np\n rng = np.random.RandomState(1)\n X = np.sort(5 * rng.rand(80, 1), axis=0)\n y = np.sin(X).ravel()\n y[::5] += 2 * (0.5 - rng.rand(16))\n return X, y\n\nX, y = make_data()\n\nX_train, X_test, y_train, y_test = train_test_split(\n X, y, test_size=0.25, random_state=42)\n\nplt.scatter(X_train, y_train)\nplt.scatter(X_test, y_test);", "_____no_output_____" ], [ "from sklearn.tree import DecisionTreeRegressor\n\ndef regress_wave(max_depth):\n tree = DecisionTreeRegressor(max_depth=max_depth)\n tree.fit(X_train, y_train)\n print('Train R^2 score:', tree.score(X_train, y_train))\n print('Test R^2 score:', tree.score(X_test, y_test))\n plt.scatter(X_train, y_train)\n plt.scatter(X_test, y_test)\n plt.step(X, tree.predict(X))\n plt.show()", "_____no_output_____" ], [ "from ipywidgets import interact\ninteract(regress_wave, max_depth=(1,8,1));", "_____no_output_____" ] ], [ [ "## Classifying a curve", "_____no_output_____" ] ], [ [ "import numpy as np\ncurve_X = np.random.rand(1000, 2) \ncurve_y = np.square(curve_X[:,0]) + np.square(curve_X[:,1]) < 1.0\ncurve_y = curve_y.astype(int)", "_____no_output_____" ], [ "from sklearn.linear_model import LogisticRegression\nfrom mlxtend.plotting import plot_decision_regions\n\nlr = LogisticRegression(solver='lbfgs')\nlr.fit(curve_X, curve_y)\nplot_decision_regions(curve_X, curve_y, lr, legend=False)\nplt.axis((0,1,0,1));", "_____no_output_____" ], [ "from sklearn.tree import DecisionTreeClassifier\n\ndef classify_curve(max_depth):\n tree = DecisionTreeClassifier(max_depth=max_depth)\n tree.fit(curve_X, curve_y)\n plot_decision_regions(curve_X, curve_y, tree, legend=False)\n plt.axis((0,1,0,1))\n plt.show()", "_____no_output_____" ], [ "interact(classify_curve, max_depth=(1,8,1));", "_____no_output_____" ] ], [ [ "## Titanic survival, by age & fare", "_____no_output_____" ] ], [ [ "import seaborn as sns\nfrom sklearn.impute import SimpleImputer\n\ntitanic = sns.load_dataset('titanic')\nimputer = SimpleImputer()\ntitanic_X = imputer.fit_transform(titanic[['age', 'fare']])\ntitanic_y = titanic['survived'].values", "_____no_output_____" ], [ "from sklearn.linear_model import LogisticRegression\nfrom mlxtend.plotting import plot_decision_regions\n\nlr = LogisticRegression(solver='lbfgs')\nlr.fit(titanic_X, titanic_y)\nplot_decision_regions(titanic_X, titanic_y, lr, legend=False);\nplt.axis((0,75,0,175));", "_____no_output_____" ], [ "def classify_titanic(max_depth):\n tree = DecisionTreeClassifier(max_depth=max_depth)\n tree.fit(titanic_X, titanic_y)\n plot_decision_regions(titanic_X, titanic_y, tree, legend=False)\n plt.axis((0,75,0,175))\n plt.show()", "_____no_output_____" ], [ "interact(classify_titanic, max_depth=(1,8,1));", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ] ]
4a0b0fe522428fb70605a4de30cbd2133bc024cd
7,700
ipynb
Jupyter Notebook
deep learning/StyleGAN/StyleGAN - Explore Directions.ipynb
italoadler/data-science-learning
b75c37a61f3fbf458aacd5299b32e6f0269205f2
[ "Apache-2.0" ]
null
null
null
deep learning/StyleGAN/StyleGAN - Explore Directions.ipynb
italoadler/data-science-learning
b75c37a61f3fbf458aacd5299b32e6f0269205f2
[ "Apache-2.0" ]
null
null
null
deep learning/StyleGAN/StyleGAN - Explore Directions.ipynb
italoadler/data-science-learning
b75c37a61f3fbf458aacd5299b32e6f0269205f2
[ "Apache-2.0" ]
1
2020-02-20T02:16:44.000Z
2020-02-20T02:16:44.000Z
29.166667
565
0.577403
[ [ [ "<h1>Table of Contents<span class=\"tocSkip\"></span></h1>\n<div class=\"toc\"><ul class=\"toc-item\"><li><span><a href=\"#Load-Network\" data-toc-modified-id=\"Load-Network-1\"><span class=\"toc-item-num\">1&nbsp;&nbsp;</span>Load Network</a></span></li><li><span><a href=\"#Explore-Directions\" data-toc-modified-id=\"Explore-Directions-2\"><span class=\"toc-item-num\">2&nbsp;&nbsp;</span>Explore Directions</a></span><ul class=\"toc-item\"><li><span><a href=\"#Interactive\" data-toc-modified-id=\"Interactive-2.1\"><span class=\"toc-item-num\">2.1&nbsp;&nbsp;</span>Interactive</a></span></li></ul></li></ul></div>", "_____no_output_____" ] ], [ [ "is_stylegan_v1 = False", "_____no_output_____" ], [ "from pathlib import Path\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport sys\nimport os\nfrom datetime import datetime\nfrom tqdm import tqdm\n\n# ffmpeg installation location, for creating videos\nplt.rcParams['animation.ffmpeg_path'] = str('/usr/bin/ffmpeg')\nimport ipywidgets as widgets\nfrom ipywidgets import interact, interact_manual\nfrom IPython.display import display\nfrom ipywidgets import Button\n\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\n\n%load_ext autoreload\n%autoreload 2\n\n# StyleGAN2 Repo\nsys.path.append('/tf/notebooks/stylegan2')\n\n# StyleGAN Utils\nfrom stylegan_utils import load_network, gen_image_fun, synth_image_fun, create_video\n# v1 override\nif is_stylegan_v1:\n from stylegan_utils import load_network_v1 as load_network\n from stylegan_utils import gen_image_fun_v1 as gen_image_fun\n from stylegan_utils import synth_image_fun_v1 as synth_image_fun\n\nimport run_projector\nimport projector\nimport training.dataset\nimport training.misc\n\n# Data Science Utils\nsys.path.append(os.path.join(*[os.pardir]*3, 'data-science-learning'))\n\nfrom ds_utils import generative_utils", "_____no_output_____" ], [ "res_dir = Path.home() / 'Documents/generated_data/stylegan'", "_____no_output_____" ] ], [ [ "# Load Network", "_____no_output_____" ] ], [ [ "MODELS_DIR = Path.home() / 'Documents/models/stylegan2'\nMODEL_NAME = 'original_ffhq'\nSNAPSHOT_NAME = 'stylegan2-ffhq-config-f'\n\nGs, Gs_kwargs, noise_vars = load_network(str(MODELS_DIR / MODEL_NAME / SNAPSHOT_NAME) + '.pkl')\n\nZ_SIZE = Gs.input_shape[1]\nIMG_SIZE = Gs.output_shape[2:]\nIMG_SIZE", "_____no_output_____" ], [ "img = gen_image_fun(Gs, np.random.randn(1, Z_SIZE), Gs_kwargs, noise_vars)\nplt.imshow(img)", "_____no_output_____" ] ], [ [ "# Explore Directions", "_____no_output_____" ] ], [ [ "def plot_direction_grid(dlatent, direction, coeffs):\n fig, ax = plt.subplots(1, len(coeffs), figsize=(15, 10), dpi=100)\n \n for i, coeff in enumerate(coeffs):\n new_latent = (dlatent.copy() + coeff*direction)\n ax[i].imshow(synth_image_fun(Gs, new_latent, Gs_kwargs, randomize_noise=False))\n ax[i].set_title(f'Coeff: {coeff:0.1f}')\n ax[i].axis('off')\n plt.show()", "_____no_output_____" ], [ "# load learned direction\ndirection = np.load('/tf/media/datasets/stylegan/learned_directions.npy')", "_____no_output_____" ], [ "nb_latents = 5\n\n# generate dlatents from mapping network\ndlatents = Gs.components.mapping.run(np.random.rand(nb_latents, Z_SIZE), None, truncation_psi=1.)\n\nfor i in range(nb_latents):\n plot_direction_grid(dlatents[i:i+1], direction, np.linspace(-2, 2, 5))", "_____no_output_____" ] ], [ [ "## Interactive", "_____no_output_____" ] ], [ [ "# Setup plot image\ndpi = 100\nfig, ax = plt.subplots(dpi=dpi, figsize=(7, 7))\nfig.subplots_adjust(left=0, right=1, bottom=0, top=1, hspace=0, wspace=0)\nplt.axis('off')\nim = ax.imshow(gen_image_fun(Gs, np.random.randn(1, Z_SIZE),Gs_kwargs, noise_vars, truncation_psi=1))\n\n#prevent any output for this cell\nplt.close()", "_____no_output_____" ], [ "# fetch attributes names\ndirections_dir = MODELS_DIR / MODEL_NAME / 'directions' / 'set01'\nattributes = [e.stem for e in directions_dir.glob('*.npy')]\n\n# get names or projected images\ndata_dir = res_dir / 'projection' / MODEL_NAME / SNAPSHOT_NAME / '20200215_192547'\nentries = [p.name for p in data_dir.glob(\"*\") if p.is_dir()]\nentries.remove('tfrecords')\n\n# set target latent to play with\ndlatents = Gs.components.mapping.run(np.random.rand(1, Z_SIZE), None, truncation_psi=0.5)\ntarget_latent = dlatents[0:1]\n#target_latent = np.array([np.load(\"/out_4/image_latents2000.npy\")])", "_____no_output_____" ], [ "%matplotlib inline\n\n@interact\ndef i_direction(attribute=attributes, \n entry=entries,\n coeff=(-10., 10.)):\n direction = np.load(directions_dir / f'{attribute}.npy')\n target_latent = np.array([np.load(data_dir / entry / \"image_latents1000.npy\")])\n \n new_latent_vector = target_latent.copy() + coeff*direction\n im.set_data(synth_image_fun(Gs, new_latent_vector, Gs_kwargs, True))\n ax.set_title('Coeff: %0.1f' % coeff)\n display(fig)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ] ]
4a0b273692235b77416ad463c92a14eab345c36b
87,686
ipynb
Jupyter Notebook
zhang2011/.ipynb_checkpoints/Single_Neuron_Analysis-checkpoint.ipynb
nikparth/mathtools-bootcamp2019
53b0de327b1aeb9333f047d6c2bbc3418b462e03
[ "MIT" ]
null
null
null
zhang2011/.ipynb_checkpoints/Single_Neuron_Analysis-checkpoint.ipynb
nikparth/mathtools-bootcamp2019
53b0de327b1aeb9333f047d6c2bbc3418b462e03
[ "MIT" ]
null
null
null
zhang2011/.ipynb_checkpoints/Single_Neuron_Analysis-checkpoint.ipynb
nikparth/mathtools-bootcamp2019
53b0de327b1aeb9333f047d6c2bbc3418b462e03
[ "MIT" ]
2
2020-08-08T19:43:10.000Z
2022-03-24T02:29:25.000Z
200.196347
27,896
0.899266
[ [ [ "import numpy as np\n# to load mat files (from matlab) we need to import a special function\nfrom scipy.io import loadmat\nimport matplotlib.pyplot as plt\n\n#we will also need to import operating system tools through the os package- this will allow us to interact with the filesystem\nimport os", "_____no_output_____" ], [ "#Define the paths to the relevant data\nraster_directory = './raster_data/'\nobject_label_file = './object_labels.npy'\nloc_label_file = './loc_labels.npy'\n ", "_____no_output_____" ], [ "#Let's load data from a single neuron, and the two label files\n\nraster_array = np.load(raster_directory + 'raster1.npy')\nobject_labels = np.load(object_label_file)\nloc_labels = np.load(loc_label_file)\n\nprint(raster_array.shape, object_labels.shape, loc_labels.shape)\n\ndef get_neuron_dat(raster_dir, neuron_ind):\n raster_arr = np.load(raster_dir + 'raster'+str(neuron_ind) + '.npy')", "(420, 1000) (420,) (420,)\n" ], [ "\nprint(raster_array[0:10, 0:10], object_labels[0:10], loc_labels[0:10])", "[[0 1 0 0 0 0 0 0 0 0]\n [0 0 0 0 0 0 0 0 0 0]\n [0 0 0 0 0 0 0 0 0 0]\n [0 0 0 0 0 0 0 0 0 0]\n [0 0 0 0 0 0 0 0 0 0]\n [0 0 0 0 0 0 0 0 0 0]\n [0 0 0 0 0 0 0 0 0 0]\n [0 0 0 0 0 0 0 0 0 0]\n [0 0 0 0 0 0 0 0 0 0]\n [0 0 0 0 0 0 0 0 0 0]] ['car' 'car' 'car' 'car' 'car' 'car' 'car' 'car' 'car' 'car'] ['lower' 'lower' 'lower' 'lower' 'lower' 'lower' 'lower' 'lower' 'lower'\n 'lower']\n" ] ], [ [ "The object labels and location labels are quite long and visualizing the first 10 labels does not tell us what all the unique objects and locations are. To do so we can use a numpy function called np.unique(). What are the unique objects and labels? ", "_____no_output_____" ] ], [ [ "print(np.unique(object_labels), np.unique(loc_labels))", "['car' 'couch' 'face' 'flower' 'guitar' 'hand' 'kiwi'] ['lower' 'middle' 'upper']\n" ] ], [ [ "There are 60 trials of each object each 1000ms long. These trials correspond to IT neural responses toobject presented at 3 different locations in the visual scene (each 20 trials). There are 7 objects for a total of 420 trials. Let's visualize all these trials. ", "_____no_output_____" ] ], [ [ "#Plotting a raster\n#Stimulus turns on at 500ms\nplt.figure(figsize=(10,10))\nplt.imshow(raster_array, cmap='gray_r', aspect='auto')\nplt.ylabel('Trial')\nplt.xlabel('Time (ms)')\nplt.title('Raster for IT Neuron 1')\n#Show when the stimulus comes on\nplt.axvline(x=500, color = 'b')\nplt.show()\n\n#Let's put this into a function\ndef plot_raster(raster_array, title=None):\n plt.figure(figsize=(10,10))\n plt.imshow(raster_array, cmap='gray_r', aspect='auto')\n plt.ylabel('Trial')\n plt.xlabel('Time (ms)')\n plt.title(title)\n #Show when the stimulus comes on\n plt.axvline(x=500, color = 'b')\n plt.show()\n", "_____no_output_____" ] ], [ [ "A common problem in dataset analysis is to compute basic information about your data (like how many trials of each category exist..). For this data calculate how many times each object appears and how many times each location is presented for each object. For example, for the \"car\" calculate how many cars there are and how many times there is 'car' and 'lower', 'car' and 'upper' etc.", "_____no_output_____" ] ], [ [ "unique_objects = np.unique(object_labels)\nunique_locations = np.unique(loc_labels)\n\n\n#Here we show 3 different ways to do the exact same thing\nprint('Method 3 implementation .... ')\nfor obj in unique_objects:\n for loc in unique_locations:\n #Method 1\n n_times = sum(object_labels[i] == obj and loc_labels[i] == loc for i in range(len(object_labels)))\n print(\"Number of times\", obj, \" and \", loc, \": \", n_times) \n\nprint('Method 2 implementation...')\nfor obj in unique_objects:\n for loc in unique_locations:\n #Method 2\n n_times = 0\n for i in range(len(object_labels)):\n if object_labels[i] == obj and loc_labels[i] == loc:\n n_times += 1\n print(\"Number of times\", obj, \" and \", loc, \": \", n_times) \n\nprint('Method 3 implementation ...')\nfor obj in unique_objects:\n for loc in unique_locations:\n #Method 3\n n_times = sum(loc_labels[object_labels == obj] == loc)\n print(\"Number of times\", obj, \" and \", loc, \": \", n_times) ", "Method 3 implementation .... \nNumber of times car and lower : 20\nNumber of times car and middle : 20\nNumber of times car and upper : 20\nNumber of times couch and lower : 20\nNumber of times couch and middle : 20\nNumber of times couch and upper : 20\nNumber of times face and lower : 20\nNumber of times face and middle : 20\nNumber of times face and upper : 20\nNumber of times flower and lower : 20\nNumber of times flower and middle : 20\nNumber of times flower and upper : 20\nNumber of times guitar and lower : 20\nNumber of times guitar and middle : 20\nNumber of times guitar and upper : 20\nNumber of times hand and lower : 20\nNumber of times hand and middle : 20\nNumber of times hand and upper : 20\nNumber of times kiwi and lower : 20\nNumber of times kiwi and middle : 20\nNumber of times kiwi and upper : 20\nMethod 2 implementation...\nNumber of times car and lower : 20\nNumber of times car and middle : 20\nNumber of times car and upper : 20\nNumber of times couch and lower : 20\nNumber of times couch and middle : 20\nNumber of times couch and upper : 20\nNumber of times face and lower : 20\nNumber of times face and middle : 20\nNumber of times face and upper : 20\nNumber of times flower and lower : 20\nNumber of times flower and middle : 20\nNumber of times flower and upper : 20\nNumber of times guitar and lower : 20\nNumber of times guitar and middle : 20\nNumber of times guitar and upper : 20\nNumber of times hand and lower : 20\nNumber of times hand and middle : 20\nNumber of times hand and upper : 20\nNumber of times kiwi and lower : 20\nNumber of times kiwi and middle : 20\nNumber of times kiwi and upper : 20\nMethod 3 implementation ...\nNumber of times car and lower : 20\nNumber of times car and middle : 20\nNumber of times car and upper : 20\nNumber of times couch and lower : 20\nNumber of times couch and middle : 20\nNumber of times couch and upper : 20\nNumber of times face and lower : 20\nNumber of times face and middle : 20\nNumber of times face and upper : 20\nNumber of times flower and lower : 20\nNumber of times flower and middle : 20\nNumber of times flower and upper : 20\nNumber of times guitar and lower : 20\nNumber of times guitar and middle : 20\nNumber of times guitar and upper : 20\nNumber of times hand and lower : 20\nNumber of times hand and middle : 20\nNumber of times hand and upper : 20\nNumber of times kiwi and lower : 20\nNumber of times kiwi and middle : 20\nNumber of times kiwi and upper : 20\n" ], [ "#Now plot the raster for just the trials with the car\n\nindices_car = np.where(object_labels == 'car')\nraster_car = raster_array[indices_car]\n\nplot_raster(raster_car, 'Raster for Neuron 1 for Car Objects')", "_____no_output_____" ] ], [ [ "Now we would like to compute the summed spikes for each trial of a \"car\" object being presentation. This will give us 60 spike counts corresponding to each of the trials. After this we want to compute the mean and standard deviation of this array of summed spike counts. ", "_____no_output_____" ] ], [ [ "#Mean firing rate for each trial \nsum_spikes = raster_car[:,500:1000].sum(axis=1)\nmean_spikes = sum_spikes.mean()\nstd_spikes = sum_spikes.std()\nprint(sum_spikes, mean_spikes, std_spikes)", "[15 1 10 6 7 9 3 13 7 11 9 7 5 2 5 8 2 15 8 5 17 6 17 7\n 6 18 2 24 9 27 21 18 6 5 15 7 8 6 19 17 4 10 11 8 3 11 12 5\n 4 3 5 2 2 11 6 4 12 5 4 3] 8.8 5.841803374529707\n" ] ], [ [ "Now we are going to plot a tuning curve. What this means, is for each object (or location) we would like to calculate the mean number of spikes fired for that object. We then want to bar plot this for the 7 objects (and then the 3 locations). We will write a function to do this that takes in a label list and the data array and calculates a tuning curve for those labels. ", "_____no_output_____" ] ], [ [ "def calc_tuning_curve(data,labels):\n tuning_curve_means = []\n tuning_curve_std = []\n for label in np.unique(labels):\n label_arr = data[labels == label]\n sum_spike = label_arr.sum(axis=1)\n tuning_curve_means.append(sum_spike.mean())\n tuning_curve_std.append(sum_spike.std())\n \n return [tuning_curve_means, tuning_curve_std]\n\ntuning_curve_object = calc_tuning_curve(raster_array[:,500:], object_labels)\ntuning_curve_loc = calc_tuning_curve(raster_array[:,500:], loc_labels)\nprint(tuning_curve_object, tuning_curve_loc)", "[[8.8, 6.383333333333334, 3.4833333333333334, 4.933333333333334, 4.733333333333333, 6.3, 4.183333333333334], [5.841803374529707, 3.6290111906995026, 2.0855987682730883, 2.6004273153122783, 2.6449112566503166, 3.2624121954978853, 2.610821496940932]] [[5.242857142857143, 6.15, 5.242857142857143], [3.177760731286438, 4.524417878894162, 3.5413303161613245]]\n" ], [ "def plot_tuning_curve(tuning_curve, labels, title = None):\n y = tuning_curve[0]\n x = list(range(len(y)))\n error = tuning_curve[1]\n plt.figure()\n plt.errorbar(x,y, error)\n plt.title(title)\n plt.xticks(np.arange(len(y)), labels)\n plt.ylabel('Mean number of spikes fired to category')\n plt.xlabel('Category')\n plt.show()\n \nplot_tuning_curve(tuning_curve_object, unique_objects, title = 'Object Tuning')\nplot_tuning_curve(tuning_curve_loc, unique_locations, title = 'Location Tuning')", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ] ]
4a0b2a268f308a3173790a8a899fb9074b98f7c4
306,597
ipynb
Jupyter Notebook
Loan_Prediction_ML_LND.ipynb
Novia-2018/Bank_loan_Approval_Prediction-PS__Analytics-vidhya
742e7c150d978ed087c7580d46a332a3b5aa4a83
[ "MIT" ]
1
2020-06-02T04:40:52.000Z
2020-06-02T04:40:52.000Z
Loan_Prediction_ML_LND.ipynb
Novia-2018/Bank_loan_Approval_Prediction-PS__Analytics-vidhya
742e7c150d978ed087c7580d46a332a3b5aa4a83
[ "MIT" ]
null
null
null
Loan_Prediction_ML_LND.ipynb
Novia-2018/Bank_loan_Approval_Prediction-PS__Analytics-vidhya
742e7c150d978ed087c7580d46a332a3b5aa4a83
[ "MIT" ]
null
null
null
80.59858
51,994
0.754065
[ [ [ "# Importing the libraries", "_____no_output_____" ] ], [ [ "import pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport seaborn as sns", "_____no_output_____" ] ], [ [ "# Importing the datasets", "_____no_output_____" ] ], [ [ "dataset = pd.read_csv(\"train_ctrUa4K.csv\")\ndataset2 = pd.read_csv(\"test_lAUu6dG.csv\")\ndataset = dataset.drop(['Loan_ID'], axis = 1)\ndataset2 = dataset2.drop(['Loan_ID'], axis = 1)", "_____no_output_____" ], [ "dataset.shape", "_____no_output_____" ], [ "dataset2.shape", "_____no_output_____" ] ], [ [ "# Analysing the Training dataset", "_____no_output_____" ] ], [ [ "dataset.head()", "_____no_output_____" ], [ "dataset.dtypes", "_____no_output_____" ], [ "dataset.count() ", "_____no_output_____" ], [ "dataset.isna().sum() ", "_____no_output_____" ], [ "dataset[\"Gender\"].isnull().sum()", "_____no_output_____" ], [ "dataset.info()", "<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 614 entries, 0 to 613\nData columns (total 12 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 Gender 601 non-null object \n 1 Married 611 non-null object \n 2 Dependents 599 non-null object \n 3 Education 614 non-null object \n 4 Self_Employed 582 non-null object \n 5 ApplicantIncome 614 non-null int64 \n 6 CoapplicantIncome 614 non-null float64\n 7 LoanAmount 592 non-null float64\n 8 Loan_Amount_Term 600 non-null float64\n 9 Credit_History 564 non-null float64\n 10 Property_Area 614 non-null object \n 11 Loan_Status 614 non-null object \ndtypes: float64(4), int64(1), object(7)\nmemory usage: 57.7+ KB\n" ], [ "dataset[\"Gender\"].value_counts() ", "_____no_output_____" ], [ "dataset[\"Education\"].value_counts() ", "_____no_output_____" ], [ "dataset[\"Self_Employed\"].value_counts() ", "_____no_output_____" ], [ "dataset[\"Property_Area\"].value_counts() ", "_____no_output_____" ], [ "dataset[\"Loan_Status\"].value_counts() ", "_____no_output_____" ] ], [ [ "# Visualising the datasets", "_____no_output_____" ] ], [ [ "categorical_columns = ['Gender', 'Married',\n 'Dependents', 'Education', 'Self_Employed', 'Property_Area','Credit_History','Loan_Amount_Term']\nfig,axes = plt.subplots(4,2,figsize=(12,15))\nfor idx,cat_col in enumerate(categorical_columns):\n row,col = idx//2,idx%2\n sns.countplot(x=cat_col,data=dataset,hue='Loan_Status',ax=axes[row,col])", "_____no_output_____" ], [ "plt.scatter(dataset['ApplicantIncome'],dataset['CoapplicantIncome'])", "_____no_output_____" ], [ "import seaborn as sns \nsns.violinplot(dataset['ApplicantIncome'], dataset['Gender']) #Variable Plot\nsns.despine()", "_____no_output_____" ], [ "fig = plt.figure()\nax = fig.add_axes([0,0,1,1])\nax.bar(dataset['Loan_Status'],dataset['CoapplicantIncome'],color = \"yellow\")\nplt.show()", "_____no_output_____" ], [ "sns.heatmap(dataset.corr(), annot=True)", "_____no_output_____" ], [ "fig, ax = plt.subplots()\nax.hist(dataset[\"Loan_Status\"],color = \"purple\")\nax.set_title('loan approvl counts')\nax.set_xlabel('Loan status')\nax.set_ylabel('Frequency')", "_____no_output_____" ] ], [ [ "# Taking Care of Missing Values", "_____no_output_____" ] ], [ [ "dataset[\"Gender\"].fillna(\"Male\", inplace = True) \ndataset[\"Married\"].fillna(\"No\", inplace = True) \ndataset[\"Education\"].fillna(\"Graduate\", inplace = True) \ndataset[\"Self_Employed\"].fillna(\"No\", inplace = True) \ndataset[\"Property_Area\"].fillna(\"Urban\", inplace = True) ", "_____no_output_____" ], [ "dataset.isnull().sum()", "_____no_output_____" ], [ "dataset2[\"Gender\"].fillna(\"Male\", inplace = True) \ndataset2[\"Married\"].fillna(\"No\", inplace = True) \ndataset2[\"Education\"].fillna(\"Graduate\", inplace = True) \ndataset2[\"Self_Employed\"].fillna(\"No\", inplace = True) \ndataset2[\"Property_Area\"].fillna(\"Urban\", inplace = True) ", "_____no_output_____" ] ], [ [ "# Encodiing the categorical variable", "_____no_output_____" ] ], [ [ "train_df_encoded = pd.get_dummies(dataset,drop_first=True)\ntrain_df_encoded.head()", "_____no_output_____" ], [ "train_df_encoded.shape", "_____no_output_____" ], [ "test_df_encoded = pd.get_dummies(dataset2,drop_first=True)\ntest_df_encoded.head()", "_____no_output_____" ], [ "test_df_encoded.shape", "_____no_output_____" ] ], [ [ "# Splitting the dependent and independewnt variable", "_____no_output_____" ] ], [ [ "X = train_df_encoded.drop(columns='Loan_Status_Y').values\ny = train_df_encoded['Loan_Status_Y'].values", "_____no_output_____" ], [ "X.shape", "_____no_output_____" ], [ "X_test_run = test_df_encoded.values\n", "_____no_output_____" ], [ "from sklearn.preprocessing import StandardScaler\nsc = StandardScaler()\nX[:,0:4] = sc.fit_transform(X[:,0:4])", "_____no_output_____" ], [ "X_test_run[:,0:4] = sc.fit_transform(X_test_run[:,0:4])", "_____no_output_____" ] ], [ [ "# Splitting in to train and test", "_____no_output_____" ] ], [ [ "from sklearn.model_selection import train_test_split\nX_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.2,stratify =y,random_state =42)", "_____no_output_____" ], [ "print(X_train)", "[[-0.35213572 -0.55448733 -1.12742973 ... 0. 0.\n 1. ]\n [-0.34214238 -0.55448733 -0.58951245 ... 0. 1.\n 0. ]\n [-0.33804675 0.0303551 0.04195565 ... 0. 0.\n 0. ]\n ...\n [-0.42667621 0.21606822 -0.28547225 ... 0. 1.\n 0. ]\n [-0.47828117 0.23282687 -0.11006445 ... 0. 1.\n 0. ]\n [-0.48827451 -0.38177071 -0.19192142 ... 0. 1.\n 0. ]]\n" ] ], [ [ "# Taking Care of numrical missing values", "_____no_output_____" ] ], [ [ "from sklearn.impute import SimpleImputer\nimp = SimpleImputer(strategy='mean')\nimp_train = imp.fit(X_train)\nX_train = imp_train.transform(X_train)\nX_test_imp = imp_train.transform(X_test)", "_____no_output_____" ], [ "X_test_run[0]", "_____no_output_____" ], [ "X_test_run= imp_train.transform(X_test_run)", "_____no_output_____" ] ], [ [ "# Testing different Clasification Models", "_____no_output_____" ], [ "## Logistic Regression", "_____no_output_____" ] ], [ [ "from sklearn.linear_model import LogisticRegression\nlog_classifier = LogisticRegression()\nlog_classifier.fit(X_train, y_train)", "_____no_output_____" ], [ "y_pred = log_classifier.predict(X_test_imp)\nprint(np.concatenate((y_pred.reshape(len(y_pred),1), y_test.reshape(len(y_test),1)),1))", "[[0 0]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 0]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [0 0]\n [0 0]\n [1 1]\n [0 0]\n [0 0]\n [1 1]\n [0 0]\n [1 1]\n [0 0]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [0 0]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [0 1]\n [1 1]\n [1 0]\n [1 1]\n [1 0]\n [1 1]\n [1 0]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 0]\n [1 1]\n [1 1]\n [0 0]\n [1 1]\n [0 0]\n [1 1]\n [1 0]\n [1 0]\n [0 0]\n [1 1]\n [1 1]\n [1 1]\n [0 0]\n [1 1]\n [1 0]\n [1 1]\n [1 0]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [0 0]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [0 0]\n [0 0]\n [1 1]\n [1 0]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 0]\n [1 1]\n [0 0]\n [0 0]\n [1 1]\n [1 1]\n [1 0]\n [0 0]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [0 0]\n [1 1]\n [1 0]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 0]\n [1 1]\n [1 0]\n [1 0]\n [1 1]\n [1 1]\n [0 0]\n [0 0]\n [1 1]\n [0 0]]\n" ], [ "from sklearn.metrics import confusion_matrix, accuracy_score\ncm = confusion_matrix(y_test, y_pred)\nprint(cm)\naccuracy_score(y_test, y_pred)", "[[22 16]\n [ 1 84]]\n" ], [ "from sklearn.metrics import f1_score\nf1_score(y_test, y_pred, average=None)", "_____no_output_____" ], [ "ax= plt.subplot()\nsns.heatmap(cm, annot=True, ax = ax, cmap='rainbow'); #annot=True to annotate cells\n\n# labels, title and ticks\nax.set_xlabel('Predicted labels');ax.set_ylabel('True labels'); \nax.set_title('Confusion Matrix'); \nax.xaxis.set_ticklabels(['Yes', 'No']); ax.yaxis.set_ticklabels(['Yes', 'No']);", "_____no_output_____" ] ], [ [ "## Knearest", "_____no_output_____" ] ], [ [ "from sklearn.neighbors import KNeighborsClassifier\nclassifier = KNeighborsClassifier(n_neighbors = 5, metric = 'minkowski', p = 2)\nclassifier.fit(X_train, y_train)", "_____no_output_____" ], [ "y_pred = classifier.predict(X_test_imp)\nprint(np.concatenate((y_pred.reshape(len(y_pred),1), y_test.reshape(len(y_test),1)),1))", "[[0 0]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [0 0]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [0 0]\n [1 0]\n [0 1]\n [0 0]\n [1 0]\n [1 1]\n [1 0]\n [1 1]\n [0 0]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 0]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [0 1]\n [1 1]\n [1 0]\n [1 1]\n [1 0]\n [1 1]\n [1 0]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 0]\n [1 1]\n [1 1]\n [1 0]\n [1 1]\n [0 0]\n [1 1]\n [1 0]\n [1 0]\n [0 0]\n [1 1]\n [1 1]\n [1 1]\n [0 0]\n [1 1]\n [1 0]\n [1 1]\n [1 0]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [0 0]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [0 0]\n [1 0]\n [1 1]\n [1 0]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 0]\n [1 1]\n [0 0]\n [0 0]\n [1 1]\n [1 1]\n [1 0]\n [0 0]\n [1 1]\n [1 1]\n [0 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [0 0]\n [1 1]\n [1 0]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 0]\n [1 1]\n [0 0]\n [1 0]\n [1 1]\n [1 1]\n [0 0]\n [0 0]\n [1 1]\n [1 0]]\n" ], [ "from sklearn.metrics import confusion_matrix, accuracy_score\ncm = confusion_matrix(y_test, y_pred)\nprint(cm)\naccuracy_score(y_test, y_pred)", "[[17 21]\n [ 3 82]]\n" ], [ "from sklearn.metrics import f1_score\nf1_score(y_test, y_pred, average=None)", "_____no_output_____" ], [ "ax= plt.subplot()\nsns.heatmap(cm, annot=True, ax = ax, cmap='flag'); #annot=True to annotate cells\n\n# labels, title and ticks\nax.set_xlabel('Predicted labels');ax.set_ylabel('True labels'); \nax.set_title('Confusion Matrix'); \nax.xaxis.set_ticklabels(['Yes', 'No']); ax.yaxis.set_ticklabels(['Yes', 'No']);", "_____no_output_____" ] ], [ [ "## SVM", "_____no_output_____" ] ], [ [ "from sklearn.svm import SVC\nclassifier = SVC(kernel = 'linear', random_state = 0)\nclassifier.fit(X_train, y_train)", "_____no_output_____" ], [ "y_pred = classifier.predict(X_test_imp)\nprint(np.concatenate((y_pred.reshape(len(y_pred),1), y_test.reshape(len(y_test),1)),1))", "[[0 0]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 0]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [0 0]\n [0 0]\n [1 1]\n [0 0]\n [0 0]\n [1 1]\n [0 0]\n [1 1]\n [1 0]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [0 0]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [0 1]\n [1 1]\n [1 0]\n [1 1]\n [1 0]\n [1 1]\n [1 0]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 0]\n [1 1]\n [1 1]\n [0 0]\n [1 1]\n [0 0]\n [1 1]\n [1 0]\n [1 0]\n [0 0]\n [1 1]\n [1 1]\n [1 1]\n [0 0]\n [1 1]\n [1 0]\n [1 1]\n [1 0]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [0 0]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [0 0]\n [0 0]\n [1 1]\n [1 0]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 0]\n [1 1]\n [0 0]\n [0 0]\n [1 1]\n [1 1]\n [1 0]\n [0 0]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [0 0]\n [1 1]\n [1 0]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 0]\n [1 1]\n [1 0]\n [1 0]\n [1 1]\n [1 1]\n [0 0]\n [0 0]\n [1 1]\n [0 0]]\n" ], [ "from sklearn.metrics import confusion_matrix, accuracy_score\ncm = confusion_matrix(y_test, y_pred)\nprint(cm)\naccuracy_score(y_test, y_pred)", "[[21 17]\n [ 1 84]]\n" ], [ "from sklearn.metrics import f1_score\nf1_score(y_test, y_pred, average=None)", "_____no_output_____" ], [ "ax= plt.subplot()\nsns.heatmap(cm, annot=True, ax = ax, cmap='gist_rainbow'); #annot=True to annotate cells\n\n# labels, title and ticks\nax.set_xlabel('Predicted labels');ax.set_ylabel('True labels'); \nax.set_title('Confusion Matrix'); \nax.xaxis.set_ticklabels(['Yes', 'No']); ax.yaxis.set_ticklabels(['Yes', 'No']);", "_____no_output_____" ] ], [ [ "## Kernal SVM", "_____no_output_____" ] ], [ [ "from sklearn.svm import SVC\nclassifier = SVC(kernel = 'rbf', random_state = 0)\nclassifier.fit(X_train, y_train)", "_____no_output_____" ], [ "y_pred = classifier.predict(X_test_imp)\nprint(np.concatenate((y_pred.reshape(len(y_pred),1), y_test.reshape(len(y_test),1)),1))", "[[0 0]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 0]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [0 0]\n [0 0]\n [1 1]\n [0 0]\n [0 0]\n [1 1]\n [0 0]\n [1 1]\n [1 0]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [0 0]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [0 1]\n [1 1]\n [1 0]\n [1 1]\n [1 0]\n [1 1]\n [1 0]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 0]\n [1 1]\n [1 1]\n [0 0]\n [1 1]\n [0 0]\n [1 1]\n [1 0]\n [1 0]\n [0 0]\n [1 1]\n [1 1]\n [1 1]\n [0 0]\n [1 1]\n [1 0]\n [1 1]\n [1 0]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [0 0]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [0 0]\n [0 0]\n [1 1]\n [1 0]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 0]\n [1 1]\n [0 0]\n [0 0]\n [1 1]\n [1 1]\n [1 0]\n [0 0]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 0]\n [1 1]\n [1 0]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 0]\n [1 1]\n [1 0]\n [1 0]\n [1 1]\n [1 1]\n [0 0]\n [0 0]\n [1 1]\n [0 0]]\n" ], [ "from sklearn.metrics import confusion_matrix, accuracy_score\ncm = confusion_matrix(y_test, y_pred)\nprint(cm)\naccuracy_score(y_test, y_pred)", "[[20 18]\n [ 1 84]]\n" ], [ "from sklearn.metrics import f1_score\nf1_score(y_test, y_pred, average=None)", "_____no_output_____" ], [ "ax= plt.subplot()\nsns.heatmap(cm, annot=True, ax = ax,); #annot=True to annotate cells\n\n# labels, title and ticks\nax.set_xlabel('Predicted labels');ax.set_ylabel('True labels'); \nax.set_title('Confusion Matrix'); \nax.xaxis.set_ticklabels(['Yes', 'No']); ax.yaxis.set_ticklabels(['Yes', 'No']);", "_____no_output_____" ] ], [ [ "## Naive Bayes", "_____no_output_____" ] ], [ [ "from sklearn.naive_bayes import GaussianNB\nclassifier = GaussianNB()\nclassifier.fit(X_train, y_train)", "_____no_output_____" ], [ "y_pred = classifier.predict(X_test_imp)\nprint(np.concatenate((y_pred.reshape(len(y_pred),1), y_test.reshape(len(y_test),1)),1))", "[[0 0]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 0]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [0 0]\n [0 0]\n [1 1]\n [0 0]\n [0 0]\n [1 1]\n [0 0]\n [1 1]\n [0 0]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [0 1]\n [0 0]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [0 1]\n [1 1]\n [1 0]\n [1 1]\n [1 0]\n [1 1]\n [1 0]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 0]\n [1 1]\n [1 1]\n [0 0]\n [1 1]\n [0 0]\n [1 1]\n [1 0]\n [1 0]\n [0 0]\n [1 1]\n [1 1]\n [1 1]\n [0 0]\n [1 1]\n [1 0]\n [1 1]\n [1 0]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [0 0]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [0 0]\n [0 0]\n [1 1]\n [1 0]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 0]\n [1 1]\n [0 0]\n [0 0]\n [1 1]\n [1 1]\n [1 0]\n [0 0]\n [0 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [0 0]\n [1 1]\n [1 0]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 0]\n [1 1]\n [1 0]\n [1 0]\n [1 1]\n [1 1]\n [0 0]\n [0 0]\n [1 1]\n [0 0]]\n" ], [ "from sklearn.metrics import confusion_matrix, accuracy_score\ncm = confusion_matrix(y_test, y_pred)\nprint(cm)\naccuracy_score(y_test, y_pred)", "[[22 16]\n [ 3 82]]\n" ], [ "from sklearn.metrics import f1_score\nf1_score(y_test, y_pred, average=None)", "_____no_output_____" ], [ "ax= plt.subplot()\nsns.heatmap(cm, annot=True, ax = ax, cmap='rainbow'); #annot=True to annotate cells\n\n# labels, title and ticks\nax.set_xlabel('Predicted labels');ax.set_ylabel('True labels'); \nax.set_title('Confusion Matrix'); \nax.xaxis.set_ticklabels(['Yes', 'No']); ax.yaxis.set_ticklabels(['Yes', 'No']);", "_____no_output_____" ] ], [ [ "## Decision Tree", "_____no_output_____" ] ], [ [ "from sklearn.tree import DecisionTreeClassifier\nclassifier = DecisionTreeClassifier(criterion = 'entropy', random_state = 0)\nclassifier.fit(X_train, y_train)", "_____no_output_____" ], [ "y_pred = classifier.predict(X_test_imp)\nprint(np.concatenate((y_pred.reshape(len(y_pred),1), y_test.reshape(len(y_test),1)),1))", "[[0 0]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [0 0]\n [0 1]\n [1 1]\n [0 1]\n [1 1]\n [1 1]\n [0 1]\n [1 1]\n [1 1]\n [0 0]\n [0 0]\n [1 1]\n [0 0]\n [0 0]\n [1 1]\n [0 0]\n [1 1]\n [0 0]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [0 1]\n [0 0]\n [1 1]\n [1 1]\n [0 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [0 1]\n [0 1]\n [0 0]\n [1 1]\n [1 0]\n [1 1]\n [1 0]\n [0 1]\n [1 1]\n [0 1]\n [1 1]\n [1 0]\n [1 1]\n [1 1]\n [0 0]\n [1 1]\n [0 0]\n [1 1]\n [1 0]\n [1 0]\n [0 0]\n [1 1]\n [1 1]\n [1 1]\n [0 0]\n [1 1]\n [0 0]\n [1 1]\n [1 0]\n [1 1]\n [0 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [0 0]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [0 1]\n [1 1]\n [0 0]\n [0 0]\n [1 1]\n [0 0]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 0]\n [0 1]\n [0 0]\n [0 0]\n [1 1]\n [0 1]\n [1 0]\n [0 0]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [0 1]\n [1 1]\n [1 1]\n [1 1]\n [1 0]\n [0 1]\n [1 0]\n [1 1]\n [1 1]\n [0 1]\n [1 1]\n [0 0]\n [0 1]\n [1 0]\n [0 0]\n [1 1]\n [1 1]\n [0 0]\n [0 0]\n [0 1]\n [0 0]]\n" ], [ "from sklearn.metrics import confusion_matrix, accuracy_score\ncm = confusion_matrix(y_test, y_pred)\nprint(cm)\naccuracy_score(y_test, y_pred)", "[[27 11]\n [18 67]]\n" ], [ "from sklearn.metrics import f1_score\nf1_score(y_test, y_pred, average=None)", "_____no_output_____" ], [ "ax= plt.subplot()\nsns.heatmap(cm, annot=True, ax = ax, cmap='flag'); #annot=True to annotate cells\n\n# labels, title and ticks\nax.set_xlabel('Predicted labels');ax.set_ylabel('True labels'); \nax.set_title('Confusion Matrix'); \nax.xaxis.set_ticklabels(['Yes', 'No']); ax.yaxis.set_ticklabels(['Yes', 'No']);", "_____no_output_____" ] ], [ [ "## Random Forest", "_____no_output_____" ] ], [ [ "from sklearn.ensemble import RandomForestClassifier\nclassifier = RandomForestClassifier(n_estimators = 10, criterion = 'entropy', random_state = 0)\nclassifier.fit(X_train, y_train)", "_____no_output_____" ], [ "y_pred = classifier.predict(X_test_imp)\nprint(np.concatenate((y_pred.reshape(len(y_pred),1), y_test.reshape(len(y_test),1)),1))", "[[0 0]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 0]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [0 0]\n [0 0]\n [0 1]\n [0 0]\n [0 0]\n [1 1]\n [0 0]\n [1 1]\n [1 0]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [0 0]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [0 1]\n [1 1]\n [0 1]\n [1 1]\n [1 0]\n [1 1]\n [1 0]\n [1 1]\n [1 0]\n [1 1]\n [0 1]\n [1 1]\n [1 1]\n [1 0]\n [1 1]\n [1 1]\n [1 0]\n [1 1]\n [0 0]\n [1 1]\n [1 0]\n [1 0]\n [1 0]\n [1 1]\n [1 1]\n [1 1]\n [0 0]\n [1 1]\n [0 0]\n [1 1]\n [1 0]\n [0 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [0 0]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [0 0]\n [0 0]\n [1 1]\n [1 0]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 0]\n [1 1]\n [0 0]\n [0 0]\n [1 1]\n [0 1]\n [1 0]\n [0 0]\n [0 1]\n [1 1]\n [0 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [0 1]\n [0 0]\n [1 1]\n [1 0]\n [1 1]\n [1 1]\n [1 1]\n [1 1]\n [1 0]\n [1 1]\n [0 0]\n [1 0]\n [1 1]\n [1 1]\n [0 0]\n [0 0]\n [1 1]\n [0 0]]\n" ], [ "from sklearn.metrics import confusion_matrix, accuracy_score\ncm = confusion_matrix(y_test, y_pred)\nprint(cm)\naccuracy_score(y_test, y_pred)", "[[21 17]\n [ 9 76]]\n" ], [ "from sklearn.metrics import f1_score\nf1_score(y_test, y_pred, average=None)", "_____no_output_____" ], [ "ax= plt.subplot()\nsns.heatmap(cm, annot=True, ax = ax, cmap='gist_rainbow'); #annot=True to annotate cells\n\n# labels, title and ticks\nax.set_xlabel('Predicted labels');ax.set_ylabel('True labels'); \nax.set_title('Confusion Matrix'); \nax.xaxis.set_ticklabels(['Yes', 'No']); ax.yaxis.set_ticklabels(['Yes', 'No']);", "_____no_output_____" ] ], [ [ "# Predicting The Test dataset", "_____no_output_____" ], [ "## Selecting Logistic Regression Based on accuracy_score and f1Score", "_____no_output_____" ] ], [ [ "log_classifier.predict(X_test_run)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ] ]
4a0b2a58da2c817912e7c8d84489572a1292f27b
8,021
ipynb
Jupyter Notebook
doc/auto_examples/manage/plot_failed_fits.ipynb
varman-m/eeg_notebooks_doc
12230719637c8087b020e8d5feeb20520a4da74d
[ "Apache-2.0" ]
1
2020-11-05T21:30:07.000Z
2020-11-05T21:30:07.000Z
doc/auto_examples/manage/plot_failed_fits.ipynb
varman-m/eeg_notebooks_doc
12230719637c8087b020e8d5feeb20520a4da74d
[ "Apache-2.0" ]
null
null
null
doc/auto_examples/manage/plot_failed_fits.ipynb
varman-m/eeg_notebooks_doc
12230719637c8087b020e8d5feeb20520a4da74d
[ "Apache-2.0" ]
null
null
null
41.133333
922
0.59818
[ [ [ "%matplotlib inline", "_____no_output_____" ] ], [ [ "\nFailed Model Fits\n=================\n\nExample of model fit failures and how to debug them.\n", "_____no_output_____" ] ], [ [ "# Import the FOOOFGroup object\nfrom fooof import FOOOFGroup\n\n# Import simulation code to create test power spectra\nfrom fooof.sim.gen import gen_group_power_spectra\n\n# Import FitError, which we will use to help debug model fit errors\nfrom fooof.core.errors import FitError", "_____no_output_____" ] ], [ [ "Model Fit Failures\n------------------\n\nThe power spectrum model is not guaranteed to fit - sometimes the fit procedure can fail.\n\nModel fit failures are rare, and they typically only happen on spectra that are\nparticular noisy, and/or are some kind of outlier for which the fitting procedure\nfails to find a good model solution.\n\nIn general, model fit failures should lead to a clean exit, meaning that\na failed model fit does not lead to a code error. The failed fit will be encoded in\nthe results as a null model, and the code can continue onwards.\n\nIn this example, we will look through what it looks like when model fits fail.\n\n\n", "_____no_output_____" ] ], [ [ "# Simulate some example power spectra to use for the example\nfreqs, powers = gen_group_power_spectra(25, [1, 50], [1, 1], [10, 0.25, 3],\n nlvs=0.1, freq_res=0.25)", "_____no_output_____" ], [ "# Initialize a FOOOFGroup object, with some desired settings\nfg = FOOOFGroup(min_peak_height=0.1, max_n_peaks=6)", "_____no_output_____" ], [ "# Fit power spectra\nfg.fit(freqs, powers)", "_____no_output_____" ] ], [ [ "If there are failed fits, these are stored as null models.\n\nLet's check if there were any null models, from model failures, in the models\nthat we have fit so far. To do so, the :class:`~fooof.FOOOFGroup` object has some\nattributes that provide information on any null model fits.\n\nThese attributes are:\n\n- ``n_null_`` : the number of model results that are null\n- ``null_inds_`` : the indices of any null model results\n\n\n", "_____no_output_____" ] ], [ [ "# Check for failed model fits\nprint('Number of Null models : \\t', fg.n_null_)\nprint('Indices of Null models : \\t', fg.null_inds_)", "_____no_output_____" ] ], [ [ "Inducing Model Fit Failures\n~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nSo far, we have no model failures (as is typical).\n\nFor this example, to induce some model fits, we will use a trick to change the number of\niterations the model uses to fit parameters (`_maxfev`), making it much more likely to fail.\n\nNote that in normal usage, you would likely never want to change the value of `_maxfev`,\nand this here is a 'hack' of the code in order to induce reproducible failure modes\nin simulated data.\n\n\n", "_____no_output_____" ] ], [ [ "# Hack the object to induce model failures\nfg._maxfev = 50", "_____no_output_____" ], [ "# Try fitting again\nfg.fit(freqs, powers)", "_____no_output_____" ] ], [ [ "As we can see, there are now some model fit failures! Note that, as above, it will\nbe printed out if there is as model fit failure when in verbose mode.\n\n\n", "_____no_output_____" ] ], [ [ "# Check how many model fit failures we have failed model fits\nprint('Number of Null models : \\t', fg.n_null_)\nprint('Indices of Null models : \\t', fg.null_inds_)", "_____no_output_____" ] ], [ [ "Debug Mode\n----------\n\nThere are multiple possible reasons why a model fit failure can occur, or at least\nmultiple possible steps in the algorithm at which the fit failure can occur.\n\nIf you have a small number of fit failures, you can likely just exclude them.\n\nHowever, if you have multiple fit failures, and/or you want to investigate why the\nmodel is failing, you can use the debug mode to get a bit more information about\nwhere the model is failing.\n\nThe debug mode will stop the FOOOF object catching and continuing any model\nfit errors, allowing you to see where the error is happening, and get more\ninformation about where it is failing.\n\nNote that here we will run the fitting in a try / except to catch the error and\nprint it out, without the error actually being raised (for website purposes).\nIf you just want to see the error, you can run the fit call without the try/except.\n\n\n", "_____no_output_____" ] ], [ [ "# Set FOOOFGroup into debug mode\nfg.set_debug_mode(True)", "_____no_output_____" ], [ "# Refit in debug mode, in which failed fits will raise an error\ntry:\n fg.fit(freqs, powers)\nexcept FitError as fooof_error:\n print(fooof_error)", "_____no_output_____" ] ], [ [ "Debugging Model Fit Errors\n~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nThis debug mode should indicate in which step the model is failing, which might indicate\nwhat aspects of the data to look into, and/or which settings to try and tweak.\n\nAlso, all known model fit failures should be caught by the object, and not raise an\nerror (when not in debug mode). If you are finding examples in which the model is failing\nto fit, and raising an error (outside of debug mode), then this might be an unanticipated\nissue with the model fit.\n\nIf you are unsure about why or how the model is failing to fit, consider\nopening an `issue <https://github.com/fooof-tools/fooof/issues>`_ on the project\nrepository, and we will try to look into what seems to be happening.\n\n\n", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ] ]
4a0b31adfb03062d2d3cf94851f2f302e54d9348
2,792
ipynb
Jupyter Notebook
appendices/section-2.ipynb
Davide95/practical_spectral_clustering
498797f26d3a6ef8d02e2d9b1734c18f5ab7e7ef
[ "CC0-1.0" ]
1
2020-07-19T15:50:24.000Z
2020-07-19T15:50:24.000Z
appendices/section-2.ipynb
Davide95/practical_spectral_clustering
498797f26d3a6ef8d02e2d9b1734c18f5ab7e7ef
[ "CC0-1.0" ]
null
null
null
appendices/section-2.ipynb
Davide95/practical_spectral_clustering
498797f26d3a6ef8d02e2d9b1734c18f5ab7e7ef
[ "CC0-1.0" ]
null
null
null
23.863248
118
0.569126
[ [ [ "# Appendix A - Graphs with 1 connected component", "_____no_output_____" ] ], [ [ "import networkx as nx\nimport numpy as np\nimport matplotlib.pyplot as plt", "_____no_output_____" ] ], [ [ "## Generate an example figure", "_____no_output_____" ] ], [ [ "graph = nx.connected_watts_strogatz_graph(20, 3, 0.5)\nnx.draw(graph)\nplt.savefig('../figures/one-component.eps')\nplt.show()", "_____no_output_____" ] ], [ [ "## Plot eigenvalues", "_____no_output_____" ] ], [ [ "n_graphs = 100\nn_nodes = 20\n\neigenvalues_graphs = []\nfor _ in range(n_graphs): # Compute the eigenvalues for each graph\n graph = nx.connected_watts_strogatz_graph(n_nodes, 3, 0.5)\n eigenvalues = nx.laplacian_spectrum(graph)\n eigenvalues_graphs.append(eigenvalues)\neigenvalues_graphs = np.array(eigenvalues_graphs)\n \nplt.boxplot(eigenvalues_graphs, showfliers=False)\nplt.xticks(np.arange(1, n_nodes+1))\nplt.xlabel('Eigenvalues')\nplt.ylabel('Intensity')\nplt.savefig('../figures/eigen-one-component.eps')\nplt.show()", "_____no_output_____" ] ], [ [ "## Empirically demonstrate the proof presented in the pdf", "_____no_output_____" ] ], [ [ "first_eigenvalue = eigenvalues_graphs[:, 0]\nprint('Is the first eigenvalue always zero?', np.allclose(first_eigenvalue, np.zeros_like(first_eigenvalue)))\n\nresults = []\nfor idx in range(1, eigenvalues_graphs.shape[1]):\n eigenvalue = eigenvalues_graphs[:, idx]\n results.append(np.allclose(eigenvalue, np.zeros_like(eigenvalue)))\nprint('Are the other eigenvalues always nonzero?', not np.any(results))", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
4a0b394b2b65eec59e7f3c9200006303632d26b3
218,151
ipynb
Jupyter Notebook
basketball_pycaret.ipynb
microprediction/nba
03c3e03702d2aace014bb81e93b5fb5194752b44
[ "MIT" ]
null
null
null
basketball_pycaret.ipynb
microprediction/nba
03c3e03702d2aace014bb81e93b5fb5194752b44
[ "MIT" ]
null
null
null
basketball_pycaret.ipynb
microprediction/nba
03c3e03702d2aace014bb81e93b5fb5194752b44
[ "MIT" ]
null
null
null
87.051476
64,854
0.70106
[ [ [ "<a href=\"https://colab.research.google.com/github/microprediction/nba/blob/main/basketball_pycaret.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ] ], [ [ "!pip uninstall numpy -y", "Found existing installation: numpy 1.19.5\nUninstalling numpy-1.19.5:\n Successfully uninstalled numpy-1.19.5\n" ], [ "!pip install pycaret", "_____no_output_____" ] ], [ [ "# Basketball Team Statistics\nHere we have a bit of fun looking at what helps teams win games. In the first stage the idea is to look at one game at a time, and the importance of a few (contemporaneous) key statistics in determining the final score. ", "_____no_output_____" ] ], [ [ "URL = 'https://raw.githubusercontent.com/microprediction/nba/main/data/games.csv'\nimport pandas as pd\ngames = pd.read_csv(URL)\ngames.columns", "_____no_output_____" ] ], [ [ "Fix the darn field goal percentages, as this currently commingle three point shots and two point shots (why do they do this???)", "_____no_output_____" ] ], [ [ "games['FGA'] = games['FGA'] - games['FG3A']\ngames['FGM'] = games['FGM'] - games['FG3M']\ngames['FG_PCT'] = games['FGM']/games['FGA']\ngames[['FG3_PCT','FG_PCT','FT_PCT']].mean()", "_____no_output_____" ], [ "games[['FGA','FG3A','FTA']].mean()", "_____no_output_____" ] ], [ [ "For interpretability we'll scale field goal percentages by typical points on offer in a game. ", "_____no_output_____" ] ], [ [ "rescaling = zip(['FG_PCT','FG3_PCT','FT_PCT'],[66.45*2,16.67*3,25.53])", "_____no_output_____" ], [ "for col,multi in rescaling:\n games[col.replace('_PCT','_SCALED')]=games[col]*multi\n", "_____no_output_____" ], [ "need = ['FG_SCALED', 'FG3_SCALED','FT_SCALED', 'OREB', 'DREB', 'AST', 'STL','BLK', 'TOV', 'PF', 'PTS']\ngames = games[need]\nlen(games)", "_____no_output_____" ], [ "test_data = games[-10000:]\ntrain_data = games[:-10000]", "_____no_output_____" ], [ "from pycaret.regression import *", "_____no_output_____" ], [ "experiment = setup(data = train_data, target = 'PTS', session_id=99)", "_____no_output_____" ], [ "compare_models()", "_____no_output_____" ] ], [ [ "Pick one and re-fit it", "_____no_output_____" ] ], [ [ "gbm_model = create_model('lightgbm')", "_____no_output_____" ], [ "!pip install shap", "_____no_output_____" ], [ "interpret_model(gbm_model)", "_____no_output_____" ] ], [ [ "... or a simple model", "_____no_output_____" ] ], [ [ "linear_model = create_model('lr')\ntuned_linear_model = tune_model(linear_model)\ntuned_linear_model", "_____no_output_____" ], [ "plot_model(linear_model)", "_____no_output_____" ], [ "final_tuned_linear_model = finalize_model(tuned_linear_model)\nfinal_tuned_linear_model", "_____no_output_____" ], [ "unseen = predict_model(final_tuned_linear_model,data=test_data)\n(unseen['Label']-unseen['PTS']).std()", "_____no_output_____" ], [ "print(list(zip(final_tuned_linear_model.coef_,need[:-1]+['const'])))", "[(0.80788237, 'FG_SCALED'), (0.4192402, 'FG3_SCALED'), (1.0501705, 'FT_SCALED'), (0.93114495, 'OREB'), (0.40593585, 'DREB'), (0.69978327, 'AST'), (0.50869644, 'STL'), (-0.028841702, 'BLK'), (-0.48521018, 'TOV'), (0.47805905, 'PF')]\n" ] ], [ [ "So now, how do you explain the extremely low coefficient assigned to the three-point shooting percentage? Is it because failed three-point shots are rebounded more often? The difference between offensive and defensive rebounding is also interesting. And blocks don't seem to matter at all! Fouling is good. \n", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ] ]
4a0b47cbb5b6dda47dbf67f798bc20ee1414e368
3,164
ipynb
Jupyter Notebook
Lab 07.ipynb
carlsondorman/IA241
377a0e4b085905e1c35fc3c15caa33ba3af2cdfb
[ "MIT" ]
null
null
null
Lab 07.ipynb
carlsondorman/IA241
377a0e4b085905e1c35fc3c15caa33ba3af2cdfb
[ "MIT" ]
null
null
null
Lab 07.ipynb
carlsondorman/IA241
377a0e4b085905e1c35fc3c15caa33ba3af2cdfb
[ "MIT" ]
null
null
null
20.815789
126
0.475032
[ [ [ "# Q1\n\nCompany: Federal Reserve Bank of Richmond\nDiscription: Researching and working with economists to create data for speeches and brief content for the president.\n[Website](https://www.indeed.com/viewjob?jk=03031870201e12fd&tk=1d5umojbfacoo802&from=serp&vjs=3)", "_____no_output_____" ], [ "# Q2 and Q3", "_____no_output_____" ] ], [ [ "import xlwt\nfrom collections import Counter", "_____no_output_____" ], [ "mybook = xlwt.Workbook()\nsheet = mybook.add_sheet('word_count')\ni = 0\nsheet.write(i,0,'word')\nsheet.write(i,1,'count')", "_____no_output_____" ], [ "with open ('job.txt','r') as job:\n count_result = Counter(job.read().split())\n for result in count_result.most_common(20):\n i = i+1\n sheet.write(i,0,result[0])\n sheet.write(i,1,result[1])\nmybook.save(\"job_word_count.xls\")", "_____no_output_____" ] ], [ [ "# Q4", "_____no_output_____" ] ], [ [ "import xlrd\nmybook = xlrd.open_workbook(\"job_word_count.xls\")\nsheet = mybook.sheet_by_name(\"word_count\")\nfor i in range(sheet.nrows):\n row = sheet.row_values(i)\n print(row)", "['word', 'count']\n['and', 33.0]\n['the', 22.0]\n['of', 19.0]\n['to', 18.0]\n['a', 11.0]\n['or', 10.0]\n['with', 9.0]\n['for', 8.0]\n['in', 8.0]\n['is', 7.0]\n['are', 7.0]\n['as', 6.0]\n['economic', 6.0]\n['data', 5.0]\n['research', 5.0]\n['special', 5.0]\n['be', 5.0]\n['support', 4.0]\n['work', 4.0]\n['this', 4.0]\n" ] ], [ [ "# Q5", "_____no_output_____" ], [ "<img src = \"wordcloud.png\">", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ] ]
4a0b4ad15a88bab00f122faf055fda31dd7b01ac
36,790
ipynb
Jupyter Notebook
lab8/Part2_experiment_with_my_dataset.ipynb
wwwbxy123/Computer-Vision-Explore
2395171d1d6a2505bb28bfe91eada3dade6607e1
[ "MIT" ]
null
null
null
lab8/Part2_experiment_with_my_dataset.ipynb
wwwbxy123/Computer-Vision-Explore
2395171d1d6a2505bb28bfe91eada3dade6607e1
[ "MIT" ]
null
null
null
lab8/Part2_experiment_with_my_dataset.ipynb
wwwbxy123/Computer-Vision-Explore
2395171d1d6a2505bb28bfe91eada3dade6607e1
[ "MIT" ]
null
null
null
33.783287
477
0.503615
[ [ [ "# Part 2 Experiment with my dataset", "_____no_output_____" ], [ "\n## Prepare the model and load my dataset", "_____no_output_____" ] ], [ [ "#install torch in google colab\n# http://pytorch.org/\nfrom os.path import exists\nfrom wheel.pep425tags import get_abbr_impl, get_impl_ver, get_abi_tag\nplatform = '{}{}-{}'.format(get_abbr_impl(), get_impl_ver(), get_abi_tag())\ncuda_output = !ldconfig -p|grep cudart.so|sed -e 's/.*\\.\\([0-9]*\\)\\.\\([0-9]*\\)$/cu\\1\\2/'\naccelerator = cuda_output[0] if exists('/dev/nvidia0') else 'cpu'\n\n!pip install -q http://download.pytorch.org/whl/{accelerator}/torch-0.4.1-{platform}-linux_x86_64.whl torchvision", "_____no_output_____" ], [ "import torch\nprint(torch.__version__)\nprint(torch.cuda.is_available())", "0.4.1\nFalse\n" ], [ "#initialization\nimport torch.nn as nn\nimport torchvision\nimport torchvision.transforms as transforms\nimport torchvision.datasets as datasets\n\n# Device configuration\ndevice = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n\n# Hyper parameters\nnum_epochs = 5\nnum_classes = 10\nbatch_size = 100\nlearning_rate = 0.001\n\n# MNIST dataset\nmnist_trainset = datasets.MNIST(root='./data', train=True, download=True, transform=None)\nlen(mnist_trainset)\nprint(mnist_trainset)\n\ntrain_dataset = torchvision.datasets.MNIST(root='./data/',\n train=True, \n transform=transforms.ToTensor(),\n download=True)\n\ntest_dataset = torchvision.datasets.MNIST(root='./data/',\n train=False, \n transform=transforms.ToTensor())", "Dataset MNIST\n Number of datapoints: 60000\n Split: train\n Root Location: ./data\n Transforms (if any): None\n Target Transforms (if any): None\n" ], [ "# Mounte files to gdrive\nfrom google.colab import drive\ndrive.mount('/content/gdrive')", "Go to this URL in a browser: https://accounts.google.com/o/oauth2/auth?client_id=947318989803-6bn6qk8qdgf4n4g3pfee6491hc0brc4i.apps.googleusercontent.com&redirect_uri=urn%3Aietf%3Awg%3Aoauth%3A2.0%3Aoob&scope=email%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdocs.test%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdrive%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdrive.photos.readonly%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fpeopleapi.readonly&response_type=code\n\nEnter your authorization code:\n··········\nMounted at /content/gdrive\n" ], [ "# loade test myDateSet\n\nimport pandas as pd\nfrom matplotlib.pyplot import imshow\nimport numpy as np\nfrom PIL import Image\nfrom torch.utils.data.dataset import Dataset\nfrom torchvision import transforms\n\nclass SimpleDataset(Dataset):\n def __init__(self, data_path, csv_name, transform = None ):\n \"\"\"\n Args:\n data_path (string): path to the folder where images and csv files are located\n csv_name (string): name of the csv lablel file\n transform: pytorch transforms for transforms and tensor conversion\n \"\"\"\n # Set path\n self.data_path = data_path\n # Transforms\n self.transform = transform\n # Read the csv file\n self.data_info = pd.read_csv(data_path + csv_name, header=None)\n # First column contains the image paths\n self.image_arr = np.asarray(self.data_info.iloc[:, 0])\n # Second column is the labels\n self.label_arr = np.asarray(self.data_info.iloc[:, 1])\n # Calculate len\n self.data_len = len(self.data_info.index)\n \n\n def __getitem__(self, index):\n # Get image name from the pandas df\n single_image_name = self.image_arr[index]\n # Open image\n img_as_img = Image.open(self.data_path + single_image_name)\n if self.transform is not None:\n img_as_img = self.transform(img_as_img)\n\n # Get label(class) of the image based on the cropped pandas column\n single_image_label = self.label_arr[index]\n #convert to tensor to be consistent with MNIST dataset\n single_image_label = torch.LongTensor( [ single_image_label ] )[0]\n return (img_as_img, single_image_label)\n\n def __len__(self):\n return self.data_len\n\n#mydata = SimpleDataset( \"gdrive/My Drive/myDataSet/\", \"label.csv\")\nmydataT = SimpleDataset( \"gdrive/My Drive/myDataSet/\", \"label.csv\", transform=transforms.ToTensor())\n\n#testc = mydataT[1]\n#testT = testc[0]\n#imgt = Image.fromarray((testT.numpy()[0] * 255).astype(\"uint8\"))\n#display(imgt)", "_____no_output_____" ], [ "# loade My test set to make my test loader\nmy_test_loader = torch.utils.data.DataLoader(dataset=mydataT,\n batch_size=batch_size, \n shuffle=False)", "_____no_output_____" ], [ "# Convolutional neural network (two convolutional layers)\nclass ConvNet(nn.Module):\n def __init__(self, num_classes=10):\n super(ConvNet, self).__init__()\n self.layer1 = nn.Sequential(\n nn.Conv2d(1, 16, kernel_size=5, stride=1, padding=2),\n nn.BatchNorm2d(16),\n nn.ReLU(),\n nn.MaxPool2d(kernel_size=2, stride=2))\n self.layer2 = nn.Sequential(\n nn.Conv2d(16, 32, kernel_size=5, stride=1, padding=2),\n nn.BatchNorm2d(32),\n nn.ReLU(),\n nn.MaxPool2d(kernel_size=2, stride=2))\n self.fc = nn.Linear(7*7*32, num_classes)\n \n def forward(self, x):\n out = self.layer1(x)\n out = self.layer2(out)\n out = out.reshape(out.size(0), -1)\n out = self.fc(out)\n return out\n\nmodel = ConvNet(num_classes).to(device)", "_____no_output_____" ], [ "# Loss and optimizer\ncriterion = nn.CrossEntropyLoss()\noptimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)", "_____no_output_____" ] ], [ [ "## 1.1 experiment on 100 size trainning set", "_____no_output_____" ] ], [ [ "# Hyper parameters\nnum_epochs = 5\nnum_classes = 10\nbatch_size = 50\nlearning_rate = 0.001\n\n# Data loader\n\n# loade trainning MNIST set \ntrain_loader = torch.utils.data.DataLoader(dataset=train_dataset,\n batch_size=batch_size, \n shuffle=True)\n\n# Train the model\ntotal_step = len(train_loader)\nfor epoch in range(num_epochs):\n for i, (images, labels) in enumerate(train_loader):\n if i > 1:\n break\n images = images.to(device)\n labels = labels.to(device)\n \n # Forward pass\n outputs = model(images)\n loss = criterion(outputs, labels)\n \n # Backward and optimize\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n \n if (i+1) % 1 == 0:\n print ('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}' \n .format(epoch+1, num_epochs, i+1, total_step, loss.item()))", "Epoch [1/5], Step [1/1200], Loss: 0.0746\nEpoch [1/5], Step [2/1200], Loss: 0.1215\nEpoch [2/5], Step [1/1200], Loss: 0.0581\nEpoch [2/5], Step [2/1200], Loss: 0.0184\nEpoch [3/5], Step [1/1200], Loss: 0.1512\nEpoch [3/5], Step [2/1200], Loss: 0.2745\nEpoch [4/5], Step [1/1200], Loss: 0.0497\nEpoch [4/5], Step [2/1200], Loss: 0.0699\nEpoch [5/5], Step [1/1200], Loss: 0.3059\nEpoch [5/5], Step [2/1200], Loss: 0.0232\n" ], [ "# Test the model on myDataSet\nmodel.eval() # eval mode (batchnorm uses moving mean/variance instead of mini-batch mean/variance)\nwith torch.no_grad():\n correct = 0\n total = 0\n for images, labels in my_test_loader:\n images = images.to(device)\n labels = labels.to(device)\n outputs = model(images)\n _, predicted = torch.max(outputs.data, 1)\n total += labels.size(0)\n correct += (predicted == labels).sum().item()\n\nprint('Test Accuracy of 100 images trained model on the my dataset: {} %'.format(100 * correct / total))", "Test Accuracy of 100 images trained model on the my dataset: 66.66666666666667 %\n" ] ], [ [ "## 1.2 experiment on 250 size trainning set", "_____no_output_____" ] ], [ [ "\nnum_epochs = 5\nnum_classes = 10\nbatch_size = 50\nlearning_rate = 0.001\n\n# Data loader\n\n# loade trainning MNIST set \ntrain_loader = torch.utils.data.DataLoader(dataset=train_dataset,\n batch_size=batch_size, \n shuffle=True)\n\n# Train the model\ntotal_step = len(train_loader)\nfor epoch in range(num_epochs):\n for i, (images, labels) in enumerate(train_loader):\n if i > 4:\n break\n images = images.to(device)\n labels = labels.to(device)\n \n # Forward pass\n outputs = model(images)\n loss = criterion(outputs, labels)\n \n # Backward and optimize\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n \n if (i+1) % 1 == 0:\n print ('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}' \n .format(epoch+1, num_epochs, i+1, total_step, loss.item()))", "Epoch [1/5], Step [1/1200], Loss: 0.0706\nEpoch [1/5], Step [2/1200], Loss: 0.1659\nEpoch [1/5], Step [3/1200], Loss: 0.0552\nEpoch [1/5], Step [4/1200], Loss: 0.2078\nEpoch [1/5], Step [5/1200], Loss: 0.0696\nEpoch [2/5], Step [1/1200], Loss: 0.0255\nEpoch [2/5], Step [2/1200], Loss: 0.0501\nEpoch [2/5], Step [3/1200], Loss: 0.1045\nEpoch [2/5], Step [4/1200], Loss: 0.0424\nEpoch [2/5], Step [5/1200], Loss: 0.0489\nEpoch [3/5], Step [1/1200], Loss: 0.1225\nEpoch [3/5], Step [2/1200], Loss: 0.0569\nEpoch [3/5], Step [3/1200], Loss: 0.1091\nEpoch [3/5], Step [4/1200], Loss: 0.1069\nEpoch [3/5], Step [5/1200], Loss: 0.0500\nEpoch [4/5], Step [1/1200], Loss: 0.0635\nEpoch [4/5], Step [2/1200], Loss: 0.1186\nEpoch [4/5], Step [3/1200], Loss: 0.0227\nEpoch [4/5], Step [4/1200], Loss: 0.2184\nEpoch [4/5], Step [5/1200], Loss: 0.1934\nEpoch [5/5], Step [1/1200], Loss: 0.0969\nEpoch [5/5], Step [2/1200], Loss: 0.1210\nEpoch [5/5], Step [3/1200], Loss: 0.0166\nEpoch [5/5], Step [4/1200], Loss: 0.0332\nEpoch [5/5], Step [5/1200], Loss: 0.1518\n" ], [ "# Test the model on MNIST dataset\nmodel.eval() # eval mode (batchnorm uses moving mean/variance instead of mini-batch mean/variance)\nwith torch.no_grad():\n correct = 0\n total = 0\n for images, labels in my_test_loader:\n images = images.to(device)\n labels = labels.to(device)\n outputs = model(images)\n _, predicted = torch.max(outputs.data, 1)\n total += labels.size(0)\n correct += (predicted == labels).sum().item()\n\nprint('Test Accuracy of 250 images trained model on the my dataset: {} %'.format(100 * correct / total))", "Test Accuracy of 250 images trained model on the my dataset: 68.33333333333333 %\n" ] ], [ [ "## 1.3 experiment on 500 size trainning set", "_____no_output_____" ] ], [ [ "# Hyper parameters\nnum_epochs = 5\nnum_classes = 10\nbatch_size = 50\nlearning_rate = 0.001\n\n# Data loader\n\n# loade trainning MNIST set \ntrain_loader = torch.utils.data.DataLoader(dataset=train_dataset,\n batch_size=batch_size, \n shuffle=True)\n\n# Train the model\ntotal_step = len(train_loader)\nfor epoch in range(num_epochs):\n for i, (images, labels) in enumerate(train_loader):\n if i > 9:\n break\n images = images.to(device)\n labels = labels.to(device)\n \n # Forward pass\n outputs = model(images)\n loss = criterion(outputs, labels)\n \n # Backward and optimize\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n \n if (i+1) % 1 == 0:\n print ('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}' \n .format(epoch+1, num_epochs, i+1, total_step, loss.item()))", "Epoch [1/5], Step [1/1200], Loss: 0.0568\nEpoch [1/5], Step [2/1200], Loss: 0.1204\nEpoch [1/5], Step [3/1200], Loss: 0.0863\nEpoch [1/5], Step [4/1200], Loss: 0.0193\nEpoch [1/5], Step [5/1200], Loss: 0.0751\nEpoch [1/5], Step [6/1200], Loss: 0.0257\nEpoch [1/5], Step [7/1200], Loss: 0.1827\nEpoch [1/5], Step [8/1200], Loss: 0.1464\nEpoch [1/5], Step [9/1200], Loss: 0.0615\nEpoch [1/5], Step [10/1200], Loss: 0.0615\nEpoch [2/5], Step [1/1200], Loss: 0.0896\nEpoch [2/5], Step [2/1200], Loss: 0.0287\nEpoch [2/5], Step [3/1200], Loss: 0.1033\nEpoch [2/5], Step [4/1200], Loss: 0.0350\nEpoch [2/5], Step [5/1200], Loss: 0.1826\nEpoch [2/5], Step [6/1200], Loss: 0.0317\nEpoch [2/5], Step [7/1200], Loss: 0.0823\nEpoch [2/5], Step [8/1200], Loss: 0.1101\nEpoch [2/5], Step [9/1200], Loss: 0.1387\nEpoch [2/5], Step [10/1200], Loss: 0.1394\nEpoch [3/5], Step [1/1200], Loss: 0.0379\nEpoch [3/5], Step [2/1200], Loss: 0.0287\nEpoch [3/5], Step [3/1200], Loss: 0.0618\nEpoch [3/5], Step [4/1200], Loss: 0.1528\nEpoch [3/5], Step [5/1200], Loss: 0.1078\nEpoch [3/5], Step [6/1200], Loss: 0.3177\nEpoch [3/5], Step [7/1200], Loss: 0.0551\nEpoch [3/5], Step [8/1200], Loss: 0.1169\nEpoch [3/5], Step [9/1200], Loss: 0.0379\nEpoch [3/5], Step [10/1200], Loss: 0.0129\nEpoch [4/5], Step [1/1200], Loss: 0.0753\nEpoch [4/5], Step [2/1200], Loss: 0.1044\nEpoch [4/5], Step [3/1200], Loss: 0.0712\nEpoch [4/5], Step [4/1200], Loss: 0.1321\nEpoch [4/5], Step [5/1200], Loss: 0.0460\nEpoch [4/5], Step [6/1200], Loss: 0.0998\nEpoch [4/5], Step [7/1200], Loss: 0.1236\nEpoch [4/5], Step [8/1200], Loss: 0.2159\nEpoch [4/5], Step [9/1200], Loss: 0.0520\nEpoch [4/5], Step [10/1200], Loss: 0.0442\nEpoch [5/5], Step [1/1200], Loss: 0.0647\nEpoch [5/5], Step [2/1200], Loss: 0.1449\nEpoch [5/5], Step [3/1200], Loss: 0.2781\nEpoch [5/5], Step [4/1200], Loss: 0.0883\nEpoch [5/5], Step [5/1200], Loss: 0.1453\nEpoch [5/5], Step [6/1200], Loss: 0.0329\nEpoch [5/5], Step [7/1200], Loss: 0.1503\nEpoch [5/5], Step [8/1200], Loss: 0.0326\nEpoch [5/5], Step [9/1200], Loss: 0.0184\nEpoch [5/5], Step [10/1200], Loss: 0.0529\n" ], [ "# Test the model on myDataSet\n\nmodel.eval() # eval mode (batchnorm uses moving mean/variance instead of mini-batch mean/variance)\nwith torch.no_grad():\n correct = 0\n total = 0\n for images, labels in my_test_loader:\n images = images.to(device)\n labels = labels.to(device)\n outputs = model(images)\n _, predicted = torch.max(outputs.data, 1)\n total += labels.size(0)\n correct += (predicted == labels).sum().item()\n\nprint('Test Accuracy of 500 images trained model on the my dataset: {} %'.format(100 * correct / total))", "Test Accuracy of 500 images trained model on the my dataset: 70.0 %\n" ] ], [ [ "## 1.4 experiment on 1000 size trainning set\n\n", "_____no_output_____" ] ], [ [ "# Hyper parameters\nnum_epochs = 5\nnum_classes = 10\nbatch_size = 50\nlearning_rate = 0.001\n\n# Data loader\n\n# loade trainning MNIST set \ntrain_loader = torch.utils.data.DataLoader(dataset=train_dataset,\n batch_size=batch_size, \n shuffle=True)\n\n# Train the model\ntotal_step = len(train_loader)\nfor epoch in range(num_epochs):\n for i, (images, labels) in enumerate(train_loader):\n if i > 19:\n break\n images = images.to(device)\n labels = labels.to(device)\n \n # Forward pass\n outputs = model(images)\n loss = criterion(outputs, labels)\n \n # Backward and optimize\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n \n if (i+1) % 1 == 0:\n print ('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}' \n .format(epoch+1, num_epochs, i+1, total_step, loss.item()))", "Epoch [1/5], Step [1/1200], Loss: 0.0120\nEpoch [1/5], Step [2/1200], Loss: 0.1557\nEpoch [1/5], Step [3/1200], Loss: 0.0498\nEpoch [1/5], Step [4/1200], Loss: 0.0168\nEpoch [1/5], Step [5/1200], Loss: 0.0265\nEpoch [1/5], Step [6/1200], Loss: 0.0753\nEpoch [1/5], Step [7/1200], Loss: 0.0644\nEpoch [1/5], Step [8/1200], Loss: 0.0198\nEpoch [1/5], Step [9/1200], Loss: 0.1191\nEpoch [1/5], Step [10/1200], Loss: 0.0466\nEpoch [1/5], Step [11/1200], Loss: 0.3127\nEpoch [1/5], Step [12/1200], Loss: 0.0728\nEpoch [1/5], Step [13/1200], Loss: 0.1182\nEpoch [1/5], Step [14/1200], Loss: 0.2562\nEpoch [1/5], Step [15/1200], Loss: 0.0844\nEpoch [1/5], Step [16/1200], Loss: 0.0859\nEpoch [1/5], Step [17/1200], Loss: 0.1902\nEpoch [1/5], Step [18/1200], Loss: 0.0768\nEpoch [1/5], Step [19/1200], Loss: 0.0727\nEpoch [1/5], Step [20/1200], Loss: 0.0614\nEpoch [2/5], Step [1/1200], Loss: 0.0515\nEpoch [2/5], Step [2/1200], Loss: 0.0375\nEpoch [2/5], Step [3/1200], Loss: 0.0705\nEpoch [2/5], Step [4/1200], Loss: 0.0562\nEpoch [2/5], Step [5/1200], Loss: 0.0729\nEpoch [2/5], Step [6/1200], Loss: 0.1545\nEpoch [2/5], Step [7/1200], Loss: 0.0767\nEpoch [2/5], Step [8/1200], Loss: 0.0307\nEpoch [2/5], Step [9/1200], Loss: 0.0711\nEpoch [2/5], Step [10/1200], Loss: 0.1464\nEpoch [2/5], Step [11/1200], Loss: 0.0440\nEpoch [2/5], Step [12/1200], Loss: 0.0433\nEpoch [2/5], Step [13/1200], Loss: 0.0755\nEpoch [2/5], Step [14/1200], Loss: 0.0639\nEpoch [2/5], Step [15/1200], Loss: 0.0332\nEpoch [2/5], Step [16/1200], Loss: 0.0135\nEpoch [2/5], Step [17/1200], Loss: 0.1410\nEpoch [2/5], Step [18/1200], Loss: 0.0319\nEpoch [2/5], Step [19/1200], Loss: 0.0082\nEpoch [2/5], Step [20/1200], Loss: 0.0108\nEpoch [3/5], Step [1/1200], Loss: 0.1283\nEpoch [3/5], Step [2/1200], Loss: 0.1578\nEpoch [3/5], Step [3/1200], Loss: 0.0229\nEpoch [3/5], Step [4/1200], Loss: 0.0231\nEpoch [3/5], Step [5/1200], Loss: 0.0510\nEpoch [3/5], Step [6/1200], Loss: 0.0162\nEpoch [3/5], Step [7/1200], Loss: 0.1096\nEpoch [3/5], Step [8/1200], Loss: 0.0789\nEpoch [3/5], Step [9/1200], Loss: 0.0525\nEpoch [3/5], Step [10/1200], Loss: 0.0163\nEpoch [3/5], Step [11/1200], Loss: 0.0128\nEpoch [3/5], Step [12/1200], Loss: 0.0892\nEpoch [3/5], Step [13/1200], Loss: 0.0739\nEpoch [3/5], Step [14/1200], Loss: 0.0578\nEpoch [3/5], Step [15/1200], Loss: 0.0601\nEpoch [3/5], Step [16/1200], Loss: 0.0671\nEpoch [3/5], Step [17/1200], Loss: 0.0828\nEpoch [3/5], Step [18/1200], Loss: 0.0077\nEpoch [3/5], Step [19/1200], Loss: 0.0269\nEpoch [3/5], Step [20/1200], Loss: 0.1492\nEpoch [4/5], Step [1/1200], Loss: 0.0319\nEpoch [4/5], Step [2/1200], Loss: 0.0223\nEpoch [4/5], Step [3/1200], Loss: 0.0588\nEpoch [4/5], Step [4/1200], Loss: 0.0755\nEpoch [4/5], Step [5/1200], Loss: 0.0371\nEpoch [4/5], Step [6/1200], Loss: 0.0809\nEpoch [4/5], Step [7/1200], Loss: 0.0213\nEpoch [4/5], Step [8/1200], Loss: 0.0880\nEpoch [4/5], Step [9/1200], Loss: 0.0954\nEpoch [4/5], Step [10/1200], Loss: 0.1407\nEpoch [4/5], Step [11/1200], Loss: 0.0300\nEpoch [4/5], Step [12/1200], Loss: 0.1095\nEpoch [4/5], Step [13/1200], Loss: 0.0202\nEpoch [4/5], Step [14/1200], Loss: 0.0151\nEpoch [4/5], Step [15/1200], Loss: 0.0352\nEpoch [4/5], Step [16/1200], Loss: 0.0646\nEpoch [4/5], Step [17/1200], Loss: 0.1348\nEpoch [4/5], Step [18/1200], Loss: 0.0856\nEpoch [4/5], Step [19/1200], Loss: 0.0057\nEpoch [4/5], Step [20/1200], Loss: 0.1028\nEpoch [5/5], Step [1/1200], Loss: 0.0106\nEpoch [5/5], Step [2/1200], Loss: 0.0162\nEpoch [5/5], Step [3/1200], Loss: 0.0203\nEpoch [5/5], Step [4/1200], Loss: 0.0509\nEpoch [5/5], Step [5/1200], Loss: 0.0216\nEpoch [5/5], Step [6/1200], Loss: 0.1055\nEpoch [5/5], Step [7/1200], Loss: 0.0246\nEpoch [5/5], Step [8/1200], Loss: 0.0530\nEpoch [5/5], Step [9/1200], Loss: 0.1653\nEpoch [5/5], Step [10/1200], Loss: 0.3039\nEpoch [5/5], Step [11/1200], Loss: 0.0216\nEpoch [5/5], Step [12/1200], Loss: 0.0419\nEpoch [5/5], Step [13/1200], Loss: 0.0314\nEpoch [5/5], Step [14/1200], Loss: 0.0686\nEpoch [5/5], Step [15/1200], Loss: 0.0600\nEpoch [5/5], Step [16/1200], Loss: 0.2127\nEpoch [5/5], Step [17/1200], Loss: 0.0256\nEpoch [5/5], Step [18/1200], Loss: 0.0451\nEpoch [5/5], Step [19/1200], Loss: 0.1293\nEpoch [5/5], Step [20/1200], Loss: 0.0513\n" ], [ "# Test the model on myDataSet\n\nmodel.eval() # eval mode (batchnorm uses moving mean/variance instead of mini-batch mean/variance)\nwith torch.no_grad():\n correct = 0\n total = 0\n for images, labels in my_test_loader:\n images = images.to(device)\n labels = labels.to(device)\n outputs = model(images)\n _, predicted = torch.max(outputs.data, 1)\n total += labels.size(0)\n correct += (predicted == labels).sum().item()\n\nprint('Test Accuracy of 50 images trained model on the my dataset: {} %'.format(100 * correct / total))", "Test Accuracy of 50 images trained model on the my dataset: 68.33333333333333 %\n" ] ], [ [ "## 1.5 experiment on 60000 size trainning set", "_____no_output_____" ] ], [ [ "# Hyper parameters\nnum_epochs = 5\nnum_classes = 10\nbatch_size = 100\nlearning_rate = 0.001\n\n# Data loader\n\n# loade trainning MNIST set \ntrain_loader = torch.utils.data.DataLoader(dataset=train_dataset,\n batch_size=batch_size, \n shuffle=True)\n# Train the model\ntotal_step = len(train_loader)\nfor epoch in range(num_epochs):\n for i, (images, labels) in enumerate(train_loader):\n images = images.to(device)\n labels = labels.to(device)\n \n # Forward pass\n outputs = model(images)\n loss = criterion(outputs, labels)\n \n # Backward and optimize\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n \n if (i+1) % 100 == 0:\n print ('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}' \n .format(epoch+1, num_epochs, i+1, total_step, loss.item()))", "Epoch [1/5], Step [100/600], Loss: 0.2975\nEpoch [1/5], Step [200/600], Loss: 0.1002\nEpoch [1/5], Step [300/600], Loss: 0.1049\nEpoch [1/5], Step [400/600], Loss: 0.0836\nEpoch [1/5], Step [500/600], Loss: 0.1222\nEpoch [1/5], Step [600/600], Loss: 0.0575\nEpoch [2/5], Step [100/600], Loss: 0.0124\nEpoch [2/5], Step [200/600], Loss: 0.0734\nEpoch [2/5], Step [300/600], Loss: 0.0132\nEpoch [2/5], Step [400/600], Loss: 0.0182\nEpoch [2/5], Step [500/600], Loss: 0.0949\nEpoch [2/5], Step [600/600], Loss: 0.1136\nEpoch [3/5], Step [100/600], Loss: 0.0144\nEpoch [3/5], Step [200/600], Loss: 0.0502\nEpoch [3/5], Step [300/600], Loss: 0.0173\nEpoch [3/5], Step [400/600], Loss: 0.0579\nEpoch [3/5], Step [500/600], Loss: 0.0267\nEpoch [3/5], Step [600/600], Loss: 0.0393\nEpoch [4/5], Step [100/600], Loss: 0.0037\nEpoch [4/5], Step [200/600], Loss: 0.0056\nEpoch [4/5], Step [300/600], Loss: 0.0556\nEpoch [4/5], Step [400/600], Loss: 0.0237\nEpoch [4/5], Step [500/600], Loss: 0.0268\nEpoch [4/5], Step [600/600], Loss: 0.0188\nEpoch [5/5], Step [100/600], Loss: 0.0127\nEpoch [5/5], Step [200/600], Loss: 0.0079\nEpoch [5/5], Step [300/600], Loss: 0.0035\nEpoch [5/5], Step [400/600], Loss: 0.0219\nEpoch [5/5], Step [500/600], Loss: 0.0375\nEpoch [5/5], Step [600/600], Loss: 0.0393\n" ], [ "# Test the model on myDataSet\n\nmodel.eval() # eval mode (batchnorm uses moving mean/variance instead of mini-batch mean/variance)\nwith torch.no_grad():\n correct = 0\n total = 0\n for images, labels in my_test_loader:\n images = images.to(device)\n labels = labels.to(device)\n outputs = model(images)\n _, predicted = torch.max(outputs.data, 1)\n total += labels.size(0)\n correct += (predicted == labels).sum().item()\n\nprint('Test Accuracy of 60000 images trained model on the my dataset: {} %'.format(100 * correct / total))", "Test Accuracy of 60000 images trained model on the my dataset: 73.33333333333333 %\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ] ]
4a0b5d261c67672963e3a3358dc1f962dc410214
12,537
ipynb
Jupyter Notebook
intro-to-pytorch/Part 8 - Transfer Learning (Solution).ipynb
subham73/deep-learning-v2-pytorch
a200ee8d644fa176fc6f2b663cac6cc0207c1b40
[ "MIT" ]
4,850
2018-09-04T19:40:22.000Z
2022-03-31T10:21:49.000Z
intro-to-pytorch/Part 8 - Transfer Learning (Solution).ipynb
subham73/deep-learning-v2-pytorch
a200ee8d644fa176fc6f2b663cac6cc0207c1b40
[ "MIT" ]
220
2018-09-15T20:30:55.000Z
2022-03-30T04:45:30.000Z
intro-to-pytorch/Part 8 - Transfer Learning (Solution).ipynb
subham73/deep-learning-v2-pytorch
a200ee8d644fa176fc6f2b663cac6cc0207c1b40
[ "MIT" ]
5,729
2018-09-04T22:07:30.000Z
2022-03-31T11:52:07.000Z
42.212121
662
0.563691
[ [ [ "# Transfer Learning\n\nIn this notebook, you'll learn how to use pre-trained networks to solved challenging problems in computer vision. Specifically, you'll use networks trained on [ImageNet](http://www.image-net.org/) [available from torchvision](http://pytorch.org/docs/0.3.0/torchvision/models.html). \n\nImageNet is a massive dataset with over 1 million labeled images in 1000 categories. It's used to train deep neural networks using an architecture called convolutional layers. I'm not going to get into the details of convolutional networks here, but if you want to learn more about them, please [watch this](https://www.youtube.com/watch?v=2-Ol7ZB0MmU).\n\nOnce trained, these models work astonishingly well as feature detectors for images they weren't trained on. Using a pre-trained network on images not in the training set is called transfer learning. Here we'll use transfer learning to train a network that can classify our cat and dog photos with near perfect accuracy.\n\nWith `torchvision.models` you can download these pre-trained networks and use them in your applications. We'll include `models` in our imports now.", "_____no_output_____" ] ], [ [ "%matplotlib inline\n%config InlineBackend.figure_format = 'retina'\n\nimport matplotlib.pyplot as plt\n\nimport torch\nfrom torch import nn\nfrom torch import optim\nimport torch.nn.functional as F\nfrom torchvision import datasets, transforms, models", "_____no_output_____" ] ], [ [ "Most of the pretrained models require the input to be 224x224 images. Also, we'll need to match the normalization used when the models were trained. Each color channel was normalized separately, the means are `[0.485, 0.456, 0.406]` and the standard deviations are `[0.229, 0.224, 0.225]`.", "_____no_output_____" ] ], [ [ "data_dir = 'Cat_Dog_data'\n\n# TODO: Define transforms for the training data and testing data\ntrain_transforms = transforms.Compose([transforms.RandomRotation(30),\n transforms.RandomResizedCrop(224),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406],\n [0.229, 0.224, 0.225])])\n\ntest_transforms = transforms.Compose([transforms.Resize(255),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406],\n [0.229, 0.224, 0.225])])\n\n# Pass transforms in here, then run the next cell to see how the transforms look\ntrain_data = datasets.ImageFolder(data_dir + '/train', transform=train_transforms)\ntest_data = datasets.ImageFolder(data_dir + '/test', transform=test_transforms)\n\ntrainloader = torch.utils.data.DataLoader(train_data, batch_size=64, shuffle=True)\ntestloader = torch.utils.data.DataLoader(test_data, batch_size=64)", "_____no_output_____" ] ], [ [ "We can load in a model such as [DenseNet](http://pytorch.org/docs/0.3.0/torchvision/models.html#id5). Let's print out the model architecture so we can see what's going on.", "_____no_output_____" ] ], [ [ "model = models.densenet121(pretrained=True)\nmodel", "_____no_output_____" ] ], [ [ "This model is built out of two main parts, the features and the classifier. The features part is a stack of convolutional layers and overall works as a feature detector that can be fed into a classifier. The classifier part is a single fully-connected layer `(classifier): Linear(in_features=1024, out_features=1000)`. This layer was trained on the ImageNet dataset, so it won't work for our specific problem. That means we need to replace the classifier, but the features will work perfectly on their own. In general, I think about pre-trained networks as amazingly good feature detectors that can be used as the input for simple feed-forward classifiers.", "_____no_output_____" ] ], [ [ "# Freeze parameters so we don't backprop through them\nfor param in model.parameters():\n param.requires_grad = False\n\nfrom collections import OrderedDict\nclassifier = nn.Sequential(OrderedDict([\n ('fc1', nn.Linear(1024, 500)),\n ('relu', nn.ReLU()),\n ('fc2', nn.Linear(500, 2)),\n ('output', nn.LogSoftmax(dim=1))\n ]))\n \nmodel.classifier = classifier", "_____no_output_____" ] ], [ [ "With our model built, we need to train the classifier. However, now we're using a **really deep** neural network. If you try to train this on a CPU like normal, it will take a long, long time. Instead, we're going to use the GPU to do the calculations. The linear algebra computations are done in parallel on the GPU leading to 100x increased training speeds. It's also possible to train on multiple GPUs, further decreasing training time.\n\nPyTorch, along with pretty much every other deep learning framework, uses [CUDA](https://developer.nvidia.com/cuda-zone) to efficiently compute the forward and backwards passes on the GPU. In PyTorch, you move your model parameters and other tensors to the GPU memory using `model.to('cuda')`. You can move them back from the GPU with `model.to('cpu')` which you'll commonly do when you need to operate on the network output outside of PyTorch. As a demonstration of the increased speed, I'll compare how long it takes to perform a forward and backward pass with and without a GPU.", "_____no_output_____" ] ], [ [ "import time", "_____no_output_____" ], [ "for device in ['cpu', 'cuda']:\n\n criterion = nn.NLLLoss()\n # Only train the classifier parameters, feature parameters are frozen\n optimizer = optim.Adam(model.classifier.parameters(), lr=0.001)\n\n model.to(device)\n\n for ii, (inputs, labels) in enumerate(trainloader):\n\n # Move input and label tensors to the GPU\n inputs, labels = inputs.to(device), labels.to(device)\n\n start = time.time()\n\n outputs = model.forward(inputs)\n loss = criterion(outputs, labels)\n\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n if ii==3:\n break\n \n print(f\"Device = {device}; Time per batch: {(time.time() - start)/3:.3f} seconds\")", "_____no_output_____" ] ], [ [ "You can write device agnostic code which will automatically use CUDA if it's enabled like so:\n```python\n# at beginning of the script\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\n...\n\n# then whenever you get a new Tensor or Module\n# this won't copy if they are already on the desired device\ninput = data.to(device)\nmodel = MyModule(...).to(device)\n```\n\nFrom here, I'll let you finish training the model. The process is the same as before except now your model is much more powerful. You should get better than 95% accuracy easily.\n\n>**Exercise:** Train a pretrained models to classify the cat and dog images. Continue with the DenseNet model, or try ResNet, it's also a good model to try out first. Make sure you are only training the classifier and the parameters for the features part are frozen.", "_____no_output_____" ] ], [ [ "# Use GPU if it's available\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\nmodel = models.densenet121(pretrained=True)\n\n# Freeze parameters so we don't backprop through them\nfor param in model.parameters():\n param.requires_grad = False\n \nmodel.classifier = nn.Sequential(nn.Linear(1024, 256),\n nn.ReLU(),\n nn.Dropout(0.2),\n nn.Linear(256, 2),\n nn.LogSoftmax(dim=1))\n\ncriterion = nn.NLLLoss()\n\n# Only train the classifier parameters, feature parameters are frozen\noptimizer = optim.Adam(model.classifier.parameters(), lr=0.003)\n\nmodel.to(device);", "_____no_output_____" ], [ "epochs = 1\nsteps = 0\nrunning_loss = 0\nprint_every = 5\nfor epoch in range(epochs):\n for inputs, labels in trainloader:\n steps += 1\n # Move input and label tensors to the default device\n inputs, labels = inputs.to(device), labels.to(device)\n \n logps = model.forward(inputs)\n loss = criterion(logps, labels)\n \n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n running_loss += loss.item()\n \n if steps % print_every == 0:\n test_loss = 0\n accuracy = 0\n model.eval()\n with torch.no_grad():\n for inputs, labels in testloader:\n inputs, labels = inputs.to(device), labels.to(device)\n logps = model.forward(inputs)\n batch_loss = criterion(logps, labels)\n \n test_loss += batch_loss.item()\n \n # Calculate accuracy\n ps = torch.exp(logps)\n top_p, top_class = ps.topk(1, dim=1)\n equals = top_class == labels.view(*top_class.shape)\n accuracy += torch.mean(equals.type(torch.FloatTensor)).item()\n \n print(f\"Epoch {epoch+1}/{epochs}.. \"\n f\"Train loss: {running_loss/print_every:.3f}.. \"\n f\"Test loss: {test_loss/len(testloader):.3f}.. \"\n f\"Test accuracy: {accuracy/len(testloader):.3f}\")\n running_loss = 0\n model.train()", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ] ]
4a0b698caf0645bfda970ced8174163322824ec4
26,629
ipynb
Jupyter Notebook
Decision Tree.ipynb
evan0322/TechNotes
ff10f2e1dc4102d2d24e85ad1e0c96c83eab8209
[ "MIT" ]
null
null
null
Decision Tree.ipynb
evan0322/TechNotes
ff10f2e1dc4102d2d24e85ad1e0c96c83eab8209
[ "MIT" ]
null
null
null
Decision Tree.ipynb
evan0322/TechNotes
ff10f2e1dc4102d2d24e85ad1e0c96c83eab8209
[ "MIT" ]
null
null
null
63.858513
17,304
0.781892
[ [ [ "import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt", "_____no_output_____" ], [ "import seaborn as sns", "_____no_output_____" ], [ "%matplotlib inline", "_____no_output_____" ], [ "df = pd.read_csv('kyphosis.csv')", "_____no_output_____" ], [ "df.head()", "_____no_output_____" ], [ "sns.distplot(df['Age'])", "_____no_output_____" ], [ "from sklearn.model_selection import train_test_split", "_____no_output_____" ], [ "X = df.drop(['Kyphosis'], axis=1)", "_____no_output_____" ], [ "y = df['Kyphosis']", "_____no_output_____" ], [ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)", "_____no_output_____" ], [ "from sklearn.tree import DecisionTreeClassifier", "_____no_output_____" ], [ "dtree = DecisionTreeClassifier()", "_____no_output_____" ], [ "dtree.fit(X_train,y_train)", "_____no_output_____" ], [ "predictions = dtree.predict(X_test)", "_____no_output_____" ], [ "from sklearn.metrics import classification_report, confusion_matrix", "_____no_output_____" ], [ "print(confusion_matrix(y_test,predictions))", "[[15 4]\n [ 4 2]]\n" ], [ "print(classification_report(y_test,predictions))", " precision recall f1-score support\n\n absent 0.79 0.79 0.79 19\n present 0.33 0.33 0.33 6\n\n micro avg 0.68 0.68 0.68 25\n macro avg 0.56 0.56 0.56 25\nweighted avg 0.68 0.68 0.68 25\n\n" ], [ "from sklearn.ensemble import RandomForestClassifier", "_____no_output_____" ], [ "rfc = RandomForestClassifier(n_estimators=200)", "_____no_output_____" ], [ "rfc.fit(X_train,y_train)", "_____no_output_____" ], [ "rfc_pred = rfc.predict(X_test)", "_____no_output_____" ], [ "print(confusion_matrix(y_test,rfc_pred))\nprint('\\n')\nprint(classification_report(y_test,rfc_pred))", "[[19 0]\n [ 5 1]]\n\n\n precision recall f1-score support\n\n absent 0.79 1.00 0.88 19\n present 1.00 0.17 0.29 6\n\n micro avg 0.80 0.80 0.80 25\n macro avg 0.90 0.58 0.58 25\nweighted avg 0.84 0.80 0.74 25\n\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
4a0b81eb4b60ce31318c56f469655a17e6b980ea
93,033
ipynb
Jupyter Notebook
data-analysis-with-python.ipynb
vodolar/Coursera_IBM_Projects
27e13e0bc862a135a6d9652ce7dfecdce4eb4871
[ "MIT" ]
null
null
null
data-analysis-with-python.ipynb
vodolar/Coursera_IBM_Projects
27e13e0bc862a135a6d9652ce7dfecdce4eb4871
[ "MIT" ]
null
null
null
data-analysis-with-python.ipynb
vodolar/Coursera_IBM_Projects
27e13e0bc862a135a6d9652ce7dfecdce4eb4871
[ "MIT" ]
null
null
null
52.799659
27,108
0.653392
[ [ [ " <a href=\"https://www.bigdatauniversity.com\"><img src = \"https://ibm.box.com/shared/static/ugcqz6ohbvff804xp84y4kqnvvk3bq1g.png\" width = 300, align = \"center\"></a>\n\n<h1 align=center><font size = 5>Data Analysis with Python</font></h1>", "_____no_output_____" ], [ "# House Sales in King County, USA", "_____no_output_____" ], [ "This dataset contains house sale prices for King County, which includes Seattle. It includes homes sold between May 2014 and May 2015.", "_____no_output_____" ], [ "<b>id</b> : A notation for a house\n\n<b> date</b>: Date house was sold\n\n\n<b>price</b>: Price is prediction target\n\n\n<b>bedrooms</b>: Number of bedrooms\n\n\n<b>bathrooms</b>: Number of bathrooms\n\n<b>sqft_living</b>: Square footage of the home\n\n<b>sqft_lot</b>: Square footage of the lot\n\n\n<b>floors</b> :Total floors (levels) in house\n\n\n<b>waterfront</b> :House which has a view to a waterfront\n\n\n<b>view</b>: Has been viewed\n\n\n<b>condition</b> :How good the condition is overall\n\n<b>grade</b>: overall grade given to the housing unit, based on King County grading system\n\n\n<b>sqft_above</b> : Square footage of house apart from basement\n\n\n<b>sqft_basement</b>: Square footage of the basement\n\n<b>yr_built</b> : Built Year\n\n\n<b>yr_renovated</b> : Year when house was renovated\n\n<b>zipcode</b>: Zip code\n\n\n<b>lat</b>: Latitude coordinate\n\n<b>long</b>: Longitude coordinate\n\n<b>sqft_living15</b> : Living room area in 2015(implies-- some renovations) This might or might not have affected the lotsize area\n\n\n<b>sqft_lot15</b> : LotSize area in 2015(implies-- some renovations)", "_____no_output_____" ], [ "You will require the following libraries: ", "_____no_output_____" ] ], [ [ "import pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport seaborn as sns\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.preprocessing import StandardScaler,PolynomialFeatures\nfrom sklearn.linear_model import LinearRegression\n%matplotlib inline", "_____no_output_____" ] ], [ [ "# Module 1: Importing Data Sets ", "_____no_output_____" ], [ " Load the csv: ", "_____no_output_____" ] ], [ [ "file_name='https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/DA0101EN/coursera/project/kc_house_data_NaN.csv'\ndf=pd.read_csv(file_name)", "_____no_output_____" ] ], [ [ "\nWe use the method <code>head</code> to display the first 5 columns of the dataframe.", "_____no_output_____" ] ], [ [ "df.head()", "_____no_output_____" ] ], [ [ "### Question 1 \nDisplay the data types of each column using the attribute dtype, then take a screenshot and submit it, include your code in the image. ", "_____no_output_____" ] ], [ [ "df.dtypes", "_____no_output_____" ] ], [ [ "We use the method describe to obtain a statistical summary of the dataframe.", "_____no_output_____" ] ], [ [ "df.describe()", "_____no_output_____" ] ], [ [ "# Module 2: Data Wrangling", "_____no_output_____" ], [ "### Question 2 \nDrop the columns <code>\"id\"</code> and <code>\"Unnamed: 0\"</code> from axis 1 using the method <code>drop()</code>, then use the method <code>describe()</code> to obtain a statistical summary of the data. Take a screenshot and submit it, make sure the <code>inplace</code> parameter is set to <code>True</code>", "_____no_output_____" ] ], [ [ "df.drop(df[['id']], axis=1, inplace=True)\ndf.drop(df[['Unnamed: 0']], axis=1, inplace=True)\ndf.describe()", "_____no_output_____" ] ], [ [ "We can see we have missing values for the columns <code> bedrooms</code> and <code> bathrooms </code>", "_____no_output_____" ] ], [ [ "print(\"number of NaN values for the column bedrooms :\", df['bedrooms'].isnull().sum())\nprint(\"number of NaN values for the column bathrooms :\", df['bathrooms'].isnull().sum())\n", "number of NaN values for the column bedrooms : 13\nnumber of NaN values for the column bathrooms : 10\n" ] ], [ [ "\nWe can replace the missing values of the column <code>'bedrooms'</code> with the mean of the column <code>'bedrooms' </code> using the method <code>replace()</code>. Don't forget to set the <code>inplace</code> parameter to <code>True</code>", "_____no_output_____" ] ], [ [ "mean=df['bedrooms'].mean()\ndf['bedrooms'].replace(np.nan,mean, inplace=True)", "_____no_output_____" ] ], [ [ "\nWe also replace the missing values of the column <code>'bathrooms'</code> with the mean of the column <code>'bathrooms' </code> using the method <code>replace()</code>. Don't forget to set the <code> inplace </code> parameter top <code> True </code>", "_____no_output_____" ] ], [ [ "mean=df['bathrooms'].mean()\ndf['bathrooms'].replace(np.nan,mean, inplace=True)", "_____no_output_____" ], [ "print(\"number of NaN values for the column bedrooms :\", df['bedrooms'].isnull().sum())\nprint(\"number of NaN values for the column bathrooms :\", df['bathrooms'].isnull().sum())", "number of NaN values for the column bedrooms : 0\nnumber of NaN values for the column bathrooms : 0\n" ] ], [ [ "# Module 3: Exploratory Data Analysis", "_____no_output_____" ], [ "### Question 3\nUse the method <code>value_counts</code> to count the number of houses with unique floor values, use the method <code>.to_frame()</code> to convert it to a dataframe.\n", "_____no_output_____" ] ], [ [ "df['floors'].value_counts().to_frame()", "_____no_output_____" ] ], [ [ "### Question 4\nUse the function <code>boxplot</code> in the seaborn library to determine whether houses with a waterfront view or without a waterfront view have more price outliers.", "_____no_output_____" ] ], [ [ "sns.boxplot(df['waterfront'],df['price'], data=df)", "_____no_output_____" ] ], [ [ "### Question 5\nUse the function <code>regplot</code> in the seaborn library to determine if the feature <code>sqft_above</code> is negatively or positively correlated with price.", "_____no_output_____" ] ], [ [ "sns.regplot(x=\"sqft_above\", y= \"price\", data=df)\nplt.ylim()", "_____no_output_____" ] ], [ [ "\nWe can use the Pandas method <code>corr()</code> to find the feature other than price that is most correlated with price.", "_____no_output_____" ] ], [ [ "df.corr()['price'].sort_values()", "_____no_output_____" ] ], [ [ "# Module 4: Model Development", "_____no_output_____" ], [ "\nWe can Fit a linear regression model using the longitude feature <code>'long'</code> and caculate the R^2.", "_____no_output_____" ] ], [ [ "X = df[['long']]\nY = df['price']\nlm = LinearRegression()\nlm.fit(X,Y)\nlm.score(X, Y)", "_____no_output_____" ] ], [ [ "### Question 6\nFit a linear regression model to predict the <code>'price'</code> using the feature <code>'sqft_living'</code> then calculate the R^2. Take a screenshot of your code and the value of the R^2.", "_____no_output_____" ] ], [ [ "X1 = df[['sqft_living']]\nY1 = df['price']\nlm1 = LinearRegression()\nlm.fit(X1,Y1)\nprint('R^2: ', lm.score(X1,Y1))", "R^2: 0.4928532179037931\n" ] ], [ [ "### Question 7\nFit a linear regression model to predict the <code>'price'</code> using the list of features:", "_____no_output_____" ] ], [ [ "features =[\"floors\", \"waterfront\",\"lat\" ,\"bedrooms\" ,\"sqft_basement\" ,\"view\" ,\"bathrooms\",\"sqft_living15\",\"sqft_above\",\"grade\",\"sqft_living\"] ", "_____no_output_____" ] ], [ [ "Then calculate the R^2. Take a screenshot of your code.", "_____no_output_____" ] ], [ [ "X2 = df[[\"floors\", \"waterfront\",\"lat\" ,\"bedrooms\" ,\"sqft_basement\" ,\"view\" ,\"bathrooms\",\"sqft_living15\",\"sqft_above\",\"grade\",\"sqft_living\"]]\nY2 = df['price']\nlm2 = LinearRegression()\nlm2.fit(X2, Y2)\nprint('R^2: ',lm2.score(X2, Y2))", "R^2: 0.6576951666037494\n" ] ], [ [ "### This will help with Question 8\n\nCreate a list of tuples, the first element in the tuple contains the name of the estimator:\n\n<code>'scale'</code>\n\n<code>'polynomial'</code>\n\n<code>'model'</code>\n\nThe second element in the tuple contains the model constructor \n\n<code>StandardScaler()</code>\n\n<code>PolynomialFeatures(include_bias=False)</code>\n\n<code>LinearRegression()</code>\n", "_____no_output_____" ] ], [ [ "Input=[('scale',StandardScaler()),('polynomial', PolynomialFeatures(include_bias=False)),('model',LinearRegression())]", "_____no_output_____" ] ], [ [ "### Question 8\nUse the list to create a pipeline object to predict the 'price', fit the object using the features in the list <code>features</code>, and calculate the R^2.", "_____no_output_____" ] ], [ [ "X3 = df[[\"floors\", \"waterfront\",\"lat\" ,\"bedrooms\" ,\"sqft_basement\" ,\"view\" ,\"bathrooms\",\"sqft_living15\",\"sqft_above\",\"grade\",\"sqft_living\"]]\nY3 = df['price']\npipe = Pipeline(Input)\npipe.fit(X3, Y3)\nprint('R^2: ',pipe.score(X3,Y3))", "R^2: 0.7513404614351351\n" ] ], [ [ "# Module 5: Model Evaluation and Refinement", "_____no_output_____" ], [ "Import the necessary modules:", "_____no_output_____" ] ], [ [ "from sklearn.model_selection import cross_val_score\nfrom sklearn.model_selection import train_test_split\nprint(\"done\")", "done\n" ] ], [ [ "We will split the data into training and testing sets:", "_____no_output_____" ] ], [ [ "features =[\"floors\", \"waterfront\",\"lat\" ,\"bedrooms\" ,\"sqft_basement\" ,\"view\" ,\"bathrooms\",\"sqft_living15\",\"sqft_above\",\"grade\",\"sqft_living\"] \nX = df[features]\nY = df['price']\n\nx_train, x_test, y_train, y_test = train_test_split(X, Y, test_size=0.15, random_state=1)\n\n\nprint(\"number of test samples:\", x_test.shape[0])\nprint(\"number of training samples:\",x_train.shape[0])", "number of test samples: 3242\nnumber of training samples: 18371\n" ] ], [ [ "### Question 9\nCreate and fit a Ridge regression object using the training data, set the regularization parameter to 0.1, and calculate the R^2 using the test data. \n", "_____no_output_____" ] ], [ [ "from sklearn.linear_model import Ridge", "_____no_output_____" ], [ "RidgeModel = Ridge(alpha = 0.1)\nRidgeModel.fit(x_train,y_train)\nprint('R^2 Test: ', RidgeModel.score(x_test, y_test))", "R^2 Test: 0.6478759163939115\n" ] ], [ [ "### Question 10\nPerform a second order polynomial transform on both the training data and testing data. Create and fit a Ridge regression object using the training data, set the regularisation parameter to 0.1, and calculate the R^2 utilising the test data provided. Take a screenshot of your code and the R^2.", "_____no_output_____" ] ], [ [ "pr=PolynomialFeatures(degree=2)\nx_train_pr=pr.fit_transform(x_train)\nx_test_pr=pr.fit_transform(x_test)\n\nRidgeModel=Ridge(alpha=0.1)\nRidgeModel.fit(x_train_pr, y_train)\n\nprint(\"Test R^2: \",RidgeModel.score(x_test_pr, y_test))", "Test R^2: 0.7002744260973095\n" ] ], [ [ "<p>Once you complete your notebook you will have to share it. Select the icon on the top right a marked in red in the image below, a dialogue box should open, and select the option all&nbsp;content excluding sensitive code cells.</p>\n <p><img width=\"600\" src=\"https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/DA0101EN/coursera/project/save_notebook.png\" alt=\"share notebook\" style=\"display: block; margin-left: auto; margin-right: auto;\"/></p>\n <p></p>\n <p>You can then share the notebook&nbsp; via a&nbsp; URL by scrolling down as shown in the following image:</p>\n <p style=\"text-align: center;\"><img width=\"600\" src=\"https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/DA0101EN/coursera/project/url_notebook.png\" alt=\"HTML\" style=\"display: block; margin-left: auto; margin-right: auto;\" /></p>\n <p>&nbsp;</p>", "_____no_output_____" ], [ "<h2>About the Authors:</h2> \n\n<a href=\"https://www.linkedin.com/in/joseph-s-50398b136/\">Joseph Santarcangelo</a> has a PhD in Electrical Engineering, his research focused on using machine learning, signal processing, and computer vision to determine how videos impact human cognition. Joseph has been working for IBM since he completed his PhD.", "_____no_output_____" ], [ "Other contributors: <a href=\"https://www.linkedin.com/in/michelleccarey/\">Michelle Carey</a>, <a href=\"www.linkedin.com/in/jiahui-mavis-zhou-a4537814a\">Mavis Zhou</a> ", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ] ]
4a0ba06d65547bb8fbf3b99ae2ee1a633d3a0baa
540,916
ipynb
Jupyter Notebook
notebooks/parcels/Plastics/ParcelsSSC.ipynb
SalishSeaCast/analysis-jose
9eed549f0e3117de69c54c162307f16bf4fe0af3
[ "Apache-2.0" ]
null
null
null
notebooks/parcels/Plastics/ParcelsSSC.ipynb
SalishSeaCast/analysis-jose
9eed549f0e3117de69c54c162307f16bf4fe0af3
[ "Apache-2.0" ]
null
null
null
notebooks/parcels/Plastics/ParcelsSSC.ipynb
SalishSeaCast/analysis-jose
9eed549f0e3117de69c54c162307f16bf4fe0af3
[ "Apache-2.0" ]
null
null
null
883.849673
240,872
0.952196
[ [ [ "# **First run Ocean parcels on SSC fieldset**", "_____no_output_____" ] ], [ [ "%matplotlib inline\nimport numpy as np\nimport xarray as xr\nimport os\nfrom matplotlib import pyplot as plt, animation, rc\nimport matplotlib.colors as mcolors\nfrom datetime import datetime, timedelta\nfrom dateutil.parser import parse\nfrom scipy.io import loadmat\nfrom cartopy import crs, feature\n\nfrom parcels import FieldSet, Field, VectorField, ParticleSet, JITParticle, ErrorCode, AdvectionRK4, AdvectionRK4_3D\n\nrc('animation', html='html5')", "_____no_output_____" ] ], [ [ "## Functions", "_____no_output_____" ], [ "#### Path prefix", "_____no_output_____" ] ], [ [ "def make_prefix(date, path, res='h'):\n \"\"\"Construct path prefix for local SalishSeaCast results given date object and paths dict\n e.g., /results2/SalishSea/nowcast-green.201905/daymonthyear/SalishSea_1h_yyyymmdd_yyyymmdd\n \"\"\"\n\n datestr = '_'.join(np.repeat(date.strftime('%Y%m%d'), 2))\n folder = date.strftime(\"%d%b%y\").lower()\n prefix = os.path.join(path, f'{folder}/SalishSea_1{res}_{datestr}')\n \n return prefix", "_____no_output_____" ] ], [ [ "#### Scatter_Colors", "_____no_output_____" ] ], [ [ "colors=['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf']\ndef scatter_particles(ax, N,colors, nmin, nmax,yvar):\n scatter=[]\n #N is the number of stations\n #Color is a list of strings picking the desired colors\n #nmin is t0, nmax is tmax\n #yvar is the y coordinate\n \n starts = np.arange(0,N*n,n)\n ends = np.arange(n-1,N*n,n)\n if N < len(colors):\n colors = colors[0:N]\n elif N > len(colors):\n con = 0\n while N > len(colors):\n colors.append(colors[con])\n con+=1\n if nmin==nmax:\n for i in range(N):\n scatter.append(ax.scatter(ds.lon[starts[i]:ends[i], nmin], yvar[starts[i]:ends[i], nmin],c=colors[i],s=5))\n else:\n for i in range(N):\n scatter.append(ax.scatter(ds.lon[starts[i]:ends[i], nmin:nmax], yvar[starts[i]:ends[i], nmin:nmax],c=colors[i],s=5))\n return scatter", "_____no_output_____" ] ], [ [ "#### Useful Kernel", "_____no_output_____" ] ], [ [ "def DeleteParticle(particle, fieldset, time):\n \"\"\"Delete particle from OceanParcels simulation to avoid run failure\n \"\"\"\n \n print(f'Particle {particle.id} lost !! [{particle.lon}, {particle.lat}, {particle.depth}, {particle.time}]')\n particle.delete()", "_____no_output_____" ] ], [ [ "## Load drifters and definitions", "_____no_output_____" ] ], [ [ "# Define paths\npaths = {\n 'NEMO': '/results2/SalishSea/nowcast-green.201905/',\n 'coords': '/ocean/jvalenti/MOAD/grid/coordinates_seagrid_SalishSea201702.nc',\n 'mask': '/ocean/jvalenti/MOAD/grid/mesh_mask201702.nc',\n 'out': '/home/jvalenti/MOAD/analysis-jose/notebooks/results',\n 'anim': '/home/jvalenti/MOAD/animations'\n}", "_____no_output_____" ], [ "# Duration and timestep [s]\nlength = 20\nduration = timedelta(days=length)\ndt = 90 #toggle between - or + to pick backwards or forwards", "_____no_output_____" ], [ "N = 6 # number of deploying locations\nn = 100 # 1000 # number of particles per location\n# Define Gaussian point cloud in the horizontal\nr = 3000 # radius of particle cloud [m]\ndeg2m = 111000 * np.cos(50 * np.pi / 180)\nvar = (r / (deg2m * 3))**2\nx_offset, y_offset = np.random.multivariate_normal([0, 0], [[var, 0], [0, var]], [n,N]).T\n# Set a uniform distribution in depth, from dmin to dmax\ndmin = 0.\ndmax = 5.\nzvals = dmin + np.random.random_sample([n,N]).T*(dmax-dmin)", "_____no_output_____" ] ], [ [ "## Simulation", "_____no_output_____" ] ], [ [ "start = datetime(2018, 1, 17)\ndaterange = [start+timedelta(days=i) for i in range(length)]\n# Build filenames\nUlist, Vlist, Wlist = [], [], []\nfor day in range(duration.days):\n path_NEMO = make_prefix(start + timedelta(days=day), paths['NEMO'])\n print (path_NEMO)\n Ulist.append(path_NEMO + '_grid_U.nc')\n Vlist.append(path_NEMO + '_grid_V.nc')\n Wlist.append(path_NEMO + '_grid_W.nc')\n\n# Load NEMO forcing : note, depth aware but no vertical advection, particles stay at their original depth\nfilenames = {\n 'U': {'lon': paths['coords'], 'lat': paths['coords'], 'depth': Wlist[0], 'data': Ulist},\n 'V': {'lon': paths['coords'], 'lat': paths['coords'], 'depth': Wlist[0], 'data': Vlist},\n 'W': {'lon': paths['coords'], 'lat': paths['coords'], 'depth': Wlist[0], 'data': Wlist},\n}\nvariables = {'U': 'vozocrtx', 'V': 'vomecrty','W': 'vovecrtz'}\ndimensions = {'lon': 'glamf', 'lat': 'gphif', 'depth': 'depthw','time': 'time_counter'}\n\n#bring salish sea results into field_set\nfield_set = FieldSet.from_nemo(filenames, variables, dimensions, allow_time_extrapolation=True)", "/results2/SalishSea/nowcast-green.201905/17jan18/SalishSea_1h_20180117_20180117\n/results2/SalishSea/nowcast-green.201905/18jan18/SalishSea_1h_20180118_20180118\n/results2/SalishSea/nowcast-green.201905/19jan18/SalishSea_1h_20180119_20180119\n/results2/SalishSea/nowcast-green.201905/20jan18/SalishSea_1h_20180120_20180120\n/results2/SalishSea/nowcast-green.201905/21jan18/SalishSea_1h_20180121_20180121\n/results2/SalishSea/nowcast-green.201905/22jan18/SalishSea_1h_20180122_20180122\n/results2/SalishSea/nowcast-green.201905/23jan18/SalishSea_1h_20180123_20180123\n/results2/SalishSea/nowcast-green.201905/24jan18/SalishSea_1h_20180124_20180124\n/results2/SalishSea/nowcast-green.201905/25jan18/SalishSea_1h_20180125_20180125\n/results2/SalishSea/nowcast-green.201905/26jan18/SalishSea_1h_20180126_20180126\n/results2/SalishSea/nowcast-green.201905/27jan18/SalishSea_1h_20180127_20180127\n/results2/SalishSea/nowcast-green.201905/28jan18/SalishSea_1h_20180128_20180128\n/results2/SalishSea/nowcast-green.201905/29jan18/SalishSea_1h_20180129_20180129\n/results2/SalishSea/nowcast-green.201905/30jan18/SalishSea_1h_20180130_20180130\n/results2/SalishSea/nowcast-green.201905/31jan18/SalishSea_1h_20180131_20180131\n/results2/SalishSea/nowcast-green.201905/01feb18/SalishSea_1h_20180201_20180201\n/results2/SalishSea/nowcast-green.201905/02feb18/SalishSea_1h_20180202_20180202\n/results2/SalishSea/nowcast-green.201905/03feb18/SalishSea_1h_20180203_20180203\n/results2/SalishSea/nowcast-green.201905/04feb18/SalishSea_1h_20180204_20180204\n/results2/SalishSea/nowcast-green.201905/05feb18/SalishSea_1h_20180205_20180205\n" ] ], [ [ "### Change name for each run!!", "_____no_output_____" ] ], [ [ "# Set output file name. Maybe change for each run\nfn = f'Long-neutral-MP' + '_'.join(d.strftime('%Y%m%d')+'_1n' for d in [start, start+duration]) + '.nc'\noutfile = os.path.join(paths['out'], fn)\nprint(outfile)", "/home/jvalenti/MOAD/analysis-jose/notebooks/results/Long-neutral-MP20180117_1n_20180206_1n.nc\n" ] ], [ [ "### Set particle location", "_____no_output_____" ] ], [ [ "lon = np.zeros([N,n])\nlat = np.zeros([N,n])\n# Execute run\nclon, clat = [-123.901172,-125.155849,-123.207648,-122.427508,-123.399769,-123.277731], [49.186308,49.975326,49.305448,47.622403,48.399420,49.11602] # choose horizontal centre of the particle cloud\nfor i in range(N):\n lon[i,:]=(clon[i] + x_offset[i,:])\n lat[i,:]=(clat[i] + y_offset[i,:])\nz = zvals", "_____no_output_____" ], [ "# pset = ParticleSet.from_list(field_set, JITParticle, lon=lon, lat=lat, depth=z, time=start+timedelta(hours=2))\n# #pset.computeTimeChunk(allow_time_extrapolation=1)\n# pset.execute(\n# pset.Kernel(AdvectionRK4_3D), runtime=duration, dt=dt,\n# output_file=pset.ParticleFile(name=outfile, outputdt=timedelta(hours=1)),\n# recovery={ErrorCode.ErrorOutOfBounds: DeleteParticle},\n# )", "_____no_output_____" ], [ "coords = xr.open_dataset(paths['coords'], decode_times=False)\nmask = xr.open_dataset(paths['mask'])\nds = xr.open_dataset(outfile)", "_____no_output_____" ], [ "fig, ax = plt.subplots(figsize=(19, 8))\nax.contour(coords.nav_lon, coords.nav_lat, mask.mbathy[0,:,:],colors='k',linewidths=0.1)\nax.contourf(coords.nav_lon, coords.nav_lat, mask.tmask[0, 0, ...], levels=[-0.01, 0.01], colors='lightgray')\nax.contour(coords.nav_lon, coords.nav_lat, mask.tmask[0, 0, ...], levels=[-0.01, 0.01], colors='k')\nax.set_aspect(1/1)\nnmin, nmax = 0, -1\nscatter_particles(ax, N,colors, nmin, nmax, ds.lat)\nax.scatter(clon,clat,c='g', marker='*', linewidths=1)\nplt.ylabel('Latitude')\nplt.xlabel('Longitude')", "_____no_output_____" ], [ "fig, ax = plt.subplots(figsize=(10, 10))\nscatter_particles(ax, N,colors, nmin, nmax, -ds.z)\nax.grid()\nplt.ylabel('Depth [m]')\nplt.xlabel('Longitude')", "_____no_output_____" ], [ "fps = 1\nfig = plt.figure(figsize=(10, 10))\nax = plt.axes(xlim=(-126,-122),ylim=(-250,10))\nss = scatter_particles(ax, N,colors, 0, 0, -ds.z)\nplt.ylabel('Depth [m]',fontsize=16)\nplt.xlabel('Longitude',fontsize=16)\nplt.grid()\n\ndef update(frames):\n global ss\n for scat in ss:\n scat.remove()\n ss = scatter_particles(ax, N,colors, frames, frames, -ds.z)\n return ss\n\nanim = animation.FuncAnimation(fig, update, frames=np.arange(0,len(ds.lon[0,:]),fps),repeat=True)\nf = paths[\"anim\"]+\"/depth_neutral.mp4\" \nFFwriter = animation.FFMpegWriter()\nanim.save(f, writer = FFwriter)", "_____no_output_____" ], [ "fps = 1\nfig = plt.figure(figsize=(19, 8))\nax = plt.axes(xlim=(-127,-121),ylim=(46.8,51.2))\nax.contour(coords.nav_lon, coords.nav_lat, mask.mbathy[0,:,:],colors='k',linewidths=0.1)\nax.contourf(coords.nav_lon, coords.nav_lat, mask.tmask[0, 0, ...], levels=[-0.01, 0.01], colors='lightgray')\nax.contour(coords.nav_lon, coords.nav_lat, mask.tmask[0, 0, ...], levels=[-0.01, 0.01], colors='k')\nax.grid()\nax.set_aspect(1/1)\nax.scatter(clon,clat,c='g', marker='*', linewidths=2)\nplt.ylabel('Latitude',fontsize=16)\nplt.xlabel('Longitude',fontsize=16)\nss = scatter_particles(ax, N,colors, 0,0, ds.lat)\n\ndef update(frames):\n global ss\n for scat in ss:\n scat.remove()\n ss = scatter_particles(ax, N,colors, frames,frames, ds.lat)\n return ss\n\n\nanim = animation.FuncAnimation(fig, update, frames=np.arange(0,len(ds.lon[0,:]),fps))\nf=paths[\"anim\"]+\"/neutral.mp4\" \nFFwriter = animation.FFMpegWriter()\nanim.save(f, writer = FFwriter)", "_____no_output_____" ], [ "colors=['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf']\ndef scatterHD_particles(ax, N,colors, nmin, nmax,yvar):\n scatter=[]\n #N is the number of stations\n #Color is a list of strings picking the desired colors\n #nmin is t0, nmax is tmax\n #yvar is the y coordinate\n \n starts = np.arange(0,N*n,n)\n ends = np.arange(n-1,N*n,n)\n if N < len(colors):\n colors = colors[0:N]\n elif N > len(colors):\n con = 0\n while N > len(colors):\n colors.append(colors[con])\n con+=1\n if nmin==nmax:\n for i in range(N):\n scatter.append(ax.scatter(ds.lon[starts[i]:ends[i], nmin], yvar[starts[i]:ends[i], nmin],c=colors[i],s=5,transform=crs.PlateCarree(),zorder=1))\n else:\n for i in range(N):\n scatter.append(ax.scatter(ds.lon[starts[i]:ends[i], nmin:nmax], yvar[starts[i]:ends[i], nmin:nmax],c=colors[i],s=5,transform=crs.PlateCarree(),zorder=1))\n return scatter", "_____no_output_____" ], [ "fps = 1\nfig = plt.figure(figsize=(19, 8))\n\n# Make map\nfig, ax = plt.subplots(figsize=(19, 8), subplot_kw={'projection': crs.Mercator()})\nax.set_extent([-127, -121, 47, 51], crs=crs.PlateCarree())\nax.add_feature(feature.GSHHSFeature('intermediate', edgecolor='k', facecolor='lightgray'),zorder=2)\nax.add_feature(feature.RIVERS, edgecolor='k',zorder=5)\n\ngl = ax.gridlines(\n linestyle=':', color='k', draw_labels=True,\n xlocs=range(-126, -121), ylocs=range(47, 52),zorder=5)\ngl.top_labels, gl.right_labels = False, False\nss=scatterHD_particles(ax, N,colors, 0, 0,ds.lat)\nax.scatter(clon,clat,c='g', marker='*', linewidth=2,transform=crs.PlateCarree(),zorder=4) \nax.text(-0.1, 0.55, 'Latitude', va='bottom', ha='center',\n rotation='vertical', rotation_mode='anchor',\n transform=ax.transAxes, fontsize=14)\nax.text(0.5, -0.1, 'Longitude', va='bottom', ha='center',\n rotation='horizontal', rotation_mode='anchor',\n transform=ax.transAxes, fontsize=14)\n\ndef animate(frames):\n global ss\n for scat in ss:\n scat.remove()\n ss=scatterHD_particles(ax, N,colors, frames, frames,ds.lat)\n\n\nanim = animation.FuncAnimation(fig, animate, frames=np.arange(0,len(ds.lon[0,:]),fps))\nf = paths[\"anim\"]+\"/neutral_HD.mp4\" \nFFwriter = animation.FFMpegWriter()\nanim.save(f, writer = FFwriter)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
4a0ba186d857bcc003d3b856c753e232ac2de97e
12,310
ipynb
Jupyter Notebook
experiments/tw-on-generator/7/tw_template.ipynb
peglegpete/gen-seq-noise
37471ad86d1fa91caa7a5be6fc374fd0db18f651
[ "MIT" ]
2
2021-07-18T09:29:27.000Z
2022-01-09T11:17:03.000Z
experiments/tw-on-generator/7/tw_template.ipynb
peglegpete/gen-seq-noise
37471ad86d1fa91caa7a5be6fc374fd0db18f651
[ "MIT" ]
null
null
null
experiments/tw-on-generator/7/tw_template.ipynb
peglegpete/gen-seq-noise
37471ad86d1fa91caa7a5be6fc374fd0db18f651
[ "MIT" ]
null
null
null
32.566138
140
0.522989
[ [ [ "#cell-width control\nfrom IPython.core.display import display, HTML\ndisplay(HTML(\"<style>.container { width:80% !important; }</style>\"))", "_____no_output_____" ] ], [ [ "# Imports", "_____no_output_____" ] ], [ [ "#packages\nimport numpy\nimport tensorflow as tf\nfrom tensorflow.core.example import example_pb2\n\n#utils\nimport os\nimport random\nimport pickle\nimport struct\nimport time\nfrom generators import *\n\n#keras\nimport keras\nfrom keras.preprocessing import text, sequence\nfrom keras.preprocessing.text import Tokenizer\nfrom keras.models import Model, Sequential\nfrom keras.models import load_model\nfrom keras.layers import Dense, Dropout, Activation, Concatenate, Dot, Embedding, LSTM, Conv1D, MaxPooling1D, Input, Lambda\n #callbacks\nfrom keras.callbacks import TensorBoard, ModelCheckpoint, Callback\n", "Using TensorFlow backend.\n" ] ], [ [ "# Seeding", "_____no_output_____" ] ], [ [ "sd = 7\nfrom numpy.random import seed\nseed(sd)\nfrom tensorflow import set_random_seed\nset_random_seed(sd)", "_____no_output_____" ] ], [ [ "# CPU usage", "_____no_output_____" ] ], [ [ "os.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\" # see issue #152\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"\"", "_____no_output_____" ] ], [ [ "# Global parameters", "_____no_output_____" ] ], [ [ "# Embedding\nmax_features = 400000\nmaxlen_text = 400\nmaxlen_summ = 80\nembedding_size = 100 #128\n\n# Convolution\nkernel_size = 5\nfilters = 64\npool_size = 4\n\n# LSTM\nlstm_output_size = 70\n\n# Training\nbatch_size = 32\nepochs = 20", "_____no_output_____" ] ], [ [ "# Load data", "_____no_output_____" ] ], [ [ "#data_dir = '/mnt/disks/500gb/experimental-data-mini/experimental-data-mini/generator-dist-1to1/1to1/'\ndata_dir = '/media/oala/4TB/experimental-data/experiment-1_nonconform-models/generator-dist/1to1/'\n#processing_dir = '/mnt/disks/500gb/stats-and-meta-data/400000/'\nprocessing_dir = '/media/oala/4TB/experimental-data/stats-and-meta-data/400000/'\n\nwith open(data_dir+'partition.pickle', 'rb') as handle: partition = pickle.load(handle)\nwith open(data_dir+'labels.pickle', 'rb') as handle: labels = pickle.load(handle)\n\nwith open(processing_dir+'tokenizer.pickle', 'rb') as handle: tokenizer = pickle.load(handle)\nembedding_matrix = numpy.load(processing_dir+'embedding_matrix.npy')\n\n#the p_n constant\nc = 80000", "_____no_output_____" ] ], [ [ "# Model", "_____no_output_____" ] ], [ [ "#2way input\ntext_input = Input(shape=(maxlen_text,embedding_size), dtype='float32')\nsumm_input = Input(shape=(maxlen_summ,embedding_size), dtype='float32')\n\n#2way dropout\ntext_route = Dropout(0.25)(text_input)\nsumm_route = Dropout(0.25)(summ_input)\n\n#2way conv\ntext_route = Conv1D(filters,\n kernel_size,\n padding='valid',\n activation='relu',\n strides=1)(text_route)\nsumm_route = Conv1D(filters,\n kernel_size,\n padding='valid',\n activation='relu',\n strides=1)(summ_route)\n\n#2way max pool\ntext_route = MaxPooling1D(pool_size=pool_size)(text_route)\nsumm_route = MaxPooling1D(pool_size=pool_size)(summ_route)\n\n#2way lstm\ntext_route = LSTM(lstm_output_size)(text_route)\nsumm_route = LSTM(lstm_output_size)(summ_route)\n\n#get dot of both routes\nmerged = Dot(axes=1,normalize=True)([text_route, summ_route])\n\n#negate results\n#merged = Lambda(lambda x: -1*x)(merged)\n\n#add p_n constant\n#merged = Lambda(lambda x: x + c)(merged)\n\n#output\noutput = Dense(1, activation='sigmoid')(merged)\n\n#define model\nmodel = Model(inputs=[text_input, summ_input], outputs=[output])\n\nmodel.compile(loss='binary_crossentropy',\n optimizer='adam',\n metrics=['accuracy'])", "_____no_output_____" ] ], [ [ "# Train model", "_____no_output_____" ] ], [ [ "#callbacks\nclass BatchHistory(keras.callbacks.Callback):\n def on_train_begin(self, logs={}):\n self.losses = []\n self.accs = []\n\n def on_batch_end(self, batch, logs={}):\n self.losses.append(logs.get('loss'))\n self.accs.append(logs.get('acc'))\n \nhistory = BatchHistory()\ntensorboard = TensorBoard(log_dir='./logs', histogram_freq=0, batch_size=batch_size, write_graph=True, write_grads=True)\nmodelcheckpoint = ModelCheckpoint('best.h5', monitor='val_loss', verbose=0, save_best_only=True, mode='min', period=1)\n\n#batch generator parameters\nparams = {'dim': [(maxlen_text,embedding_size),(maxlen_summ,embedding_size)],\n 'batch_size': batch_size,\n 'shuffle': True,\n 'tokenizer':tokenizer,\n 'embedding_matrix':embedding_matrix,\n 'maxlen_text':maxlen_text,\n 'maxlen_summ':maxlen_summ,\n 'data_dir':data_dir,\n 'sample_info':None}\n\n#generators\ntraining_generator = ContAllGenerator(partition['train'], labels, **params)\nvalidation_generator = ContAllGenerator(partition['validation'], labels, **params)\n\n# Train model on dataset\nmodel.fit_generator(generator=training_generator,\n validation_data=validation_generator,\n use_multiprocessing=True,\n workers=6,\n epochs=epochs,\n callbacks=[tensorboard, modelcheckpoint, history])", "Epoch 1/20\n17944/17944 [==============================] - 4842s 270ms/step - loss: 0.3166 - acc: 0.8629 - val_loss: 0.2461 - val_acc: 0.8957\nEpoch 2/20\n17944/17944 [==============================] - 4920s 274ms/step - loss: 0.2546 - acc: 0.8937 - val_loss: 0.2384 - val_acc: 0.8998\nEpoch 3/20\n17944/17944 [==============================] - 5042s 281ms/step - loss: 0.2411 - acc: 0.8998 - val_loss: 0.2304 - val_acc: 0.9045\nEpoch 4/20\n17944/17944 [==============================] - 4677s 261ms/step - loss: 0.2336 - acc: 0.9031 - val_loss: 0.2266 - val_acc: 0.9052\nEpoch 5/20\n17944/17944 [==============================] - 5680s 317ms/step - loss: 0.2286 - acc: 0.9051 - val_loss: 0.2259 - val_acc: 0.9074\nEpoch 6/20\n17944/17944 [==============================] - 5773s 322ms/step - loss: 0.2253 - acc: 0.9068 - val_loss: 0.2204 - val_acc: 0.9086\nEpoch 7/20\n17944/17944 [==============================] - 5938s 331ms/step - loss: 0.2222 - acc: 0.9081 - val_loss: 0.2171 - val_acc: 0.9105\nEpoch 8/20\n17944/17944 [==============================] - 6300s 351ms/step - loss: 0.2202 - acc: 0.9087 - val_loss: 0.2238 - val_acc: 0.9059\nEpoch 9/20\n17944/17944 [==============================] - 6342s 353ms/step - loss: 0.2179 - acc: 0.9099 - val_loss: 0.2196 - val_acc: 0.9092\nEpoch 10/20\n17944/17944 [==============================] - 5740s 320ms/step - loss: 0.2163 - acc: 0.9102 - val_loss: 0.2179 - val_acc: 0.9089\nEpoch 11/20\n17944/17944 [==============================] - 6139s 342ms/step - loss: 0.2153 - acc: 0.9108 - val_loss: 0.2162 - val_acc: 0.9111\nEpoch 12/20\n17944/17944 [==============================] - 6802s 379ms/step - loss: 0.2148 - acc: 0.9110 - val_loss: 0.2177 - val_acc: 0.9097\nEpoch 13/20\n17944/17944 [==============================] - 4354s 243ms/step - loss: 0.2139 - acc: 0.9115 - val_loss: 0.2211 - val_acc: 0.9094\nEpoch 14/20\n17944/17944 [==============================] - 4442s 248ms/step - loss: 0.2135 - acc: 0.9117 - val_loss: 0.2177 - val_acc: 0.9082\nEpoch 15/20\n17944/17944 [==============================] - 4431s 247ms/step - loss: 0.2124 - acc: 0.9124 - val_loss: 0.2174 - val_acc: 0.9099\nEpoch 16/20\n17944/17944 [==============================] - 4352s 243ms/step - loss: 0.2123 - acc: 0.9120 - val_loss: 0.2238 - val_acc: 0.9049\nEpoch 17/20\n17944/17944 [==============================] - 4954s 276ms/step - loss: 0.2128 - acc: 0.9115 - val_loss: 0.2243 - val_acc: 0.9057\nEpoch 18/20\n17944/17944 [==============================] - 4250s 237ms/step - loss: 0.2114 - acc: 0.9124 - val_loss: 0.2186 - val_acc: 0.9104\nEpoch 19/20\n17944/17944 [==============================] - 5062s 282ms/step - loss: 0.2110 - acc: 0.9127 - val_loss: 0.2201 - val_acc: 0.9085\nEpoch 20/20\n17944/17944 [==============================] - 4445s 248ms/step - loss: 0.2104 - acc: 0.9129 - val_loss: 0.2265 - val_acc: 0.9059\n" ], [ "with open('losses.pickle', 'wb') as handle: pickle.dump(history.losses, handle, protocol=pickle.HIGHEST_PROTOCOL)\nwith open('accs.pickle', 'wb') as handle: pickle.dump(history.accs, handle, protocol=pickle.HIGHEST_PROTOCOL)", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ] ]
4a0ba621819a2d10e96b23e1f4197dd7057c5758
222,108
ipynb
Jupyter Notebook
notebook/hw.ipynb
pipepipexiaji/matplotlib
f7a25f22afeceb11f37354ff8249790090ab3df6
[ "MIT" ]
null
null
null
notebook/hw.ipynb
pipepipexiaji/matplotlib
f7a25f22afeceb11f37354ff8249790090ab3df6
[ "MIT" ]
null
null
null
notebook/hw.ipynb
pipepipexiaji/matplotlib
f7a25f22afeceb11f37354ff8249790090ab3df6
[ "MIT" ]
null
null
null
197.780944
67,058
0.841996
[ [ [ "%pylab inline\nimport numpy as np\nimport matplotlib\nfrom matplotlib.pylab import plot, legend, csv2rec", "Populating the interactive namespace from numpy and matplotlib\n" ], [ "trends = csv2rec('trends.csv')", "_____no_output_____" ], [ "plot(trends.week_start, trends.spring_break, label='spring break') \nplot(trends.week_start, trends.textbooks, label='texbooks') \nplot(trends.week_start, trends.skiing, label='skiing') \nplot(trends.week_start, trends.kayak, label='kayak') \nlegend()", "_____no_output_____" ] ], [ [ "show the trends.csv", "_____no_output_____" ] ], [ [ "import pandas as pd\ndf = pd.read_csv('trends.csv',index_col=0, parse_dates=True)\ndf", "_____no_output_____" ], [ "print (df.iloc[0])\ndf.spring_break.plot()\ndf.textbooks.plot()\ndf.skiing.plot()\ndf.kayak.plot()\nlegend()", "week_end 2004-01-10\ntextbooks 44\nspring_break 30\nkayak 23\nskiing 92\nglobal_warming 14\nName: 2004-01-04 00:00:00, dtype: object\n" ] ], [ [ "### Find the maxima and minimum \n\nCreata vector of year and week numbers", "_____no_output_____" ] ], [ [ "dates = trends.week_start\nyears = zeros_like(dates)\nweeks = zeros_like(dates)\n\nfor i in range(len(dates)):\n years[i] = dates[i].year\n weeks[i] = dates[i].isocalendar()[1]", "_____no_output_____" ], [ "trend = trends.global_warming\nfor year in range(2004, 2011):\n idx = find(years == year)\n print(year, weeks[find(trend[idx] == max(trend[idx]))], weeks[find(trend[idx]==min(trend[idx]))])", "2004 [46] [28 30 31 32 33]\n2005 [38 48 49] [52]\n2006 [49 53] [33]\n2007 [10] [51]\n2008 [16] [51]\n2009 [49] [32 33]\n2010 [1] [51]\n" ], [ "def std_median(datums):\n return sqrt( sum( (datums - median(datums))**2 ) )", "_____no_output_____" ], [ "print (std_median(trends.spring_break))\nprint (std_median(trends.textbooks)) \nprint (std_median(trends.skiing))\nprint (std_median(trends.kayak))\nprint (std_median(trends.global_warming))", "310.621956726\n205.684223994\n449.831079406\n462.606744439\n305.695927353\n" ], [ "result = np.correlate(trends.skiing,trends.spring_break, mode='full')\ngap=arange(result.size)- result.size/2\nplot(gap, result)\nprint(gap[find(result==max(result))])", "[-6.5]\n" ], [ "result = np.correlate(trends.skiing,trends.global_warming, mode='full') gap = arange(result.size) - result.size/2 plot(gap,result) \nprint (gap[find(result==max(result))])", "_____no_output_____" ], [ "result = np.correlate(trends.skiing,trends.global_warming, mode='full') \ngap = arange(result.size) - result.size/2 \nplot(gap,result) \nprint (gap[find(result==max(result))])", "[-61.5]\n" ] ] ]
[ "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ] ]
4a0bd13615ee1875ba4ad57a64aefe436a264b8e
24,141
ipynb
Jupyter Notebook
Model backlog/Models/Inference/97-cassava-leaf-inf-effnetb3-scl-cce-512x512.ipynb
dimitreOliveira/Cassava-Leaf-Disease-Classification
22a42e840875190e2d8cd1c838d1aef7b956f39f
[ "MIT" ]
8
2021-02-18T22:35:19.000Z
2021-03-29T07:59:10.000Z
Model backlog/Models/Inference/97-cassava-leaf-inf-effnetb3-scl-cce-512x512.ipynb
dimitreOliveira/Cassava-Leaf-Disease-Classification
22a42e840875190e2d8cd1c838d1aef7b956f39f
[ "MIT" ]
null
null
null
Model backlog/Models/Inference/97-cassava-leaf-inf-effnetb3-scl-cce-512x512.ipynb
dimitreOliveira/Cassava-Leaf-Disease-Classification
22a42e840875190e2d8cd1c838d1aef7b956f39f
[ "MIT" ]
3
2021-03-27T13:48:23.000Z
2021-07-26T13:05:35.000Z
31.722733
112
0.533201
[ [ [ "## Dependencies", "_____no_output_____" ] ], [ [ "!pip install --quiet /kaggle/input/kerasapplications\n!pip install --quiet /kaggle/input/efficientnet-git", "_____no_output_____" ], [ "import warnings, glob\nfrom tensorflow.keras import Sequential, Model\nimport efficientnet.tfkeras as efn\nfrom cassava_scripts import *\n\n\nseed = 0\nseed_everything(seed)\nwarnings.filterwarnings('ignore')", "_____no_output_____" ] ], [ [ "### Hardware configuration", "_____no_output_____" ] ], [ [ "# TPU or GPU detection\n# Detect hardware, return appropriate distribution strategy\nstrategy, tpu = set_up_strategy()\n\nAUTO = tf.data.experimental.AUTOTUNE\nREPLICAS = strategy.num_replicas_in_sync\nprint(f'REPLICAS: {REPLICAS}')", "REPLICAS: 1\n" ] ], [ [ "# Model parameters", "_____no_output_____" ] ], [ [ "BATCH_SIZE = 8 * REPLICAS\nHEIGHT = 512\nWIDTH = 512\nCHANNELS = 3\nN_CLASSES = 5\nTTA_STEPS = 0 # Do TTA if > 0 ", "_____no_output_____" ] ], [ [ "# Augmentation", "_____no_output_____" ] ], [ [ "def data_augment(image, label):\n p_spatial = tf.random.uniform([], 0, 1.0, dtype=tf.float32)\n p_rotate = tf.random.uniform([], 0, 1.0, dtype=tf.float32)\n# p_pixel_1 = tf.random.uniform([], 0, 1.0, dtype=tf.float32)\n# p_pixel_2 = tf.random.uniform([], 0, 1.0, dtype=tf.float32)\n# p_pixel_3 = tf.random.uniform([], 0, 1.0, dtype=tf.float32)\n p_crop = tf.random.uniform([], 0, 1.0, dtype=tf.float32)\n \n # Flips\n image = tf.image.random_flip_left_right(image)\n image = tf.image.random_flip_up_down(image)\n if p_spatial > .75:\n image = tf.image.transpose(image)\n \n # Rotates\n if p_rotate > .75:\n image = tf.image.rot90(image, k=3) # rotate 270º\n elif p_rotate > .5:\n image = tf.image.rot90(image, k=2) # rotate 180º\n elif p_rotate > .25:\n image = tf.image.rot90(image, k=1) # rotate 90º\n \n# # Pixel-level transforms\n# if p_pixel_1 >= .4:\n# image = tf.image.random_saturation(image, lower=.7, upper=1.3)\n# if p_pixel_2 >= .4:\n# image = tf.image.random_contrast(image, lower=.8, upper=1.2)\n# if p_pixel_3 >= .4:\n# image = tf.image.random_brightness(image, max_delta=.1)\n \n # Crops\n if p_crop > .7:\n if p_crop > .9:\n image = tf.image.central_crop(image, central_fraction=.7)\n elif p_crop > .8:\n image = tf.image.central_crop(image, central_fraction=.8)\n else:\n image = tf.image.central_crop(image, central_fraction=.9)\n elif p_crop > .4:\n crop_size = tf.random.uniform([], int(HEIGHT*.8), HEIGHT, dtype=tf.int32)\n image = tf.image.random_crop(image, size=[crop_size, crop_size, CHANNELS])\n \n# # Crops\n# if p_crop > .6:\n# if p_crop > .9:\n# image = tf.image.central_crop(image, central_fraction=.5)\n# elif p_crop > .8:\n# image = tf.image.central_crop(image, central_fraction=.6)\n# elif p_crop > .7:\n# image = tf.image.central_crop(image, central_fraction=.7)\n# else:\n# image = tf.image.central_crop(image, central_fraction=.8)\n# elif p_crop > .3:\n# crop_size = tf.random.uniform([], int(HEIGHT*.6), HEIGHT, dtype=tf.int32)\n# image = tf.image.random_crop(image, size=[crop_size, crop_size, CHANNELS])\n \n\n return image, label", "_____no_output_____" ] ], [ [ "## Auxiliary functions", "_____no_output_____" ] ], [ [ "# Datasets utility functions\ndef resize_image(image, label):\n image = tf.image.resize(image, [HEIGHT, WIDTH])\n image = tf.reshape(image, [HEIGHT, WIDTH, CHANNELS])\n return image, label\n\ndef process_path(file_path):\n name = get_name(file_path)\n img = tf.io.read_file(file_path)\n img = decode_image(img)\n img, _ = scale_image(img, None)\n# img = center_crop(img, HEIGHT, WIDTH)\n return img, name\n\ndef get_dataset(files_path, shuffled=False, tta=False, extension='jpg'):\n dataset = tf.data.Dataset.list_files(f'{files_path}*{extension}', shuffle=shuffled)\n dataset = dataset.map(process_path, num_parallel_calls=AUTO)\n if tta:\n dataset = dataset.map(data_augment, num_parallel_calls=AUTO)\n dataset = dataset.map(resize_image, num_parallel_calls=AUTO)\n dataset = dataset.batch(BATCH_SIZE)\n dataset = dataset.prefetch(AUTO)\n return dataset", "_____no_output_____" ] ], [ [ "# Load data", "_____no_output_____" ] ], [ [ "database_base_path = '/kaggle/input/cassava-leaf-disease-classification/'\nsubmission = pd.read_csv(f'{database_base_path}sample_submission.csv')\ndisplay(submission.head())\n\nTEST_FILENAMES = tf.io.gfile.glob(f'{database_base_path}test_tfrecords/ld_test*.tfrec')\nNUM_TEST_IMAGES = count_data_items(TEST_FILENAMES)\nprint(f'GCS: test: {NUM_TEST_IMAGES}')", "_____no_output_____" ], [ "model_path_list = glob.glob('/kaggle/input/97-cassava-leaf-effnetb3-scl-cce-512x512/*.h5')\nmodel_path_list.sort()\n\nprint('Models to predict:')\nprint(*model_path_list, sep='\\n')", "Models to predict:\n/kaggle/input/97-cassava-leaf-effnetb3-scl-cce-512x512/model_0.h5\n" ] ], [ [ "# Model", "_____no_output_____" ] ], [ [ "def encoder_fn(input_shape):\n inputs = L.Input(shape=input_shape, name='input_image')\n base_model = efn.EfficientNetB3(input_tensor=inputs, \n include_top=False, \n weights=None, \n pooling='avg')\n \n model = Model(inputs=inputs, outputs=base_model.output)\n return model\n\ndef classifier_fn(input_shape, N_CLASSES, encoder, trainable=True):\n for layer in encoder.layers:\n layer.trainable = trainable\n \n inputs = L.Input(shape=input_shape, name='input_image')\n \n features = encoder(inputs)\n features = L.Dropout(.5)(features)\n features = L.Dense(512, activation='relu')(features)\n features = L.Dropout(.5)(features)\n \n output = L.Dense(N_CLASSES, activation='softmax', name='output', dtype='float32')(features)\n output_healthy = L.Dense(1, activation='sigmoid', name='output_healthy', dtype='float32')(features)\n output_cmd = L.Dense(1, activation='sigmoid', name='output_cmd', dtype='float32')(features)\n \n model = Model(inputs=inputs, outputs=[output, output_healthy, output_cmd])\n return model\n\nwith strategy.scope():\n encoder = encoder_fn((None, None, CHANNELS))\n model = classifier_fn((None, None, CHANNELS), N_CLASSES, encoder, trainable=False)\n \nmodel.summary()", "Model: \"model_1\"\n__________________________________________________________________________________________________\nLayer (type) Output Shape Param # Connected to \n==================================================================================================\ninput_image (InputLayer) [(None, None, None, 0 \n__________________________________________________________________________________________________\nmodel (Model) (None, 1536) 10783528 input_image[0][0] \n__________________________________________________________________________________________________\ndropout (Dropout) (None, 1536) 0 model[1][0] \n__________________________________________________________________________________________________\ndense (Dense) (None, 512) 786944 dropout[0][0] \n__________________________________________________________________________________________________\ndropout_1 (Dropout) (None, 512) 0 dense[0][0] \n__________________________________________________________________________________________________\noutput (Dense) (None, 5) 2565 dropout_1[0][0] \n__________________________________________________________________________________________________\noutput_healthy (Dense) (None, 1) 513 dropout_1[0][0] \n__________________________________________________________________________________________________\noutput_cmd (Dense) (None, 1) 513 dropout_1[0][0] \n==================================================================================================\nTotal params: 11,574,063\nTrainable params: 790,535\nNon-trainable params: 10,783,528\n__________________________________________________________________________________________________\n" ] ], [ [ "# Test set predictions", "_____no_output_____" ] ], [ [ "files_path = f'{database_base_path}test_images/'\ntest_size = len(os.listdir(files_path))\ntest_preds = np.zeros((test_size, N_CLASSES))\n\n\nfor model_path in model_path_list:\n print(model_path)\n K.clear_session()\n model.load_weights(model_path)\n\n if TTA_STEPS > 0:\n test_ds = get_dataset(files_path, tta=True).repeat()\n ct_steps = TTA_STEPS * ((test_size/BATCH_SIZE) + 1)\n preds = model.predict(test_ds, steps=ct_steps, verbose=1)[0][:(test_size * TTA_STEPS)]\n preds = np.mean(preds.reshape(test_size, TTA_STEPS, N_CLASSES, order='F'), axis=1)\n test_preds += preds / len(model_path_list)\n else:\n test_ds = get_dataset(files_path, tta=False)\n x_test = test_ds.map(lambda image, image_name: image)\n test_preds += model.predict(x_test)[0] / len(model_path_list)\n \ntest_preds = np.argmax(test_preds, axis=-1)\ntest_names_ds = get_dataset(files_path)\nimage_names = [img_name.numpy().decode('utf-8') for img, img_name in iter(test_names_ds.unbatch())]", "/kaggle/input/97-cassava-leaf-effnetb3-scl-cce-512x512/model_0.h5\n" ], [ "submission = pd.DataFrame({'image_id': image_names, 'label': test_preds})\nsubmission.to_csv('submission.csv', index=False)\ndisplay(submission.head())", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ] ]
4a0bf086908732cdd303b6c026a94d19e553d243
397,615
ipynb
Jupyter Notebook
Churn_Risk_Score_Prediction/Model/churn_risk_score_prediction.ipynb
malay5/Awesome-Machine-Learning-Models
816b1b49e0f119fcdb67ef87b3a3e987d7c8283f
[ "MIT" ]
null
null
null
Churn_Risk_Score_Prediction/Model/churn_risk_score_prediction.ipynb
malay5/Awesome-Machine-Learning-Models
816b1b49e0f119fcdb67ef87b3a3e987d7c8283f
[ "MIT" ]
null
null
null
Churn_Risk_Score_Prediction/Model/churn_risk_score_prediction.ipynb
malay5/Awesome-Machine-Learning-Models
816b1b49e0f119fcdb67ef87b3a3e987d7c8283f
[ "MIT" ]
null
null
null
80.261405
149,444
0.684207
[ [ [ "#import libraries\nimport pandas as pd\nimport numpy as np \nimport seaborn as sb\nimport matplotlib.pyplot as plt\nimport warnings\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.model_selection import RandomizedSearchCV\nwarnings.filterwarnings('ignore') ", "_____no_output_____" ], [ "#import data\ntrain_df = pd.read_csv(\"../Dataset/train.csv\")\ntest_df = pd.read_csv(\"../Dataset/test.csv\")", "_____no_output_____" ] ], [ [ "# Data inspection", "_____no_output_____" ] ], [ [ "train_df.head()", "_____no_output_____" ], [ "test_df.head()", "_____no_output_____" ], [ "#shape of dataset \nprint(\"shape of dataframe:\", train_df.shape)\n#data types \nprint(\"\\nVariable types:\\n\", train_df.dtypes.value_counts(),train_df.dtypes.value_counts().plot.pie())\nplt.draw()", "shape of dataframe: (36992, 25)\n\nVariable types:\n object 19\nfloat64 3\nint64 3\ndtype: int64 AxesSubplot(0.260833,0.125;0.503333x0.755)\n" ], [ "#shape of dataset \nprint(\"shape of dataframe:\", test_df.shape)\n#data types \nprint(\"\\nVariable types:\\n\", test_df.dtypes.value_counts(),test_df.dtypes.value_counts().plot.pie())\nplt.draw()", "shape of dataframe: (19919, 24)\n\nVariable types:\n object 19\nfloat64 3\nint64 2\ndtype: int64 AxesSubplot(0.260833,0.125;0.503333x0.755)\n" ], [ "train_df.info()", "<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 36992 entries, 0 to 36991\nData columns (total 25 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 customer_id 36992 non-null object \n 1 Name 36992 non-null object \n 2 age 36992 non-null int64 \n 3 gender 36992 non-null object \n 4 security_no 36992 non-null object \n 5 region_category 31564 non-null object \n 6 membership_category 36992 non-null object \n 7 joining_date 36992 non-null object \n 8 joined_through_referral 36992 non-null object \n 9 referral_id 36992 non-null object \n 10 preferred_offer_types 36704 non-null object \n 11 medium_of_operation 36992 non-null object \n 12 internet_option 36992 non-null object \n 13 last_visit_time 36992 non-null object \n 14 days_since_last_login 36992 non-null int64 \n 15 avg_time_spent 36992 non-null float64\n 16 avg_transaction_value 36992 non-null float64\n 17 avg_frequency_login_days 36992 non-null object \n 18 points_in_wallet 33549 non-null float64\n 19 used_special_discount 36992 non-null object \n 20 offer_application_preference 36992 non-null object \n 21 past_complaint 36992 non-null object \n 22 complaint_status 36992 non-null object \n 23 feedback 36992 non-null object \n 24 churn_risk_score 36992 non-null int64 \ndtypes: float64(3), int64(3), object(19)\nmemory usage: 7.1+ MB\n" ], [ "test_df.info()", "<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 19919 entries, 0 to 19918\nData columns (total 24 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 customer_id 19919 non-null object \n 1 Name 19919 non-null object \n 2 age 19919 non-null int64 \n 3 gender 19919 non-null object \n 4 security_no 19919 non-null object \n 5 region_category 16971 non-null object \n 6 membership_category 19919 non-null object \n 7 joining_date 19919 non-null object \n 8 joined_through_referral 19919 non-null object \n 9 referral_id 19919 non-null object \n 10 preferred_offer_types 19760 non-null object \n 11 medium_of_operation 19919 non-null object \n 12 internet_option 19919 non-null object \n 13 last_visit_time 19919 non-null object \n 14 days_since_last_login 19919 non-null int64 \n 15 avg_time_spent 19919 non-null float64\n 16 avg_transaction_value 19919 non-null float64\n 17 avg_frequency_login_days 19919 non-null object \n 18 points_in_wallet 17956 non-null float64\n 19 used_special_discount 19919 non-null object \n 20 offer_application_preference 19919 non-null object \n 21 past_complaint 19919 non-null object \n 22 complaint_status 19919 non-null object \n 23 feedback 19919 non-null object \ndtypes: float64(3), int64(2), object(19)\nmemory usage: 3.6+ MB\n" ] ], [ [ "# Data Cleaning", "_____no_output_____" ] ], [ [ "train_df = train_df.drop(['Name', 'referral_id'], axis=1) # dropping unnecessary columns \ntrain_df", "_____no_output_____" ], [ "test_df = test_df.drop(['Name', 'referral_id'], axis=1)\ntest_df", "_____no_output_____" ] ], [ [ "# Checking Null Values", "_____no_output_____" ] ], [ [ "#ratio of null values\ntrain_df.isnull().sum()/test_df.shape[0]*100", "_____no_output_____" ], [ "#ratio of null values\ntest_df.isnull().sum()/test_df.shape[0]*100", "_____no_output_____" ] ], [ [ "# Treating Null Values", "_____no_output_____" ] ], [ [ "train_df['region_category'] = train_df['region_category'].fillna(train_df['region_category'].mode()[0])\ntrain_df['preferred_offer_types'] = train_df['preferred_offer_types'].fillna(train_df['preferred_offer_types'].mode()[0])\ntrain_df['points_in_wallet'] = train_df['points_in_wallet'].fillna(train_df['points_in_wallet'].mean())\n\n\ntest_df['region_category'] = test_df['region_category'].fillna(test_df['region_category'].mode()[0])\ntest_df['preferred_offer_types'] = test_df['preferred_offer_types'].fillna(test_df['preferred_offer_types'].mode()[0])\ntest_df['points_in_wallet'] = test_df['points_in_wallet'].fillna(test_df['points_in_wallet'].mean())\n", "_____no_output_____" ], [ "#checking null values is present or not\nprint(train_df.info())\nprint('-'*50)\nprint(test_df.info())", "<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 36992 entries, 0 to 36991\nData columns (total 23 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 customer_id 36992 non-null object \n 1 age 36992 non-null int64 \n 2 gender 36992 non-null object \n 3 security_no 36992 non-null object \n 4 region_category 36992 non-null object \n 5 membership_category 36992 non-null object \n 6 joining_date 36992 non-null object \n 7 joined_through_referral 36992 non-null object \n 8 preferred_offer_types 36992 non-null object \n 9 medium_of_operation 36992 non-null object \n 10 internet_option 36992 non-null object \n 11 last_visit_time 36992 non-null object \n 12 days_since_last_login 36992 non-null int64 \n 13 avg_time_spent 36992 non-null float64\n 14 avg_transaction_value 36992 non-null float64\n 15 avg_frequency_login_days 36992 non-null object \n 16 points_in_wallet 36992 non-null float64\n 17 used_special_discount 36992 non-null object \n 18 offer_application_preference 36992 non-null object \n 19 past_complaint 36992 non-null object \n 20 complaint_status 36992 non-null object \n 21 feedback 36992 non-null object \n 22 churn_risk_score 36992 non-null int64 \ndtypes: float64(3), int64(3), object(17)\nmemory usage: 6.5+ MB\nNone\n--------------------------------------------------\n<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 19919 entries, 0 to 19918\nData columns (total 22 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 customer_id 19919 non-null object \n 1 age 19919 non-null int64 \n 2 gender 19919 non-null object \n 3 security_no 19919 non-null object \n 4 region_category 19919 non-null object \n 5 membership_category 19919 non-null object \n 6 joining_date 19919 non-null object \n 7 joined_through_referral 19919 non-null object \n 8 preferred_offer_types 19919 non-null object \n 9 medium_of_operation 19919 non-null object \n 10 internet_option 19919 non-null object \n 11 last_visit_time 19919 non-null object \n 12 days_since_last_login 19919 non-null int64 \n 13 avg_time_spent 19919 non-null float64\n 14 avg_transaction_value 19919 non-null float64\n 15 avg_frequency_login_days 19919 non-null object \n 16 points_in_wallet 19919 non-null float64\n 17 used_special_discount 19919 non-null object \n 18 offer_application_preference 19919 non-null object \n 19 past_complaint 19919 non-null object \n 20 complaint_status 19919 non-null object \n 21 feedback 19919 non-null object \ndtypes: float64(3), int64(2), object(17)\nmemory usage: 3.3+ MB\nNone\n" ] ], [ [ "# DATA VISUALIZATION", "_____no_output_____" ] ], [ [ "sb.distplot(train_df.age) #age is uniformly distributed", "_____no_output_____" ], [ "train_df[\"gender\"].value_counts()", "_____no_output_____" ], [ "train_df[train_df.gender == \"Unknown\"]", "_____no_output_____" ], [ "train_df.drop(train_df.index[train_df['gender'] == 'Unknown'],axis = 0, inplace = True)", "_____no_output_____" ], [ "sb.countplot(train_df.gender) #male and female is equaly distributed", "_____no_output_____" ], [ "# checking the distribution of outcomes\nsb.countplot(x = 'churn_risk_score', data = train_df)", "_____no_output_____" ], [ "sb.countplot(train_df.gender,hue=train_df.churn_risk_score)", "_____no_output_____" ], [ "cat = []\ncon = []\nfor i in train_df.columns:\n if (train_df[i].dtypes == \"object\"):\n cat.append(i)\n else:\n con.append(i)", "_____no_output_____" ] ], [ [ "# Data Preprocessing", "_____no_output_____" ] ], [ [ "from sklearn.preprocessing import LabelEncoder", "_____no_output_____" ], [ "label_encoder = LabelEncoder()\nfor i in cat:\n test_df[i]=label_encoder.fit_transform(test_df[i])", "_____no_output_____" ], [ "for i in cat:\n train_df[i]=label_encoder.fit_transform(train_df[i]) ", "_____no_output_____" ], [ "convert = [\"avg_time_spent\",\"avg_transaction_value\",\"points_in_wallet\"]\nfor k in convert:\n train_df[k] = train_df[k].astype(int)", "_____no_output_____" ], [ "for k in convert:\n test_df[k] = test_df[k].astype(int)", "_____no_output_____" ], [ "train = train_df.drop(['points_in_wallet'],axis = 1)\ntest = test_df.drop(['points_in_wallet'],axis = 1)", "_____no_output_____" ], [ "X= train.drop(columns = ['churn_risk_score'], axis=1)\ny= train[['churn_risk_score']]", "_____no_output_____" ], [ "from sklearn.preprocessing import StandardScaler\n\nX_scaled=StandardScaler().fit_transform(X)", "_____no_output_____" ] ], [ [ "### Checking Variance", "_____no_output_____" ] ], [ [ "train_df.columns", "_____no_output_____" ], [ "# checking variance\nfrom statsmodels.stats.outliers_influence import variance_inflation_factor\nvariables = train_df[['customer_id', 'age', 'gender', 'security_no', 'region_category',\n 'membership_category', 'joining_date', 'joined_through_referral',\n 'preferred_offer_types', 'medium_of_operation', 'internet_option',\n 'last_visit_time', 'days_since_last_login', 'avg_time_spent',\n 'avg_transaction_value', 'avg_frequency_login_days', 'points_in_wallet',\n 'used_special_discount', 'offer_application_preference',\n 'past_complaint', 'complaint_status', 'feedback', 'churn_risk_score']]\nvif = pd.DataFrame()\nvif['VIF'] = [variance_inflation_factor(variables.values, i) for i in range(variables.shape[1])]\nvif['Features'] = variables.columns", "_____no_output_____" ], [ "vif", "_____no_output_____" ] ], [ [ "# model building", "_____no_output_____" ] ], [ [ "from sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X_scaled, y, test_size=0.2, random_state=0) ", "_____no_output_____" ], [ "pd.DataFrame(X_scaled).describe()", "_____no_output_____" ] ], [ [ "#### Decision Tree Model", "_____no_output_____" ] ], [ [ "from sklearn.tree import DecisionTreeClassifier\nclf = DecisionTreeClassifier()", "_____no_output_____" ] ], [ [ "#### Using GridSearchCV for finding best parameters", "_____no_output_____" ] ], [ [ "gs=GridSearchCV(clf,\n {\n 'max_depth':range(3,10),\n 'min_samples_split':range(10,100,10)\n },\n cv=5,\n n_jobs=2,\n scoring='neg_mean_squared_error',\n verbose=2\n )\n\ngs.fit(X_train,y_train)\nclf=gs.best_estimator_\nclf.fit(X_train,y_train)\nprint(gs.best_params_)", "Fitting 5 folds for each of 63 candidates, totalling 315 fits\n{'max_depth': 6, 'min_samples_split': 30}\n" ] ], [ [ "#### Making Predictions", "_____no_output_____" ] ], [ [ "pred = clf.predict(X_test)", "_____no_output_____" ] ], [ [ "#### Checking Accuracy", "_____no_output_____" ] ], [ [ "score = clf.score(X_test, y_test)\nscore", "_____no_output_____" ] ], [ [ "0.570867740625423", "_____no_output_____" ] ], [ [ "from sklearn import tree\ns = plt.figure(figsize=(20,10))\ntree.plot_tree(clf, max_depth=3, filled=True, fontsize=10)\nplt.title(\"Decision Tree for Customer Churn Data\", fontsize=30)\nplt.show() ", "_____no_output_____" ] ], [ [ "#### Random Forrest", "_____no_output_____" ] ], [ [ "from sklearn.ensemble import RandomForestClassifier\nrf = RandomForestClassifier(min_samples_split=20)", "_____no_output_____" ] ], [ [ "##### Randomized Grid Search CV", "_____no_output_____" ] ], [ [ "gs=RandomizedSearchCV(rf,\n {\n 'criterion':('gini', 'entropy'),\n 'n_estimators':np.linspace(50,200,5).astype(int)\n #'min_samples_split':range(5,105,20)\n },\n cv=5,\n n_jobs=2,\n scoring='neg_mean_squared_error',\n )\n\ngs.fit(X_train,y_train)\nrf=gs.best_estimator_\nrf.fit(X_train,y_train)\nprint(gs.best_params_)", "Fitting 5 folds for each of 10 candidates, totalling 50 fits\n{'n_estimators': 200, 'criterion': 'gini'}\n" ] ], [ [ "#### Prediction", "_____no_output_____" ] ], [ [ "pred1 = rf.predict(X_test)", "_____no_output_____" ] ], [ [ "#### Checking Accuracy", "_____no_output_____" ] ], [ [ "score1 = rf.score(X_test, y_test)\nscore1", "_____no_output_____" ], [ "rf.score(X_train,y_train)", "_____no_output_____" ] ], [ [ "0.6302964667659402", "_____no_output_____" ], [ "#### Gradient Boosting Classifier ", "_____no_output_____" ] ], [ [ "from sklearn.ensemble import GradientBoostingClassifier\ngb = GradientBoostingClassifier(n_estimators=500,max_depth=5)", "_____no_output_____" ], [ "gb.fit(X_train,y_train)", "_____no_output_____" ] ], [ [ "#### Prediction", "_____no_output_____" ] ], [ [ "pred2 = gb.predict(X_test)", "_____no_output_____" ] ], [ [ "#### Checking Accuracy", "_____no_output_____" ] ], [ [ "score2 = gb.score(X_test, y_test)\nscore2", "_____no_output_____" ] ], [ [ "0.6376066062000812\n", "_____no_output_____" ], [ "#### AdaBoostClassifier", "_____no_output_____" ] ], [ [ "from sklearn.ensemble import AdaBoostClassifier\nad = AdaBoostClassifier()", "_____no_output_____" ] ], [ [ "##### Randomized Grid Search CV", "_____no_output_____" ] ], [ [ "gs=RandomizedSearchCV(ad,\n {\n 'learning_rate':np.logspace(-2,2,5),\n 'n_estimators':np.linspace(20,1020,5).astype(int),\n 'algorithm':('SAMME', 'SAMME.R')\n \n },\n cv=2,\n n_jobs=2,\n scoring='neg_mean_squared_error',\n verbose=2\n )\n\ngs.fit(X_train,y_train)\nad=gs.best_estimator_\nad.fit(X_train,y_train)\nprint(gs.best_params_)", "Fitting 2 folds for each of 10 candidates, totalling 20 fits\n{'n_estimators': 1020, 'learning_rate': 1.0, 'algorithm': 'SAMME'}\n" ] ], [ [ "#### Prediction", "_____no_output_____" ] ], [ [ "pred3 = ad.predict(X_test)", "_____no_output_____" ] ], [ [ "#### Checking Accuracy", "_____no_output_____" ] ], [ [ "score3 = ad.score(X_test, y_test)\nscore3", "_____no_output_____" ] ], [ [ "GRADIENT BOOSTING IS THE PREDICTOR AMONG THOSE MODELS", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
4a0bf6fd54773fc7d69a17235e5717a8ba3617aa
27,460
ipynb
Jupyter Notebook
ai/pixelcnn/notebook.ipynb
admariner/playground
02a3104472c8fa3589fe87f7265e70c61d5728c7
[ "MIT" ]
3
2021-06-12T04:42:32.000Z
2021-06-24T13:57:38.000Z
ai/pixelcnn/notebook.ipynb
admariner/playground
02a3104472c8fa3589fe87f7265e70c61d5728c7
[ "MIT" ]
null
null
null
ai/pixelcnn/notebook.ipynb
admariner/playground
02a3104472c8fa3589fe87f7265e70c61d5728c7
[ "MIT" ]
1
2021-08-19T14:57:17.000Z
2021-08-19T14:57:17.000Z
226.942149
24,768
0.924727
[ [ [ "import numpy as np\nimport tensorflow as tf\nimport matplotlib.pyplot as plt", "_____no_output_____" ], [ "model = tf.keras.models.load_model('model/pixel_cnn')", "_____no_output_____" ], [ "h = 28\nw = 28\ngrid_row = 5\ngrid_col = 5\nbatch = grid_row * grid_col\nimages = np.ones((batch, h, w, 1), dtype=np.float32)\nimages[0].shape", "_____no_output_____" ], [ "for row in range(h):\n for col in range(w):\n prob = model.predict(images)[:, row,col, 0]\n pixel_samples = tf.random.categorical(tf.math.log(np.stack([1-prob, prob], 1)), 1)\n images[:,row,col,0] = tf.reshape(pixel_samples, [batch])", "_____no_output_____" ], [ "f, axarr = plt.subplots(grid_row, grid_col, figsize=(grid_col * 1.1, grid_row))\n\ni = 0\nfor row in range(grid_row):\n for col in range(grid_col):\n axarr[row,col].imshow(images[i, :, :, 0], cmap='gray')\n axarr[row,col].axis('off')\n i += 1\n\nf.tight_layout(pad=0.1, h_pad=0.2, w_pad=0.1)", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code" ] ]
4a0c1b2410595a5248b63008a56033d9f963b286
12,196
ipynb
Jupyter Notebook
day2.ipynb
veeresh745/Demo-Github-Testing
e4ea4eb2d6da0700716919cf7128dcb42dbe125a
[ "MIT" ]
null
null
null
day2.ipynb
veeresh745/Demo-Github-Testing
e4ea4eb2d6da0700716919cf7128dcb42dbe125a
[ "MIT" ]
null
null
null
day2.ipynb
veeresh745/Demo-Github-Testing
e4ea4eb2d6da0700716919cf7128dcb42dbe125a
[ "MIT" ]
null
null
null
29.387952
231
0.330436
[ [ [ "<a href=\"https://colab.research.google.com/github/veeresh745/Demo-Github-Testing/blob/main/day2.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ] ], [ [ "## loading dataset\nimport pandas as pd", "_____no_output_____" ], [ "dataframe=pd.read_csv(\"train.csv\")", "_____no_output_____" ], [ "#viewing dataset\ndataframe.head()", "_____no_output_____" ], [ "dataframe.info()", "<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 891 entries, 0 to 890\nData columns (total 12 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 PassengerId 891 non-null int64 \n 1 Survived 891 non-null int64 \n 2 Pclass 891 non-null int64 \n 3 Name 891 non-null object \n 4 Sex 891 non-null object \n 5 Age 714 non-null float64\n 6 SibSp 891 non-null int64 \n 7 Parch 891 non-null int64 \n 8 Ticket 891 non-null object \n 9 Fare 891 non-null float64\n 10 Cabin 204 non-null object \n 11 Embarked 889 non-null object \ndtypes: float64(2), int64(5), object(5)\nmemory usage: 83.7+ KB\n" ], [ "## checking missing values\n## in pthon the missing values denoted by NAN or none\ndataframe.isnull().sum()", "_____no_output_____" ], [ "## ways to track missing values\n## replace the values, drop the rows that contain missing values\n", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "", "_____no_output_____" ], [ "dataframe=dataframe.dropna()", "_____no_output_____" ], [ "dataframe.isnull().sum()", "_____no_output_____" ], [ "dataframe.shape", "_____no_output_____" ], [ "", "_____no_output_____" ] ] ]
[ "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
4a0c21a63ea36384d181e3b0d4b4fd349de07e72
17,647
ipynb
Jupyter Notebook
tutorial/253_ttn_en.ipynb
ryuNagai/Blueqat-tutorials
53dcad86d028ac7113f9f0368b9529c213253af2
[ "Apache-2.0" ]
1
2022-02-09T02:10:48.000Z
2022-02-09T02:10:48.000Z
tutorial/253_ttn_en.ipynb
ryuNagai/Blueqat-tutorials
53dcad86d028ac7113f9f0368b9529c213253af2
[ "Apache-2.0" ]
null
null
null
tutorial/253_ttn_en.ipynb
ryuNagai/Blueqat-tutorials
53dcad86d028ac7113f9f0368b9529c213253af2
[ "Apache-2.0" ]
null
null
null
61.919298
9,848
0.771803
[ [ [ "# Quantum Machine Learning and TTN\nLet's look at the Tree Tensor Network as a model for quantum machine learning.\n\n## What you will learn\n1. TTN model\n2. Optimization", "_____no_output_____" ], [ "## Install Blueqat", "_____no_output_____" ] ], [ [ "!pip install blueqat", "Requirement already satisfied: blueqat in /home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages (0.3.13)\nRequirement already satisfied: scipy>=1.1.0 in /home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages (from blueqat) (1.1.0)\nRequirement already satisfied: numpy~=1.12 in /home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages (from blueqat) (1.18.4)\n\u001b[31mdwave-cloud-client 0.7.2 has requirement click>=7.0, but you'll have click 6.7 which is incompatible.\u001b[0m\n\u001b[33mYou are using pip version 10.0.1, however version 20.1 is available.\nYou should consider upgrading via the 'pip install --upgrade pip' command.\u001b[0m\n" ] ], [ [ "The model we are going to build is called TTN. The quantum circuit is as follows.\n\n<img src=\"../tutorial-ja/img/253_img.png\" width=\"25%\">\n\nIt has a shape that takes on tree structure. \nThis circuit uses a one qubit arbitrary rotation gate (a combination of $Rz$ and $Ry$ gates) and a two qubit gate ($CX$ gate). \nMore details are as follows.\n\n<img src=\"../tutorial-ja/img/253_img_2.png\" width=\"35%\">", "_____no_output_____" ] ], [ [ "from blueqat import Circuit\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport time\n%matplotlib inline", "_____no_output_____" ] ], [ [ "Configure hyperparameters and other settings.", "_____no_output_____" ] ], [ [ "np.random.seed(45)\n\n# Number of steps of optimizetaion\nnsteps = 2000\n\n# Number of parameters of the quantum circuit to be optimized\nnparams = 18\n\n# Fineness of numerical differentiation\nh = 0.01\n\n# Learning rate\ne = 0.01\n\n# Initial parameter\nparam_init = [np.random.rand()*np.pi*2 for i in range(nparams)]\n\n# list for containing results\narr = []\n\n#1: train, 2: prediction\nmode = 1", "_____no_output_____" ] ], [ [ "We create a model of the tree structure. \nSet upthe input to the quantum circuit and the target label for it and start learning. \nThis time, the input data can be selected by arguments.", "_____no_output_____" ] ], [ [ "def TTN_Z(a, ran, mode=1):\n \n # Input circuit\n init = [Circuit(4).x[0,1], Circuit(4).x[2,3], Circuit(4).x[0], Circuit(4).x[1], Circuit(4).x[2], Circuit(4).x[0,2]]\n # Target label\n target = [1,1,-1,-1,-1,1]\n \n # Circuit construction\n u = init[ran]\n u.rz(a[0])[0].ry(a[1])[0].rz(a[2])[0]\n u.rz(a[3])[1].ry(a[4])[1].rz(a[5])[1]\n u.rz(a[6])[2].ry(a[7])[2].rz(a[8])[2]\n u.rz(a[9])[3].ry(a[10])[3].rz(a[11])[3]\n u.cx[0,1].cx[2,3]\n u.rz(a[12])[1].ry(a[13])[1].rz(a[14])[1]\n u.rz(a[15])[3].ry(a[16])[3].rz(a[17])[3]\n u.cx[1,3]\n \n # Calculate expectation value from state vector\n full = u.run()\n expt = sum(np.abs(full[:8])**2)-sum(np.abs(full[8:])**2)\n \n if(mode ==1):\n # return error between label and prediction\n return (expt - target[ran])**2\n else:\n return expt", "_____no_output_____" ] ], [ [ "Stochastic gradient descent (SGD) is used to learning.\nAt the start of each step, the input data is randomly selected from 6 ways (0 to 5), and the gradient is calculated and the parameters are updated.\n\nIn each step, the gradient calculation and parameter update are performed on only one data, but by repeating the process while randomly selecting input data, the system eventually learns to minimize the loss function for all data.", "_____no_output_____" ] ], [ [ "start = time.time()\n\nparam = param_init.copy()\nfor i in range(nsteps):\n it = np.random.randint(0,6)\n \n loss = TTN_Z(param, it, mode)\n arr.append(loss)\n param_new = [0 for i in range(nparams)]\n \n for j in range(nparams):\n _param = param.copy()\n _param[j] += h\n param_new[j] = param[j] - e*(TTN_Z(_param, it, mode) - loss)/h\n\n param = param_new\n\nplt.plot(arr)\nplt.show()\nprint(time.time() - start)", "_____no_output_____" ] ], [ [ "It converged well. \nLet's check it out.", "_____no_output_____" ] ], [ [ "target = [1,1,-1,-1,-1,1]\npreds = []\nfor i in range(6):\n pred = TTN_Z(param, i, mode=2)\n preds.append(pred)\n print(\"Prediction :\", pred, \" Target :\", target[i])", "Prediction : 0.9884934363107443 Target : 1\nPrediction : 0.9842263178153033 Target : 1\nPrediction : -0.9884934363107445 Target : -1\nPrediction : -0.9862086284188133 Target : -1\nPrediction : -0.9842263178153033 Target : -1\nPrediction : 0.9865065331709494 Target : 1\n" ] ], [ [ "From the above, we were able to learn a quantum circuit using the TTN model.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
4a0c2be5d5f4d619451d8b2b4a60fc3d71833109
186,625
ipynb
Jupyter Notebook
covid_19.ipynb
DhruvAwasthi/COVID19Tracker
927f5bd95802affdc08dd47de9b4a255679a962c
[ "Apache-2.0" ]
2
2020-06-09T08:01:04.000Z
2020-10-22T16:53:16.000Z
covid_19.ipynb
DhruvAwasthi/COVID19Tracker
927f5bd95802affdc08dd47de9b4a255679a962c
[ "Apache-2.0" ]
null
null
null
covid_19.ipynb
DhruvAwasthi/COVID19Tracker
927f5bd95802affdc08dd47de9b4a255679a962c
[ "Apache-2.0" ]
null
null
null
217.25844
114,968
0.829401
[ [ [ "# Importing needed libraries\nimport datetime\nimport pandas as pd\n\n# Fetching the data from official site of Ministry of Health and Family Welfare | Government of India\ntry:\n url = \"https://www.mohfw.gov.in/\"\n dfs = pd.read_html(url)\n\n for i in range(len(dfs)):\n df = dfs[i]\n if (len(df.columns) == 6):\n cols_match = sum(df.columns==['S. No.', 'Name of State / UT', 'Active Cases*',\n 'Cured/Discharged/Migrated*', 'Deaths**', 'Total Confirmed cases*'])\n if (cols_match == 6):\n now = datetime.datetime.now()\n dt_string = now.strftime(\"%d/%m/%Y %H:%M:%S\")\n df.to_csv(\"/home/caesar/covid_19.csv\")\n break\nexcept:\n df = pd.read_csv(\"/home/caesar/covid_19.csv\")\n df = df.drop(columns=[\"Unnamed: 0\"]) \n now = datetime.datetime.fromtimestamp(os.path.getmtime(\"/home/caesar/covid_19.csv\"))\n dt_string = now.strftime(\"%d/%m/%Y %H:%M:%S\")\n\ndf", "_____no_output_____" ], [ "# Preprocessing the column data to remove any special characters inbetween because we cannot rely on the source completely.\nfor col in ['Active Cases*', 'Cured/Discharged/Migrated*', 'Deaths**', 'Total Confirmed cases*' ]:\n if df[col].dtypes=='O':\n df[col] = df[col].str.replace('\\W', '')", "_____no_output_____" ], [ "# Fetching out the values from the DataFrame \nm = 35\nstates = df[\"Name of State / UT\"][:m]\nactive_cases = df[\"Active Cases*\"][:m].astype(int)\nconfirmed_cases = df[\"Total Confirmed cases*\"][:m].astype(int)\ncasualties = df[\"Deaths**\"][:m].astype(int)", "_____no_output_____" ], [ "# Plotting the bar graph!\n%matplotlib inline\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nmax_cases = max(active_cases)\ntotal_active_cases = int(df[\"Active Cases*\"][36])\ntotal_death_casualties = df[\"Deaths**\"][36]\ntotal_cured_cases = df[\"Cured/Discharged/Migrated*\"][36]\ntotal_confirmed_cases = df[\"Total Confirmed cases*\"][36]\nbarWidth = 0.4\nr1 = np.arange(len(active_cases))\nr2 = [x + barWidth for x in r1]\n\nplt.figure(figsize=(16, 8))\nplt.bar(r1, active_cases, color=\"royalblue\", width=barWidth, edgecolor=\"white\", label=\"Active Cases\")\nplt.bar(r2, casualties, color=\"orchid\", width=barWidth, edgecolor=\"white\", label=\"Death Casualties\")\nplt.xlabel(\"States / UT\", fontweight=\"bold\", fontsize=16)\nplt.xticks([r + barWidth - 0.19 for r in range(len(active_cases))], states, rotation=\"78\", fontsize=14)\nplt.ylabel(\"Number of COVID-19 cases\", fontweight=\"bold\", fontsize=16)\nplt.legend(fontsize=16, loc=\"upper right\")\nplt.text(-1, max_cases, \"Total active cases: \" + str(total_active_cases), fontsize=16)\nplt.text(-1, max_cases - 2000, \"Total death casualties: \" + str(total_death_casualties), fontsize=16)\nplt.text(-1, max_cases - 4000, \"Total cured cases: \" + str(total_cured_cases), fontsize=16)\nplt.title(\"Data updated at: \" + dt_string, loc=\"center\")\nplt.show()", "_____no_output_____" ], [ "# A more visualistic comparison!\n\nmortality_rate = str(round(total_active_cases / int(total_confirmed_cases), 2))\nsizes=[total_confirmed_cases, total_active_cases]\nnames=[\"Total Confirmed Cases\", \"Total Active Cases\"]\nplt.pie(sizes, explode=(0, 0.1), labels=names, autopct='%1.1f%%', shadow=True, startangle=90)\nplt.text(-1, 1.2, \"Mortality Rate: \" + mortality_rate, fontsize=16)\nplt.show()", "_____no_output_____" ], [ "# In case you need a more fancy donut-like graph!\nfrom palettable.colorbrewer.qualitative import Pastel1_7\nsizes=[total_confirmed_cases, total_active_cases]\nnames=[\"Total Confirmed Cases\", \"Total Active Cases\"]\nmy_circle=plt.Circle((0,0), 0.7, color='white')\nplt.pie(sizes, labels=names, colors=Pastel1_7.hex_colors, autopct='%1.1f%%', explode=(0, 0.1))\np=plt.gcf()\np.gca().add_artist(my_circle)\nplt.text(-1, 1.2, \"Mortality Rate: \" + mortality_rate, fontsize=16)\nplt.show()", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code" ] ]
4a0c35a89ea7e8eaec4bc39a5dc120fe8601b59f
33,221
ipynb
Jupyter Notebook
machine_translation.ipynb
joelcampusanorojas/nlp_machine_translation
7cf05e862dcc2f62b8606d04088b88f4c998f7a1
[ "MIT" ]
1
2020-11-10T02:02:33.000Z
2020-11-10T02:02:33.000Z
machine_translation.ipynb
joelcampusanorojas/nlp_machine_translation
7cf05e862dcc2f62b8606d04088b88f4c998f7a1
[ "MIT" ]
null
null
null
machine_translation.ipynb
joelcampusanorojas/nlp_machine_translation
7cf05e862dcc2f62b8606d04088b88f4c998f7a1
[ "MIT" ]
null
null
null
42.700514
614
0.629572
[ [ [ "# Artificial Intelligence Nanodegree\n## Machine Translation Project\nIn this notebook, sections that end with **'(IMPLEMENTATION)'** in the header indicate that the following blocks of code will require additional functionality which you must provide. Please be sure to read the instructions carefully!\n\n## Introduction\nIn this notebook, you will build a deep neural network that functions as part of an end-to-end machine translation pipeline. Your completed pipeline will accept English text as input and return the French translation.\n\n- **Preprocess** - You'll convert text to sequence of integers.\n- **Models** Create models which accepts a sequence of integers as input and returns a probability distribution over possible translations. After learning about the basic types of neural networks that are often used for machine translation, you will engage in your own investigations, to design your own model!\n- **Prediction** Run the model on English text.", "_____no_output_____" ] ], [ [ "%load_ext autoreload\n%aimport helper, tests\n%autoreload 1", "_____no_output_____" ], [ "import collections\n\nimport helper\nimport numpy as np\nimport project_tests as tests\n\nfrom keras.preprocessing.text import Tokenizer\nfrom keras.preprocessing.sequence import pad_sequences\nfrom keras.models import Model\nfrom keras.layers import GRU, Input, Dense, TimeDistributed, Activation, RepeatVector, Bidirectional\nfrom keras.layers.embeddings import Embedding\nfrom keras.optimizers import Adam\nfrom keras.losses import sparse_categorical_crossentropy", "_____no_output_____" ] ], [ [ "### Verify access to the GPU\nThe following test applies only if you expect to be using a GPU, e.g., while running in a Udacity Workspace or using an AWS instance with GPU support. Run the next cell, and verify that the device_type is \"GPU\".\n- If the device is not GPU & you are running from a Udacity Workspace, then save your workspace with the icon at the top, then click \"enable\" at the bottom of the workspace.\n- If the device is not GPU & you are running from an AWS instance, then refer to the cloud computing instructions in the classroom to verify your setup steps.", "_____no_output_____" ] ], [ [ "from tensorflow.python.client import device_lib\nprint(device_lib.list_local_devices())", "_____no_output_____" ] ], [ [ "## Dataset\nWe begin by investigating the dataset that will be used to train and evaluate your pipeline. The most common datasets used for machine translation are from [WMT](http://www.statmt.org/). However, that will take a long time to train a neural network on. We'll be using a dataset we created for this project that contains a small vocabulary. You'll be able to train your model in a reasonable time with this dataset.\n### Load Data\nThe data is located in `data/small_vocab_en` and `data/small_vocab_fr`. The `small_vocab_en` file contains English sentences with their French translations in the `small_vocab_fr` file. Load the English and French data from these files from running the cell below.", "_____no_output_____" ] ], [ [ "# Load English data\nenglish_sentences = helper.load_data('data/small_vocab_en')\n# Load French data\nfrench_sentences = helper.load_data('data/small_vocab_fr')\n\nprint('Dataset Loaded')", "_____no_output_____" ] ], [ [ "### Files\nEach line in `small_vocab_en` contains an English sentence with the respective translation in each line of `small_vocab_fr`. View the first two lines from each file.", "_____no_output_____" ] ], [ [ "for sample_i in range(2):\n print('small_vocab_en Line {}: {}'.format(sample_i + 1, english_sentences[sample_i]))\n print('small_vocab_fr Line {}: {}'.format(sample_i + 1, french_sentences[sample_i]))", "_____no_output_____" ] ], [ [ "From looking at the sentences, you can see they have been preprocessed already. The puncuations have been delimited using spaces. All the text have been converted to lowercase. This should save you some time, but the text requires more preprocessing.\n### Vocabulary\nThe complexity of the problem is determined by the complexity of the vocabulary. A more complex vocabulary is a more complex problem. Let's look at the complexity of the dataset we'll be working with.", "_____no_output_____" ] ], [ [ "english_words_counter = collections.Counter([word for sentence in english_sentences for word in sentence.split()])\nfrench_words_counter = collections.Counter([word for sentence in french_sentences for word in sentence.split()])\n\nprint('{} English words.'.format(len([word for sentence in english_sentences for word in sentence.split()])))\nprint('{} unique English words.'.format(len(english_words_counter)))\nprint('10 Most common words in the English dataset:')\nprint('\"' + '\" \"'.join(list(zip(*english_words_counter.most_common(10)))[0]) + '\"')\nprint()\nprint('{} French words.'.format(len([word for sentence in french_sentences for word in sentence.split()])))\nprint('{} unique French words.'.format(len(french_words_counter)))\nprint('10 Most common words in the French dataset:')\nprint('\"' + '\" \"'.join(list(zip(*french_words_counter.most_common(10)))[0]) + '\"')", "_____no_output_____" ] ], [ [ "For comparison, _Alice's Adventures in Wonderland_ contains 2,766 unique words of a total of 15,500 words.\n## Preprocess\nFor this project, you won't use text data as input to your model. Instead, you'll convert the text into sequences of integers using the following preprocess methods:\n1. Tokenize the words into ids\n2. Add padding to make all the sequences the same length.\n\nTime to start preprocessing the data...\n### Tokenize (IMPLEMENTATION)\nFor a neural network to predict on text data, it first has to be turned into data it can understand. Text data like \"dog\" is a sequence of ASCII character encodings. Since a neural network is a series of multiplication and addition operations, the input data needs to be number(s).\n\nWe can turn each character into a number or each word into a number. These are called character and word ids, respectively. Character ids are used for character level models that generate text predictions for each character. A word level model uses word ids that generate text predictions for each word. Word level models tend to learn better, since they are lower in complexity, so we'll use those.\n\nTurn each sentence into a sequence of words ids using Keras's [`Tokenizer`](https://keras.io/preprocessing/text/#tokenizer) function. Use this function to tokenize `english_sentences` and `french_sentences` in the cell below.\n\nRunning the cell will run `tokenize` on sample data and show output for debugging.", "_____no_output_____" ] ], [ [ "def tokenize(x):\n \"\"\"\n Tokenize x\n :param x: List of sentences/strings to be tokenized\n :return: Tuple of (tokenized x data, tokenizer used to tokenize x)\n \"\"\"\n # TODO: Implement\n #x_tk = Tokenizer(char_level=True)\n x_tk = Tokenizer(num_words=None, char_level=False)\n x_tk.fit_on_texts(x)\n\n return x_tk.texts_to_sequences(x), x_tk\n #return None, None\n\ntests.test_tokenize(tokenize)\n\n# Tokenize Example output\ntext_sentences = [\n 'The quick brown fox jumps over the lazy dog .',\n 'By Jove , my quick study of lexicography won a prize .',\n 'This is a short sentence .']\ntext_tokenized, text_tokenizer = tokenize(text_sentences)\nprint(text_tokenizer.word_index)\nprint()\nfor sample_i, (sent, token_sent) in enumerate(zip(text_sentences, text_tokenized)):\n print('Sequence {} in x'.format(sample_i + 1))\n print(' Input: {}'.format(sent))\n print(' Output: {}'.format(token_sent))", "_____no_output_____" ] ], [ [ "### Padding (IMPLEMENTATION)\nWhen batching the sequence of word ids together, each sequence needs to be the same length. Since sentences are dynamic in length, we can add padding to the end of the sequences to make them the same length.\n\nMake sure all the English sequences have the same length and all the French sequences have the same length by adding padding to the **end** of each sequence using Keras's [`pad_sequences`](https://keras.io/preprocessing/sequence/#pad_sequences) function.", "_____no_output_____" ] ], [ [ "def pad(x, length=None):\n \"\"\"\n Pad x\n :param x: List of sequences.\n :param length: Length to pad the sequence to. If None, use length of longest sequence in x.\n :return: Padded numpy array of sequences\n \"\"\"\n # TODO: Implement\n #return None\n if length is None:\n length = max([len(sentence) for sentence in x])\n #return pad_sequences(x, maxlen=length, padding='post')\n return pad_sequences(x, maxlen=length, padding='post', truncating='post')\n\n\ntests.test_pad(pad)\n\n# Pad Tokenized output\ntest_pad = pad(text_tokenized)\nfor sample_i, (token_sent, pad_sent) in enumerate(zip(text_tokenized, test_pad)):\n print('Sequence {} in x'.format(sample_i + 1))\n print(' Input: {}'.format(np.array(token_sent)))\n print(' Output: {}'.format(pad_sent))", "_____no_output_____" ] ], [ [ "### Preprocess Pipeline\nYour focus for this project is to build neural network architecture, so we won't ask you to create a preprocess pipeline. Instead, we've provided you with the implementation of the `preprocess` function.", "_____no_output_____" ] ], [ [ "def preprocess(x, y):\n \"\"\"\n Preprocess x and y\n :param x: Feature List of sentences\n :param y: Label List of sentences\n :return: Tuple of (Preprocessed x, Preprocessed y, x tokenizer, y tokenizer)\n \"\"\"\n preprocess_x, x_tk = tokenize(x)\n preprocess_y, y_tk = tokenize(y)\n\n preprocess_x = pad(preprocess_x)\n preprocess_y = pad(preprocess_y)\n\n # Keras's sparse_categorical_crossentropy function requires the labels to be in 3 dimensions\n preprocess_y = preprocess_y.reshape(*preprocess_y.shape, 1)\n\n return preprocess_x, preprocess_y, x_tk, y_tk\n\npreproc_english_sentences, preproc_french_sentences, english_tokenizer, french_tokenizer =\\\n preprocess(english_sentences, french_sentences)\n \nmax_english_sequence_length = preproc_english_sentences.shape[1]\nmax_french_sequence_length = preproc_french_sentences.shape[1]\nenglish_vocab_size = len(english_tokenizer.word_index)\nfrench_vocab_size = len(french_tokenizer.word_index)\n\nprint('Data Preprocessed')\nprint(\"Max English sentence length:\", max_english_sequence_length)\nprint(\"Max French sentence length:\", max_french_sequence_length)\nprint(\"English vocabulary size:\", english_vocab_size)\nprint(\"French vocabulary size:\", french_vocab_size)", "_____no_output_____" ] ], [ [ "## Models\nIn this section, you will experiment with various neural network architectures.\nYou will begin by training four relatively simple architectures.\n- Model 1 is a simple RNN\n- Model 2 is a RNN with Embedding\n- Model 3 is a Bidirectional RNN\n- Model 4 is an optional Encoder-Decoder RNN\n\nAfter experimenting with the four simple architectures, you will construct a deeper architecture that is designed to outperform all four models.\n### Ids Back to Text\nThe neural network will be translating the input to words ids, which isn't the final form we want. We want the French translation. The function `logits_to_text` will bridge the gab between the logits from the neural network to the French translation. You'll be using this function to better understand the output of the neural network.", "_____no_output_____" ] ], [ [ "def logits_to_text(logits, tokenizer):\n \"\"\"\n Turn logits from a neural network into text using the tokenizer\n :param logits: Logits from a neural network\n :param tokenizer: Keras Tokenizer fit on the labels\n :return: String that represents the text of the logits\n \"\"\"\n index_to_words = {id: word for word, id in tokenizer.word_index.items()}\n index_to_words[0] = '<PAD>'\n\n return ' '.join([index_to_words[prediction] for prediction in np.argmax(logits, 1)])\n\nprint('`logits_to_text` function loaded.')", "_____no_output_____" ] ], [ [ "### Model 1: RNN (IMPLEMENTATION)\n![RNN](images/rnn.png)\nA basic RNN model is a good baseline for sequence data. In this model, you'll build a RNN that translates English to French.", "_____no_output_____" ] ], [ [ "def simple_model(input_shape, output_sequence_length, english_vocab_size, french_vocab_size):\n \"\"\"\n Build and train a basic RNN on x and y\n :param input_shape: Tuple of input shape\n :param output_sequence_length: Length of output sequence\n :param english_vocab_size: Number of unique English words in the dataset\n :param french_vocab_size: Number of unique French words in the dataset\n :return: Keras model built, but not trained\n \"\"\"\n # TODO: Build the layers\n learning_rate = 0.01\n\n input_seq = Input(input_shape[1:])\n rnn = GRU(output_sequence_length, return_sequences=True)(input_seq)\n #logits = TimeDistributed(Dense(french_vocab_size))(rnn)\n logits = TimeDistributed(Dense(french_vocab_size, activation='softmax'))(rnn)\n \n #model = None\n #model = Model(input_seq, Activation('softmax')(logits))\n model = Model(inputs=input_seq, outputs=logits)\n model.compile(loss=sparse_categorical_crossentropy,\n optimizer=Adam(learning_rate),\n metrics=['accuracy'])\n return model\n\ntests.test_simple_model(simple_model)\n\n# Reshaping the input to work with a basic RNN\ntmp_x = pad(preproc_english_sentences, max_french_sequence_length)\ntmp_x = tmp_x.reshape((-1, preproc_french_sentences.shape[-2], 1))\n\n# Train the neural network\nsimple_rnn_model = simple_model(\n tmp_x.shape,\n max_french_sequence_length,\n english_vocab_size,\n french_vocab_size)\nsimple_rnn_model.fit(tmp_x, preproc_french_sentences, batch_size=1024, epochs=10, validation_split=0.2)\n\n# Print prediction(s)\nprint(logits_to_text(simple_rnn_model.predict(tmp_x[:1])[0], french_tokenizer))", "_____no_output_____" ] ], [ [ "### Model 2: Embedding (IMPLEMENTATION)\n![RNN](images/embedding.png)\nYou've turned the words into ids, but there's a better representation of a word. This is called word embeddings. An embedding is a vector representation of the word that is close to similar words in n-dimensional space, where the n represents the size of the embedding vectors.\n\nIn this model, you'll create a RNN model using embedding.", "_____no_output_____" ] ], [ [ "def embed_model(input_shape, output_sequence_length, english_vocab_size, french_vocab_size):\n \"\"\"\n Build and train a RNN model using word embedding on x and y\n :param input_shape: Tuple of input shape\n :param output_sequence_length: Length of output sequence\n :param english_vocab_size: Number of unique English words in the dataset\n :param french_vocab_size: Number of unique French words in the dataset\n :return: Keras model built, but not trained\n \"\"\"\n # TODO: Implement\n learning_rate = 0.01\n\n input_seq = Input(input_shape[1:])\n \n embedding_layer = Embedding(input_dim=english_vocab_size, output_dim=output_sequence_length, mask_zero=False)(input_seq) \n rnn = GRU(output_sequence_length, return_sequences=True)(embedding_layer)\n logits = TimeDistributed(Dense(french_vocab_size, activation='softmax'))(rnn)\n \n model = Model(inputs=input_seq, outputs=logits)\n model.compile(loss=sparse_categorical_crossentropy,\n optimizer=Adam(learning_rate),\n metrics=['accuracy'])\n return model\n \n #return None\n\ntests.test_embed_model(embed_model)\n\n\n# TODO: Reshape the input\ntmp_x = pad(preproc_english_sentences, preproc_french_sentences.shape[1])\ntmp_x = tmp_x.reshape((-1, preproc_french_sentences.shape[-2]))\n\n# TODO: Train the neural network\nembed_rnn_model = embed_model(\n tmp_x.shape,\n preproc_french_sentences.shape[1],\n len(english_tokenizer.word_index) + 1,\n len(french_tokenizer.word_index) + 1)\nembed_rnn_model.summary()\nembed_rnn_model.fit(tmp_x, preproc_french_sentences, batch_size=1024, epochs=10, validation_split=0.2)\n\n# TODO: Print prediction(s)\nprint(logits_to_text(embed_rnn_model.predict(tmp_x[:1])[0], french_tokenizer))", "_____no_output_____" ] ], [ [ "### Model 3: Bidirectional RNNs (IMPLEMENTATION)\n![RNN](images/bidirectional.png)\nOne restriction of a RNN is that it can't see the future input, only the past. This is where bidirectional recurrent neural networks come in. They are able to see the future data.", "_____no_output_____" ] ], [ [ "from keras.layers import Bidirectional\n\ndef bd_model(input_shape, output_sequence_length, english_vocab_size, french_vocab_size):\n \"\"\"\n Build and train a bidirectional RNN model on x and y\n :param input_shape: Tuple of input shape\n :param output_sequence_length: Length of output sequence\n :param english_vocab_size: Number of unique English words in the dataset\n :param french_vocab_size: Number of unique French words in the dataset\n :return: Keras model built, but not trained\n \"\"\"\n # TODO: Implement\n #Config Hyperparameters\n learning_rate = 0.01\n \n #Create Model\n inputs = Input(shape=input_shape[1:])\n hidden_layer = Bidirectional(GRU(output_sequence_length, return_sequences=True))(inputs)\n outputs = TimeDistributed(Dense(french_vocab_size, activation='softmax'))(hidden_layer)\n \n #Create Model from parameters defined above\n model = Model(inputs=inputs, outputs=outputs)\n model.compile(loss=sparse_categorical_crossentropy,\n optimizer=Adam(learning_rate),\n metrics=['accuracy'])\n \n #return None\n return model\n\ntests.test_bd_model(bd_model)\n\ntmp_x = pad(preproc_english_sentences, preproc_french_sentences.shape[1])\ntmp_x = tmp_x.reshape((-1, preproc_french_sentences.shape[-2], 1))\n\n# TODO: Train and Print prediction(s)\n# Train the neural network\nbd_rnn_model = bd_model(\n tmp_x.shape,\n preproc_french_sentences.shape[1],\n len(english_tokenizer.word_index) + 1,\n len(french_tokenizer.word_index) + 1)\nbd_rnn_model.summary()\nbd_rnn_model.fit(tmp_x, preproc_french_sentences, batch_size=1024, epochs=10, validation_split=0.2)\n\n# Print prediction(s)\nprint(logits_to_text(bd_rnn_model.predict(tmp_x[:1])[0], french_tokenizer))", "_____no_output_____" ] ], [ [ "### Model 4: Encoder-Decoder (OPTIONAL)\nTime to look at encoder-decoder models. This model is made up of an encoder and decoder. The encoder creates a matrix representation of the sentence. The decoder takes this matrix as input and predicts the translation as output.\n\nCreate an encoder-decoder model in the cell below.", "_____no_output_____" ] ], [ [ "from keras.layers import RepeatVector\n\ndef encdec_model(input_shape, output_sequence_length, english_vocab_size, french_vocab_size):\n \"\"\"\n Build and train an encoder-decoder model on x and y\n :param input_shape: Tuple of input shape\n :param output_sequence_length: Length of output sequence\n :param english_vocab_size: Number of unique English words in the dataset\n :param french_vocab_size: Number of unique French words in the dataset\n :return: Keras model built, but not trained\n \"\"\"\n # OPTIONAL: Implement\n #Config Hyperparameters\n learning_rate = 0.01\n latent_dim = 128\n\n #Config Encoder\n encoder_inputs = Input(shape=input_shape[1:])\n encoder_gru = GRU(output_sequence_length)(encoder_inputs)\n encoder_outputs = Dense(latent_dim, activation='relu')(encoder_gru)\n \n #Config Decoder\n decoder_inputs = RepeatVector(output_sequence_length)(encoder_outputs)\n decoder_gru = GRU(latent_dim, return_sequences=True)(decoder_inputs)\n output_layer = TimeDistributed(Dense(french_vocab_size, activation='softmax'))\n outputs = output_layer(decoder_gru)\n\n #Create Model from parameters defined above\n model = Model(inputs=encoder_inputs, outputs=outputs)\n model.compile(loss=sparse_categorical_crossentropy,\n optimizer=Adam(learning_rate),\n metrics=['accuracy'])\n \n \n #return None\n return model\n\ntests.test_encdec_model(encdec_model)\n\n\n# OPTIONAL: Train and Print prediction(s)\ntmp_x = pad(preproc_english_sentences, preproc_french_sentences.shape[1])\ntmp_x = tmp_x.reshape((-1, preproc_french_sentences.shape[-2], 1))\n\n# Train the neural network\nencdec_rnn_model = encdec_model(\n tmp_x.shape,\n preproc_french_sentences.shape[1],\n len(english_tokenizer.word_index) + 1,\n len(french_tokenizer.word_index) + 1)\nencdec_rnn_model.summary()\nencdec_rnn_model.fit(tmp_x, preproc_french_sentences, batch_size=1024, epochs=10, validation_split=0.2)\n\n# Print prediction(s)\nprint(logits_to_text(encdec_rnn_model.predict(tmp_x[:1])[0], french_tokenizer))", "_____no_output_____" ] ], [ [ "### Model 5: Custom (IMPLEMENTATION)\nUse everything you learned from the previous models to create a model that incorporates embedding and a bidirectional rnn into one model.", "_____no_output_____" ] ], [ [ "def model_final(input_shape, output_sequence_length, english_vocab_size, french_vocab_size):\n \"\"\"\n Build and train a model that incorporates embedding, encoder-decoder, and bidirectional RNN on x and y\n :param input_shape: Tuple of input shape\n :param output_sequence_length: Length of output sequence\n :param english_vocab_size: Number of unique English words in the dataset\n :param french_vocab_size: Number of unique French words in the dataset\n :return: Keras model built, but not trained\n \"\"\"\n # TODO: Implement\n\n \n #Config Hyperparameters\n learning_rate = 0.01\n latent_dim = 128\n \n #Config Model\n inputs = Input(shape=input_shape[1:])\n embedding_layer = Embedding(input_dim=english_vocab_size, output_dim=output_sequence_length, mask_zero=False)(inputs)\n \n #bd_layer = Bidirectional(GRU(output_sequence_length))(embedding_layer)\n bd_layer = Bidirectional(GRU(256))(embedding_layer)\n \n encoding_layer = Dense(latent_dim, activation='relu')(bd_layer)\n decoding_layer = RepeatVector(output_sequence_length)(encoding_layer)\n \n #output_layer = Bidirectional(GRU(latent_dim, return_sequences=True))(decoding_layer)\n output_layer = Bidirectional(GRU(256, return_sequences=True))(decoding_layer)\n \n \n outputs = TimeDistributed(Dense(french_vocab_size, activation='softmax'))(output_layer)\n \n #Create Model from parameters defined above\n model = Model(inputs=inputs, outputs=outputs)\n model.compile(loss=sparse_categorical_crossentropy,\n optimizer=Adam(learning_rate),\n metrics=['accuracy'])\n \n \n #return None\n return model\n\ntests.test_model_final(model_final)\n\n\nprint('Final Model Loaded')\n# TODO: Train the final model", "_____no_output_____" ] ], [ [ "## Prediction (IMPLEMENTATION)", "_____no_output_____" ] ], [ [ "def final_predictions(x, y, x_tk, y_tk):\n \"\"\"\n Gets predictions using the final model\n :param x: Preprocessed English data\n :param y: Preprocessed French data\n :param x_tk: English tokenizer\n :param y_tk: French tokenizer\n \"\"\"\n # TODO: Train neural network using model_final\n #model = None\n #model = model_final(x.shape, y.shape[1], len(x_tk.word_index) + 1, len(y_tk.word_index) + 1)\n model = model_final(x.shape, y.shape[1], len(x_tk.word_index) + 1, len(y_tk.word_index) + 1)\n \n model.summary()\n #model.fit(x, y, batch_size=1024, epochs=10, validation_split=0.2)\n model.fit(x, y, batch_size=512, epochs=10, validation_split=0.2)\n \n ## DON'T EDIT ANYTHING BELOW THIS LINE\n y_id_to_word = {value: key for key, value in y_tk.word_index.items()}\n y_id_to_word[0] = '<PAD>'\n\n sentence = 'he saw a old yellow truck'\n sentence = [x_tk.word_index[word] for word in sentence.split()]\n sentence = pad_sequences([sentence], maxlen=x.shape[-1], padding='post')\n sentences = np.array([sentence[0], x[0]])\n predictions = model.predict(sentences, len(sentences))\n\n print('Sample 1:')\n print(' '.join([y_id_to_word[np.argmax(x)] for x in predictions[0]]))\n print('Il a vu un vieux camion jaune')\n print('Sample 2:')\n print(' '.join([y_id_to_word[np.argmax(x)] for x in predictions[1]]))\n print(' '.join([y_id_to_word[np.max(x)] for x in y[0]]))\n\n\nfinal_predictions(preproc_english_sentences, preproc_french_sentences, english_tokenizer, french_tokenizer)", "_____no_output_____" ] ], [ [ "## Submission\nWhen you're ready to submit, complete the following steps:\n1. Review the [rubric](https://review.udacity.com/#!/rubrics/1004/view) to ensure your submission meets all requirements to pass\n2. Generate an HTML version of this notebook\n\n - Run the next cell to attempt automatic generation (this is the recommended method in Workspaces)\n - Navigate to **FILE -> Download as -> HTML (.html)**\n - Manually generate a copy using `nbconvert` from your shell terminal\n```\n$ pip install nbconvert\n$ python -m nbconvert machine_translation.ipynb\n```\n \n3. Submit the project\n\n - If you are in a Workspace, simply click the \"Submit Project\" button (bottom towards the right)\n \n - Otherwise, add the following files into a zip archive and submit them \n - `helper.py`\n - `machine_translation.ipynb`\n - `machine_translation.html`\n - You can export the notebook by navigating to **File -> Download as -> HTML (.html)**.", "_____no_output_____" ], [ "### Generate the html\n\n**Save your notebook before running the next cell to generate the HTML output.** Then submit your project.", "_____no_output_____" ] ], [ [ "# Save before you run this cell!\n!!jupyter nbconvert *.ipynb", "_____no_output_____" ] ], [ [ "## Optional Enhancements\n\nThis project focuses on learning various network architectures for machine translation, but we don't evaluate the models according to best practices by splitting the data into separate test & training sets -- so the model accuracy is overstated. Use the [`sklearn.model_selection.train_test_split()`](http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html) function to create separate training & test datasets, then retrain each of the models using only the training set and evaluate the prediction accuracy using the hold out test set. Does the \"best\" model change?", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ] ]
4a0c379f734bb77b89f7ff19fe117fd5cc83e00b
35,070
ipynb
Jupyter Notebook
.ipynb_checkpoints/land_expansion-checkpoint 7.ipynb
hangulu/expandharvard
8169ea1601cb32083efa65dfec5506a62bf55af0
[ "Apache-2.0" ]
1
2018-04-07T15:35:37.000Z
2018-04-07T15:35:37.000Z
.ipynb_checkpoints/land_expansion-checkpoint 7.ipynb
hangulu/expandharvard
8169ea1601cb32083efa65dfec5506a62bf55af0
[ "Apache-2.0" ]
null
null
null
.ipynb_checkpoints/land_expansion-checkpoint 7.ipynb
hangulu/expandharvard
8169ea1601cb32083efa65dfec5506a62bf55af0
[ "Apache-2.0" ]
null
null
null
45.545455
1,740
0.59521
[ [ [ "%matplotlib inline", "_____no_output_____" ], [ "import numpy as np\nimport pandas as pd\nimport math\nfrom scipy import stats\nimport pickle\nfrom causality.analysis.dataframe import CausalDataFrame\nfrom sklearn.linear_model import LinearRegression\nimport datetime", "_____no_output_____" ], [ "import matplotlib\nimport matplotlib.pyplot as plt\nmatplotlib.rcParams['font.sans-serif'] = \"Gotham\"\nmatplotlib.rcParams['font.family'] = \"sans-serif\"\nimport plotly\nimport plotly.graph_objs as go\nfrom plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot\ninit_notebook_mode(connected=True)", "_____no_output_____" ] ], [ [ "Open the data from past notebooks and correct them to only include years that are common between the data structures (>1999).", "_____no_output_____" ] ], [ [ "with open('VariableData/money_data.pickle', 'rb') as f:\n income_data, housing_data, rent_data = pickle.load(f)\nwith open('VariableData/demographic_data.pickle', 'rb') as f:\n demographic_data = pickle.load(f)\nwith open('VariableData/endowment.pickle', 'rb') as f:\n endowment = pickle.load(f)\nwith open('VariableData/expander.pickle', 'rb') as f:\n expander = pickle.load(f)", "_____no_output_____" ], [ "endowment = endowment[endowment['FY'] > 1997].reset_index()\nendowment.drop('index', axis=1, inplace=True)\n\ndemographic_data = demographic_data[demographic_data['year'] > 1999].reset_index()\ndemographic_data.drop('index', axis=1, inplace=True)\n\nincome_data = income_data[income_data['year'] > 1999].reset_index()\nincome_data.drop('index', axis=1, inplace=True)\n\nhousing_data = housing_data[housing_data['year'] > 1999].reset_index()\nhousing_data.drop('index', axis=1, inplace=True)\n\nrent_data = rent_data[rent_data['year'] > 1999].reset_index()\nrent_data.drop('index', axis=1, inplace=True)", "_____no_output_____" ] ], [ [ "Read in the data on Harvard owned land and Cambridge's property records. Restrict the Harvard data to Cambridge, MA.", "_____no_output_____" ] ], [ [ "harvard_land = pd.read_excel(\"Spreadsheets/2018_building_reference_list.xlsx\", header=3)\nharvard_land = harvard_land[harvard_land['City'] == 'Cambridge']", "_____no_output_____" ], [ "cambridge_property = pd.read_excel(\"Spreadsheets/cambridge_properties.xlsx\")", "_____no_output_____" ] ], [ [ "Restrict the Cambridge data to Harvard properties, and only use relevant columns.", "_____no_output_____" ] ], [ [ "cambridge_property = cambridge_property[cambridge_property['Owner_Name'].isin(['PRESIDENT & FELLOWS OF HARVARD COLLEGE', 'PRESIDENT & FELLOW OF HARVARD COLLEGE'])]", "_____no_output_____" ], [ "cambridge_property = cambridge_property[['Address', 'PropertyClass', 'LandArea', 'BuildingValue', 'LandValue', 'AssessedValue', 'SalePrice', 'SaleDate', 'Owner_Name']]", "_____no_output_____" ] ], [ [ "Fix the time data.", "_____no_output_____" ] ], [ [ "cambridge_property['SaleDate'] = pd.to_datetime(cambridge_property['SaleDate'], infer_datetime_format=True)", "_____no_output_____" ], [ "clean_property = cambridge_property.drop_duplicates(subset=['Address'])", "_____no_output_____" ], [ "clean_property.head()\ntype(clean_property['SaleDate'])", "_____no_output_____" ] ], [ [ "Only look at properties purchased after 2000.", "_____no_output_____" ] ], [ [ "recent_property = clean_property[clean_property['SaleDate'] > datetime.date(2000, 1, 1)]", "_____no_output_____" ], [ "property_numbers = recent_property[['LandArea', 'AssessedValue', 'SalePrice']]\nnum_recent = recent_property['Address'].count()\nsum_properties = property_numbers.sum()", "_____no_output_____" ], [ "sum_properties", "_____no_output_____" ], [ "full_property_numbers = clean_property[['LandArea', 'AssessedValue', 'SalePrice']]\nsum_full = full_property_numbers.sum()", "_____no_output_____" ], [ "delta_property = sum_properties / sum_full", "_____no_output_____" ], [ "delta_property", "_____no_output_____" ] ], [ [ "What can be gathered from above?\n\nSince the year 2000, Harvard has increased its presence in Cambridge by about 3%, corresponding to about 2% of its overall assessed value, an increase of 281,219 square feet and \\$115,226,500. Although the assessed value increase is so high, Harvard only paid \\$57,548,900 for the property at their times of purchase.\n\nTo make some adjustments for inflation:\n\nNote that the inflation rate since 2000 is ~37.8% (https://data.bls.gov/timeseries/CUUR0000SA0L1E?output_view=pct_12mths).", "_____no_output_____" ] ], [ [ "inflation_data = pd.read_excel(\"Spreadsheets/inflation.xlsx\", header=11)\ninflation_data = inflation_data[['Year', 'Jan']]\ninflation_data['Year'] = pd.to_datetime(inflation_data['Year'], format='%Y')\ninflation_data['CumulativeInflation'] = inflation_data['Jan'].cumsum()\ninflation_data.rename(columns={'Year' : 'SaleDate'}, inplace=True)\nrecent_property['SaleDate'] = recent_property['SaleDate'].dt.year\ninflation_data['SaleDate'] = inflation_data['SaleDate'].dt.year", "_____no_output_____" ], [ "recent_property = pd.merge(recent_property, inflation_data, how=\"left\", on=['SaleDate'])\nrecent_property = recent_property.drop('Jan', 1)", "_____no_output_____" ], [ "recent_property['TodaySale'] = (1 + (recent_property['CumulativeInflation'] / 100)) * recent_property['SalePrice']", "_____no_output_____" ], [ "today_sale_sum = recent_property['TodaySale'].sum()", "_____no_output_____" ], [ "today_sale_sum", "_____no_output_____" ], [ "sum_properties['AssessedValue'] - today_sale_sum", "_____no_output_____" ] ], [ [ "Hence, adjusted for inflation, the sale price of the property Harvard has acquired since 2000 is \\$65,929,240.\n\nThe difference between this value and the assessed value of the property (in 2018) is: \\$49,297,260, showing that Harvard's property has appreciated in value even more than (twice more than) inflation would account for, illustrating a clear advantageous dynamic for Harvard.", "_____no_output_____" ] ], [ [ "sorted_df = recent_property.sort_values(by=['SaleDate'])\nsorted_df = sorted_df.reset_index().drop('index', 1)\nsorted_df['CumLand'] = sorted_df['LandArea'].cumsum()\nsorted_df['CumValue'] = sorted_df['AssessedValue'].cumsum()\nsorted_df", "_____no_output_____" ] ], [ [ "Graph the results.", "_____no_output_____" ] ], [ [ "def fitter(x, y, regr_x):\n \"\"\"\n Use linear regression to make a best fit line for a set of data.\n Args:\n x (numpy array): The independent variable.\n y (numpy array): The dependent variable.\n regr_x (numpy array): The array used to extrapolate the regression.\n \"\"\"\n slope, intercept, r_value, p_value, std_err = stats.linregress(x, y)\n return (slope * regr_x + intercept)", "_____no_output_____" ], [ "years = sorted_df['SaleDate'].as_matrix()\ncum_land = sorted_df['CumLand'].as_matrix()\ncum_value = sorted_df['CumValue'].as_matrix()\nregr = np.arange(2000, 2012)\n\nline0 = fitter(years, cum_land, regr)\n\ntrace0 = go.Scatter(\n x = years,\n y = cum_land,\n mode = 'markers',\n name='Harvard Land\\n In Cambridge',\n marker=go.Marker(color='#601014')\n )\nfit0 = go.Scatter(\n x = regr,\n y = line0,\n mode='lines',\n marker=go.Marker(color='#D2232A'),\n name='Fit'\n )\n\ndata = [trace0, fit0]\n\nlayout = go.Layout(\n title = \"The Change In Harvard's Land in Cambridge Since 2000\",\n font = dict(family='Gotham', size=18),\n yaxis=dict(\n title='Land Accumulated Since 2000 (Sq. Feet)'\n ),\n xaxis=dict(\n title='Year')\n )\n\nfig = go.Figure(data=data, layout=layout)\niplot(fig, filename=\"land_changes\")", "_____no_output_____" ], [ "graph2_df = pd.DataFrame(list(zip(regr, line0)))\ngraph2_df.to_csv('graph2.csv')", "_____no_output_____" ], [ "def grapher(x, y, city, title, ytitle, xtitle, filename):\n slope, intercept, r_value, p_value, std_err = stats.linregress(x, y)\n fit = slope * x + intercept\n\n trace0 = go.Scatter(\n x = x,\n y = y,\n mode = 'markers',\n name=city,\n marker=go.Marker(color='#D2232A')\n )\n fit0 = go.Scatter(\n x = x,\n y = fit,\n mode='lines',\n marker=go.Marker(color='#AC1D23'),\n name='Linear Fit'\n )\n\n data = [trace0, fit0]\n\n layout = go.Layout(\n title = title,\n font = dict(family='Gotham', size=12),\n yaxis=dict(\n title=ytitle\n ),\n xaxis=dict(\n title=xtitle)\n )\n\n fig = go.Figure(data=data, layout=layout)\n return iplot(fig, filename=filename)", "_____no_output_____" ], [ "len(line0)", "_____no_output_____" ] ], [ [ "Restrict the demographic data to certain years (up to 2012) in order to fit the data well.", "_____no_output_____" ] ], [ [ "demographic_data = demographic_data[demographic_data['year'] < 2011]\nrent_data = rent_data[rent_data['year'] < 2011]\nhousing_data = housing_data[housing_data['year'] < 2011]\nx = cum_land\ny = pd.to_numeric(demographic_data['c_black']).as_matrix()\nz1 = pd.to_numeric(rent_data['cambridge']).as_matrix()\nz2 = pd.to_numeric(housing_data['cambridge']).as_matrix()", "_____no_output_____" ], [ "endow_black = grapher(x, y, \"Cambridge\", \"The Correlation Between Harvard Land Change and Black Population\", \"Black Population of Cambridge\", \"Land Change (Sq. Feet)\", \"land_black\")", "_____no_output_____" ], [ "X = CausalDataFrame({'x': x, 'y': y, 'z1': z1, 'z2': z2})\ncausal_land_black = X.zplot(x='x', y='y', z=['z1', 'z2'], z_types={'z1': 'c', 'z2': 'c'}, kind='line', color=\"#D2232A\")\n\nfig = causal_land_black.get_figure()\nfig.set_size_inches(9, 5.5)\nax = plt.gca()\nax.set_frame_on(False)\nax.get_yaxis().set_visible(False)\nax.legend_.remove()\n\nax.set_title(\"The Controlled Correlation Between Land Use (Square Feet) and Black Population\", fontproperties=gotham_black, size=10, color=\"#595959\")\nax.set_xlabel(\"Land Use\", fontproperties=gotham_book, fontsize=10, color=\"#595959\")\nfor tick in ax.get_xticklabels():\n tick.set_fontproperties(gotham_book)\n tick.set_fontsize(10)\n tick.set_color(\"#595959\")\n \nfig.savefig('images/black_land.svg', format='svg', dpi=2400, bbox_inches='tight')", "_____no_output_____" ], [ "z2", "_____no_output_____" ], [ "graph9_df = pd.DataFrame(X)\ngraph9_df.to_csv('graph9.csv')", "_____no_output_____" ], [ "y = pd.to_numeric(rent_data['cambridge']).as_matrix()\nz1 = pd.to_numeric(housing_data['cambridge']).as_matrix()\n\nX = CausalDataFrame({'x': x, 'y': y, 'z1': z1})\ncausal_land_rent = X.zplot(x='x', y='y', z=['z1'], z_types={'z1': 'c'}, kind='line', color=\"#D2232A\")\nfig = causal_land_rent.get_figure()\nfig.set_size_inches(9, 5.5)\n\nax = plt.gca()\nax.set_frame_on(False)\nax.get_yaxis().set_visible(False)\nax.legend_.remove()\n\nax.set_title(\"The Controlled Correlation Between Land Use (Square Feet) and Rent\", fontproperties=gotham_black, size=10, color=\"#595959\")\nax.set_xlabel(\"Land Use\", fontproperties=gotham_book, fontsize=10, color=\"#595959\")\nfor tick in ax.get_xticklabels():\n tick.set_fontproperties(gotham_book)\n tick.set_fontsize(10)\n tick.set_color(\"#595959\")\n \nfig.savefig('images/rent_land.svg', format='svg', dpi=1200, bbox_inches='tight')", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ] ]
4a0c3afb0ed46e7dd73c11da5fcd34b539b4d3b7
153,874
ipynb
Jupyter Notebook
old/old ipy/Untitled.ipynb
ai-se/heroes_compsci
613fd623a6da073b2c62c773ed902acb0c756809
[ "MIT" ]
7
2018-09-16T02:55:02.000Z
2021-01-26T05:45:17.000Z
old/old ipy/Untitled.ipynb
ai-se/heroes_compsci
613fd623a6da073b2c62c773ed902acb0c756809
[ "MIT" ]
12
2019-12-17T04:04:19.000Z
2019-12-26T20:23:02.000Z
old/old ipy/Untitled.ipynb
ai-se/Git_miner
126de39b24336fa689150fe8779be7ac84b664db
[ "MIT" ]
2
2019-04-29T13:31:35.000Z
2019-05-01T18:21:05.000Z
37.493665
1,732
0.49755
[ [ [ "import git_access,api_access,git2repo\nimport json\nfrom __future__ import division\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport math\nimport networkx as nx\nimport re\nimport git2data\nimport social_interaction", "_____no_output_____" ], [ "access_token = '--'\nrepo_owner = 'jankotek'\nsource_type = 'github_repo'\ngit_url = 'git://github.com/jankotek/jankotek-mapdb.git'\napi_base_url = 'http://api.github.com'\nrepo_name = 'jankotek-mapdb'\nurl_type = 'issues'\nurl_details = 'comments'\naccess_project = api_access.git_api_access(access_token,repo_owner,source_type,git_url,api_base_url,repo_name)", "131753b03a46335ae3ce75e349447dc0418d4717\n" ], [ "issue_comment = access_project.get_comments(url_type = url_type,url_details = url_details)", "_____no_output_____" ], [ "issue = access_project.get_issues(url_type = url_type,url_details = '')", "_____no_output_____" ], [ "events = access_project.get_events(url_type = url_type,url_details = 'events')", "_____no_output_____" ], [ "git_repo = git2repo.git2repo(repo_url,repo_name)\nrepo = git_repo.clone_repo()", "_____no_output_____" ], [ "obj = repo.get('95693814f4c733ece3563b51c317c89203f1ff59')\nprint(obj)", "<_pygit2.Commit object at 0x000001C278A26490>\n" ], [ "commits = git_repo.get_commits()", "_____no_output_____" ], [ "committed_files = git_repo.get_committed_files()", "_____no_output_____" ], [ "issue_df = pd.DataFrame(issue, columns = ['Issue_number','user_logon','author_type','Desc','title'])\ncommit_df = pd.DataFrame(commits, columns=['commit_number', 'message', 'parent'])\nevents_df = pd.DataFrame(events, columns=['event_type', 'issue_number', 'commit_number'])", "_____no_output_____" ], [ "import re\nissue_commit_dict = {}\nfor i in range(commit_df.shape[0]):\n _commit_number = commit_df.loc[i,'commit_number']\n _commit_message = commit_df.loc[i,'message']\n _commit_parent = commit_df.loc[i,'parent']\n res = re.search(\"#[0-9]+$\", _commit_message)\n if res is not None:\n _issue_id = res.group(0)[1:]\n issue_commit_dict[_commit_number] = _issue_id", "_____no_output_____" ], [ "links = events_df.dropna()\nlinks.reset_index(inplace=True)\nfor i in range(links.shape[0]):\n if links.loc[i,'commit_number'] in issue_commit_dict.keys():\n continue\n else:\n issue_commit_dict[links.loc[i,'commit_number']] = links.loc[i,'issue_number']", "_____no_output_____" ], [ "issue_commit_temp = []\ncommit_df['issues'] = pd.Series([None]*commit_df.shape[0])\nissue_df['commits'] = pd.Series([None]*issue_df.shape[0])\nfor i in range(commit_df.shape[0]):\n _commit_number = commit_df.loc[i,'commit_number']\n _commit_message = commit_df.loc[i,'message']\n _commit_parent = commit_df.loc[i,'parent']\n res = re.search(\"#[0-9]+$\", _commit_message)\n if res is not None:\n _issue_id = res.group(0)[1:]\n issue_commit_temp.append([_commit_number,np.int64(_issue_id)])\nissue_commit_list_1 = np.array(issue_commit_temp) ", "_____no_output_____" ], [ "links = events_df.dropna()\nlinks.reset_index(inplace=True)\nissue_commit_temp = []\nfor i in range(links.shape[0]):\n if links.loc[i,'commit_number'] in issue_commit_list[:,0]:\n continue\n else:\n issue_commit_temp.append([links.loc[i,'commit_number'],links.loc[i,'issue_number']])\nissue_commit_list_2 = np.array(issue_commit_temp)", "_____no_output_____" ], [ "issue_commit_list = np.append(issue_commit_list_1,issue_commit_list_2, axis = 0)", "_____no_output_____" ], [ "df = pd.DataFrame(issue_commit_list2, columns = ['commit_id','issues']).drop_duplicates()\ndf = df.drop_duplicates()", "_____no_output_____" ], [ "df_unique_issues = df.issues.unique()\nfor i in df_unique:\n i = np.int64(i)\n commits = df[df['issues'] == i]['commit_id']\n x = issue_df['Issue_number'] == i\n j = x[x == True].index.values\n if len(j) != 1:\n continue\n issue_df.at[j[0],'commits'] = commits.values", "_____no_output_____" ], [ "df_unique_commits = df.commit_id.unique()\nfor i in df_unique_commits:\n issues = df[df['commit_id'] == i]['issues']\n x = commit_df['commit_number'] == i\n j = x[x == True].index.values\n if len(j) != 1:\n continue\n commit_df.at[j[0],'issues'] = issues.values", "['24']\n['39']\n['9']\n['6']\n['47']\n['283']\n['330']\n['338']\n['348']\n['321']\n['354']\n['186']\n['362']\n['252']\n['424']\n['426']\n['426']\n['426']\n['426']\n['426']\n['427']\n['427']\n['431']\n['431']\n['455']\n['302']\n['437']\n['437']\n['464']\n['415']\n['522']\n['525']\n['461']\n['547']\n['554']\n['501']\n['555']\n['581']\n['581']\n['316']\n['617']\n['448']\n['628']\n['521']\n['648']\n['635']\n['654']\n['573']\n['573']\n['663']\n['663']\n['664']\n['699']\n['679']\n['731']\n['10584']\n['742']\n['772']\n['808']\n['839']\n['855']\n['879']\n['879']\n['813']\n['891']\n['869']\n['893']\n['763']\n['905']\n['911']\n['922']\n['860']\n['894']\n['902']\n['961']\n['1000']\n['994']\n['1029']\n['1048']\n['1085']\n['1083']\n['1091']\n['1115']\n['1133']\n['1106']\n['1294']\n['1377']\n['1382']\n['1386']\n['1412']\n['1044']\n['1044']\n['1044']\n['1413']\n['1452']\n['1475']\n['1339']\n['1402']\n['1403']\n['1403']\n['1512']\n['1544']\n['1558']\n['1597']\n['1496']\n['1613']\n['1613']\n['1656']\n['1656']\n['1689']\n['1795']\n['1790']\n['1814']\n['1831']\n['1856']\n['1813']\n['1907']\n['1960']\n['1977']\n['1705']\n['1944']\n['1958']\n['1941']\n['976']\n['2015']\n['2015']\n['2015']\n['1576' '2015']\n['1576']\n['2014']\n['2009']\n['2013']\n['1309']\n['2009']\n['2009']\n['2010']\n['1941']\n['2007']\n['2005']\n['2001']\n['1999']\n['1951']\n['1997']\n['1951']\n['1951']\n['1857']\n['818']\n['1882']\n['1992']\n['1958']\n['1989']\n['1990']\n['1705']\n['1925']\n['1959']\n['1984']\n['1930']\n['1930']\n['1985']\n['1857']\n['1944']\n['1979']\n['1982']\n['1979']\n['1982']\n['1981']\n['1980']\n['1977']\n['1813']\n['1813']\n['1813']\n['1655']\n['1655']\n['1944']\n['1943']\n['1943']\n['1960']\n['1962']\n['1951']\n['1955']\n['1944']\n['1951']\n['1951']\n['1955']\n['1955']\n['1955']\n['1955']\n['1950']\n['1532']\n['1949']\n['586' '70']\n['1936']\n['1524']\n['1932']\n['1929']\n['1705']\n['1924']\n['1919' '1920']\n['1919']\n['1650']\n['1916']\n['1909']\n['1907' '1903']\n['1914']\n['1886']\n['1913']\n['1912']\n['1903']\n['1906']\n['1880']\n['1899']\n['1889' '1893']\n['1888']\n['1907']\n['1914']\n['1886']\n['1650']\n['1913']\n['1912']\n['1650']\n['1903']\n['1909']\n['1906']\n['1889']\n['1880']\n['1532']\n['1899']\n['1889' '1893']\n['1889']\n['1888']\n['1884']\n['1884']\n['1872' '1865']\n['1869']\n['1393']\n['1874']\n['1865' '1872']\n['1865']\n['1869']\n['1867']\n['1813']\n['1864']\n['1839']\n['1856']\n['1853']\n['1859']\n['1858']\n['1124']\n['1825']\n['1275']\n['1275']\n['1800']\n['1800']\n['1831']\n['1831']\n['1831']\n['1048']\n['1048']\n['1048']\n['1048']\n['1813']\n['1813']\n['1813']\n['1813']\n['1813']\n['1813']\n['1813']\n['1813']\n['1813']\n['1813']\n['1813']\n['1831']\n['1813']\n['1800']\n['1800']\n['1800']\n['1800']\n['1813']\n['1813']\n['1813']\n['1813']\n['1817']\n['1811']\n['1811']\n['1817']\n['1813']\n['1822']\n['1800']\n['1817']\n['1817']\n['1402' '1815']\n['1402']\n['1402']\n['1402']\n['1814']\n['1814']\n['1814']\n['1160']\n['1809']\n['1807']\n['1803']\n['1803']\n['1801']\n['1801']\n['1710']\n['1669']\n['1669']\n['1790']\n['1795']\n['1655']\n['1799']\n['1798']\n['1797']\n['1655']\n['1655']\n['1655']\n['1539']\n['1539']\n['1655']\n['1655']\n['1539']\n['1539']\n['1539']\n['1655']\n['1658']\n['1655']\n['1655']\n['1655']\n['1655']\n['1655']\n['1655']\n['1372']\n['1769']\n['1779']\n['1652']\n['1652']\n['1652']\n['1652']\n['1775']\n['1774']\n['1772']\n['1771']\n['1770']\n['1765']\n['1768']\n['1725']\n['1033']\n['1127']\n['1761']\n['1033']\n['1127']\n['1033']\n['1127']\n['1033']\n['1127']\n['1033']\n['1127']\n['1760']\n['1390']\n['1749']\n['148']\n['1532']\n['1525']\n['1559']\n['1659']\n['1659']\n['1744']\n['1658']\n['1743']\n['1742']\n['1680' '1710']\n['1669']\n['1525']\n['1739']\n['1732']\n['1390']\n['1390']\n['1390']\n['1390']\n['1729']\n['1731']\n['1730']\n['818']\n['1725']\n['1725']\n['1052']\n['1723']\n['1722']\n['1722']\n['1187']\n['1108']\n['1713']\n['1023']\n['1711']\n['1669']\n['1669']\n['1532']\n['1703']\n['1430']\n['1532']\n['1644']\n['1532']\n['1532']\n['1532']\n['1532']\n['1532']\n['1685']\n['1685']\n['1644']\n['1662']\n['1662']\n['1554']\n['1689']\n['1684']\n['1684']\n['1684']\n['1684']\n['1678' '1645']\n['1645' '1678']\n['1645']\n['1676']\n['1644']\n['1671']\n['1664']\n['1661']\n['1661']\n['1656' '1660']\n['1654']\n['1653']\n['1648']\n['1647']\n['1343']\n['1638']\n['1640']\n['1639']\n['1636']\n['1637']\n['1635']\n['904']\n['1549']\n['1632']\n['1579' '1241']\n['1579' '1241']\n['1579' '1241']\n['1579' '1241']\n['1579' '1241']\n['1579' '1241']\n['1311']\n['1631']\n['1623']\n['1623']\n['1621']\n['1613']\n['1103']\n['1619']\n['1617']\n['1616']\n['1496']\n['1615']\n['1614']\n['1608']\n['1603']\n['1578']\n['1600']\n['1600']\n['1600']\n['1598']\n['1598']\n['1597']\n['1597']\n['1578']\n['976']\n['1587']\n['1587']\n['1558']\n['1309']\n['1573']\n['1529']\n['1529']\n['1592']\n['1591']\n['1589']\n['1532']\n['1580']\n['1580']\n['1532']\n['1532']\n['1532']\n['1532']\n['1532']\n['1576']\n['1575']\n['1572']\n['1571']\n['1570']\n['1560']\n['1532']\n['738' '1565']\n['738']\n['1533' '1532']\n['1532']\n['1553']\n['1522']\n['1550']\n['1550']\n['1548']\n['1547']\n['1532']\n['1543']\n['1540']\n['1540']\n['1532']\n['1544']\n['1544']\n['1537']\n['1537']\n['1532']\n['1540']\n['1535']\n['1532']\n['1533' '1532']\n['1532']\n['1536']\n['1535']\n['1532']\n['1535']\n['1532']\n['1532']\n['1535']\n['1532']\n['1534']\n['1535']\n['1534']\n['1532']\n['1532']\n['1532']\n['1533' '1532']\n['1532']\n['1532']\n['976']\n['1512']\n['1526']\n['1523']\n['1521']\n['1518']\n['1516']\n['1510']\n['1492']\n['936']\n['1503' '1508']\n['1402']\n['1505']\n['1402']\n['1501']\n['1442' '1501']\n['1442']\n['396']\n['1442']\n['1502']\n['1501']\n['1499']\n['1501']\n['1442']\n['1499']\n['1501']\n['1403']\n['1403']\n['1442']\n['1500']\n['1497']\n['1493']\n['1485']\n['1493']\n['1489']\n['1486']\n['1479']\n['1479']\n['1480']\n['1343']\n['1476']\n['787']\n['1464']\n['1464']\n['1466']\n['1468']\n['1462']\n['1465']\n['1463']\n['1430']\n['864']\n['864']\n['1452']\n['1458']\n['1458']\n['1413']\n['232']\n['1430']\n['1044']\n['1044']\n['1044']\n['1044']\n['1456']\n['1325']\n['864']\n['864']\n['864']\n['864']\n['864']\n['864']\n['1264']\n['1325']\n['864']\n['864']\n['1237']\n['1237']\n['1237']\n['1277' '1264']\n['1277' '1264']\n['1350' '1277' '1264']\n['1350' '1277' '1264']\n['1277' '1264']\n['1325']\n['1325']\n['1445']\n['1444']\n['1237']\n['1413']\n['1046']\n['1440']\n['1439']\n['1438']\n['232']\n['1430' '1436']\n['1430']\n['1430']\n['232']\n['1044' '1435']\n['1044']\n['1434']\n['1432']\n['1431']\n['1425']\n['1423']\n['1422']\n['1419']\n['1414']\n['1412']\n['1418']\n['1414']\n['1412' '1414']\n['1414']\n['1412']\n['1412']\n['1076']\n['1035']\n['1372']\n['1171']\n['1398']\n['1396']\n['1398']\n['1396']\n['1396']\n['1394']\n['1395']\n['1394']\n['1394']\n['1076']\n['1076']\n['1076']\n['1076']\n['1264']\n['1103']\n['1076']\n['1388' '1389']\n['1386']\n['1388']\n['1076']\n['876']\n['1386']\n['1386']\n['1386']\n['1386']\n['1386']\n['1386']\n['1076']\n['1384']\n['1383']\n['1273']\n['1380']\n['1355']\n['1379']\n['1378']\n['1372']\n['1375']\n['1355']\n['1098']\n['1355']\n['1187']\n['1187']\n['1187']\n['1364']\n['1361']\n['1361']\n['1360']\n['1187']\n['758']\n['1356']\n['1350']\n['1350']\n['1355']\n['1354']\n['1273']\n['1076']\n['1076']\n['403']\n['119']\n['130']\n['126']\n['119']\n['38']\n['122']\n['121']\n['123']\n['124']\n['33']\n['115']\n['116']\n['108']\n['94']\n['105']\n['103']\n['101']\n['98' '89']\n['99']\n['96']\n['95']\n['91']\n['90']\n['36']\n['81']\n['75']\n['43']\n['51']\n['73' '72']\n['72']\n['73']\n['48']\n['8']\n['45']\n['56']\n['44']\n['37']\n['11']\n['31']\n['30']\n['1339']\n['1327']\n['1289']\n['1339']\n['1338']\n['1330']\n['1323']\n['1308']\n['1308']\n['1308']\n['1236']\n['1336']\n['1336']\n['1236']\n['1236']\n['1313']\n['1313']\n['1313']\n['1313' '1327']\n['925']\n['1324']\n['1320']\n['1309']\n['1309']\n['1318' '1310' '1305' '1303' '1319']\n['1318']\n['1310']\n['1301']\n['1318']\n['1318']\n['858']\n['858']\n['858']\n['879']\n['1309']\n['1309']\n['1310']\n['1310']\n['1171']\n['858']\n['858']\n['1305']\n['1303']\n['1301']\n['1264' '1273']\n['1295']\n['1292']\n['1292']\n['1293']\n['1226']\n['1238']\n['1226']\n['1187']\n['1171']\n['932']\n['1238']\n['1238']\n['1285']\n['1281']\n['1283']\n['1280']\n['1226']\n['1277']\n['1171']\n['1278']\n['858']\n['858']\n['858']\n['1272']\n['1171']\n['1271']\n['1171']\n['1260']\n['1266']\n['1265']\n['1264']\n['1248']\n['1248']\n['1261']\n['1231']\n['1231']\n['1231']\n['1236']\n['1231']\n['1259']\n['1258']\n['1257']\n['1256']\n['1187']\n['1187']\n['1187']\n['1187']\n['1187']\n['1187']\n['1187']\n['1187']\n['829']\n['829']\n['829']\n['950']\n['476']\n['1185']\n['1234']\n['1231']\n['1223']\n['1231']\n['1231']\n['1224' '1194']\n['1221']\n['1222']\n['1220']\n['1103']\n['696']\n['1216']\n['1215']\n['1206']\n['1206']\n['712']\n['1204']\n['1204']\n['1103']\n['1199']\n['1053']\n['1053']\n['1196']\n['1194']\n['1192']\n['758']\n['1190']\n['1193']\n['534']\n['1186']\n['1178']\n['936']\n['1176']\n['1168']\n['1035']\n['215']\n['1167']\n['1162']\n['1164']\n['1163']\n['1162']\n['1150']\n['1145']\n['1155']\n['1159']\n['1158']\n['1158']\n['1157']\n['1149']\n['1153']\n['1142']\n['1142']\n['1145']\n['1146']\n['1144']\n['1103']\n['1141']\n['610']\n['610']\n['936']\n['758']\n['1139' '1136']\n['1136']\n['1138']\n['1138']\n['1137']\n['1139']\n['1135']\n['1135']\n['1133']\n['1133']\n['1103']\n['1123']\n['1123']\n['1128']\n['1118']\n" ], [ "commit_df", "_____no_output_____" ], [ "git_data = git2data.git2data(access_token,repo_owner,source_type,git_url,api_base_url,repo_name)", "131753b03a46335ae3ce75e349447dc0418d4717\n" ], [ "git_data.get_api_data()\ngit_data.get_commit_data()\ncommitted_files_data = git_data.get_committed_files()", "_____no_output_____" ], [ "committed_files_df = pd.DataFrame(committed_files_data, columns = ['commit_id','file_id','file_mode','file_path'])", "_____no_output_____" ], [ "issue_data,commit_data = git_data.create_link()", "_____no_output_____" ], [ "issue_data.to_pickle('rails_issue.pkl')\ncommit_data.to_pickle('rails_commit.pkl')\ncommitted_files_df.to_pickle('rails_committed_file.pkl')", "_____no_output_____" ], [ "type(committed_files_df.loc[1,'file_id'])", "_____no_output_____" ], [ "git_data.create_data()", "http://api.github.com/repos/rspec/rspec-rails/issues?state=all&page=1&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues?state=all&page=2&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues?state=all&page=3&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues?state=all&page=4&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues?state=all&page=5&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues?state=all&page=6&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues?state=all&page=7&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues?state=all&page=8&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues?state=all&page=9&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues?state=all&page=10&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues?state=all&page=11&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues?state=all&page=12&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues?state=all&page=13&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues?state=all&page=14&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues?state=all&page=15&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues?state=all&page=16&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues?state=all&page=17&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues?state=all&page=18&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues?state=all&page=19&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues?state=all&page=20&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues?state=all&page=21&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=1&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=2&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=3&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=4&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=5&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=6&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=7&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=8&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=9&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=10&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=11&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=12&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=13&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=14&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=15&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=16&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=17&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=18&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=19&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=20&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=21&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=22&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=23&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=24&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=25&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=26&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=27&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=28&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=29&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=30&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=31&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=32&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=33&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=34&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=35&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=36&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=37&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=38&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=39&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=40&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=41&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=42&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=43&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=44&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=45&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=46&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=47&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=48&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=49&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=50&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=51&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=52&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=53&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=54&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=55&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=56&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=57&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=58&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=59&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=60&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=61&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=62&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=63&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=64&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=65&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=66&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=67&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=68&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=69&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=70&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=71&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=72&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=73&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=74&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=75&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=76&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=77&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=78&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=79&per_page=100\nhttp://api.github.com/repos/rspec/rspec-rails/issues/events?page=80&per_page=100\n" ], [ "si = social_interaction.create_social_inteaction_graph('rspec-rails')", "_____no_output_____" ], [ "x = si.get_user_node_degree()", "_____no_output_____" ], [ "x", "_____no_output_____" ], [ "import magician_package", "_____no_output_____" ], [ "x = magician_package.learner('pitsE',1,'C:\\Users\\suvod\\AI4SE\\magician_package\\magician_package\\data\\preprocessed\\')", "_____no_output_____" ], [ "import magician_package\ndata_path = '/home/suvo/AI4SE/pypi/magician_package/magician_package/data/preprocessed/'\ndata_file = 'pitsD'\nresult = magician_package.learner(data_file,'1',data_path)", "The Program started============================================================= \n/home/suvo/AI4SE/pypi/magician_package/magician_package/data/preprocessed/pitsD.txt\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
4a0c58aa8da073e95ca0c35d20eaa2ba5293cae5
52,940
ipynb
Jupyter Notebook
time_series/pycaret/pycaret_ts_architecture.ipynb
ngupta23/medium_articles
53dee1cec0677f1129d0f791be060b69a62a8214
[ "MIT" ]
2
2021-11-20T16:13:42.000Z
2021-11-20T16:13:43.000Z
time_series/pycaret/pycaret_ts_architecture.ipynb
ngupta23/medium_articles
53dee1cec0677f1129d0f791be060b69a62a8214
[ "MIT" ]
null
null
null
time_series/pycaret/pycaret_ts_architecture.ipynb
ngupta23/medium_articles
53dee1cec0677f1129d0f791be060b69a62a8214
[ "MIT" ]
2
2021-11-23T07:59:10.000Z
2021-11-26T13:32:26.000Z
41.816746
264
0.387533
[ [ [ "<a href=\"https://colab.research.google.com/github/ngupta23/medium_articles/blob/main/time_series/pycaret/pycaret_ts_architecture.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ] ], [ [ "try:\n import pycaret\nexcept:\n !pip install pycaret-ts-alpha", "_____no_output_____" ], [ "#### Import libraries ----\nfrom pprint import pprint\nfrom pycaret.datasets import get_data\nfrom pycaret.internal.pycaret_experiment import TimeSeriesExperiment", "/usr/local/lib/python3.7/dist-packages/distributed/config.py:20: YAMLLoadWarning: calling yaml.load() without Loader=... is deprecated, as the default Loader is unsafe. Please read https://msg.pyyaml.org/load for full details.\n defaults = yaml.load(f)\n" ], [ "#### Get the data ---\ny = get_data(\"airline\")\n", "_____no_output_____" ], [ "#### Setup the experiment ----\nexp = TimeSeriesExperiment()\nexp.setup(data=y, fh=12, seasonal_period=12, session_id=42)", "_____no_output_____" ], [ "#### Create different types of models ----\n\n# ARIMA model from `pmdarima`\narima_model = exp.create_model(\"arima\")\n\n# ETS and Exponential Smoothing models from `statsmodels`\nets_model = exp.create_model(\"ets\")\nexp_smooth_model = exp.create_model(\"exp_smooth\")\n\n# Reduced Regression model using `sklearn` Linear Regression\nlr_model = exp.create_model(\"lr_cds_dt\")", "_____no_output_____" ], [ "#### Check model types ----\nprint(type(arima_model)) # <-- sktime `pmdarima` adapter \nprint(type(ets_model)) # <-- sktime `statsmodels` adapter\nprint(type(exp_smooth_model)) # <-- sktime `statsmodels` adapter\nprint(type(lr_model)) # <-- Your custom sktime compatible model pipeline", "<class 'sktime.forecasting.arima.ARIMA'>\n<class 'sktime.forecasting.ets.AutoETS'>\n<class 'sktime.forecasting.exp_smoothing.ExponentialSmoothing'>\n<class 'pycaret.containers.models.time_series.BaseCdsDtForecaster'>\n" ], [ "#### Access internal models using `_forecaster` ----\nprint(type(arima_model._forecaster))\nprint(type(ets_model._forecaster))\nprint(type(exp_smooth_model._forecaster))\nprint(type(lr_model._forecaster))", "<class 'pmdarima.arima.arima.ARIMA'>\n<class 'statsmodels.tsa.exponential_smoothing.ets.ETSModel'>\n<class 'statsmodels.tsa.holtwinters.model.ExponentialSmoothing'>\n<class 'sktime.forecasting.compose._pipeline.TransformedTargetForecaster'>\n" ], [ "#### What hyperparameters were used to train the model? ----\nprint(arima_model)", "ARIMA(maxiter=50, method='lbfgs', order=(1, 0, 0), out_of_sample_size=0,\n scoring='mse', scoring_args=None, seasonal_order=(0, 1, 0, 12),\n start_params=None, suppress_warnings=False, trend=None,\n with_intercept=True)\n" ], [ "#### Access statistical fit properties using underlying `pmdarima`\narima_model._forecaster.summary()\n\n#### Alternately, use sktime's convenient wrapper to do so ---- \narima_model.summary()", "_____no_output_____" ] ], [ [ "**You can not starts correlating these properties to the forecasts that you see. I will write about it in a subsewquent post.** ", "_____no_output_____" ] ], [ [ "#### What hyperparameters were used to train the model? ----\nprint(ets_model)", "AutoETS(additive_only=False, allow_multiplicative_trend=False, auto=False,\n bounds=None, callback=None, damped_trend=False, dates=None, disp=False,\n error='add', freq=None, full_output=True, ignore_inf_ic=True,\n information_criterion='aic', initial_level=None, initial_seasonal=None,\n initial_trend=None, initialization_method='estimated', maxiter=1000,\n missing='none', n_jobs=None, restrict=True, return_params=False,\n seasonal='mul', sp=12, start_params=None, trend='add')\n" ], [ "#### Access statsitical fit properties using underlying statsmodel\nets_model._forecaster.fit().summary()\n\n#### Alternatively, use sktime's convenient wrapper to do so ---- \nets_model.summary()", "_____no_output_____" ], [ "#### sktime pipelines are similar to sklearn.\n#### Access steps using `named_steps` attribute\nprint(lr_model._forecaster.named_steps.keys(), \"\\n\\n\")\n\n#### Details about the steps ----\npprint(lr_model._forecaster.named_steps)", "dict_keys(['conditional_deseasonalise', 'detrend', 'forecast']) \n\n\n{'conditional_deseasonalise': ConditionalDeseasonalizer(model='additive', seasonality_test=None, sp=1),\n 'detrend': Detrender(forecaster=PolynomialTrendForecaster(degree=1, regressor=None,\n with_intercept=True)),\n 'forecast': RecursiveTabularRegressionForecaster(estimator=LinearRegression(copy_X=True,\n fit_intercept=True,\n n_jobs=-1,\n normalize=False,\n positive=False),\n window_length=10)}\n" ] ] ]
[ "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ] ]
4a0c5a66943608c100f8a30f716522e3692b3d3b
314,753
ipynb
Jupyter Notebook
Relaxation_failure_example.ipynb
pierre-haessig/convex-storage-loss
821929c887e9a12b70e7ae9becb2830f1764e5d6
[ "CC-BY-4.0" ]
null
null
null
Relaxation_failure_example.ipynb
pierre-haessig/convex-storage-loss
821929c887e9a12b70e7ae9becb2830f1764e5d6
[ "CC-BY-4.0" ]
null
null
null
Relaxation_failure_example.ipynb
pierre-haessig/convex-storage-loss
821929c887e9a12b70e7ae9becb2830f1764e5d6
[ "CC-BY-4.0" ]
null
null
null
380.136473
58,694
0.91399
[ [ [ "empty" ] ] ]
[ "empty" ]
[ [ "empty" ] ]
4a0c5d00b5cad7e4a2b65f4bad6474a6a5081732
22,940
ipynb
Jupyter Notebook
Data Manipulation in R.ipynb
ekuhn12/UrbanAnalyticsCourse
655bfd5b3111a76d38677a47ccd83a30a8746061
[ "Apache-2.0" ]
null
null
null
Data Manipulation in R.ipynb
ekuhn12/UrbanAnalyticsCourse
655bfd5b3111a76d38677a47ccd83a30a8746061
[ "Apache-2.0" ]
null
null
null
Data Manipulation in R.ipynb
ekuhn12/UrbanAnalyticsCourse
655bfd5b3111a76d38677a47ccd83a30a8746061
[ "Apache-2.0" ]
null
null
null
24.561028
169
0.38034
[ [ [ "empty" ] ] ]
[ "empty" ]
[ [ "empty" ] ]
4a0c6c99358b1351b669b17b21246786d2cb623c
8,002
ipynb
Jupyter Notebook
examples/tutorial.ipynb
leighton/aiterutils
10cffc6795125fd9b8d65ab1741206211e425213
[ "Apache-2.0" ]
null
null
null
examples/tutorial.ipynb
leighton/aiterutils
10cffc6795125fd9b8d65ab1741206211e425213
[ "Apache-2.0" ]
null
null
null
examples/tutorial.ipynb
leighton/aiterutils
10cffc6795125fd9b8d65ab1741206211e425213
[ "Apache-2.0" ]
null
null
null
21.113456
99
0.468633
[ [ [ "# `aiterutils` tutorial\n\nA functional programming toolkit for manipulation of asynchronous iterators in python >3.5\n\nIt has two types of operations:\n\n1. Iterator functions\n * `au.map(fn, aiter): aiter`\n * `au.each(fn, aiter): coroutine`\n * `au.filter(fn, aiter): aiter`\n * `au.merge([aiter...]): aiter`\n * `au.bifurcate(fn, aiter): (aiter, aiter)`\n * `au.branch([fn...], aiter): (aiter...)`\n\n2. Dynamic streams\n * `au.Stream(aiter)'\n\nDynamics streams can have their undelying object methods invocated implicitly\n\n```\ncapitals = au.Stream(['a','b','c']).upper()\n```", "_____no_output_____" ] ], [ [ "# if executing this notebook, downgrade tornado \n# as tornado does not play nice with asyncio \n# ! pip install tornado==4.5.3 ", "_____no_output_____" ] ], [ [ "## 1. Setup", "_____no_output_____" ] ], [ [ "import functools as ft\nimport asyncio\n\nimport aiterutils as au\n\nasync def symbol_stream(symbols, interval):\n for symbol in symbols:\n yield symbol\n await asyncio.sleep(interval)\n \nsmiley = lambda: symbol_stream([\"🙂\"]*5, 1)\nsunny = lambda: symbol_stream([\"☀️\"]*5, 0.5)\nclown = lambda: symbol_stream([\"🤡\"]*5, 0.2)\nteam = lambda: au.merge([smiley(), sunny(), clown()])\n\nsingle_line_print = ft.partial(print, end='')\n\nloop = asyncio.get_event_loop()", "_____no_output_____" ] ], [ [ "## 2. Iterator functions", "_____no_output_____" ], [ "### `au.map(fn, aiter): aiter`", "_____no_output_____" ] ], [ [ "stream = au.map(lambda s: s + '!', team())\napp = au.println(stream, end='')\n\nloop.run_until_complete(app)", "🙂!☀️!🤡!🤡!🤡!☀️!🤡!🤡!🙂!☀️!☀️!🙂!☀️!🙂!🙂!" ] ], [ [ "### `au.each(fn, aiter): coroutine`", "_____no_output_____" ] ], [ [ "import functools as ft\n\napp = au.each(single_line_print, team())\nloop.run_until_complete(app)", "🙂☀️🤡🤡🤡☀️🤡🤡🙂☀️☀️🙂☀️🙂🙂" ] ], [ [ "### `au.filter(fn, aiter): aiter`", "_____no_output_____" ] ], [ [ "stream = au.filter(lambda s: s == '☀️', team())\napp = au.println(stream, end=\"\")\nloop.run_until_complete(app)", "☀️☀️☀️☀️☀️" ] ], [ [ "### `au.merge([aiter...]): aiter`", "_____no_output_____" ] ], [ [ "stream = au.merge([smiley(), sunny()])\napp = au.println(stream, end=\"\")\nloop.run_until_complete(app)", "🙂☀️☀️🙂☀️☀️🙂☀️🙂🙂" ] ], [ [ "### `au.bifurcate(fn, aiter): (aiter, aiter)`", "_____no_output_____" ] ], [ [ "smile_stream, other_stream = au.bifurcate(lambda s: s == '🙂', team())\n\nloop.run_until_complete(au.println(smile_stream, end=\"\"))\nloop.run_until_complete(au.println(other_stream, end=\"\"))", "🙂🙂🙂🙂🙂☀️🤡🤡🤡☀️🤡🤡☀️☀️☀️" ] ], [ [ "### `au.branch([fn...], aiter): (aiter...)`", "_____no_output_____" ] ], [ [ "filters = [\n lambda s: s == '🙂',\n lambda s: s == '☀️',\n lambda s: s == '🤡'\n]\n\nsmile_stream, sun_stream, clown_stream = au.branch(filters, team())\n\nloop.run_until_complete(au.println(smile_stream, end=''))\nloop.run_until_complete(au.println(sun_stream, end=''))\nloop.run_until_complete(au.println(clown_stream, end=''))", "🙂🙂🙂🙂🙂☀️☀️☀️☀️☀️🤡🤡🤡🤡🤡" ] ], [ [ "## 3. Dynamic Streams", "_____no_output_____" ], [ "### 3.1 map and each methods", "_____no_output_____" ] ], [ [ "#dynamic streams have regular map an each methods\n\napp = (au.Stream(team())\n .map(lambda s: s+'!')\n .each(single_line_print))\n\nloop.run_until_complete(app)", "🙂!☀️!🤡!🤡!🤡!☀️!🤡!🤡!🙂!☀️!☀️!🙂!☀️!🙂!🙂!" ] ], [ [ "### 3.2 operator overloading ", "_____no_output_____" ] ], [ [ "# dynamics streams can have underlying object methods called implicitly\n\nstream = au.Stream(symbol_stream([{\"key-2\" : 1, \"key-2\" : 2}]*10, 0.5))\nvalue2 = stream['key-2'] + 3 / 5\n\napp = au.println(value2, end='')\nloop.run_until_complete(app)\n", "2.62.62.62.62.62.62.62.62.62.6" ] ], [ [ "### 3.3 dynamic method invocation", "_____no_output_____" ] ], [ [ "stream = au.Stream(symbol_stream([{\"key-1\" : 1, \"key-2\" : 2}]*5, 0.5))\n\nkeys = stream.keys()\nkey = keys.map(lambda key: list(key))\nkey = key[-1]\nkey = key.upper().encode('utf-8')\n\napp = au.println(key, end='')\n\nloop.run_until_complete(app)", "b'KEY-2'b'KEY-2'b'KEY-2'b'KEY-2'b'KEY-2'" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
4a0c74a4a5b29861ab44a0d2fd3aa2dbaaddf181
601,719
ipynb
Jupyter Notebook
Linear Algebra.ipynb
kedswamy/Kedar-ML
501bc16e77e36097342925e986e82135b86e2479
[ "Apache-2.0" ]
null
null
null
Linear Algebra.ipynb
kedswamy/Kedar-ML
501bc16e77e36097342925e986e82135b86e2479
[ "Apache-2.0" ]
null
null
null
Linear Algebra.ipynb
kedswamy/Kedar-ML
501bc16e77e36097342925e986e82135b86e2479
[ "Apache-2.0" ]
null
null
null
96.910775
97,893
0.377628
[ [ [ "# Solve a linear system using 3 different approaches : Gaussian elimination, Inverse , PLU factorization & measure times.\n\nimport numpy as np\nfrom scipy.linalg import solve_triangular\nfrom numpy.linalg import inv\nfrom scipy.linalg import lu\nimport time\n\n\ndef gaussElim(Matrix):\n j = 1\n num_rows, num_cols = Matrix.shape\n for i in range(0,num_rows):\n Matrix[i] = Matrix[i]/Matrix[i,i]\n while( j < num_rows):\n Matrix[j] = Matrix[j] - Matrix[j,i]*Matrix[i]\n j+=1\n i+=1\n j = i+ 1\n A = Matrix[0:10,0:10]\n B = Matrix[0:,10:]\n X1 = solve_triangular(A, B, unit_diagonal = True)\n return(X1)\n\n\ndef pluTrans(upper,lower,perm,b):\n RHS1 = perm.T.dot(b)\n Y = solve_triangular(lower, RHS1, lower=True)\n X = solve_triangular(upper, Y)\n return(X) \n\n\nA_ORIG = np.array([[20, 37, 38, 23, 19, 31, 35, 29, 21, 30],\n [39, 13, 12, 29, 12, 16, 39, 36, 18, 18],\n [38, 42, 12, 39, 17, 22, 43, 38, 29, 24],\n [26, 23, 17, 42, 23, 18, 22, 35, 38, 24],\n [24, 21, 42, 19, 32, 12, 26, 24, 39, 22],\n [36, 18, 41, 14, 26, 19, 44, 22, 20, 27],\n [26, 36, 21, 42, 42, 33, 22, 34, 13, 21],\n [15, 25, 28, 22, 44, 44, 25, 18, 15, 35],\n [39, 43, 19, 27, 14, 34, 16, 25, 37, 13],\n [25, 35, 31, 18, 43, 20, 37, 14, 26, 14]])\n\nb1 = np.array([[447],\n [310],\n [313],\n [486],\n [396],\n [317],\n [320],\n [342],\n [445],\n [487]])\n\nb2 = np.array([[223],\n [498],\n [416],\n [370],\n [260],\n [295],\n [417],\n [290],\n [341],\n [220]])\n\nb3 = np.array([[443],\n [350],\n [763],\n [556],\n [641],\n [347],\n [749],\n [563],\n [735],\n [248]])\n\n# 1- Convert A to an Upper triangular matrix & then solve for X using solve triangular\ntic1 = time.perf_counter()\naugMatrix1 = np.column_stack((A_ORIG,b1)).astype(float)\nX1 = gaussElim(augMatrix1)\naugMatrix2 = np.column_stack((A_ORIG,b2)).astype(float)\nX2 = gaussElim(augMatrix2)\naugMatrix3 = np.column_stack((A_ORIG,b3)).astype(float)\nX3 = gaussElim(augMatrix3)\ntoc1 = time.perf_counter()\nX = np.column_stack((X1,X2,X3))\nprint(X)\nprint(\"\\nGaussian Elimination took %s seconds\\n\" % (toc1-tic1))\n\n# 2- get inv of A & then find B\ntic1 = time.perf_counter()\nAinv = inv(A_ORIG)\nX1 = Ainv.dot(b1)\nX2 = Ainv.dot(b2)\nX3 = Ainv.dot(b3)\ntoc1 = time.perf_counter()\nX = np.column_stack((X1,X2,X3))\nprint(X)\nprint(\"\\nInverse method took %s seconds\\n\" % (toc1-tic1))\n#3 - A = LU factorization\ntic1 = time.perf_counter()\nplu = lu(A_ORIG, permute_l=False, overwrite_a=False, check_finite=True)\nperm = plu[0]\nlower =plu[1]\nupper = plu[2]\nX1 = pluTrans(upper,lower,perm,b1)\nX2 = pluTrans(upper,lower,perm,b2)\nX3 = pluTrans(upper,lower,perm,b3)\ntoc1 = time.perf_counter()\nX = np.column_stack((X1,X2,X3))\nprint(X)\nprint(\"\\nPLU factorization took %s seconds\\n\" % (toc1-tic1))", "[[-12.10710752 4.64768699 21.01075846]\n [-11.34348998 -3.24316455 26.12626291]\n [ 12.1989702 -4.42425461 -19.52210838]\n [ 23.00743905 -5.40344451 -43.70383888]\n [ -7.97915438 4.63676968 20.14006475]\n [ 18.75807823 3.5417007 -24.57978448]\n [ 16.05216641 -0.13794706 -33.45692627]\n [-13.44692544 13.24388917 40.58170632]\n [ 11.31479883 1.07385421 -3.30663376]\n [-24.10843133 -1.90808919 41.53386166]]\n\nGaussian Elimination took 0.0018024509990937077 seconds\n\n[[-12.10710752 4.64768699 21.01075846]\n [-11.34348998 -3.24316455 26.12626291]\n [ 12.1989702 -4.42425461 -19.52210838]\n [ 23.00743905 -5.40344451 -43.70383888]\n [ -7.97915438 4.63676968 20.14006475]\n [ 18.75807823 3.5417007 -24.57978448]\n [ 16.05216641 -0.13794706 -33.45692627]\n [-13.44692544 13.24388917 40.58170632]\n [ 11.31479883 1.07385421 -3.30663376]\n [-24.10843133 -1.90808919 41.53386166]]\n\nInverse method took 0.00022643499687546864 seconds\n\n[[-12.10710752 4.64768699 21.01075846]\n [-11.34348998 -3.24316455 26.12626291]\n [ 12.1989702 -4.42425461 -19.52210838]\n [ 23.00743905 -5.40344451 -43.70383888]\n [ -7.97915438 4.63676968 20.14006475]\n [ 18.75807823 3.5417007 -24.57978448]\n [ 16.05216641 -0.13794706 -33.45692627]\n [-13.44692544 13.24388917 40.58170632]\n [ 11.31479883 1.07385421 -3.30663376]\n [-24.10843133 -1.90808919 41.53386166]]\n\nPLU factorization took 0.0010394660021120217 seconds\n\n" ], [ "#RREF form\nimport numpy as np\nimport sympy as sp\nfrom sympy import init_printing\ninit_printing()\nM = np.rint(np.random.randn(20,30)*100)\nM1 =sp.Matrix(M)\nK = M1.rref()\nK", "_____no_output_____" ], [ "# A = QR factorization\n\nimport numpy as np\nfrom scipy import linalg\nM = np.rint(np.random.randn(20,20)*100)\nq,r = linalg.qr(M)\nprint(q)\nprint(r)\ncol1 = q[0:19,0:1]\nk = np.square(col1)\nprint(sum(k))", "[[-2.33618717e-02 1.56981091e-01 -1.20153077e-01 1.65975704e-01\n 2.45752002e-01 -1.54713021e-01 4.77524022e-03 4.62913032e-02\n 8.16701642e-02 -3.21646050e-01 -3.42885645e-01 1.61431956e-02\n 1.48236486e-01 -5.59152507e-01 2.45843649e-01 2.11288880e-01\n -2.39052852e-02 1.67621495e-01 -2.90123206e-01 -2.56565136e-01]\n [-2.92023396e-02 -2.36778526e-01 -3.30396989e-01 -8.01047483e-02\n -4.27299152e-01 -1.97506028e-01 -1.44670939e-01 1.32975861e-01\n 5.51915939e-02 -3.36639497e-01 -2.61979512e-01 1.32712273e-01\n -3.63420360e-01 8.37874782e-02 -1.08183755e-01 -2.61542217e-01\n 1.44911652e-01 1.84920479e-01 1.35816579e-01 -2.68023900e-01]\n [ 2.33618717e-01 3.20160117e-01 2.12345329e-02 -3.97566528e-01\n -2.18914066e-01 -2.10590547e-01 4.29934950e-01 -2.93668642e-01\n -1.03082230e-01 -3.14195332e-01 3.37164071e-01 5.39409667e-02\n 9.92154189e-02 -1.73216310e-01 5.56725061e-02 -2.42210169e-02\n 2.44813058e-02 5.41257769e-02 2.14094482e-01 -4.71138812e-02]\n [-3.35826906e-01 -5.42950443e-01 -2.07667380e-03 -8.14449398e-02\n -5.45067725e-02 -1.01375495e-01 1.21239801e-01 -9.56448116e-02\n 4.34160812e-01 -1.24596681e-01 6.65186533e-02 -1.17622327e-01\n 3.74440298e-01 -1.86315379e-01 -2.81174670e-03 -6.20987415e-02\n -2.18277126e-01 -2.33388424e-01 2.09995415e-01 3.76374557e-02]\n [-3.35826906e-01 -9.18340806e-03 -7.13251743e-02 8.49892330e-02\n -2.99244119e-01 -2.27072318e-01 1.87334069e-01 1.61860061e-01\n -1.42116164e-01 7.17852553e-04 1.59283638e-02 2.64148264e-02\n -1.85006332e-01 -3.54452690e-02 -1.06929776e-01 7.03373497e-01\n 1.24973804e-01 -1.19731730e-01 4.97815325e-03 2.82212742e-01]\n [-1.19729593e-01 -2.88020732e-02 -2.33777107e-01 -3.21101830e-01\n 3.70366607e-01 -1.83993242e-01 -3.60758589e-02 1.41495517e-01\n -1.59841933e-02 -1.87241559e-01 2.57033623e-01 2.66641080e-01\n 8.19945653e-02 3.60321208e-01 -1.09491472e-01 8.57380056e-02\n 2.78486558e-02 -3.07853340e-01 -3.79948964e-01 -2.57772773e-01]\n [-3.50428076e-01 3.17404489e-02 -2.43910372e-01 -5.20011089e-02\n 2.72408934e-01 -6.11401024e-02 1.86240961e-02 -4.45321421e-01\n -6.92096372e-02 -1.01633074e-02 -2.34597236e-01 1.91989071e-01\n 1.25905865e-01 1.88140875e-01 1.75665572e-01 -1.16297196e-01\n 3.63542498e-01 2.32002017e-01 1.23775195e-01 3.79029730e-01]\n [ 7.00856151e-02 -2.85758793e-01 3.81950781e-03 -2.31678046e-01\n -2.46871591e-01 -1.95969321e-02 -2.47631196e-03 -3.00092847e-01\n 1.06106414e-01 4.26944603e-01 7.97354617e-02 2.15637304e-01\n -2.10370439e-01 -7.84301206e-02 4.82540874e-01 1.11387081e-01\n -3.74093805e-02 7.93627569e-02 -3.80704097e-01 -1.16869093e-01]\n [-2.62821057e-02 -1.22959404e-01 3.92933966e-02 -1.88915548e-02\n 1.42827992e-01 -6.69660191e-01 -1.11520024e-02 2.19814056e-01\n -4.46205797e-01 2.69995914e-01 3.09831566e-03 -1.20134695e-01\n -1.42236945e-02 -1.65017215e-01 1.21391892e-01 -3.21962789e-01\n -1.24485469e-01 -5.02006992e-02 4.81333353e-02 1.11356388e-01]\n [-1.13889125e-01 1.63749911e-02 -3.13485404e-01 -2.39592051e-01\n -1.09527933e-01 2.57710226e-01 8.43057981e-02 7.69641891e-03\n -3.55206509e-01 -1.04466954e-01 -2.29099278e-01 -3.72137856e-01\n 1.00453687e-01 2.47396961e-01 2.21241303e-01 7.92559339e-02\n -5.31463647e-01 7.52099891e-02 -5.22051714e-02 9.32887248e-03]\n [ 6.22009834e-01 -3.77893086e-01 -8.79188418e-02 -1.45768449e-01\n 4.94873988e-02 -6.19246537e-02 -2.82615499e-01 4.12476528e-02\n -7.32103914e-02 -1.71576055e-01 -4.71676447e-02 6.77963792e-02\n 2.45892332e-01 3.16451579e-03 -7.92180383e-02 2.69082307e-01\n 2.71343944e-02 1.47298734e-01 -7.03787331e-03 3.87569428e-01]\n [-8.17665510e-02 -4.42458413e-02 4.29877494e-01 1.75371015e-01\n 3.30954713e-02 -3.17587156e-01 -1.24632937e-01 -7.76026024e-02\n 1.40518116e-01 -2.68662941e-01 1.87463961e-01 -2.79863066e-01\n -2.71500982e-02 4.38221407e-01 2.17396906e-01 1.50318477e-01\n -5.20607693e-02 4.10614341e-01 -4.12334500e-02 -1.06096201e-01]\n [ 8.76070189e-02 -1.82907214e-01 -2.88818551e-01 8.61777106e-02\n 3.51557629e-01 8.96194609e-02 5.31140727e-02 6.33599496e-02\n -6.85725629e-02 1.83860344e-01 2.25566966e-01 -7.49725513e-03\n -1.28487336e-01 -1.74271736e-02 1.87495263e-01 2.87632692e-01\n 4.96845000e-02 1.40355189e-01 5.82516435e-01 -3.79381668e-01]\n [-8.76070189e-02 -3.76801828e-02 -1.09529647e-01 3.95932210e-01\n -1.54074939e-01 1.38377394e-01 -3.83810985e-01 -1.79937844e-01\n -3.16972476e-01 -3.34813315e-01 4.06655985e-01 1.24577138e-01\n -1.96864583e-02 -1.25544085e-01 2.96296715e-01 -9.86509512e-02\n -3.88411705e-02 -2.89621348e-01 2.45574800e-04 8.39544929e-02]\n [ 4.08832755e-02 -1.71231464e-01 -4.03082140e-01 2.92985892e-01\n 4.82814475e-02 3.70642074e-02 3.41000004e-01 -4.32468680e-02\n 3.86760151e-02 2.66555874e-02 3.80112358e-01 -2.73339471e-01\n -7.97349173e-02 -8.07886569e-02 -2.61234048e-01 -1.63516313e-01\n 4.98069472e-02 3.31685986e-01 -3.75283120e-01 1.27400958e-01]\n [-2.36538951e-01 -1.86158831e-01 2.86774738e-01 -4.29532109e-01\n 2.69450441e-01 3.01057564e-01 -5.42380578e-02 1.93300212e-01\n -1.02563888e-01 -2.42852544e-01 1.44104378e-01 -7.82175715e-02\n -4.15147260e-01 -3.01139371e-01 2.41696718e-02 -6.03333484e-02\n 7.53003063e-02 1.66846980e-01 -2.73607660e-02 2.03019236e-01]\n [ 4.38035095e-02 1.08709031e-01 -5.03311931e-02 1.19174902e-01\n 2.12711755e-01 -1.44522342e-01 8.28725681e-03 -2.02662623e-01\n 2.01724583e-01 -5.62815142e-02 -2.40167549e-02 3.68009747e-01\n -3.98153115e-01 -7.01211203e-04 -1.70780896e-01 2.45180060e-02\n -6.57997128e-01 5.27785787e-02 9.78980930e-02 2.20821253e-01]\n [ 2.45299653e-01 -2.04951825e-01 1.22528881e-01 2.36981300e-01\n 1.06730609e-01 8.46217102e-02 5.70266377e-01 1.99955870e-01\n 1.30732211e-02 -2.27453572e-01 -1.99646820e-01 1.15970006e-01\n -1.67093858e-01 2.19542060e-01 3.79272973e-01 -1.17093331e-01\n 9.16206706e-02 -2.76675834e-01 -2.14377134e-02 1.36439503e-01]\n [ 1.51852166e-01 2.65021071e-01 -2.90631383e-01 -1.37426495e-01\n 7.78109594e-02 -1.52748909e-01 -2.11194670e-01 -3.62005688e-03\n 4.23970016e-01 4.27792801e-03 2.69010043e-02 -4.88224294e-01\n -2.87194563e-01 -1.51605550e-03 2.38421248e-01 1.32296079e-04\n 1.30720513e-01 -3.20353318e-01 3.63218125e-02 2.23902749e-01]\n [-1.05128423e-01 2.35283804e-01 -1.49055380e-01 -3.30680510e-02\n -1.52830259e-01 5.26084332e-02 -2.98123727e-02 5.80863869e-01\n 2.57840394e-01 7.47460453e-02 2.35487320e-01 3.01227212e-01\n 2.42532539e-01 3.18213543e-02 3.14277527e-01 -1.11335619e-01\n -9.08899930e-02 2.98667512e-01 6.11526951e-02 2.35367596e-01]]\n[[ 342.43831561 70.35719691 68.96716554 31.56772916 -6.98227941\n 119.74419371 -121.18386906 41.88199552 -162.92277311 93.55261529\n 178.66867465 103.3120372 -73.27743087 -68.36559734 -201.06394892\n 129.83944253 119.79091746 -36.46788175 6.29018396 -14.6508138 ]\n [ 0. 367.20139548 -33.7970841 7.07236709 34.87528578\n -112.15879439 -5.36719818 -154.36678755 -173.67638347 4.70014615\n -115.28721744 -71.55132215 -7.80608517 -130.33716319 -228.98525221\n 157.42276987 3.84488417 -94.72246699 280.70274666 15.23902213]\n [ 0. 0. -390.47443858 -11.17330138 -60.10951977\n 95.38923463 -117.63974225 -82.63887976 83.92465739 126.03695046\n 32.62862453 100.60675051 -54.34648646 28.22472743 -70.0859624\n -35.46908811 38.73158565 53.06687122 31.38971623 52.02527587]\n [ 0. 0. 0. 363.21428584 -21.93156549\n 1.22238738 -88.09941456 51.72503043 -69.77390589 53.67565322\n 147.53758521 -120.65654176 -117.53342791 -90.24616864 -6.16575841\n -37.47758641 -38.83096161 47.91400861 42.28613154 -91.01235893]\n [ 0. 0. 0. 0. -342.70368291\n 20.14782147 -68.34947394 -111.49003365 -30.05179565 -1.72015434\n -88.75367247 85.10278274 57.56820922 20.35130401 18.5554377\n -64.95827239 116.31087301 43.13493904 89.62391823 131.09456574]\n [ 0. 0. 0. 0. 0.\n -431.19392144 -249.90017354 -105.11093022 17.18720323 -32.77239362\n 37.76395109 -126.69920212 51.21850286 -25.2505193 25.53685758\n -233.70639677 -28.50098204 110.67826096 170.61833538 -266.55030539]\n [ 0. 0. 0. 0. 0.\n 0. -495.62717837 -107.59843482 24.95196524 -177.26760723\n 83.28166998 -24.48187293 10.68061419 -95.25961425 31.11792871\n 86.22024239 37.95970503 -239.58335639 -180.30128461 2.10091367]\n [ 0. 0. 0. 0. 0.\n 0. 0. -424.54254404 -70.34169502 18.38374079\n 119.72717556 29.91370321 -30.12516821 109.65195342 -43.13708993\n 77.47590473 -101.06372408 66.78436785 -26.78267489 17.99967124]\n [ 0. 0. 0. 0. 0.\n 0. 0. 0. 322.07277557 -62.40018657\n 40.37274989 -123.41871694 121.82376017 101.1796782 135.46761976\n 72.16462615 232.71930034 11.95648541 68.0504266 -115.51798281]\n [ 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 413.10396957\n 13.65679827 56.21193891 -125.27626245 -38.20851962 39.72593938\n 6.30182557 -88.78018888 17.06600691 -41.82705136 27.2430869 ]\n [ 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0.\n -345.63733223 103.22244278 81.81326841 120.07925344 -93.51459856\n 91.13726267 32.26318753 -171.10337249 88.4624956 -26.05783665]\n [ 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0.\n 0. -276.92980031 -67.27880196 60.8393599 -15.49446423\n 117.61421789 79.73277849 -65.12871595 133.97452677 32.74581903]\n [ 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0.\n 0. 0. -259.67822841 34.70553194 4.13874431\n -235.16869031 -70.63328594 -101.3205801 118.38956003 46.05031727]\n [ 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0.\n 0. 0. 0. -177.40774077 -197.71185704\n -106.69636764 -251.43776386 -101.95993169 32.29774908 63.24866086]\n [ 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 231.14415889\n 73.86295448 -85.53741076 158.2816466 -177.16872789 57.20222031]\n [ 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0.\n -101.21633739 111.96486442 -26.87869511 47.66559673 122.14332509]\n [ 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0.\n 0. 156.39315639 142.48966893 -161.45317433 71.3309891 ]\n [ 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0.\n 0. 0. -196.31711289 -121.77102999 -75.00141746]\n [ 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0.\n 0. 0. 0. -213.74419675 69.2369638 ]\n [ 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0.\n 0. 0. 0. 0. 0.\n 0. 0. 0. 0. -117.28134742]]\n[0.98894801]\n" ], [ "# diagonalize a matrix & get power\n\nimport numpy as np\nfrom scipy import linalg as LA\nfrom numpy.linalg import matrix_power\nimport sympy as sp\nfrom sympy import init_printing\ninit_printing()\nM = np.rint(np.random.randn(50,50))\nM = M.dot(M.T)\neig = LA.eigvals(M)\ndiagMatrix = np.diag(eig)\ndiagMat = sp.Matrix(diagMatrix)\npowerMatrix = matrix_power(diagMatrix,9)\npowermat = sp.Matrix(powerMatrix)\npowermat", "_____no_output_____" ], [ "# Markov matrix & steady state\n\nimport numpy as np\nfrom scipy import linalg as LA\nfrom numpy.linalg import matrix_power\nimport sympy as sp\n\nk = np.array([72, 32, 34])\nmarkov = np.zeros((3,3))\nfor i in range(0,3):\n m = np.random.rand(1,3)\n m = m/np.sum(m)\n markov[i] = m\nfor i in range (1,100000):\n base = matrix_power(markov, i)\n base_1 = matrix_power( markov,i+1)\n if (base==base_1).all():\n print(\"steady state reached for i = %s\" % i)\n break\nprint(markov)\nprint(base_1)\nprint(k.dot(base_1))", "steady state reached for i = 180\n[[0.68991098 0.16168705 0.14840196]\n [0.45741842 0.10102452 0.44155706]\n [0.06250443 0.54703293 0.39046264]]\n[[0.44346497 0.26012679 0.29640824]\n [0.44346497 0.26012679 0.29640824]\n [0.44346497 0.26012679 0.29640824]]\n[61.19816597 35.89749759 40.90433643]\n" ], [ "#DFT & FFT\n\nimport numpy as np\nfrom scipy import linalg as LA\nfrom scipy.linalg import dft \nfrom scipy.fftpack import fft\nimport sympy as sp\nfrom sympy import init_printing\nimport time\n\ninit_printing()\nmatrix = np.random.randint(0 , 10000, 2500).reshape(50,50)\n\ntic1 = time.perf_counter()\ndft = dft(50).dot(matrix)\ntoc1 = time.perf_counter()\nprint(\"\\n DFT took %s seconds\\n\" % (toc1-tic1))\ndft1 = sp.Matrix(dft)\ntic1 = time.perf_counter()\nfft = fft(matrix)\ntoc1 = time.perf_counter()\nprint(\"\\n FFT took %s seconds\\n\" % (toc1-tic1))\nfft1 = sp.Matrix(fft)\nfft1", "\n DFT took 0.0015871549994699308 seconds\n\n\n FFT took 0.00013783499980490888 seconds\n\n" ], [ "# check similarity\n\"\"\"\n1) Two matrices A & B will be similar only when they have the same eigen values.\nIf they have different eigen values , there will be no solution to the equation PA = PB.\nWe will verify this through a 10* 10 matrix\n2) Given a 50 by 50 matrix , how to find a similar matrix ( non diagonal)\nGet any invertible 50 by 50 matrix & multiply Pinv. A. P\nThe resultant matrix should have same eigen values & similar to A\n3) Also we can find the similar matrix by multiplying Eigen values with V*VT where V is the column of any orthonormal basis\n\n\"\"\"\nimport numpy as np\nfrom scipy import linalg as LA\nfrom numpy.linalg import inv\n\nnp.set_printoptions(suppress=True)\nA = np.random.randint(1,100,2500).reshape(50,50)\nA = A.dot(A.T)\nP = np.random.randn(50,50)\nP_inv = inv(P)\neig1 = LA.eigvals(A)\neig1 = np.sort(eig1)\n\nB1 = P_inv.dot(A)\nB = B1.dot(P)\neig2 = LA.eigvals(B)\neig2 = np.sort(eig2)\n\nprint(np.real(eig1))\nprint(np.real(eig2))", "[ 0.61299541 40.5904105 150.63643592 392.60069182\n 657.87501648 949.01831848 1216.38304867 2491.66708938\n 3648.09011413 3952.4210281 4809.48633337 5248.20360795\n 7192.5849483 7410.04138778 7793.48702946 9094.59604975\n 11070.56032108 12060.7825494 15127.89983541 15869.9719397\n 16560.48048864 18756.06737826 21738.38359667 23493.12505903\n 25572.48937707 29250.06848224 29660.39309054 31609.2960214\n 36010.29791256 43294.17925211 43985.58804656 46350.16235575\n 52338.1365957 53983.69210315 56582.08677284 62584.14695133\n 66293.08942119 69362.99060637 69911.60534016 76928.42927365\n 83613.02226074 92305.04914814 97898.45891822 100277.73795682\n 106072.81046699 111620.01352803 118478.68785976 139401.26194024\n 149090.93731188 6342274.80333284]\n[ 0.61299541 40.5904105 150.63643592 392.60069182\n 657.87501648 949.01831848 1216.38304868 2491.66708938\n 3648.09011413 3952.4210281 4809.48633337 5248.20360794\n 7192.5849483 7410.04138778 7793.48702945 9094.59604975\n 11070.56032108 12060.78254939 15127.89983541 15869.9719397\n 16560.48048864 18756.06737826 21738.38359667 23493.12505903\n 25572.48937707 29250.06848224 29660.39309053 31609.2960214\n 36010.29791254 43294.17925213 43985.58804657 46350.16235575\n 52338.13659571 53983.69210315 56582.08677284 62584.14695133\n 66293.0894212 69362.99060637 69911.60534017 76928.42927366\n 83613.02226074 92305.04914814 97898.45891822 100277.73795683\n 106072.810467 111620.01352803 118478.68785976 139401.26194023\n 149090.93731189 6342274.80333284]\n" ], [ "# jordan normal form\nfrom scipy import linalg as LA\nimport numpy as np\nimport sympy as sp\nfrom sympy import Matrix\nfrom sympy import init_printing\ninit_printing()\nC = np.eye(50,50)\nfor i in range (25,50):\n C[i] = C[i]*2\nfor i in range(0,48):\n k = np.random.randint(0,2)\n if k == 0:\n C[i,i+1] =1\nP = np.random.rand(50,50)\np_inv = inv(P)\nJMatrix = p_inv.dot(C).dot(P)\neigC, eigV =LA.eig(C)\neigJ, eigK = LA.eig(JMatrix)\n\nprint(eigC)\nprint(eigJ)\n\n", "[1.+0.j 1.+0.j 1.+0.j 1.+0.j 1.+0.j 1.+0.j 1.+0.j 1.+0.j 1.+0.j 1.+0.j\n 1.+0.j 1.+0.j 1.+0.j 1.+0.j 1.+0.j 1.+0.j 1.+0.j 1.+0.j 1.+0.j 1.+0.j\n 1.+0.j 1.+0.j 1.+0.j 1.+0.j 1.+0.j 2.+0.j 2.+0.j 2.+0.j 2.+0.j 2.+0.j\n 2.+0.j 2.+0.j 2.+0.j 2.+0.j 2.+0.j 2.+0.j 2.+0.j 2.+0.j 2.+0.j 2.+0.j\n 2.+0.j 2.+0.j 2.+0.j 2.+0.j 2.+0.j 2.+0.j 2.+0.j 2.+0.j 2.+0.j 2.+0.j]\n[0.9444812 +0.01623606j 0.9444812 -0.01623606j 0.96194689+0.04365289j\n 0.96194689-0.04365289j 0.99151349+0.05740311j 0.99151349-0.05740311j\n 1.02396327+0.05299336j 1.02396327-0.05299336j 1.04894381+0.03160911j\n 1.04894381-0.03160911j 1.05830266+0.j 1.00000657+0.00001138j\n 1.00000657-0.00001138j 0.99998686+0.j 2.00026498+0.000265j\n 2.00026498-0.000265j 1.99973502+0.00026496j 1.99973502-0.00026496j\n 2.00001596+0.00001103j 2.00001596-0.00001103j 2.00000808+0.00001399j\n 2.00000808-0.00001399j 2.00000157+0.00001933j 2.00000157-0.00001933j\n 1.99998247+0.0000083j 1.99998247-0.0000083j 1.99998384+0.j\n 0.99999995+0.00000011j 0.99999995-0.00000011j 1.00000005+0.00000011j\n 1.00000005-0.00000011j 1. +0.00000002j 1. -0.00000002j\n 1. +0.00000002j 1. -0.00000002j 1. +0.j\n 1. +0.j 1. +0.j 1.99999993+0.00000006j\n 1.99999993-0.00000006j 2.00000007+0.00000006j 2.00000007-0.00000006j\n 1.99999997+0.00000001j 1.99999997-0.00000001j 2.00000003+0.00000001j\n 2.00000003-0.00000001j 2. +0.j 2. +0.j\n 2. +0.j 2. +0.j ]\n" ], [ "# Singular value decomposition\n\nfrom scipy import linalg as LA\nimport numpy as np\nfrom sympy import Matrix\nfrom sympy import init_printing\ninit_printing(num_columns = 40)\n\nmatrix = np.random.randint(1,10,1200).reshape(30,40)\nU, Sigma, VT = LA.svd(matrix)\nSigma = np.diag(Sigma)\nk = np.zeros((30,10))\nSigma = np.column_stack((Sigma,k))\nmatrix = sp.Matrix(matrix)\nproduct = U.dot(Sigma).dot(VT)\nproduct = np.round(product , decimals =2)\nproduct = sp.Matrix(product)\nmatrix == product", "_____no_output_____" ], [ "#psuedo inverse\nfrom scipy import linalg as LA\nimport numpy as np\nfrom sympy import Matrix\nfrom sympy import init_printing\ninit_printing(num_columns = 40, use_latex = True)\n\nmatrix = np.random.randint(1,10,1200).reshape(30,40)\nmatrixT = matrix.T\npsuInv1 = LA.pinv(matrix)\npsuInv2 = LA.pinv(matrixT)\npsuInv1s= sp.Matrix(psuInv1)\npsuInv2s= sp.Matrix(psuInv2)\npsuInv2s\n", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
4a0c833749aabec1871da8820b73011913d15d05
87,737
ipynb
Jupyter Notebook
code/04.PythonCrawler_beautifulsoup.ipynb
XinyueSha/cjc
c20b0dbc929f5fb00dbdbc15ce4e1b1c8657a607
[ "MIT" ]
2
2019-06-12T06:21:38.000Z
2019-06-17T09:47:06.000Z
code/04.PythonCrawler_beautifulsoup.ipynb
XinyueSha/cjc
c20b0dbc929f5fb00dbdbc15ce4e1b1c8657a607
[ "MIT" ]
null
null
null
code/04.PythonCrawler_beautifulsoup.ipynb
XinyueSha/cjc
c20b0dbc929f5fb00dbdbc15ce4e1b1c8657a607
[ "MIT" ]
null
null
null
43.391197
11,227
0.582992
[ [ [ "\n# 数据抓取:\n\n> # Beautifulsoup简介\n***\n\n王成军\n\[email protected]\n\n计算传播网 http://computational-communication.com", "_____no_output_____" ], [ "# 需要解决的问题 \n\n- 页面解析\n- 获取Javascript隐藏源数据\n- 自动翻页\n- 自动登录\n- 连接API接口\n", "_____no_output_____" ] ], [ [ "import urllib2\nfrom bs4 import BeautifulSoup", "_____no_output_____" ] ], [ [ "- 一般的数据抓取,使用urllib2和beautifulsoup配合就可以了。\n- 尤其是对于翻页时url出现规则变化的网页,只需要处理规则化的url就可以了。\n- 以简单的例子是抓取天涯论坛上关于某一个关键词的帖子。\n - 在天涯论坛,关于雾霾的帖子的第一页是:\nhttp://bbs.tianya.cn/list.jsp?item=free&nextid=0&order=8&k=雾霾\n - 第二页是:\nhttp://bbs.tianya.cn/list.jsp?item=free&nextid=1&order=8&k=雾霾\n", "_____no_output_____" ], [ "# Beautiful Soup\n> Beautiful Soup is a Python library designed for quick turnaround projects like screen-scraping. Three features make it powerful:\n\n- Beautiful Soup provides a few simple methods. It doesn't take much code to write an application\n- Beautiful Soup automatically converts incoming documents to Unicode and outgoing documents to UTF-8. Then you just have to specify the original encoding.\n- Beautiful Soup sits on top of popular Python parsers like lxml and html5lib.\n", "_____no_output_____" ], [ "# Install beautifulsoup4\n\n### open your terminal/cmd\n\n> $ pip install beautifulsoup4", "_____no_output_____" ], [ "# 第一个爬虫\n\nBeautifulsoup Quick Start \n\nhttp://www.crummy.com/software/BeautifulSoup/bs4/doc/\n\n![](./img/bs.jpg)\n", "_____no_output_____" ] ], [ [ "url = 'file:///Users/chengjun/GitHub/cjc/data/test.html'\n# http://computational-class.github.io/cjc/data/test.html\ncontent = urllib2.urlopen(url).read() \nsoup = BeautifulSoup(content, 'html.parser') \nsoup", "_____no_output_____" ] ], [ [ "# html.parser\nBeautiful Soup supports the html.parser included in Python’s standard library\n\n# lxml\nbut it also supports a number of third-party Python parsers. One is the lxml parser `lxml`. Depending on your setup, you might install lxml with one of these commands:\n\n> $ apt-get install python-lxml\n\n> $ easy_install lxml\n\n> $ pip install lxml", "_____no_output_____" ], [ "# html5lib\nAnother alternative is the pure-Python html5lib parser `html5lib`, which parses HTML the way a web browser does. Depending on your setup, you might install html5lib with one of these commands:\n\n> $ apt-get install python-html5lib\n\n> $ easy_install html5lib\n\n> $ pip install html5lib", "_____no_output_____" ] ], [ [ "print(soup.prettify())", "<html>\n <head>\n <title>\n The Dormouse's story\n </title>\n </head>\n <body>\n <p class=\"title\">\n <b>\n The Dormouse's story\n </b>\n </p>\n <p class=\"story\">\n Once upon a time there were three little sisters; and their names were\n <a class=\"sister\" href=\"http://example.com/elsie\" id=\"link1\">\n Elsie\n </a>\n ,\n <a class=\"sister\" href=\"http://example.com/lacie\" id=\"link2\">\n Lacie\n </a>\n and\n <a class=\"sister\" href=\"http://example.com/tillie\" id=\"link3\">\n Tillie\n </a>\n ;\nand they lived at the bottom of a well.\n </p>\n <p class=\"story\">\n ...\n </p>\n </body>\n</html>\n" ] ], [ [ "- html\n - head\n - title\n - body\n - p (class = 'title', 'story' )\n - a (class = 'sister')\n - href/id", "_____no_output_____" ], [ "# Select 方法", "_____no_output_____" ] ], [ [ "soup.select('.sister')", "_____no_output_____" ], [ "soup.select('.story')", "_____no_output_____" ], [ "soup.select('#link2')", "_____no_output_____" ], [ "soup.select('#link2')[0]['href']", "_____no_output_____" ] ], [ [ "# find_all方法", "_____no_output_____" ] ], [ [ "soup('p')", "_____no_output_____" ], [ "soup.find_all('p')", "_____no_output_____" ], [ "[i.text for i in soup('p')]", "_____no_output_____" ], [ "for i in soup('p'):\n print i.text", "The Dormouse's story\nOnce upon a time there were three little sisters; and their names were\nElsie,\nLacie and\nTillie;\nand they lived at the bottom of a well.\n...\n" ], [ "for tag in soup.find_all(True):\n print(tag.name)", "html\nhead\ntitle\nbody\np\nb\np\na\na\na\np\n" ], [ "soup('head') # or soup.head", "_____no_output_____" ], [ "soup('body') # or soup.body", "_____no_output_____" ], [ "soup('title') # or soup.title", "_____no_output_____" ], [ "soup('p')", "_____no_output_____" ], [ "soup.p", "_____no_output_____" ], [ "soup.title.name", "_____no_output_____" ], [ "soup.title.string", "_____no_output_____" ], [ "soup.title.text\n# 推荐使用text方法", "_____no_output_____" ], [ "soup.title.parent.name", "_____no_output_____" ], [ "soup.p", "_____no_output_____" ], [ "soup.p['class']", "_____no_output_____" ], [ "soup.find_all('p', {'class', 'title'})", "_____no_output_____" ], [ "soup.find_all('p', class_= 'title')", "_____no_output_____" ], [ "soup.find_all('p', {'class', 'story'})", "_____no_output_____" ], [ "soup.find_all('p', {'class', 'story'})[0].find_all('a')", "_____no_output_____" ], [ "soup.a", "_____no_output_____" ], [ "soup('a')", "_____no_output_____" ], [ "soup.find(id=\"link3\")", "_____no_output_____" ], [ "soup.find_all('a')", "_____no_output_____" ], [ "soup.find_all('a', {'class', 'sister'}) # compare with soup.find_all('a')", "_____no_output_____" ], [ "soup.find_all('a', {'class', 'sister'})[0]", "_____no_output_____" ], [ "soup.find_all('a', {'class', 'sister'})[0].text", "_____no_output_____" ], [ "soup.find_all('a', {'class', 'sister'})[0]['href']", "_____no_output_____" ], [ "soup.find_all('a', {'class', 'sister'})[0]['id']", "_____no_output_____" ], [ "soup.find_all([\"a\", \"b\"])", "_____no_output_____" ], [ "print(soup.get_text())", "The Dormouse's story\n\nThe Dormouse's story\nOnce upon a time there were three little sisters; and their names were\nElsie,\nLacie and\nTillie;\nand they lived at the bottom of a well.\n...\n" ] ], [ [ "***\n***\n# 数据抓取:\n > # 根据URL抓取微信公众号文章内容\n***\n***\n\n王成军\n\[email protected]\n\n计算传播网 http://computational-communication.com\n", "_____no_output_____" ] ], [ [ "from IPython.display import display_html, HTML\nHTML('<iframe src=http://mp.weixin.qq.com/s?__biz=MzA3MjQ5MTE3OA==&\\\nmid=206241627&idx=1&sn=471e59c6cf7c8dae452245dbea22c8f3&3rd=MzA3MDU4NTYzMw==&scene=6#rd\\\nwidth=500 height=500></iframe>')\n# the webpage we would like to crawl", "_____no_output_____" ] ], [ [ "# 查看源代码\n\n# Inspect", "_____no_output_____" ] ], [ [ "url = \"http://mp.weixin.qq.com/s?__biz=MzA3MjQ5MTE3OA==&\\\nmid=206241627&idx=1&sn=471e59c6cf7c8dae452245dbea22c8f3&3rd=MzA3MDU4NTYzMw==&scene=6#rd\"\ncontent = urllib2.urlopen(url).read() #获取网页的html文本\nsoup = BeautifulSoup(content, 'html.parser') ", "_____no_output_____" ], [ "title = soup.select(\"div .title #id1 img \")\nfor i in title:\n print i.text", "_____no_output_____" ], [ "print soup.find('h2', {'class', 'rich_media_title'}).text", "\r\n 南大新传 | 微议题:地震中民族自豪—“中国人先撤” \n" ], [ "print soup.find('div', {'class', 'rich_media_meta_list'})\n", "<div class=\"rich_media_meta_list\">\n<em class=\"rich_media_meta rich_media_meta_text\" id=\"post-date\">2015-05-04</em>\n<em class=\"rich_media_meta rich_media_meta_text\">南大新传院</em>\n<a class=\"rich_media_meta rich_media_meta_link rich_media_meta_nickname\" href=\"javascript:void(0);\" id=\"post-user\">微议题排行榜</a>\n<span class=\"rich_media_meta rich_media_meta_text rich_media_meta_nickname\">微议题排行榜</span>\n<div class=\"profile_container\" id=\"js_profile_qrcode\" style=\"display:none;\">\n<div class=\"profile_inner\">\n<strong class=\"profile_nickname\">微议题排行榜</strong>\n<img alt=\"\" class=\"profile_avatar\" id=\"js_profile_qrcode_img\" src=\"\">\n<p class=\"profile_meta\">\n<label class=\"profile_meta_label\">微信号</label>\n<span class=\"profile_meta_value\">IssuesRank</span>\n</p>\n<p class=\"profile_meta\">\n<label class=\"profile_meta_label\">功能介绍</label>\n<span class=\"profile_meta_value\">感谢关注《微议题排行榜》。我们是南京大学新闻传播学院,计算传播学实验中心,致力于研究社会化媒体时代的公共议程,发布新媒体平台的议题排行榜。</span>\n</p>\n</img></div>\n<span class=\"profile_arrow_wrp\" id=\"js_profile_arrow_wrp\">\n<i class=\"profile_arrow arrow_out\"></i>\n<i class=\"profile_arrow arrow_in\"></i>\n</span>\n</div>\n</div>\n" ], [ "print soup.find('em').text\n", "2015-05-04\n" ], [ "article = soup.find('div', {'class' , 'rich_media_content'}).text\nprint article", "\n点击上方“微议题排行榜”可以订阅哦!导读2015年4月25日,尼泊尔发生8.1级地震,造成至少7000多人死亡,中国西藏、印度、孟加拉国、不丹等地均出现人员伤亡。尼泊尔地震后,祖国派出救援机接国人回家,这一“先撤”行为被大量报道,上演了一出霸道总裁不由分说爱国民的新闻。我们对“地震”中人的关注,远远小于国民尊严的保护。通过“撤离”速度来证明中国的影响力也显得有失妥当,灾难应急管理、救援和灾后重建能力才应是“地震”关注焦点。 热词图现 本文以“地震”为关键词,选取了2015年4月10日至4月30日期间微议题TOP100阅读排行进行分析。根据微议题TOP100标题的词频统计,我们可以看出有关“地震”的话题最热词汇的有“尼泊尔”、“油价”、“发改委”。4月25日尼泊尔发生了8级地震,深受人们的关注。面对国外灾难性事件,微媒体的重心却转向“油价”、“发改委”、“祖国先撤”,致力于将世界重大事件与中国政府关联起来。 微议题演化趋势 总文章数总阅读数从4月10日到4月30日,有关“地震”议题出现三个峰值,分别是在4月15日内蒙古地震,20日台湾地震和25日尼泊尔地震。其中对台湾地震与内蒙古地震报道文章较少,而对尼泊尔地震却给予了极大的关注,无论是在文章量还是阅读量上都空前增多。内蒙古、台湾地震由于级数较小,关注少,议程时间也比较短,一般3天后就会淡出公共视野。而尼泊尔地震虽然接近性较差,但规模大,且衍生话题性较强,其讨论热度持续了一周以上。 议题分类 如图,我们将此议题分为6大类。1尼泊尔地震这类文章是对4月25日尼泊尔地震的新闻报道,包括现场视频,地震强度、规模,损失程度、遇难人员介绍等。更进一步的,有对尼泊尔地震原因探析,认为其处在板块交界处,灾难是必然的。因尼泊尔是佛教圣地,也有从佛学角度解释地震的启示。2国内地震报道主要是对10日内蒙古、甘肃、山西等地的地震,以及20日台湾地震的报道。偏重于对硬新闻的呈现,介绍地震范围、级数、伤亡情况,少数几篇是对甘肃地震的辟谣,称其只是微震。3中国救援回应地震救援的报道大多是与尼泊尔地震相关,并且80%的文章是中国政府做出迅速反应派出救援机接国人回家。以“中国人又先撤了”,来为祖国点赞。少数几篇是滴滴快的、腾讯基金、万达等为尼泊尔捐款的消息。4发改委与地震这类文章内容相似,纯粹是对发改委的调侃。称其“预测”地震非常准确,只要一上调油价,便会发生地震。5地震常识介绍该类文章介绍全国地震带、地震频发地,地震逃生注意事项,“专家传受活命三角”,如何用手机自救等小常识。6地震中的故事讲述地震中的感人瞬间,回忆汶川地震中的故事,传递“:地震无情,人间有情”的正能量。 国内外地震关注差异大关于“地震”本身的报道仍旧是媒体关注的重点,尼泊尔地震与国内地震报道占一半的比例。而关于尼泊尔话题的占了45%,国内地震相关的只有22%。微媒体对国内外地震关注有明显的偏差,而且在衍生话题方面也相差甚大。尼泊尔地震中,除了硬新闻报道外,还有对其原因分析、中国救援情况等,而国内地震只是集中于硬新闻。地震常识介绍只占9%,地震知识普及还比较欠缺。 阅读与点赞分析 爱国新闻容易激起点赞狂潮整体上来说,网民对地震议题关注度较高,自然灾害类话题一旦爆发,很容易引起人们情感共鸣,掀起热潮。但从点赞数来看,“中国救援回应”类的总点赞与平均点赞都是最高的,网民对地震的关注点并非地震本身,而是与之相关的“政府行动”。尼泊尔地震后,祖国派出救援机接国人回家,这一“先撤”行为被大量报道,上演了一出霸道总裁不由分说爱国民的新闻。而爱国新闻则往往是最容易煽动民族情绪,产生民族优越感,激起点赞狂潮。 人的关注小于国民尊严的保护另一方面,国内地震的关注度却很少,不仅体现在政府救援的报道量小,网民的兴趣点与评价也较低。我们对“地震”中人的关注,远远小于国民尊严的保护。通过“撤离”速度来证明中国的影响力也显得有失妥当,灾难应急管理、救援和灾后重建能力才应是“地震”关注焦点。“发改委与地震”的点赞量也相对较高,网民对发改委和地震的调侃,反映出的是对油价上涨的不满,这种“怨气”也容易产生共鸣。一面是民族优越感,一面是对政策不满,两种情绪虽矛盾,但同时体现了网民心理趋同。 数据附表 微文章排行TOP50:公众号排行TOP20:作者:晏雪菲出品单位:南京大学计算传播学实验中心技术支持:南京大学谷尼舆情监测分析实验室题图鸣谢:谷尼舆情新微榜、图悦词云\n\n" ], [ "rmml = soup.find('div', {'class', 'rich_media_meta_list'})\ndate = rmml.find(id = 'post-date').text\nrmc = soup.find('div', {'class', 'rich_media_content'})\ncontent = rmc.get_text()\nprint title\nprint date\nprint content", "[]\n2015-05-04\n\n点击上方“微议题排行榜”可以订阅哦!导读2015年4月25日,尼泊尔发生8.1级地震,造成至少7000多人死亡,中国西藏、印度、孟加拉国、不丹等地均出现人员伤亡。尼泊尔地震后,祖国派出救援机接国人回家,这一“先撤”行为被大量报道,上演了一出霸道总裁不由分说爱国民的新闻。我们对“地震”中人的关注,远远小于国民尊严的保护。通过“撤离”速度来证明中国的影响力也显得有失妥当,灾难应急管理、救援和灾后重建能力才应是“地震”关注焦点。 热词图现 本文以“地震”为关键词,选取了2015年4月10日至4月30日期间微议题TOP100阅读排行进行分析。根据微议题TOP100标题的词频统计,我们可以看出有关“地震”的话题最热词汇的有“尼泊尔”、“油价”、“发改委”。4月25日尼泊尔发生了8级地震,深受人们的关注。面对国外灾难性事件,微媒体的重心却转向“油价”、“发改委”、“祖国先撤”,致力于将世界重大事件与中国政府关联起来。 微议题演化趋势 总文章数总阅读数从4月10日到4月30日,有关“地震”议题出现三个峰值,分别是在4月15日内蒙古地震,20日台湾地震和25日尼泊尔地震。其中对台湾地震与内蒙古地震报道文章较少,而对尼泊尔地震却给予了极大的关注,无论是在文章量还是阅读量上都空前增多。内蒙古、台湾地震由于级数较小,关注少,议程时间也比较短,一般3天后就会淡出公共视野。而尼泊尔地震虽然接近性较差,但规模大,且衍生话题性较强,其讨论热度持续了一周以上。 议题分类 如图,我们将此议题分为6大类。1尼泊尔地震这类文章是对4月25日尼泊尔地震的新闻报道,包括现场视频,地震强度、规模,损失程度、遇难人员介绍等。更进一步的,有对尼泊尔地震原因探析,认为其处在板块交界处,灾难是必然的。因尼泊尔是佛教圣地,也有从佛学角度解释地震的启示。2国内地震报道主要是对10日内蒙古、甘肃、山西等地的地震,以及20日台湾地震的报道。偏重于对硬新闻的呈现,介绍地震范围、级数、伤亡情况,少数几篇是对甘肃地震的辟谣,称其只是微震。3中国救援回应地震救援的报道大多是与尼泊尔地震相关,并且80%的文章是中国政府做出迅速反应派出救援机接国人回家。以“中国人又先撤了”,来为祖国点赞。少数几篇是滴滴快的、腾讯基金、万达等为尼泊尔捐款的消息。4发改委与地震这类文章内容相似,纯粹是对发改委的调侃。称其“预测”地震非常准确,只要一上调油价,便会发生地震。5地震常识介绍该类文章介绍全国地震带、地震频发地,地震逃生注意事项,“专家传受活命三角”,如何用手机自救等小常识。6地震中的故事讲述地震中的感人瞬间,回忆汶川地震中的故事,传递“:地震无情,人间有情”的正能量。 国内外地震关注差异大关于“地震”本身的报道仍旧是媒体关注的重点,尼泊尔地震与国内地震报道占一半的比例。而关于尼泊尔话题的占了45%,国内地震相关的只有22%。微媒体对国内外地震关注有明显的偏差,而且在衍生话题方面也相差甚大。尼泊尔地震中,除了硬新闻报道外,还有对其原因分析、中国救援情况等,而国内地震只是集中于硬新闻。地震常识介绍只占9%,地震知识普及还比较欠缺。 阅读与点赞分析 爱国新闻容易激起点赞狂潮整体上来说,网民对地震议题关注度较高,自然灾害类话题一旦爆发,很容易引起人们情感共鸣,掀起热潮。但从点赞数来看,“中国救援回应”类的总点赞与平均点赞都是最高的,网民对地震的关注点并非地震本身,而是与之相关的“政府行动”。尼泊尔地震后,祖国派出救援机接国人回家,这一“先撤”行为被大量报道,上演了一出霸道总裁不由分说爱国民的新闻。而爱国新闻则往往是最容易煽动民族情绪,产生民族优越感,激起点赞狂潮。 人的关注小于国民尊严的保护另一方面,国内地震的关注度却很少,不仅体现在政府救援的报道量小,网民的兴趣点与评价也较低。我们对“地震”中人的关注,远远小于国民尊严的保护。通过“撤离”速度来证明中国的影响力也显得有失妥当,灾难应急管理、救援和灾后重建能力才应是“地震”关注焦点。“发改委与地震”的点赞量也相对较高,网民对发改委和地震的调侃,反映出的是对油价上涨的不满,这种“怨气”也容易产生共鸣。一面是民族优越感,一面是对政策不满,两种情绪虽矛盾,但同时体现了网民心理趋同。 数据附表 微文章排行TOP50:公众号排行TOP20:作者:晏雪菲出品单位:南京大学计算传播学实验中心技术支持:南京大学谷尼舆情监测分析实验室题图鸣谢:谷尼舆情新微榜、图悦词云\n\n" ] ], [ [ "# 尝试抓取阅读数和点赞数", "_____no_output_____" ] ], [ [ "url = 'http://mp.weixin.qq.com/s?src=3&timestamp=1463191394&ver=1&signature=cV3qMIBeBTS6i8cJJOPu98j-H9veEPx0Y0BekUE7F6*sal9nkYG*w*FwDiaySIfR4XZL-XFbo2TFzrMxEniDETDYIMRuKmisV8xjfOcCjEWmPkYfK57G*cffYv4JxuM*RUtN8LUIg*n6Kd0AKB8--w=='", "_____no_output_____" ], [ "content = urllib2.urlopen(url).read() #获取网页的html文本\nsoup = BeautifulSoup(content, 'html.parser') ", "_____no_output_____" ], [ "print soup", "<!DOCTYPE html>\n\n<html>\n<head>\n<meta content=\"text/html; charset=utf-8\" http-equiv=\"Content-Type\">\n<meta content=\"IE=edge\" http-equiv=\"X-UA-Compatible\">\n<meta content=\"width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=0\" name=\"viewport\"/>\n<meta content=\"yes\" name=\"apple-mobile-web-app-capable\">\n<meta content=\"black\" name=\"apple-mobile-web-app-status-bar-style\">\n<meta content=\"telephone=no\" name=\"format-detection\">\n<script type=\"text/javascript\">\r\n window.logs = {\r\n pagetime: {}\r\n };\r\n window.logs.pagetime['html_begin'] = (+new Date());\r\n </script>\n<script type=\"text/javascript\"> \r\n\r\n var page_begintime = (+new Date());\r\n\r\n var biz = \"\"||\"MjM5NzE0ODM2MA==\";\r\n var sn = \"\" || \"\"|| \"be39ae0b1519b7f9ae644d4f0a0f449b\";\r\n var mid = \"\" || \"\"|| \"400316403\";\r\n var idx = \"\" || \"\" || \"2\";\r\n\r\n \n var is_rumor = \"\"*1;\r\n var norumor = \"\"*1;\r\n if (!!is_rumor&&!norumor){\r\n if (!document.referrer || document.referrer.indexOf(\"mp.weixin.qq.com/mp/rumor\") == -1){\r\n location.href = \"http://mp.weixin.qq.com/mp/rumor?action=info&__biz=\" + biz + \"&mid=\" + mid + \"&idx=\" + idx + \"&sn=\" + sn + \"#wechat_redirect\";\r\n }\r\n }\r\n\r\n \n \r\n</script>\n<script type=\"text/javascript\">\r\nvar MutationObserver = window.WebKitMutationObserver||window.MutationObserver||window.MozMutationObserver;\r\nvar isDangerSrc = function(src) {\r\n if(src) {\r\n var host = src.match(/http(?:s)?:\\/\\/([^\\/]+?)(\\/|$)/);\r\n if(host && !/qq\\.com$/.test(host[1])) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n}\r\nvar ishttp = location.href.indexOf(\"http://\")==0;\r\nif (ishttp && typeof MutationObserver === 'function') {\r\n window.__observer_data = {count:0, exec_time: 0, list:[]};\r\n window.__observer = new MutationObserver(function(mutations) {\r\n \n window.__observer_data.count++;\r\n var begin = new Date(), deleteNodes = [];\r\n mutations.forEach(function(mutation) {\r\n var nodes = mutation.addedNodes;\r\n for (var i = 0; i < nodes.length; i++) {\r\n var node = nodes[i];\r\n\r\n if (node.tagName === 'SCRIPT') {\r\n var scriptSrc = node.src;\r\n if(isDangerSrc(scriptSrc)) {\r\n window.__observer_data.list.push(scriptSrc);\r\n deleteNodes.push(node);\r\n }\r\n \r\n }\r\n }\r\n });\r\n for(var i=0; i<deleteNodes.length; i++) {\r\n var node = deleteNodes[i];\r\n node.parentNode.removeChild(node);\r\n }\r\n window.__observer_data.exec_time += (new Date() - begin);\r\n });\r\n window.__observer.observe(document, {subtree: true, childList: true});\r\n}\r\n(function() {\r\n if (Math.random()<0.01 && ishttp && HTMLScriptElement.prototype.__lookupSetter__ && typeof Object.defineProperty !== \"undefined\") {\r\n window.__danger_src = {xmlhttprequest:[], script_src: [], script_setAttribute: []};\r\n var t = \"$\"+Math.random();\r\n \r\n \n HTMLScriptElement.prototype.__old_method_script_src = HTMLScriptElement.prototype.__lookupSetter__ ('src');\r\n HTMLScriptElement.prototype.__defineSetter__ ('src', function(url) {\r\n if (url && isDangerSrc(url)) {\r\n \n window.__danger_src.script_src.push(url);\r\n }\r\n this.__old_method_script_src(url);\r\n });\r\n var element_setAttribute_method = \"element_setAttribute\"+t;\r\n Object.defineProperty(Element.prototype, element_setAttribute_method, {\r\n value: Element.prototype.setAttribute,\r\n enumerable: false\r\n });\r\n Element.prototype.setAttribute = function(name, url) {\r\n if (this.tagName == 'SCRIPT' && name == 'src' && isDangerSrc(url)) {\r\n \n window.__danger_src.script_setAttribute.push(url);\r\n }\r\n this[element_setAttribute_method](name, url);\r\n };\r\n }\r\n})();\r\n</script>\n<link href=\"//res.wx.qq.com\" rel=\"dns-prefetch\">\n<link href=\"//mmbiz.qpic.cn\" rel=\"dns-prefetch\">\n<link href=\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/images/icon/common/favicon22c41b.ico\" rel=\"shortcut icon\" type=\"image/x-icon\">\n<script type=\"text/javascript\">\r\n String.prototype.html = function(encode) {\r\n var replace =[\"&#39;\", \"'\", \"&quot;\", '\"', \"&nbsp;\", \" \", \"&gt;\", \">\", \"&lt;\", \"<\", \"&amp;\", \"&\", \"&yen;\", \"¥\"];\r\n if (encode) {\r\n replace.reverse();\r\n }\r\n for (var i=0,str=this;i< replace.length;i+= 2) {\r\n str=str.replace(new RegExp(replace[i],'g'),replace[i+1]);\r\n }\r\n return str;\r\n };\r\n\r\n window.isInWeixinApp = function() {\r\n return /MicroMessenger/.test(navigator.userAgent);\r\n };\r\n\r\n window.getQueryFromURL = function(url) {\r\n url = url || 'http://qq.com/s?a=b#rd'; \n var query = url.split('?')[1].split('#')[0].split('&'),\r\n params = {};\r\n for (var i=0; i<query.length; i++) {\r\n var arg = query[i].split('=');\r\n params[arg[0]] = arg[1];\r\n }\r\n if (params['pass_ticket']) {\r\n \tparams['pass_ticket'] = encodeURIComponent(params['pass_ticket'].html(false).html(false).replace(/\\s/g,\"+\"));\r\n }\r\n return params;\r\n };\r\n\r\n (function() {\r\n\t var params = getQueryFromURL(location.href);\r\n window.uin = params['uin'] || '';\r\n window.key = params['key'] || '';\r\n window.wxtoken = params['wxtoken'] || '';\r\n window.pass_ticket = params['pass_ticket'] || '';\r\n })();\r\n\r\n</script>\n<title>维密还没开始,海尔就先来了一场生活大秀</title>\n<link href=\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/style/page/appmsg/page_mp_article_improve2d1390.css\" rel=\"stylesheet\" type=\"text/css\">\n<style>\n</style>\n<!--[if lt IE 9]>\r\n<link rel=\"stylesheet\" type=\"text/css\" href=\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/style/page/appmsg/page_mp_article_improve_pc2c9cd6.css\">\r\n<![endif]-->\n<script type=\"text/javascript\">\r\n document.domain = \"qq.com\";\r\n</script>\n</link></link></link></link></meta></meta></meta></meta></meta></head>\n<body class=\"zh_CN sougou_body\" id=\"activity-detail\" ontouchstart=\"\">\n<script type=\"text/javascript\">\r\n var write_sceen_time = (+new Date());\r\n </script>\n<div class=\"discuss_container editing access\" id=\"js_cmt_mine\" style=\"display:none;\">\n<div class=\"discuss_container_inner\">\n<h2 class=\"rich_media_title\">维密还没开始,海尔就先来了一场生活大秀</h2>\n<span id=\"log\"></span>\n<div class=\"frm_textarea_box_wrp\">\n<span class=\"frm_textarea_box\">\n<textarea class=\"frm_textarea\" id=\"js_cmt_input\" placeholder=\"留言将由公众号筛选后显示,对所有人可见。\"></textarea>\n<div class=\"emotion_tool\">\n<span class=\"emotion_switch\" style=\"display:none;\"></span>\n<span class=\"pic_emotion_switch_wrp\" id=\"js_emotion_switch\">\n<img alt=\"\" class=\"pic_default\" src=\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/images/icon/appmsg/emotion/icon_emotion_switch.2x278965.png\">\n<img alt=\"\" class=\"pic_active\" src=\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/images/icon/appmsg/emotion/icon_emotion_switch_active.2x278965.png\">\n</img></img></span>\n<div class=\"emotion_panel\" id=\"js_emotion_panel\">\n<span class=\"emotion_panel_arrow_wrp\" id=\"js_emotion_panel_arrow_wrp\">\n<i class=\"emotion_panel_arrow arrow_out\"></i>\n<i class=\"emotion_panel_arrow arrow_in\"></i>\n</span>\n<div class=\"emotion_list_wrp\" id=\"js_slide_wrapper\">\n</div>\n<ul class=\"emotion_navs\" id=\"js_navbar\">\n</ul>\n</div>\n</div>\n</span>\n</div>\n<div class=\"discuss_btn_wrp\"><a class=\"btn btn_primary btn_discuss btn_disabled\" href=\"javascript:;\" id=\"js_cmt_submit\">提交</a></div>\n<div class=\"discuss_list_wrp\" style=\"display:none\">\n<div class=\"rich_tips with_line title_tips discuss_title_line\">\n<span class=\"tips\">我的留言</span>\n</div>\n<ul class=\"discuss_list\" id=\"js_cmt_mylist\"></ul>\n</div>\n<div class=\"rich_tips tips_global loading_tips\" id=\"js_mycmt_loading\">\n<img alt=\"\" class=\"rich_icon icon_loading_white\" src=\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/images/icon/common/icon_loading_white2805ea.gif\">\n<span class=\"tips\">加载中</span>\n</img></div>\n<div class=\"wx_poptips\" id=\"js_cmt_toast\" style=\"display:none;\">\n<img alt=\"\" class=\"icon_toast\" src=\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGoAAABqCAYAAABUIcSXAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAA3NpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuNS1jMDE0IDc5LjE1MTQ4MSwgMjAxMy8wMy8xMy0xMjowOToxNSAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wTU09Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9tbS8iIHhtbG5zOnN0UmVmPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvc1R5cGUvUmVzb3VyY2VSZWYjIiB4bWxuczp4bXA9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iIHhtcE1NOk9yaWdpbmFsRG9jdW1lbnRJRD0ieG1wLmRpZDoyMTUxMzkxZS1jYWVhLTRmZTMtYTY2NS0xNTRkNDJiOGQyMWIiIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6MTA3QzM2RTg3N0UwMTFFNEIzQURGMTQzNzQzMDAxQTUiIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6MTA3QzM2RTc3N0UwMTFFNEIzQURGMTQzNzQzMDAxQTUiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENDIChNYWNpbnRvc2gpIj4gPHhtcE1NOkRlcml2ZWRGcm9tIHN0UmVmOmluc3RhbmNlSUQ9InhtcC5paWQ6NWMyOGVjZTMtNzllZS00ODlhLWIxZTYtYzNmM2RjNzg2YjI2IiBzdFJlZjpkb2N1bWVudElEPSJ4bXAuZGlkOjIxNTEzOTFlLWNhZWEtNGZlMy1hNjY1LTE1NGQ0MmI4ZDIxYiIvPiA8L3JkZjpEZXNjcmlwdGlvbj4gPC9yZGY6UkRGPiA8L3g6eG1wbWV0YT4gPD94cGFja2V0IGVuZD0iciI/Pmvxj1gAAAVrSURBVHja7J15rF1TFMbXk74q1ZKHGlMkJVIhIgg1FH+YEpEQJCKmGBpThRoSs5jVVNrSQUvEEENIhGiiNf9BiERICCFIRbUiDa2qvudbOetF3Tzv7XWGffa55/uS7593977n3vO7e5+199p7v56BgQGh0tcmvAUERREUQVEERREUQVEERREUQVEERREUQVEERREUQVEERREUQVEERVAUQVEERVAUQbVYk+HdvZVG8b5F0xj4RvhouB+eCy8KrdzDJc1RtAX8ILxvx98V1GyCSkN98Cx4z/95/Wn4fj6j6tUEeN4wkFSnw1MJqj5NhBfAuwaUHREUg4lqNMmePVsHll/HFhVfe1t3FwpJI8DXCCquDrCWNN4B6Tb4M3Z98aTPmTvh0YHl18PXw29yZiKejoPvcUD6E74yFBJbVDk6Bb7K8aP/Hb4c/tRzEYIqprPhSxzlf4Uvhb/0Xoig8qnHAJ3lqPMzfDH8XZ4LEpRf2sVdA5/sqPO9Qfop70UJyn+/boaPddT5yrq7VUUvTIVJI7q74MMddXR8NB1eXcYvhBpZm0s2w72/o86HFoKvLau/pYaXzjLMdUJ6y0LwtWV9CIIaXtvA8+G9HHV03u5q+K+yH47U0NoRngPv7KjzHDwTLj0bS1BDazfJJlcnOOostC6ysnCT+q80G/sIvFVgeW09D8FPVT0uoP7VfvAD8NjA8pqmuAN+OcYAjso0RbIZ8DGB5TVNcRO8JMaHY9SXSdfa3eeANJimWBLrA7JFiZwIXye+NMUV8CcxP2SRFjXefok7NRjSGZJlWUPvw2/wtNiQirSoXWyMsR28wR7AzzYM0oXw+Y7yK+CLJGeaoqjyrJSdZJD6Ov4+z5y6NJc0Az7NUecHydIUy+v60KNyQHoM3nKI1y7YCFiq0i7uBvgER52vDdKqWn9djhY1Dn4G3n6Ecqm2rF74dvgoR53S0hQxW9RJAZAGW5bSn58QJA27dQ7uIEedjywEX5NKVxCqsY6y+qA+LxFI4+yZ6oH0trWkNan80jygtIUsc5SflgAsDXgehfdx1KkkTRE76tN+Xue2jnTU0Ru1oIbvpt30bBtKhOp5yaaRkts0lic8V1i6dPcIRx2d/l8Y8XtNNEg7OOo8bl1kmmOKnDsO88CaYzejau0hWZqiL7C83oCH4SeTHvwV2BqqsHRVztSEYOmWF80NeXZT6Hd4KflResE9vCnBOlCyGfDNAstHTVPUDWoQ1t3iW+9WNizvlhfd4aerXd+ThqiMfNR6+9LvOOro5OY5JX2H4+F7HZD+kGzlamMgldWiirQsjcwWFbjmqZJteekJLK9pisvgL6RhKvuciZiwzrWWGapfrPy30kBVcSBIrw0aD3PU0XB6cehntq7rTMf7/2iQlktDVdXJLXlg6VjmiYBn6rWSTRCH6hvJ0hQrpcGq8oidsmHpTP8t8DGO9/vcWt9qabiqPgup1yKyQwvC2tSefZ73SSpNkUJ4PlLorlHZ+446nc8f3fIyywlJhwrTuwVSjBa1ccvSxN0hjjoK5xVrYZMd9V6XbFfgBukixTwGLg8sDam3dZR/wZ6L/dJlin1en8LS+bgpFbz3Ygvzu1J1HKxYNqxGpCmaCEo12rrBorD6LRp8UbpcdR5VWhTW35KlKd6QFqjuM2XzwlpnMxTvSkuUwuG/Xlg6NtPjbT6WFimF/VG6LEvXgn8QGDjMbBukVECFwhpoS+CQatfX2Q1q6H7wENHdrfCr0lKleEB9JyxNneus+VJpsVL9TwI6W65LovWIGl3KtVJaLv7LBwYTFEERFEVQFEERFEVQFEERFEVQFEERFEVQFEERFEVQFEERFFWq/hFgADUMN4RzT6/OAAAAAElFTkSuQmCC\">\n<p class=\"toast_content\">已留言</p>\n</img></div>\n</div>\n</div>\n<div class=\"rich_media\" id=\"js_article\">\n<div class=\"top_banner\" id=\"js_top_ad_area\">\n</div>\n<div class=\"rich_media_inner\">\n<div id=\"page-content\">\n<div class=\"rich_media_area_primary\" id=\"img-content\">\n<h2 class=\"rich_media_title\" id=\"activity-name\">\r\n 维密还没开始,海尔就先来了一场生活大秀 \r\n </h2>\n<div class=\"rich_media_meta_list\">\n<em class=\"rich_media_meta rich_media_meta_text\" id=\"post-date\">2015-11-10</em>\n<a class=\"rich_media_meta rich_media_meta_link rich_media_meta_nickname\" href=\"javascript:void(0);\" id=\"post-user\">海尔北京</a>\n<span class=\"rich_media_meta rich_media_meta_text rich_media_meta_nickname\">海尔北京</span>\n<div class=\"profile_container\" id=\"js_profile_qrcode\" style=\"display:none;\">\n<div class=\"profile_inner\">\n<strong class=\"profile_nickname\">海尔北京</strong>\n<img alt=\"\" class=\"profile_avatar\" id=\"js_profile_qrcode_img\" src=\"\">\n<p class=\"profile_meta\">\n<label class=\"profile_meta_label\">微信号</label>\n<span class=\"profile_meta_value\">haier_bj</span>\n</p>\n<p class=\"profile_meta\">\n<label class=\"profile_meta_label\">功能介绍</label>\n<span class=\"profile_meta_value\">海尔网络生活智慧,为千家万户打造不拘一格的智能家居体验</span>\n</p>\n</img></div>\n<span class=\"profile_arrow_wrp\" id=\"js_profile_arrow_wrp\">\n<i class=\"profile_arrow arrow_out\"></i>\n<i class=\"profile_arrow arrow_in\"></i>\n</span>\n</div>\n</div>\n<div class=\"rich_media_content \" id=\"js_content\">\n<p style=\"text-align: center;\"><strong><span style=\"font-family: 微软雅黑, sans-serif\">今年,维密大秀还没开始</span></strong></p><p style=\"text-align: center;\"><strong><span style=\"font-family: 微软雅黑, sans-serif\">海尔就在双11发酵的时候</span></strong></p><p style=\"text-align: center;\"><strong><span style=\"font-family: 微软雅黑, sans-serif\">来了一场生活大秀</span></strong></p><p style=\"text-align: center;\"><strong><span style=\"font-family: 微软雅黑, sans-serif\">属于海尔双11的“天使翅膀”可见轮廓</span></strong></p><p style=\"text-align: center;\"><img data-ratio=\"0.6370558375634517\" data-s=\"300,640\" data-src=\"http://mmbiz.qpic.cn/mmbiz/miaIWQgrbRJY6mBve39n8EKwPoock3edAdv3kzH9XcTibnibvxDFSQHIUhO4fKM8UsPeenAJgUKHo2KF0114pzf6A/0?wx_fmt=png\" data-type=\"png\" data-w=\"394\"/><br/></p><p style=\"text-align: center;\"><strong><span style=\"font-size: 16px;font-family: 微软雅黑, sans-serif\">今年双11,海尔玩不同,超级学校吹响大咖集结号!</span></strong></p><p style=\"text-align: center;\"><span style=\"font-family:微软雅黑,sans-serif\">又是一年双11</span></p><p style=\"text-align: center;\"><span style=\"font-family:微软雅黑,sans-serif\">唱主角的不是嗖嗖的小北风和单身汪</span></p><p style=\"text-align: center;\"><span style=\"font-family:微软雅黑,sans-serif\">占据各大头条的是那群</span></p><p style=\"text-align: center;\"><span style=\"font-family:微软雅黑,sans-serif\">在战火中厮杀的Buy家娘们和各大品牌</span></p><p style=\"text-align: center;\"><span style=\"font-family:微软雅黑,sans-serif\">去年家电销售量第一的品牌大佬海尔,今年又有大动作——</span></p><p style=\"text-align: center;\"><span style=\"font-family:微软雅黑,sans-serif\">竟办起学校传授“享乐主义”!还是O2O授课模式!</span></p><p style=\"margin-left: 28px; text-align: center;\"><span style=\"font-family:微软雅黑,sans-serif\"><img data-ratio=\"1.3702928870292888\" data-s=\"300,640\" data-src=\"http://mmbiz.qpic.cn/mmbiz/miaIWQgrbRJY6mBve39n8EKwPoock3edA2l93yqoy8FUYwkx1I0Hub3F1Gib63iandAUoeLVDVJeibdbka1n3yp44A/0?wx_fmt=jpeg\" data-type=\"jpeg\" data-w=\"478\"/><br/></span></p><p style=\"margin-left: 28px; text-align: center;\"><span style=\"font-family:微软雅黑,sans-serif\">海尔、统帅、青啤、罗莱、茵曼、阿芙、芝华仕、酒仙网</span></p><p style=\"text-align: center;\"><span style=\"font-family:微软雅黑,sans-serif\">媒体、网红、达人、粉丝……</span></p><p style=\"text-align: center;\"><span style=\"font-family:微软雅黑,sans-serif\">各路大咖云集星光闪耀的场面</span></p><p style=\"text-align: center;\"><span style=\"font-family:微软雅黑,sans-serif\">八成是在发布会、奥斯卡,或黄教主大婚</span></p><p style=\"text-align: center;\"><span style=\"font-family:微软雅黑,sans-serif\">万万没想到竟是场开学式?!</span></p><p style=\"text-align: center;\"><span style=\"font-family:微软雅黑,sans-serif\"><img data-ratio=\"1.3715415019762847\" data-s=\"300,640\" data-src=\"http://mmbiz.qpic.cn/mmbiz/miaIWQgrbRJY6mBve39n8EKwPoock3edAGsoSG2C7BicsgAbUGrVs4sb8f14b6pAWdjTJLjluhJiaIicdIxe7l434A/0?wx_fmt=jpeg\" data-type=\"jpeg\" data-w=\"\"/><br/></span></p><p style=\"text-align: center;\"><span style=\"font-family:微软雅黑,sans-serif\">这样大手笔?闹哪样 ?</span></p><p style=\"text-align: center;\"><span style=\"font-family:微软雅黑,sans-serif\">海尔11.11生活+联盟开学式也能如此高调奢华?</span></p><p style=\"text-align: center;\"><span style=\"font-family:微软雅黑,sans-serif\">八大TOP品牌负责人、当红KOL,各路大咖悉数亮相</span></p><p style=\"text-align: center;\"><span style=\"font-family:微软雅黑,sans-serif\">还有重量级葩神——雷洋担任主持,耳熟吗?</span></p><p style=\"text-align: center;\"><span style=\"font-family:微软雅黑,sans-serif\">百度一下就知道有多大牌!</span></p><p style=\"text-align: center;\"><span style=\"font-family:微软雅黑,sans-serif\"><img data-ratio=\"0.66600790513834\" data-s=\"300,640\" data-src=\"http://mmbiz.qpic.cn/mmbiz/miaIWQgrbRJY6mBve39n8EKwPoock3edAQwGEBRcX9xRTykFClHHRJDjvWoBSn6nm9Q3BoqpRm065wQniaaVrAPg/0?wx_fmt=jpeg\" data-type=\"jpeg\" data-w=\"\"/><br/></span></p><p style=\"text-align: center;\"><span style=\"font-family:微软雅黑,sans-serif\">辣么,被称为“互联网+时代的霍格沃茨魔法学校”</span></p><p style=\"text-align: center;\"><span style=\"font-family:微软雅黑,sans-serif\">海尔生活+学院到底能教给我们哪些技能?</span></p><p style=\"text-align: center;\"><strong><span style=\"font-family:微软雅黑,sans-serif;color:red\">咱接着看!</span></strong></p><p style=\"text-align: center;\"><strong><span style=\"font-size: 16px;font-family: 微软雅黑, sans-serif\">剧透2:海尔11.11“生活+”学院,不只吃喝玩乐,主要教你玩转生活!</span></strong></p><p style=\"text-align: center;\"><strong><span style=\"font-size: 16px;font-family: 微软雅黑, sans-serif\"><img data-ratio=\"1.3621730382293762\" data-s=\"300,640\" data-src=\"http://mmbiz.qpic.cn/mmbiz/miaIWQgrbRJY6mBve39n8EKwPoock3edAEjQhjSrCMfW52Glq2HIwgzJPW0ib20xUo1zg6iak7aJUnDVlLyVrPegA/0?wx_fmt=jpeg\" data-type=\"jpeg\" data-w=\"497\"/><br/></span></strong></p><p style=\"text-align: center;\"><span style=\"font-family:微软雅黑,sans-serif\">体验各种神秘家居、与模特亲密互动,完成任务就赢走肾6s!</span></p><p style=\"text-align: center;\"><span style=\"font-family:微软雅黑,sans-serif\">抵制不住诱惑的诸位生活达人、粉丝和媒体人 “宽衣解带”卸下高冷~</span></p><p style=\"text-align: center;\"><span style=\"font-family:微软雅黑,sans-serif\">现场实战把生活玩出高潮~享受起来一个比一个生猛!</span></p><p style=\"text-align: center;\"><span style=\"font-family:微软雅黑,sans-serif\">现场打破常规 生活场景真实再现</span></p><p style=\"text-align: center;\"><span style=\"font-family:微软雅黑,sans-serif\">开学式现场直接真实搭建一个畅享生活的jia!</span></p><p style=\"text-align: center;\"><span style=\"font-family:微软雅黑,sans-serif\"><img data-ratio=\"1\" data-s=\"300,640\" data-src=\"http://mmbiz.qpic.cn/mmbiz/miaIWQgrbRJY6mBve39n8EKwPoock3edAqdWD0b0hQhkTxd5e9C1fHib6ID1bQ6HhF9iaRNjmuiaxO7GKsKQqZY8eQ/0?wx_fmt=jpeg\" data-type=\"jpeg\" data-w=\"497\"/><br/></span></p><p style=\"text-align: center;\"><strong><span style=\"font-family:微软雅黑,sans-serif\">睡了哆啦A喝了白啤醉</span></strong></p><p style=\"text-align: center;\"><strong><span style=\"font-family:微软雅黑,sans-serif\">躺了芝华仕喝了红酒美</span></strong></p><p style=\"text-align: center;\"><strong><span style=\"font-family:微软雅黑,sans-serif\">水果榨出人生滋味,把生活调戏出大白风味</span></strong></p><p style=\"text-align: center;\"><strong><span style=\"font-family:微软雅黑,sans-serif\">衣服穿上范玮琪同款,馨厨冰箱活出健康智能生活惠</span></strong></p><p style=\"text-align: center;\"><strong><span style=\"font-family:微软雅黑,sans-serif\">空调和苹果最搭有范儿,配!</span></strong></p><p style=\"text-align: center;\"><strong><span style=\"font-family:微软雅黑,sans-serif\">生活+起来,领跑生活嘿!</span></strong></p><p style=\"text-align: center;\"><strong><span style=\"font-family:微软雅黑,sans-serif\">生活玩得美,老师要找对!</span></strong></p><p style=\"text-align: center;\"><strong><span style=\"font-family:微软雅黑,sans-serif\"><img data-ratio=\"1.1118568232662192\" data-s=\"300,640\" data-src=\"http://mmbiz.qpic.cn/mmbiz/miaIWQgrbRJY6mBve39n8EKwPoock3edAPWsib2EoQU86xUGa5qFHXv760GnzCxmk1VTWYQSmradXkj5mXG1YgAQ/0?wx_fmt=jpeg\" data-type=\"jpeg\" data-w=\"447\"/><br/></span></strong></p><p style=\"text-align: center;\"><strong><span style=\"font-size: 16px;font-family: 微软雅黑, sans-serif\">剧透3:八大品牌师资担当,海尔生活+带你玩转双11</span></strong></p><p style=\"text-align: center;\"><span style=\"font-family:微软雅黑,sans-serif\">海尔、统帅、青啤、罗莱、茵曼、阿芙、芝华仕、酒仙网等</span></p><p style=\"text-align: center;\"><span style=\"font-family:微软雅黑,sans-serif\">八大品牌代表正式宣布今年双11“生活+学院”正式成立</span></p><p style=\"text-align: center;\"><span style=\"font-family:微软雅黑,sans-serif\">不教任何书本冷知识,就让你怎么玩转生活</span></p><p style=\"text-align: center;\"><span style=\"font-family:微软雅黑,sans-serif\">畅享今年双11</span></p><p style=\"text-align: center;\"><span style=\"font-family:微软雅黑,sans-serif\"><img data-ratio=\"0.66600790513834\" data-s=\"300,640\" data-src=\"http://mmbiz.qpic.cn/mmbiz/miaIWQgrbRJY6mBve39n8EKwPoock3edAgBoZ3t7cd0T8TPnvctaCOrVdEoW22vvwO1f5SYOQbiaz6KLlmljRicpQ/0?wx_fmt=jpeg\" data-type=\"jpeg\" data-w=\"\"/><br/><span style=\"color:red\"><img data-ratio=\"0.66600790513834\" data-s=\"300,640\" data-src=\"http://mmbiz.qpic.cn/mmbiz/miaIWQgrbRJY6mBve39n8EKwPoock3edACicQWibfWX6NibyMicdVoMV4gQzsLl6HiapM0PrTGGYI0HNBzicZKnPwnxjA/0?wx_fmt=jpeg\" data-type=\"jpeg\" data-w=\"\"/><br/></span></span></p><p style=\"text-align: center;\"><strong><span style=\"font-size: 16px;font-family: 微软雅黑, sans-serif\">剧透4:海尔11.11提前登场没收住,海尔这次玩大了!</span></strong></p><p style=\"text-align: center;\"><span style=\"font-family:微软雅黑,sans-serif\">开学玩太嗨,开学式当天海尔11.11多样玩法现场剧透,</span></p><p style=\"text-align: center;\"><span style=\"font-family:微软雅黑,sans-serif\">看样子,今年双11,海尔真的玩大了!</span></p><p style=\"text-align: center;\"><strong><span style=\"font-family:微软雅黑,sans-serif\">玩大了1:11.11当天海尔天猫旗舰店,豪洒一千五百万重金</span></strong></p><p style=\"text-align: center;\"><span style=\"font-family:微软雅黑,sans-serif\">只要你来玩,海尔就给你送Money!</span></p><p style=\"text-align: center;\"><span style=\"font-family:微软雅黑,sans-serif\">赶紧抢,手一抖,就被别人抢走了!</span></p><p style=\"text-align: center;\"><strong><span style=\"font-family:微软雅黑,sans-serif\">玩大了2:十大可叠加优惠政策,惠及新老客户</span></strong></p><p style=\"text-align: center;\"><span style=\"font-family:微软雅黑,sans-serif\">没错,“可叠加使用”效果超乎想象,越早买奖品越丰厚!</span></p><p style=\"text-align: center;\"><span style=\"font-family:微软雅黑,sans-serif\">定好闹表11.11零点开抢</span></p><p style=\"text-align: center;\"><span style=\"font-family:微软雅黑,sans-serif\">十大优惠可累加,24小时惊喜不间断</span></p><p style=\"text-align: center;\"><span style=\"font-family:微软雅黑,sans-serif\">侵袭淫类的“剁手病毒”可真是无药可救了~</span></p><p style=\"text-align: center;\"><strong><span style=\"font-family:微软雅黑,sans-serif\">玩大了3:8大TOP商家,送吃喝玩乐大礼包</span></strong></p><p style=\"text-align: center;\"><span style=\"font-family:微软雅黑,sans-serif\">你负责享受,海尔负责埋单;优惠只是手段,玩嗨才是目的!</span></p><p style=\"text-align: center;\"><span style=\"font-family:微软雅黑,sans-serif\">“异业联盟”借势双11掀起新生活主义浪潮</span></p><p style=\"text-align: center;\"><span style=\"font-family:微软雅黑,sans-serif\">据说,生活+联盟会一直玩下去</span></p><p style=\"text-align: center;\"><span style=\"font-family:微软雅黑,sans-serif\">让购物有趣方便,消费者更受益</span></p><p style=\"text-align: center;\"><span style=\"font-family:微软雅黑,sans-serif\">八大品牌积分互通、会员权益共享的八大品牌联合政策</span></p><p style=\"text-align: center;\"><span style=\"font-family:微软雅黑,sans-serif\">双11能出现吗?</span></p><p style=\"text-align: center;\"><span style=\"font-family:微软雅黑,sans-serif\">答案……</span></p><p style=\"text-align: center;\"><span style=\"font-family:微软雅黑,sans-serif\"><img data-ratio=\"0.7509881422924901\" data-s=\"300,640\" data-src=\"http://mmbiz.qpic.cn/mmbiz/miaIWQgrbRJY6mBve39n8EKwPoock3edAOia0QT2KR8ic7icdXKF4zgOSEsSpRRe0MLrYgsE79MUNNWibZlg4bWRMiag/0?wx_fmt=jpeg\" data-type=\"jpeg\" data-w=\"\"/><br/></span></p><p style=\"text-align: center;\"><span style=\"font-family:微软雅黑,sans-serif\">对不起,只能剧透到这里!</span></p><p style=\"text-align: center;\"><span style=\"font-family:微软雅黑,sans-serif\">BOSS</span><span style=\"font-family:微软雅黑,sans-serif\">说,再泄密就不发工资了!</span></p><p style=\"text-align: center;\"><span style=\"font-family:微软雅黑,sans-serif\">那就11月11日约起~</span></p><p style=\"text-align: center;\"><span style=\"font-family:微软雅黑,sans-serif\">海尔商城、海尔天猫旗舰店,答案给你,所有福利都给你!</span></p><p style=\"text-align: center;\"><span style=\"font-family:微软雅黑,sans-serif\"> </span></p><p style=\"text-align: center;\"><img data-ratio=\"0.5316205533596838\" data-s=\"300,640\" data-src=\"http://mmbiz.qpic.cn/mmbiz/uXyUiafode1ZWhb9gibiabicq2gEoYbcuibIHLaPNlNxNkPH04MypmOMb2icicPPxfe5U1L5YBRNHj6biawnBzexbkFMAA/0?wx_fmt=jpeg\" data-type=\"jpeg\" data-w=\"\"/><br/><img data-ratio=\"0.44861660079051385\" data-s=\"300,640\" data-src=\"http://mmbiz.qpic.cn/mmbiz/uXyUiafode1b0Kr8NuUPts6Zc86zChAIG20cvj4jKOq21Gc9wQPwiaq6JZfXuiaGrTdkvEuKPqhTohfa5PuZW2QLQ/0\" data-type=\"jpeg\" data-w=\"\"/><br/></p>\n</div>\n<script type=\"text/javascript\">\r\n var first_sceen__time = (+new Date());\r\n\r\n if (\"\" == 1 && document.getElementById('js_content'))\r\n document.getElementById('js_content').addEventListener(\"selectstart\",function(e){ e.preventDefault(); });\r\n\r\n (function(){\r\n if (navigator.userAgent.indexOf(\"WindowsWechat\") != -1){\r\n var link = document.createElement('link');\r\n var head = document.getElementsByTagName('head')[0];\r\n link.rel = 'stylesheet';\r\n link.type = 'text/css';\r\n link.href = \"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/style/page/appmsg/page_mp_article_improve_winwx2c9cd6.css\";\r\n head.appendChild(link);\r\n }\r\n })();\r\n </script>\n<link href=\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/style/page/appmsg/page_mp_article_improve_combo2d1390.css\" rel=\"stylesheet\" type=\"text/css\">\n<div class=\"rich_media_tool\" id=\"js_toobar3\">\n<div class=\"media_tool_meta tips_global meta_primary\" id=\"js_read_area3\" style=\"display:none;\">阅读 <span id=\"readNum3\"></span></div>\n<span class=\"media_tool_meta meta_primary tips_global meta_praise\" id=\"like3\" style=\"display:none;\">\n<i class=\"icon_praise_gray\"></i><span class=\"praise_num\" id=\"likeNum3\"></span>\n</span>\n<a class=\"media_tool_meta tips_global meta_extra\" href=\"javascript:void(0);\" id=\"js_report_article3\" style=\"display:none;\">投诉</a>\n</div>\n<div class=\"rich_media_tool\" id=\"js_sg_bar\">\n<a class=\"media_tool_meta meta_primary\" href=\"\" target=\"_blank\">阅读原文</a>\n<div class=\"media_tool_meta tips_global meta_primary\">阅读 <span><span id=\"sg_readNum3\"></span></span></div>\n<span class=\"media_tool_meta meta_primary tips_global meta_praise\">\n<i class=\"icon_praise_gray\"></i><span class=\"praise_num\"><span class=\"praise_num\" id=\"sg_likeNum3\"></span>\n</span>\n</span></div>\n</link></div>\n<div class=\"rich_media_area_primary sougou\" id=\"sg_tj\" style=\"display:none\">\n</div>\n<div class=\"rich_media_area_extra\">\n<div class=\"mpda_bottom_container\" id=\"js_bottom_ad_area\">\n</div>\n<div id=\"js_iframetest\" style=\"display:none;\"></div>\n<div class=\"rich_media_extra\" id=\"sg_cmt_area\">\n<div class=\"discuss_container\" id=\"sg_cmt_main\" style=\"display:none\">\n<div class=\"rich_tips with_line title_tips discuss_title_line\">\n<span class=\"tips\">精选留言</span>\n</div>\n<ul class=\"discuss_list\" id=\"sg_cmt_list\"></ul>\n</div>\n<div class=\"rich_tips tips_global loading_tips\" id=\"sg_cmt_loading\">\n<img alt=\"\" class=\"rich_icon icon_loading_white\" src=\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/images/icon/common/icon_loading_white2805ea.gif\">\n<span class=\"tips\">加载中</span>\n</img></div>\n<div class=\"rich_tips with_line tips_global\" id=\"sg_cmt_statement\" style=\"display:none\">\n<span class=\"tips\">以上留言由公众号筛选后显示</span>\n</div>\n<p class=\"rich_split_tips tc\" id=\"sg_cmt_qa\" style=\"display:none;\">\n<a href=\"http://kf.qq.com/touch/sappfaq/150211YfyMVj150313qmMbyi.html?scene_id=kf264\">\r\n 了解留言功能详情\r\n </a>\n</p>\n</div>\n</div>\n</div>\n<div class=\"qr_code_pc_outer\" id=\"js_pc_qr_code\" style=\"display:none;\">\n<div class=\"qr_code_pc_inner\">\n<div class=\"qr_code_pc\">\n<img class=\"qr_code_pc_img\" id=\"js_pc_qr_code_img\">\n<p>微信扫一扫<br>关注该公众号</br></p>\n</img></div>\n</div>\n</div>\n</div>\n</div>\n<script>\r\n var __DEBUGINFO = {\r\n debug_js : \"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/biz_wap/debug/console2ca724.js\",\r\n safe_js : \"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/biz_wap/safe/moonsafe2d5cb8.js\",\r\n res_list: []\r\n };\r\n</script>\n<script>window.moon_map = {\"appmsg/emotion/caret.js\":\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/appmsg/emotion/caret278965.js\",\"biz_wap/jsapi/cardticket.js\":\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/biz_wap/jsapi/cardticket275627.js\",\"appmsg/emotion/map.js\":\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/appmsg/emotion/map278965.js\",\"appmsg/emotion/textarea.js\":\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/appmsg/emotion/textarea27cdc5.js\",\"appmsg/emotion/nav.js\":\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/appmsg/emotion/nav278965.js\",\"appmsg/emotion/common.js\":\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/appmsg/emotion/common278965.js\",\"appmsg/emotion/slide.js\":\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/appmsg/emotion/slide2a9cd9.js\",\"pages/report.js\":\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/pages/report2c9cd6.js\",\"pages/music_player.js\":\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/pages/music_player2b674b.js\",\"pages/loadscript.js\":\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/pages/loadscript2c9cd6.js\",\"appmsg/emotion/dom.js\":\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/appmsg/emotion/dom278965.js\",\"biz_wap/utils/hashrouter.js\":\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/biz_wap/utils/hashrouter2805ea.js\",\"a/gotoappdetail.js\":\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/a/gotoappdetail2a2c13.js\",\"a/ios.js\":\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/a/ios275627.js\",\"a/android.js\":\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/a/android2c5484.js\",\"a/profile.js\":\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/a/profile29b1f8.js\",\"a/mpshop.js\":\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/a/mpshop2da3e2.js\",\"a/card.js\":\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/a/card2d1390.js\",\"biz_wap/utils/position.js\":\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/biz_wap/utils/position29b1f8.js\",\"appmsg/a_report.js\":\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/appmsg/a_report2d87eb.js\",\"biz_common/utils/respTypes.js\":\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/biz_common/utils/respTypes2c57d0.js\",\"appmsg/cmt_tpl.html.js\":\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/appmsg/cmt_tpl.html2a2c13.js\",\"sougou/a_tpl.html.js\":\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/sougou/a_tpl.html2c6e7c.js\",\"appmsg/emotion/emotion.js\":\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/appmsg/emotion/emotion2a9cd9.js\",\"biz_common/utils/report.js\":\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/biz_common/utils/report275627.js\",\"biz_common/utils/huatuo.js\":\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/biz_common/utils/huatuo293afc.js\",\"biz_common/utils/cookie.js\":\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/biz_common/utils/cookie275627.js\",\"pages/voice_component.js\":\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/pages/voice_component2c5484.js\",\"new_video/ctl.js\":\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/new_video/ctl2d441f.js\",\"biz_common/utils/monitor.js\":\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/biz_common/utils/monitor2a30ee.js\",\"biz_common/utils/spin.js\":\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/biz_common/utils/spin275627.js\",\"biz_wap/jsapi/pay.js\":\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/biz_wap/jsapi/pay275627.js\",\"appmsg/reward_entry.js\":\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/appmsg/reward_entry2db716.js\",\"appmsg/comment.js\":\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/appmsg/comment2d39f3.js\",\"appmsg/like.js\":\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/appmsg/like2b5583.js\",\"appmsg/a.js\":\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/appmsg/a2da3e2.js\",\"pages/version4video.js\":\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/pages/version4video2c7543.js\",\"rt/appmsg/getappmsgext.rt.js\":\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/rt/appmsg/getappmsgext.rt2c21f6.js\",\"biz_wap/utils/storage.js\":\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/biz_wap/utils/storage2a74ac.js\",\"biz_common/tmpl.js\":\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/biz_common/tmpl2b3578.js\",\"appmsg/img_copyright_tpl.html.js\":\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/appmsg/img_copyright_tpl.html2a2c13.js\",\"appmsg/a_tpl.html.js\":\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/appmsg/a_tpl.html2d1390.js\",\"biz_common/ui/imgonepx.js\":\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/biz_common/ui/imgonepx275627.js\",\"biz_common/dom/attr.js\":\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/biz_common/dom/attr275627.js\",\"biz_wap/utils/ajax.js\":\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/biz_wap/utils/ajax2c7a90.js\",\"biz_common/utils/string/html.js\":\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/biz_common/utils/string/html29f4e9.js\",\"sougou/index.js\":\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/sougou/index2c7543.js\",\"biz_wap/safe/mutation_observer_report.js\":\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/biz_wap/safe/mutation_observer_report2d5cb8.js\",\"appmsg/report.js\":\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/appmsg/report2cf2a3.js\",\"biz_common/dom/class.js\":\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/biz_common/dom/class275627.js\",\"appmsg/report_and_source.js\":\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/appmsg/report_and_source2c0ff9.js\",\"appmsg/page_pos.js\":\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/appmsg/page_pos2d38d6.js\",\"appmsg/cdn_speed_report.js\":\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/appmsg/cdn_speed_report2c57d0.js\",\"appmsg/voice.js\":\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/appmsg/voice2ab8bd.js\",\"appmsg/qqmusic.js\":\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/appmsg/qqmusic2ab8bd.js\",\"appmsg/iframe.js\":\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/appmsg/iframe2cc9e4.js\",\"appmsg/review_image.js\":\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/appmsg/review_image2d0cfe.js\",\"appmsg/outer_link.js\":\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/appmsg/outer_link275627.js\",\"biz_wap/jsapi/core.js\":\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/biz_wap/jsapi/core2c30c1.js\",\"biz_common/dom/event.js\":\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/biz_common/dom/event275627.js\",\"appmsg/copyright_report.js\":\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/appmsg/copyright_report2c57d0.js\",\"appmsg/cache.js\":\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/appmsg/cache2a74ac.js\",\"appmsg/pay_for_reading.js\":\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/appmsg/pay_for_reading2c5484.js\",\"appmsg/async.js\":\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/appmsg/async2da3e2.js\",\"biz_wap/ui/lazyload_img.js\":\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/biz_wap/ui/lazyload_img2b18f6.js\",\"biz_common/log/jserr.js\":\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/biz_common/log/jserr2805ea.js\",\"appmsg/share.js\":\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/appmsg/share2daac1.js\",\"biz_wap/utils/mmversion.js\":\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/biz_wap/utils/mmversion275627.js\",\"appmsg/cdn_img_lib.js\":\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/appmsg/cdn_img_lib275627.js\",\"biz_common/utils/url/parse.js\":\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/biz_common/utils/url/parse2d1e61.js\",\"biz_wap/utils/device.js\":\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/biz_wap/utils/device2b3aae.js\",\"biz_wap/jsapi/a8key.js\":\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/biz_wap/jsapi/a8key2a30ee.js\",\"appmsg/index.js\":\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/appmsg/index2d625d.js\"};</script><script src=\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/js/biz_wap/moon2c7b0a.js\" type=\"text/javascript\"></script>\n<script id=\"voice_tpl\" type=\"text/html\"> \r\n <span id=\"voice_main_<#=voiceid#>_<#=posIndex#>\" class=\"db audio_area <#if(!musicSupport){#> unsupport<#}#>\">\r\n <span class=\"tc tips_global unsupport_tips\" <#if(show_not_support!==true){#>style=\"display:none;\"<#}#>>\r\n 当前浏览器不支持播放音乐或语音,请在微信或其他浏览器中播放 </span>\r\n <span class=\"audio_wrp db\">\r\n <span id=\"voice_play_<#=voiceid#>_<#=posIndex#>\" class=\"audio_play_area\">\r\n <i class=\"icon_audio_default\"></i>\r\n <i class=\"icon_audio_playing\"></i>\r\n <img src=\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/images/icon/appmsg/audio/icon_audio_unread26f1f1.png\" alt=\"\" class=\"pic_audio_default\">\r\n </span>\r\n <span class=\"audio_length tips_global\"><#=duration_str#></span>\r\n <span class=\"db audio_info_area\">\r\n <strong class=\"db audio_title\"><#=title#></strong>\r\n <span class=\"audio_source tips_global\"><#if(window.nickname){#>来自<#=window.nickname#><#}#></span>\r\n </span>\r\n <span id=\"voice_progress_<#=voiceid#>_<#=posIndex#>\" class=\"progress_bar\" style=\"width:0px;\"></span>\r\n </span>\r\n </span>\r\n </script>\n<script id=\"qqmusic_tpl\" type=\"text/html\"> \r\n <span id=\"qqmusic_main_<#=comment_id#>_<#=posIndex#>\" class=\"db qqmusic_area <#if(!musicSupport){#> unsupport<#}#>\">\r\n <span class=\"tc tips_global unsupport_tips\" <#if(show_not_support!==true){#>style=\"display:none;\"<#}#>>\r\n 当前浏览器不支持播放音乐或语音,请在微信或其他浏览器中播放 </span>\r\n <span class=\"db qqmusic_wrp\">\r\n <span class=\"db qqmusic_bd\">\r\n <span id=\"qqmusic_play_<#=musicid#>_<#=posIndex#>\" class=\"play_area\">\r\n <i class=\"icon_qqmusic_switch\"></i>\r\n <img src=\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/images/icon/appmsg/qqmusic/icon_qqmusic_default.2x26f1f1.png\" alt=\"\" class=\"pic_qqmusic_default\">\r\n <img src=\"<#=music_img#>\" data-autourl=\"<#=audiourl#>\" data-musicid=\"<#=musicid#>\" class=\"qqmusic_thumb\" alt=\"\">\r\n </span>\r\n <a id=\"qqmusic_home_<#=musicid#>_<#=posIndex#>\" href=\"javascript:void(0);\" class=\"access_area\">\r\n <span class=\"qqmusic_songname\"><#=music_name#></span>\r\n <span class=\"qqmusic_singername\"><#=singer#></span>\r\n <span class=\"qqmusic_source\"><img src=\"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/images/icon/appmsg/qqmusic/icon_qqmusic_source263724.png\" alt=\"\"></span>\r\n </a>\r\n </span>\r\n </span> \r\n </span>\r\n </script>\n<script type=\"text/javascript\">\r\n var not_in_mm_css = \"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/style/page/appmsg/not_in_mm2c9cd6.css\";\r\n var windowwx_css = \"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/style/page/appmsg/page_mp_article_improve_winwx2c9cd6.css\";\r\n var tid = \"\";\r\n var aid = \"\";\r\n var clientversion = \"0\";\r\n var appuin = \"\"||\"MjM5NzE0ODM2MA==\";\r\n\r\n var source = \"\";\r\n var scene = 75;\r\n \r\n var itemidx = \"\";\r\n\r\n var _copyright_stat = \"0\";\r\n var _ori_article_type = \"\";\r\n\r\n var nickname = \"海尔北京\";\r\n var appmsg_type = \"9\";\r\n var ct = \"1447147910\";\r\n var publish_time = \"2015-11-10\" || \"\";\r\n var user_name = \"gh_63d8d14efccb\";\r\n var user_name_new = \"\";\r\n var fakeid = \"\";\r\n var version = \"\";\r\n var is_limit_user = \"0\";\r\n var round_head_img = \"http://mmsns.qpic.cn/mmsns/uXyUiafode1btBWqEK4F7RF94J5pJ2Yeu31p2PmzfBX6XqaUyEOw0Nw/0\";\r\n var msg_title = \"维密还没开始,海尔就先来了一场生活大秀\";\r\n var msg_desc = \"今年,维密大秀还没开始海尔就在双11发酵的时候来了一场生活大秀属于海尔双11的“天使翅膀”可见轮廓今年双11\";\r\n var msg_cdn_url = \"http://mmbiz.qpic.cn/mmbiz/uXyUiafode1ZfQAZeRM6GiaIb8mpqaurspG4Pu9XPw5QEiblfbqVW0MlhwQN4X5SicvOXZ2Yh9obx7b2kBefHXiauRw/0?wx_fmt=jpeg\";\r\n var msg_link = \"http://mp.weixin.qq.com/s?__biz=MjM5NzE0ODM2MA==&amp;mid=400316403&amp;idx=2&amp;sn=be39ae0b1519b7f9ae644d4f0a0f449b#rd\";\r\n var user_uin = \"0\"*1;\r\n var msg_source_url = '';\r\n var img_format = 'jpeg';\r\n var srcid = '';\r\n var networkType;\r\n var appmsgid = '' || ''|| \"400316403\";\r\n var comment_id = \"0\" * 1;\r\n var comment_enabled = \"\" * 1;\r\n var is_need_reward = \"0\" * 1;\r\n var is_https_res = (\"\" * 1) && (location.protocol == \"https:\");\r\n\r\n var devicetype = \"\";\r\n var source_username = \"\"; \r\n var profile_ext_signature = \"\" || \"\";\r\n var reprint_ticket = \"\";\r\n var source_mid = \"\";\r\n var source_idx = \"\";\r\n\r\n var show_comment = \"\";\r\n var __appmsgCgiData = {\r\n can_use_page : \"0\"*1,\r\n is_wxg_stuff_uin : \"0\"*1,\r\n card_pos : \"\",\r\n copyright_stat : \"0\",\r\n source_biz : \"\",\r\n hd_head_img : \"http://wx.qlogo.cn/mmhead/Q3auHgzwzM5pUsCtUC0NYmbCicrj226uYQvic4duuMu480fMCPqtzM3g/0\"||(window.location.protocol+\"//\"+window.location.host + \"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/images/pic/appmsg/pic_rumor_link.2x264e76.jpg\")\r\n };\r\n var _empty_v = \"http://res.wx.qq.com/mmbizwap/zh_CN/htmledition/images/pic/pages/voice/empty26f1f1.mp3\";\r\n\r\n var copyright_stat = \"0\" * 1;\r\n\r\n var pay_fee = \"\" * 1;\r\n var pay_timestamp = \"\";\r\n var need_pay = \"\" * 1;\r\n\r\n var need_report_cost = \"0\" * 1;\r\n var use_tx_video_player = \"0\" * 1;\r\n\r\n var friend_read_source = \"\" || \"\";\r\n var friend_read_version = \"\" || \"\";\r\n var friend_read_class_id = \"\" || \"\";\r\n\r\n var is_only_read = \"1\" * 1;\r\n\r\n \r\n window.wxtoken = \"\";\r\n if(!!window.__initCatch){\r\n window.__initCatch({\r\n idkey : 27613,\r\n startKey : 0,\r\n limit : 128,\r\n reportOpt : {\r\n uin : uin,\r\n biz : biz,\r\n mid : mid,\r\n idx : idx,\r\n sn : sn\r\n },\r\n extInfo : {\r\n network_rate : 0.01 \n }\r\n });\r\n }\r\n </script>\n<script type=\"text/javascript\">\r\n window.isSg=true;\r\n window.sg_qr_code=\"/rr?timestamp=1463194316&src=3&ver=1&signature=OPPQA7aOWPCbC-c788NOa1wcSscBZ-Y0haA7lCXE2X0w-59MIasW5FOzhGXXu5o6FXKhTYfRSYV46UwC3DVHRZhW-D2WRPYjWI8EVt4hc5U=\";\r\n window.sg_data={\r\n src:\"3\",\r\n ver:\"1\",\r\n timestamp:\"1463191394\",\r\n signature:\"cV3qMIBeBTS6i8cJJOPu98j-H9veEPx0Y0BekUE7F6*sal9nkYG*w*FwDiaySIfR4XZL-XFbo2TFzrMxEniDETDYIMRuKmisV8xjfOcCjEWmPkYfK57G*cffYv4JxuM*RUtN8LUIg*n6Kd0AKB8--w==\"\r\n }\r\n seajs.use('appmsg/index.js');\r\n </script>\n</body>\n</html>\n\n" ], [ "soup.find(id='sg_likeNum3')", "_____no_output_____" ] ], [ [ "# 作业:\n\n- 抓取复旦新媒体微信公众号最新一期的内容\n", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ] ]
4a0c873d33fad63b70d1211ec092d1f2f415e059
51,363
ipynb
Jupyter Notebook
.ipynb_checkpoints/ctc_2019-checkpoint.ipynb
LeoWood/captcha_break
bae7052d7452132032f1c6d27e3e9d0114d63181
[ "MIT" ]
null
null
null
.ipynb_checkpoints/ctc_2019-checkpoint.ipynb
LeoWood/captcha_break
bae7052d7452132032f1c6d27e3e9d0114d63181
[ "MIT" ]
null
null
null
.ipynb_checkpoints/ctc_2019-checkpoint.ipynb
LeoWood/captcha_break
bae7052d7452132032f1c6d27e3e9d0114d63181
[ "MIT" ]
null
null
null
76.093333
30,508
0.795203
[ [ [ "# 导入必要的库\n\n我们需要导入一个叫 [captcha](https://github.com/lepture/captcha/) 的库来生成验证码。\n\n我们生成验证码的字符由数字和大写字母组成。\n\n```sh\npip install captcha numpy matplotlib tensorflow-gpu pydot tqdm\n```", "_____no_output_____" ] ], [ [ "from captcha.image import ImageCaptcha\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport random\n\n%matplotlib inline\n%config InlineBackend.figure_format = 'retina'\n\nimport string\ncharacters = string.digits + string.ascii_uppercase\nprint(characters)\n\nwidth, height, n_len, n_class = 128, 64, 4, len(characters) + 1", "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\n" ] ], [ [ "# 防止 tensorflow 占用所有显存", "_____no_output_____" ] ], [ [ "import tensorflow as tf\nimport tensorflow.keras.backend as K\n\nconfig = tf.ConfigProto()\nconfig.gpu_options.allow_growth=True\nsess = tf.Session(config=config)\nK.set_session(sess)", "_____no_output_____" ] ], [ [ "# 定义 CTC Loss", "_____no_output_____" ] ], [ [ "import tensorflow.keras.backend as K\n\ndef ctc_lambda_func(args):\n y_pred, labels, input_length, label_length = args\n return K.ctc_batch_cost(labels, y_pred, input_length, label_length)", "_____no_output_____" ] ], [ [ "# 定义网络结构", "_____no_output_____" ] ], [ [ "from tensorflow.keras.models import *\nfrom tensorflow.keras.layers import *\n\ninput_tensor = Input((height, width, 3))\nx = input_tensor\nfor i, n_cnn in enumerate([2, 2, 2, 2, 2]):\n for j in range(n_cnn):\n x = Conv2D(32*2**min(i, 3), kernel_size=3, padding='same', kernel_initializer='he_uniform')(x)\n x = BatchNormalization()(x)\n x = Activation('relu')(x)\n x = MaxPooling2D(2 if i < 3 else (2, 1))(x)\n\nx = Permute((2, 1, 3))(x)\nx = TimeDistributed(Flatten())(x)\n\nrnn_size = 128\nx = Bidirectional(CuDNNGRU(rnn_size, return_sequences=True))(x)\nx = Bidirectional(CuDNNGRU(rnn_size, return_sequences=True))(x)\nx = Dense(n_class, activation='softmax')(x)\n\nbase_model = Model(inputs=input_tensor, outputs=x)", "_____no_output_____" ], [ "labels = Input(name='the_labels', shape=[n_len], dtype='float32')\ninput_length = Input(name='input_length', shape=[1], dtype='int64')\nlabel_length = Input(name='label_length', shape=[1], dtype='int64')\nloss_out = Lambda(ctc_lambda_func, output_shape=(1,), name='ctc')([x, labels, input_length, label_length])\n\nmodel = Model(inputs=[input_tensor, labels, input_length, label_length], outputs=loss_out)", "_____no_output_____" ] ], [ [ "# 网络结构可视化", "_____no_output_____" ] ], [ [ "from tensorflow.keras.utils import plot_model\nfrom IPython.display import Image\n\nplot_model(model, to_file='ctc.png', show_shapes=True)\nImage('ctc.png')", "_____no_output_____" ], [ "base_model.summary()", "_____no_output_____" ] ], [ [ "# 定义数据生成器", "_____no_output_____" ] ], [ [ "from tensorflow.keras.utils import Sequence\n\nclass CaptchaSequence(Sequence):\n def __init__(self, characters, batch_size, steps, n_len=4, width=128, height=64, \n input_length=16, label_length=4):\n self.characters = characters\n self.batch_size = batch_size\n self.steps = steps\n self.n_len = n_len\n self.width = width\n self.height = height\n self.input_length = input_length\n self.label_length = label_length\n self.n_class = len(characters)\n self.generator = ImageCaptcha(width=width, height=height)\n \n def __len__(self):\n return self.steps\n\n def __getitem__(self, idx):\n X = np.zeros((self.batch_size, self.height, self.width, 3), dtype=np.float32)\n y = np.zeros((self.batch_size, self.n_len), dtype=np.uint8)\n input_length = np.ones(self.batch_size)*self.input_length\n label_length = np.ones(self.batch_size)*self.label_length\n for i in range(self.batch_size):\n random_str = ''.join([random.choice(self.characters) for j in range(self.n_len)])\n X[i] = np.array(self.generator.generate_image(random_str)) / 255.0\n y[i] = [self.characters.find(x) for x in random_str]\n return [X, y, input_length, label_length], np.ones(self.batch_size)", "d:\\anaconda3\\envs\\py36\\lib\\site-packages\\tensorflow\\python\\framework\\dtypes.py:523: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n _np_qint8 = np.dtype([(\"qint8\", np.int8, 1)])\nd:\\anaconda3\\envs\\py36\\lib\\site-packages\\tensorflow\\python\\framework\\dtypes.py:524: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n _np_quint8 = np.dtype([(\"quint8\", np.uint8, 1)])\nd:\\anaconda3\\envs\\py36\\lib\\site-packages\\tensorflow\\python\\framework\\dtypes.py:525: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n _np_qint16 = np.dtype([(\"qint16\", np.int16, 1)])\nd:\\anaconda3\\envs\\py36\\lib\\site-packages\\tensorflow\\python\\framework\\dtypes.py:526: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n _np_quint16 = np.dtype([(\"quint16\", np.uint16, 1)])\nd:\\anaconda3\\envs\\py36\\lib\\site-packages\\tensorflow\\python\\framework\\dtypes.py:527: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n _np_qint32 = np.dtype([(\"qint32\", np.int32, 1)])\nd:\\anaconda3\\envs\\py36\\lib\\site-packages\\tensorflow\\python\\framework\\dtypes.py:532: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n np_resource = np.dtype([(\"resource\", np.ubyte, 1)])\n" ] ], [ [ "# 测试生成器", "_____no_output_____" ] ], [ [ "data = CaptchaSequence(characters, batch_size=1, steps=1)\n[X_test, y_test, _, _], _ = data[0]\nplt.imshow(X_test[0])\nplt.title(''.join([characters[x] for x in y_test[0]]))\nprint(input_length, label_length)", "[[[0.96862745 0.9882353 0.9372549 ]\n [0.96862745 0.9882353 0.9372549 ]\n [0.96862745 0.9882353 0.9372549 ]\n ...\n [0.96862745 0.9882353 0.9372549 ]\n [0.96862745 0.9882353 0.9372549 ]\n [0.96862745 0.9882353 0.9372549 ]]\n\n [[0.96862745 0.9882353 0.9372549 ]\n [0.96862745 0.9882353 0.9372549 ]\n [0.96862745 0.9882353 0.9372549 ]\n ...\n [0.96862745 0.9882353 0.9372549 ]\n [0.96862745 0.9882353 0.9372549 ]\n [0.96862745 0.9882353 0.9372549 ]]\n\n [[0.96862745 0.9882353 0.9372549 ]\n [0.96862745 0.9882353 0.9372549 ]\n [0.96862745 0.9882353 0.9372549 ]\n ...\n [0.96862745 0.9882353 0.9372549 ]\n [0.96862745 0.9882353 0.9372549 ]\n [0.96862745 0.9882353 0.9372549 ]]\n\n ...\n\n [[0.96862745 0.9882353 0.9372549 ]\n [0.96862745 0.9882353 0.9372549 ]\n [0.96862745 0.9882353 0.9372549 ]\n ...\n [0.96862745 0.9882353 0.9372549 ]\n [0.96862745 0.9882353 0.9372549 ]\n [0.96862745 0.9882353 0.9372549 ]]\n\n [[0.96862745 0.9882353 0.9372549 ]\n [0.96862745 0.9882353 0.9372549 ]\n [0.96862745 0.9882353 0.9372549 ]\n ...\n [0.96862745 0.9882353 0.9372549 ]\n [0.96862745 0.9882353 0.9372549 ]\n [0.96862745 0.9882353 0.9372549 ]]\n\n [[0.96862745 0.9882353 0.9372549 ]\n [0.96862745 0.9882353 0.9372549 ]\n [0.96862745 0.9882353 0.9372549 ]\n ...\n [0.96862745 0.9882353 0.9372549 ]\n [0.96862745 0.9882353 0.9372549 ]\n [0.96862745 0.9882353 0.9372549 ]]]\n" ] ], [ [ "# 准确率回调函数", "_____no_output_____" ] ], [ [ "from tqdm import tqdm\n\ndef evaluate(model, batch_size=128, steps=20):\n batch_acc = 0\n valid_data = CaptchaSequence(characters, batch_size, steps)\n for [X_test, y_test, _, _], _ in valid_data:\n y_pred = base_model.predict(X_test)\n shape = y_pred.shape\n out = K.get_value(K.ctc_decode(y_pred, input_length=np.ones(shape[0])*shape[1])[0][0])[:, :4]\n if out.shape[1] == 4:\n batch_acc += (y_test == out).all(axis=1).mean()\n return batch_acc / steps", "_____no_output_____" ], [ "from tensorflow.keras.callbacks import Callback\n\nclass Evaluate(Callback):\n def __init__(self):\n self.accs = []\n \n def on_epoch_end(self, epoch, logs=None):\n logs = logs or {}\n acc = evaluate(base_model)\n logs['val_acc'] = acc\n self.accs.append(acc)\n print(f'\\nacc: {acc*100:.4f}')", "_____no_output_____" ] ], [ [ "# 训练模型", "_____no_output_____" ] ], [ [ "from tensorflow.keras.callbacks import EarlyStopping, CSVLogger, ModelCheckpoint\nfrom tensorflow.keras.optimizers import *\n\ntrain_data = CaptchaSequence(characters, batch_size=128, steps=1000)\nvalid_data = CaptchaSequence(characters, batch_size=128, steps=100)\ncallbacks = [EarlyStopping(patience=5), Evaluate(), \n CSVLogger('ctc.csv'), ModelCheckpoint('ctc_best.h5', save_best_only=True)]\n\nmodel.compile(loss={'ctc': lambda y_true, y_pred: y_pred}, optimizer=Adam(1e-3, amsgrad=True))\nmodel.fit_generator(train_data, epochs=100, validation_data=valid_data, workers=4, use_multiprocessing=True,\n callbacks=callbacks)", "_____no_output_____" ] ], [ [ "### 载入最好的模型继续训练一会", "_____no_output_____" ] ], [ [ "model.load_weights('ctc_best.h5')\n\ncallbacks = [EarlyStopping(patience=5), Evaluate(), \n CSVLogger('ctc.csv', append=True), ModelCheckpoint('ctc_best.h5', save_best_only=True)]\n\nmodel.compile(loss={'ctc': lambda y_true, y_pred: y_pred}, optimizer=Adam(1e-4, amsgrad=True))\nmodel.fit_generator(train_data, epochs=100, validation_data=valid_data, workers=4, use_multiprocessing=True,\n callbacks=callbacks)", "_____no_output_____" ], [ "model.load_weights('ctc_best.h5')", "_____no_output_____" ] ], [ [ "# 测试模型", "_____no_output_____" ] ], [ [ "characters2 = characters + ' '\n[X_test, y_test, _, _], _ = data[0]\ny_pred = base_model.predict(X_test)\nout = K.get_value(K.ctc_decode(y_pred, input_length=np.ones(y_pred.shape[0])*y_pred.shape[1], )[0][0])[:, :4]\nout = ''.join([characters[x] for x in out[0]])\ny_true = ''.join([characters[x] for x in y_test[0]])\n\nplt.imshow(X_test[0])\nplt.title('pred:' + str(out) + '\\ntrue: ' + str(y_true))\n\nargmax = np.argmax(y_pred, axis=2)[0]\nlist(zip(argmax, ''.join([characters2[x] for x in argmax])))", "_____no_output_____" ] ], [ [ "# 计算模型总体准确率", "_____no_output_____" ] ], [ [ "evaluate(base_model)", "_____no_output_____" ] ], [ [ "# 保存模型", "_____no_output_____" ] ], [ [ "base_model.save('ctc.h5', include_optimizer=False)", "_____no_output_____" ] ], [ [ "# 可视化训练曲线\n\n```sh\npip install pandas\n```", "_____no_output_____" ] ], [ [ "import pandas as pd\n\ndf = pd.read_csv('ctc.csv')\ndf[['loss', 'val_loss']].plot()", "_____no_output_____" ], [ "df[['loss', 'val_loss']].plot(logy=True)", "_____no_output_____" ], [ "df['val_acc'].plot()", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ] ]
4a0c93685d71fe89683cd901fdc83da34f1356cd
487,070
ipynb
Jupyter Notebook
Pneumonia_Detection.ipynb
AneezaNiamat/Pneumonia-Detection
e42f7bece58e5fd4f5e8bcd99d24a4aa316fcc5b
[ "MIT" ]
null
null
null
Pneumonia_Detection.ipynb
AneezaNiamat/Pneumonia-Detection
e42f7bece58e5fd4f5e8bcd99d24a4aa316fcc5b
[ "MIT" ]
null
null
null
Pneumonia_Detection.ipynb
AneezaNiamat/Pneumonia-Detection
e42f7bece58e5fd4f5e8bcd99d24a4aa316fcc5b
[ "MIT" ]
null
null
null
88.2853
155
0.684821
[ [ [ "!unzip \"/content/drive/MyDrive/archive.zip\" -d archive", "\u001b[1;30;43mStreaming output truncated to the last 5000 lines.\u001b[0m\n inflating: archive/chest_xray/train/NORMAL/IM-0435-0001-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0435-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0437-0001-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0437-0001-0002.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0437-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0438-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0439-0001-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0439-0001-0002.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0439-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0440-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0441-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0442-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0444-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0445-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0446-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0447-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0448-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0449-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0450-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0451-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0452-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0453-0001-0002.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0453-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0455-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0456-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0457-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0458-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0459-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0460-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0461-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0463-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0464-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0465-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0466-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0467-0001-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0467-0001-0002.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0467-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0469-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0471-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0472-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0473-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0474-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0475-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0476-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0477-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0478-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0479-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0480-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0481-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0482-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0483-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0484-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0485-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0486-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0487-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0488-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0489-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0490-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0491-0001-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0491-0001-0002.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0491-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0492-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0493-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0494-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0495-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0496-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0497-0001-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0497-0001-0002.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0497-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0499-0001-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0499-0001-0002.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0499-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0500-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0501-0001-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0501-0001-0002.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0501-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0502-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0503-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0504-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0505-0001-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0505-0001-0002.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0505-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0506-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0507-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0508-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0509-0001-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0509-0001-0002.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0509-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0510-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0511-0001-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0511-0001-0002.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0511-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0512-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0513-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0514-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0515-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0516-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0517-0001-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0517-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0519-0001-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0519-0001-0002.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0519-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0520-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0521-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0522-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0523-0001-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0523-0001-0002.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0523-0001-0003.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0523-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0524-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0525-0001-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0525-0001-0002.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0525-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0526-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0527-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0528-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0529-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0530-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0531-0001-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0531-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0532-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0533-0001-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0533-0001-0002.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0533-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0534-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0535-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0536-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0537-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0538-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0539-0001-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0539-0001-0002.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0539-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0540-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0541-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0542-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0543-0001-0002.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0543-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0544-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0545-0001-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0545-0001-0002.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0545-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0546-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0547-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0548-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0549-0001-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0549-0001-0002.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0549-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0551-0001-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0551-0001-0002.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0551-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0552-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0553-0001-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0553-0001-0002.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0553-0001-0003.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0553-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0554-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0555-0001-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0555-0001-0002.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0555-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0556-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0557-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0559-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0560-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0561-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0562-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0563-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0564-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0565-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0566-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0568-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0569-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0570-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0571-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0574-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0575-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0577-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0578-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0579-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0580-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0581-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0582-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0583-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0584-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0586-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0588-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0590-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0591-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0592-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0593-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0595-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0596-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0598-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0599-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0600-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0601-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0602-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0604-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0605-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0606-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0607-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0608-0001-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0608-0001-0002.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0608-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0609-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0612-0001-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0612-0001-0002.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0612-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0613-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0614-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0615-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0616-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0617-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0618-0001-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0618-0001-0002.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0618-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0619-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0620-0001-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0620-0001-0002.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0620-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0621-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0622-0001-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0622-0001-0002.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0622-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0623-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0624-0001-0002.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0624-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0625-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0626-0001-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0626-0001-0002.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0627-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0628-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0629-0001-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0629-0001-0002.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0629-0001-0003.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0629-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0630-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0631-0001-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0631-0001-0002.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0631-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0632-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0633-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0634-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0635-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0636-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0637-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0640-0001-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0640-0001-0002.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0640-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0641-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0642-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0643-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0644-0001-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0644-0001-0002.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0644-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0645-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0646-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0647-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0648-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0649-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0650-0001-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0650-0001-0002.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0650-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0651-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0652-0001-0002.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0652-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0654-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0655-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0656-0001-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0656-0001-0002.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0656-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0657-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0658-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0659-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0660-0001-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0660-0001-0002.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0660-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0661-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0662-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0663-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0664-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0665-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0666-0001-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0666-0001-0002.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0666-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0667-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0668-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0669-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0670-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0671-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0672-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0673-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0674-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0675-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0676-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0677-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0678-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0679-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0680-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0681-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0682-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0683-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0684-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0685-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0686-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0687-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0688-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0689-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0691-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0692-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0693-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0694-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0695-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0696-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0697-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0698-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0700-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0701-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0702-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0703-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0704-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0705-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0706-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0707-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0709-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0710-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0711-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0712-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0713-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0714-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0715-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0716-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0717-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0718-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0719-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0721-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0722-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0724-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0727-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0728-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0729-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0730-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0732-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0733-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0734-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0735-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0736-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0737-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0738-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0739-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0740-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0741-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0742-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0746-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0747-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0748-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0750-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0751-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0752-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0753-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0754-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0755-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0757-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0761-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0764-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/IM-0766-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0383-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0384-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0385-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0386-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0388-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0389-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0390-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0391-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0392-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0393-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0394-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0395-0001-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0395-0001-0002.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0395-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0396-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0397-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0399-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0401-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0402-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0403-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0404-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0406-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0407-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0408-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0409-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0410-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0412-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0413-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0414-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0415-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0416-0001-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0416-0001-0002.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0416-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0417-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0418-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0419-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0421-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0423-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0424-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0425-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0427-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0428-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0429-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0433-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0435-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0437-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0439-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0440-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0441-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0443-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0445-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0447-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0448-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0449-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0450-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0451-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0452-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0453-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0454-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0455-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0456-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0458-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0460-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0462-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0463-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0464-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0465-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0466-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0468-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0472-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0473-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0474-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0475-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0476-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0478-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0479-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0480-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0481-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0482-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0485-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0486-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0487-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0488-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0489-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0490-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0491-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0493-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0496-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0497-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0499-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0500-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0501-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0502-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0503-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0506-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0507-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0508-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0509-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0511-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0512-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0513-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0515-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0516-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0517-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0518-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0520-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0521-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0522-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0523-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0525-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0526-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0528-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0529-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0530-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0531-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0533-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0535-0001-0002.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0535-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0536-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0537-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0539-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0540-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0541-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0543-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0545-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0547-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0550-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0551-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0552-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0553-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0554-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0555-0001-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0555-0001-0002.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0555-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0557-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0558-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0559-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0561-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0563-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0564-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0566-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0567-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0568-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0569-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0571-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0572-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0573-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0575-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0576-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0577-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0578-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0579-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0580-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0582-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0583-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0585-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0587-0001-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0587-0001-0002.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0587-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0588-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0589-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0592-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0594-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0595-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0596-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0599-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0600-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0601-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0602-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0603-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0604-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0609-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0611-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0616-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0617-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0618-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0619-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0620-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0621-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0622-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0623-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0626-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0627-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0629-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0630-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0633-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0634-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0635-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0636-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0637-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0640-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0641-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0642-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0643-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0645-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0647-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0648-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0649-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0650-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0651-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0651-0004.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0652-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0653-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0654-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0655-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0657-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0659-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0660-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0661-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0662-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0663-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0664-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0665-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0666-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0667-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0668-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0669-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0671-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0672-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0673-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0675-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0678-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0680-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0682-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0683-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0684-0001-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0686-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0687-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0689-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0690-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0692-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0693-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0694-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0695-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0696-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0698-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0699-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0700-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0702-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0705-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0707-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0718-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0719-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0723-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0725-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0727-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0730-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0736-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0741-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0744-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0746-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0749-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0753-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0757-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0765-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0771-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0772-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0774-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0775-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0776-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0777-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0780-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0781-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0790-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0793-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0796-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0797-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0798-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0799-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0803-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0804-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0806-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0807-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0808-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0809-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0810-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0811-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0812-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0814-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0815-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0816-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0818-0001-0002.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0818-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0819-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0820-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0821-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0822-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0824-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0825-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0826-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0827-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0828-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0829-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0830-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0831-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0832-0001-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0832-0001-0002.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0832-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0833-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0834-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0836-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0837-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0838-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0839-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0840-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0841-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0842-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0843-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0845-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0846-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0847-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0848-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0849-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0851-0001-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0851-0001-0002.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0851-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0852-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0853-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0854-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0855-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0856-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0857-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0858-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0859-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0860-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0862-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0863-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0865-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0866-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0867-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0868-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0869-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0870-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0871-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0872-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0873-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0874-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0875-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0876-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0877-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0879-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0880-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0881-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0882-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0885-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0886-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0887-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0888-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0890-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0892-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0893-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0894-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0895-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0896-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0897-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0898-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0899-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0900-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0903-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0904-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0905-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0906-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0907-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0908-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0909-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0910-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0911-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0912-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0913-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0914-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0915-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0917-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0918-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0919-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0922-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0923-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0924-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0925-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0926-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0927-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0929-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0930-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0931-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0932-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0933-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0934-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0935-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0936-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0937-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0939-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0941-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0942-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0944-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0945-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0946-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0947-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0948-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0949-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0950-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0951-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0952-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0954-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0955-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0956-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0957-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0959-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0960-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0961-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0962-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0965-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0966-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0967-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0969-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0970-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0971-0001-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0971-0001-0002.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0974-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0975-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0976-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0977-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0978-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0979-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0980-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0981-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0983-0001-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0983-0001-0002.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0983-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0986-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0987-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0988-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0989-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0992-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0993-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0994-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0995-0001-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0995-0001-0002.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0995-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0997-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0998-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-0999-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1001-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1002-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1004-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1005-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1006-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1008-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1010-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1011-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1014-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1015-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1016-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1017-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1018-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1019-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1020-0001-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1020-0001-0002.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1020-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1022-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1023-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1024-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1025-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1026-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1027-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1028-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1030-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1033-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1035-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1037-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1038-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1039-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1040-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1041-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1043-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1044-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1045-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1046-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1047-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1048-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1049-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1050-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1051-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1052-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1053-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1054-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1055-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1056-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1058-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1059-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1060-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1062-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1064-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1067-0001-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1067-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1073-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1084-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1086-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1088-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1089-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1090-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1091-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1093-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1094-0001-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1094-0001-0002.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1094-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1096-0001-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1096-0001-0003.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1096-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1098-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1100-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1102-0001-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1102-0001-0002.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1102-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1103-0001-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1104-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1105-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1106-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1108-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1109-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1110-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1111-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1112-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1113-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1114-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1116-0001-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1116-0001-0002.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1116-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1117-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1118-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1120-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1122-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1123-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1124-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1125-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1126-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1127-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1128-0001-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1128-0001-0002.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1128-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1130-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1131-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1132-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1134-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1135-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1136-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1138-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1141-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1142-0001-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1142-0001-0002.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1142-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1144-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1145-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1147-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1148-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1149-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1150-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1151-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1152-0001-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1152-0001-0002.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1152-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1153-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1154-0001-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1154-0001-0002.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1154-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1155-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1156-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1157-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1158-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1160-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1161-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1162-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1163-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1164-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1167-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1168-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1169-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1170-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1171-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1173-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1174-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1175-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1176-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1177-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1178-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1179-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1180-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1181-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1182-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1183-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1184-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1185-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1187-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1188-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1189-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1190-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1191-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1192-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1194-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1196-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1197-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1198-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1200-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1201-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1202-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1203-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1204-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1205-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1206-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1209-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1214-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1218-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1219-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1220-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1221-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1222-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1223-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1224-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1225-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1226-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1227-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1228-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1231-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1232-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1234-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1236-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1237-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1240-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1241-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1242-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1243-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1244-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1245-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1247-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1250-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1252-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1253-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1254-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1256-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1257-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1258-0001-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1258-0001-0002.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1258-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1260-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1261-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1262-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1264-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1266-0001-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1266-0001-0002.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1266-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1267-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1269-0001-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1269-0001-0002.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1269-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1270-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1271-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1272-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1273-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1274-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1275-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1276-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1277-0001-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1277-0001-0002.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1277-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1278-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1279-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1280-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1281-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1282-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1285-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1286-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1287-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1288-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1289-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1290-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1291-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1292-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1293-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1294-0001-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1294-0001-0002.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1294-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1295-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1296-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1300-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1301-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1302-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1303-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1304-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1305-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1306-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1307-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1308-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1310-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1311-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1314-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1315-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1316-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1317-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1318-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1319-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1320-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1321-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1322-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1323-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1326-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1327-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1328-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1329-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1330-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1332-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1333-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1334-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1335-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1336-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1337-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1338-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1341-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1342-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1343-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1344-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1345-0001-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1345-0001-0002.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1345-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1346-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1347-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1348-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1349-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1350-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1351-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1356-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1357-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1360-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1362-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1365-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1371-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1376-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1379-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1385-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1396-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1400-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1401-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1406-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1412-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1419-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1422-0001.jpeg \n inflating: archive/chest_xray/train/NORMAL/NORMAL2-IM-1423-0001.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1000_bacteria_2931.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1000_virus_1681.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1001_bacteria_2932.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1002_bacteria_2933.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1003_bacteria_2934.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1003_virus_1685.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1004_bacteria_2935.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1004_virus_1686.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1005_bacteria_2936.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1005_virus_1688.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1006_bacteria_2937.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1007_bacteria_2938.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1007_virus_1690.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1008_bacteria_2939.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1008_virus_1691.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1009_virus_1694.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person100_virus_184.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1010_bacteria_2941.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1010_virus_1695.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1011_bacteria_2942.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1012_bacteria_2943.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1014_bacteria_2945.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1015_virus_1701.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1015_virus_1702.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1016_bacteria_2947.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1016_virus_1704.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1017_bacteria_2948.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1018_bacteria_2949.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1018_virus_1706.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1019_bacteria_2950.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1019_virus_1707.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1019_virus_1708.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person101_virus_187.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person101_virus_188.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1020_bacteria_2951.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1020_virus_1710.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1021_virus_1711.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1022_bacteria_2953.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1022_virus_1712.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1023_bacteria_2954.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1023_virus_1714.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1024_bacteria_2955.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1024_virus_1716.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1026_bacteria_2957.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1026_virus_1718.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1028_bacteria_2959.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1028_bacteria_2960.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1029_bacteria_2961.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1029_virus_1721.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person102_virus_189.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1030_virus_1722.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1031_bacteria_2963.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1031_bacteria_2964.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1031_virus_1723.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1033_bacteria_2966.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1034_bacteria_2968.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1034_virus_1728.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1035_bacteria_2969.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1035_virus_1729.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1036_bacteria_2970.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1036_virus_1730.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1037_bacteria_2971.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1038_bacteria_2972.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1038_virus_1733.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1039_bacteria_2973.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person103_virus_190.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1040_bacteria_2974.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1040_virus_1735.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1041_bacteria_2975.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1041_virus_1736.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1042_virus_1737.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1043_bacteria_2977.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1043_virus_1738.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1044_bacteria_2978.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1044_virus_1740.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1045_bacteria_2979.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1045_virus_1741.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1046_bacteria_2980.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1046_virus_1742.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1048_bacteria_2982.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1048_virus_1744.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1049_bacteria_2983.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1049_virus_1746.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person104_virus_191.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1050_bacteria_2984.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1051_bacteria_2985.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1051_virus_1750.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1052_bacteria_2986.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1052_virus_1751.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1053_bacteria_2987.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1054_bacteria_2988.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1055_bacteria_2989.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1056_bacteria_2990.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1056_virus_1755.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1057_bacteria_2991.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1057_virus_1756.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1058_bacteria_2992.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1058_virus_1757.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1059_bacteria_2993.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1059_virus_1758.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person105_virus_192.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person105_virus_193.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1060_virus_1760.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1062_bacteria_2996.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1062_virus_1762.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1063_bacteria_2997.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1063_virus_1765.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1065_bacteria_2999.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1065_virus_1768.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1066_bacteria_3000.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1066_virus_1769.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1067_bacteria_3001.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1067_virus_1770.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1068_bacteria_3002.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1068_virus_1771.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1069_bacteria_3003.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1069_virus_1772.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person106_virus_194.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1070_virus_1773.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1071_bacteria_3005.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1071_virus_1774.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1072_bacteria_3006.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1072_bacteria_3007.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1072_virus_1775.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1073_bacteria_3008.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1073_bacteria_3011.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1073_virus_1776.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1074_bacteria_3012.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1074_bacteria_3014.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1075_bacteria_3015.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1076_bacteria_3016.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1077_bacteria_3017.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1077_virus_1787.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1078_bacteria_3018.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1078_virus_1788.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1079_bacteria_3019.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1079_virus_1789.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person107_virus_197.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1080_bacteria_3020.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1080_virus_1791.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1081_bacteria_3021.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1081_virus_1793.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1082_bacteria_3022.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1082_virus_1794.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1083_bacteria_3023.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1083_virus_1795.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1084_bacteria_3024.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1084_virus_1796.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1085_bacteria_3025.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1085_virus_1797.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1086_bacteria_3026.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1086_virus_1798.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1087_bacteria_3027.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1087_virus_1799.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1088_bacteria_3028.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1088_virus_1800.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1089_bacteria_3029.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1089_virus_1808.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person108_virus_199.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person108_virus_200.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person108_virus_201.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1090_virus_1809.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1091_bacteria_3031.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1091_virus_1810.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1092_bacteria_3032.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1092_virus_1811.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1093_bacteria_3033.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1094_virus_1814.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1095_virus_1815.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1096_bacteria_3037.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1096_virus_1816.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1097_bacteria_3038.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1097_virus_1817.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1098_bacteria_3039.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1098_virus_1818.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1099_bacteria_3040.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1099_virus_1819.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person109_virus_203.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person10_bacteria_43.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1100_bacteria_3041.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1100_virus_1820.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1101_bacteria_3042.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1102_bacteria_3043.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1102_virus_1822.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1103_bacteria_3044.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1103_virus_1825.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1104_virus_1826.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1105_bacteria_3046.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1106_virus_1829.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1107_bacteria_3048.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1107_virus_1831.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1107_virus_1832.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1108_bacteria_3049.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1108_virus_1833.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1109_bacteria_3050.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person110_virus_205.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person110_virus_206.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person110_virus_207.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person110_virus_208.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1110_bacteria_3051.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1110_virus_1835.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1111_bacteria_3052.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1111_virus_1836.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1112_bacteria_3053.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1112_virus_1837.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1113_virus_1838.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1114_bacteria_3055.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1115_bacteria_3056.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1115_virus_1840.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1116_virus_1841.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1118_bacteria_3059.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1119_virus_1844.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person111_virus_209.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person111_virus_210.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person111_virus_212.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1120_virus_1845.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1121_virus_1846.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1122_bacteria_3063.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1122_virus_1847.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1123_virus_1848.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1124_bacteria_3065.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1124_virus_1851.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1125_bacteria_3066.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1125_virus_1852.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1126_virus_1853.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1127_bacteria_3068.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1127_virus_1854.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1128_bacteria_3069.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1129_bacteria_3070.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1129_virus_1857.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person112_virus_213.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1130_bacteria_3072.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1130_virus_1860.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1131_bacteria_3073.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1132_virus_1863.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1133_bacteria_3075.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1133_virus_1865.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1134_bacteria_3076.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1135_bacteria_3077.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1136_bacteria_3078.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1137_virus_1876.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1138_bacteria_3080.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1138_virus_1877.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1138_virus_1879.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1139_bacteria_3081.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1139_bacteria_3082.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1139_virus_1882.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person113_virus_215.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person113_virus_216.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1140_bacteria_3083.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1140_virus_1885.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1141_bacteria_3084.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1141_bacteria_3085.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1141_virus_1886.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1141_virus_1890.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1142_bacteria_3086.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1142_virus_1892.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1143_virus_1896.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1143_virus_1897.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1144_bacteria_3089.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1145_bacteria_3090.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1145_virus_1902.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1145_virus_1905.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1145_virus_1906.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1146_bacteria_3091.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1147_virus_1917.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1147_virus_1919.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1147_virus_1920.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1149_bacteria_3094.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1149_virus_1924.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1149_virus_1925.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person114_virus_217.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1150_bacteria_3095.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1151_virus_1928.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1152_virus_1930.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1153_virus_1932.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1154_bacteria_3099.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1154_virus_1933.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1155_bacteria_3100.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1155_virus_1934.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1156_bacteria_3101.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1156_virus_1935.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1156_virus_1936.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1157_bacteria_3102.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1157_virus_1937.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1158_bacteria_3103.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1158_virus_1938.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1158_virus_1940.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1158_virus_1941.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1158_virus_1942.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1158_virus_1943.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1159_bacteria_3104.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1159_virus_1944.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1159_virus_1945.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1159_virus_1946.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person115_virus_218.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person115_virus_219.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1160_bacteria_3105.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1160_virus_1947.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1161_virus_1948.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1162_bacteria_3107.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1162_virus_1949.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1162_virus_1950.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1163_virus_1951.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1164_bacteria_3110.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1164_virus_1952.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1164_virus_1955.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1164_virus_1956.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1164_virus_1957.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1164_virus_1958.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1165_bacteria_3111.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1165_virus_1959.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1167_bacteria_3113.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1168_bacteria_3114.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1168_bacteria_3115.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1168_virus_1965.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1168_virus_1966.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1169_virus_1968.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person116_virus_221.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1170_bacteria_3117.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1170_virus_1969.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1170_virus_1970.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1171_bacteria_3118.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1172_bacteria_3119.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1172_virus_1977.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1173_virus_1978.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1174_virus_1980.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1175_bacteria_3122.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1175_virus_1981.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1176_bacteria_3123.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1176_bacteria_3124.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1176_virus_1996.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1176_virus_1997.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1176_virus_1998.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1177_bacteria_3125.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1177_virus_1999.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1177_virus_2000.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1177_virus_2001.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1177_virus_2002.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1178_bacteria_3126.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1178_virus_2004.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1179_bacteria_3127.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1179_virus_2006.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person117_virus_223.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1180_bacteria_3128.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1180_virus_2007.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1180_virus_2008.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1180_virus_2009.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1180_virus_2010.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1180_virus_2011.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1180_virus_2012.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1180_virus_2013.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1180_virus_2014.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1180_virus_2015.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1181_bacteria_3129.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1181_virus_2016.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1182_virus_2017.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1183_bacteria_3131.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1183_virus_2018.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1184_bacteria_3132.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1184_virus_2019.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1185_bacteria_3133.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1186_bacteria_3134.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1186_bacteria_3135.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1186_virus_2021.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1186_virus_2022.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1187_bacteria_3136.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1187_virus_2023.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1188_bacteria_3137.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1188_virus_2024.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person118_virus_224.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1190_virus_2031.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1191_virus_2032.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1192_bacteria_3141.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1193_virus_2034.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1194_bacteria_3143.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1195_bacteria_3144.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1196_bacteria_3146.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1197_bacteria_3147.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1197_virus_2039.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1198_bacteria_3148.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1199_bacteria_3149.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person119_virus_225.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person11_bacteria_45.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1200_virus_2042.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1201_bacteria_3151.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1202_bacteria_3152.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1202_bacteria_3153.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1202_virus_2045.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1203_bacteria_3154.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1203_bacteria_3155.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1204_bacteria_3156.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1205_bacteria_3157.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1206_bacteria_3158.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1206_virus_2051.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1207_bacteria_3159.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1208_bacteria_3160.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1209_bacteria_3161.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person120_virus_226.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1211_bacteria_3163.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1211_virus_2056.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1212_bacteria_3164.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1212_virus_2057.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1213_virus_2058.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1214_bacteria_3166.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1214_virus_2059.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1215_bacteria_3167.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1216_bacteria_3168.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1216_virus_2062.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1217_bacteria_3169.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1217_virus_2063.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1218_bacteria_3171.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1218_virus_2066.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1219_bacteria_3172.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1219_virus_2067.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1220_bacteria_3173.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1220_bacteria_3174.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1220_virus_2068.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1222_bacteria_3177.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1222_virus_2071.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1223_bacteria_3178.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1223_virus_2073.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1224_virus_2074.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1225_bacteria_3180.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1225_virus_2076.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1226_virus_2077.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1227_bacteria_3182.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1227_virus_2078.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1228_bacteria_3183.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1228_virus_2079.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1229_virus_2080.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person122_virus_229.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1230_bacteria_3185.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1230_virus_2081.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1231_bacteria_3186.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1231_virus_2088.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1232_virus_2089.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1233_bacteria_3188.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1233_virus_2090.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1234_bacteria_3189.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1234_bacteria_3190.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1234_virus_2093.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1235_bacteria_3191.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1235_virus_2095.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1236_bacteria_3192.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1236_virus_2096.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1237_bacteria_3193.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1237_virus_2097.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1238_bacteria_3194.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1238_virus_2098.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1239_bacteria_3195.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1239_virus_2099.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person123_virus_230.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1240_bacteria_3196.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1241_bacteria_3197.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1241_virus_2106.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1242_bacteria_3198.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1242_virus_2108.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1242_virus_2109.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1243_bacteria_3199.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1243_virus_2110.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1244_bacteria_3200.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1244_virus_2111.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1246_bacteria_3202.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1247_bacteria_3203.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1247_virus_2115.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1248_bacteria_3204.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1248_virus_2117.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1249_bacteria_3205.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1249_virus_2118.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person124_virus_231.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person124_virus_233.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person124_virus_234.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person124_virus_236.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person124_virus_237.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person124_virus_238.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person124_virus_239.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person124_virus_240.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person124_virus_242.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person124_virus_244.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person124_virus_245.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person124_virus_246.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person124_virus_247.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person124_virus_249.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person124_virus_250.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person124_virus_251.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1250_bacteria_3207.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1251_bacteria_3208.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1252_bacteria_3209.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1252_virus_2124.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1253_bacteria_3211.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1253_virus_2129.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1254_virus_2130.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1255_virus_2132.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1256_bacteria_3214.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1257_bacteria_3215.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1258_bacteria_3216.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1258_virus_2138.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1259_bacteria_3217.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1259_virus_2139.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person125_virus_254.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1260_bacteria_3218.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1260_virus_2140.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1261_bacteria_3219.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1261_virus_2145.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1261_virus_2147.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1261_virus_2148.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1262_bacteria_3220.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1263_bacteria_3221.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1264_bacteria_3222.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1264_virus_2155.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1265_bacteria_3223.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1265_virus_2156.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1266_bacteria_3224.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1266_bacteria_3225.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1266_virus_2158.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1267_bacteria_3226.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1267_virus_2160.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1268_bacteria_3227.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1268_bacteria_3228.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1268_virus_2161.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1269_bacteria_3229.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1269_virus_2162.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person126_virus_255.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1270_bacteria_3230.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1270_virus_2163.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1271_bacteria_3231.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1271_virus_2164.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1272_bacteria_3232.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1272_virus_2190.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1273_bacteria_3233.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1273_bacteria_3234.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1273_virus_2191.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1274_bacteria_3235.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1274_bacteria_3236.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1274_virus_2193.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1275_bacteria_3237.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1276_bacteria_3239.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1276_virus_2198.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1277_bacteria_3240.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1278_virus_2201.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1279_bacteria_3242.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1280_bacteria_3243.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1281_bacteria_3244.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1281_virus_2204.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1282_bacteria_3245.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1283_bacteria_3246.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1283_virus_2206.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1284_bacteria_3247.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1284_virus_2207.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1285_virus_2208.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1286_bacteria_3249.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1286_virus_2209.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1287_bacteria_3250.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1287_virus_2210.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1288_bacteria_3251.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1288_virus_2211.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1289_bacteria_3252.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person128_virus_261.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1290_bacteria_3253.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1290_virus_2215.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1290_virus_2216.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1291_virus_2217.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1292_bacteria_3255.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1292_virus_2218.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1293_virus_2219.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1294_bacteria_3257.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1294_virus_2221.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1294_virus_2222.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1295_bacteria_3258.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1295_virus_2223.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1296_virus_2224.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1297_bacteria_3260.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1298_bacteria_3261.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1298_virus_2226.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1298_virus_2228.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person12_bacteria_46.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person12_bacteria_47.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person12_bacteria_48.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1300_bacteria_3264.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1300_virus_2240.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1301_virus_2241.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1302_bacteria_3266.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1303_bacteria_3267.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1303_virus_2243.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1304_bacteria_3269.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1305_bacteria_3271.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1306_bacteria_3272.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1306_bacteria_3274.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1306_bacteria_3275.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1306_bacteria_3276.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1306_bacteria_3277.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1306_virus_2249.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1307_bacteria_3278.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1307_virus_2251.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1308_bacteria_3280.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1308_bacteria_3283.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1308_bacteria_3285.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1308_bacteria_3286.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1308_bacteria_3288.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1308_bacteria_3290.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1308_bacteria_3292.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1308_virus_2252.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1308_virus_2253.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1309_bacteria_3294.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1309_virus_2254.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person130_virus_263.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1310_bacteria_3295.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1310_bacteria_3297.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1310_bacteria_3300.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1310_bacteria_3301.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1310_bacteria_3302.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1310_bacteria_3304.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1310_virus_2255.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1311_bacteria_3312.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1311_virus_2257.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1311_virus_2259.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1312_bacteria_3313.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1312_bacteria_3314.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1312_bacteria_3316.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1312_bacteria_3317.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1312_bacteria_3318.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1312_bacteria_3319.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1312_virus_2261.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1313_bacteria_3320.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1313_virus_2264.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1314_virus_2266.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1314_virus_2268.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1314_virus_2269.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1315_bacteria_3322.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1315_virus_2270.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1316_bacteria_3326.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1316_virus_2271.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1317_bacteria_3332.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1317_virus_2273.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1318_bacteria_3334.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1318_bacteria_3335.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1318_virus_2274.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1319_virus_2276.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person131_virus_265.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1320_bacteria_3339.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1320_bacteria_3340.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1320_bacteria_3342.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1320_bacteria_3344.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1320_bacteria_3345.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1320_bacteria_3346.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1320_bacteria_3347.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1320_bacteria_3348.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1320_bacteria_3350.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1320_bacteria_3351.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1320_bacteria_3352.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1320_bacteria_3353.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1320_bacteria_3355.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1320_virus_2277.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1321_bacteria_3358.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1321_bacteria_3359.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1321_virus_2279.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1322_bacteria_3360.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1323_bacteria_3361.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1323_bacteria_3362.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1323_bacteria_3363.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1323_virus_2282.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1323_virus_2283.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1324_virus_2284.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1324_virus_2285.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1325_bacteria_3366.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1325_virus_2287.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1326_bacteria_3372.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1327_bacteria_3373.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1327_bacteria_3374.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1328_bacteria_3376.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1328_virus_2293.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1328_virus_2294.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1328_virus_2295.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1329_bacteria_3377.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person132_virus_266.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1331_bacteria_3380.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1331_virus_2299.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1332_virus_2300.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1333_bacteria_3383.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1333_bacteria_3384.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1333_bacteria_3385.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1333_bacteria_3386.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1333_virus_2301.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1336_virus_2306.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1337_virus_2307.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1338_bacteria_3394.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1338_bacteria_3395.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1338_bacteria_3397.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1338_virus_2308.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1339_bacteria_3399.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1339_bacteria_3402.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person133_virus_267.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1340_bacteria_3405.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1340_virus_2311.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1340_virus_2312.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1341_bacteria_3406.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1341_virus_2313.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1342_bacteria_3407.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1342_virus_2315.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1343_bacteria_3409.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1343_bacteria_3411.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1343_bacteria_3413.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1343_bacteria_3414.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1343_bacteria_3415.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1343_bacteria_3416.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1343_bacteria_3417.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1343_bacteria_3418.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1343_bacteria_3419.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1343_virus_2316.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1343_virus_2317.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1344_bacteria_3421.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1344_virus_2319.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1344_virus_2320.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1345_bacteria_3422.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1345_bacteria_3424.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1345_bacteria_3425.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1345_bacteria_3426.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1345_bacteria_3427.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1345_bacteria_3428.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1345_virus_2321.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1346_bacteria_3430.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1346_virus_2322.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1347_virus_2323.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1348_virus_2324.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1348_virus_2326.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1349_bacteria_3434.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1349_bacteria_3436.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1349_bacteria_3437.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1349_bacteria_3438.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1349_bacteria_3439.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person134_virus_268.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1350_virus_2329.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1351_bacteria_3441.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1351_virus_2330.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1352_bacteria_3442.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1352_bacteria_3443.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1352_bacteria_3444.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1352_bacteria_3445.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1353_bacteria_3446.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1353_virus_2333.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1354_bacteria_3448.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1355_bacteria_3449.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1355_bacteria_3452.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1355_virus_2336.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1356_virus_2337.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1357_virus_2338.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1358_bacteria_3463.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1358_bacteria_3465.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1358_virus_2339.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1359_virus_2340.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person135_virus_270.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person135_virus_271.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1360_virus_2341.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1361_bacteria_3476.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1361_bacteria_3477.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1361_virus_2342.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1361_virus_2344.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1362_virus_2345.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1363_bacteria_3483.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1363_bacteria_3484.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1363_virus_2346.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1365_bacteria_3489.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1365_virus_2348.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1366_bacteria_3490.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1366_virus_2349.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1367_virus_2351.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1368_virus_2352.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1368_virus_2353.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1368_virus_2354.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1369_virus_2355.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1369_virus_2356.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1371_virus_2361.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1371_virus_2362.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1372_bacteria_3498.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1372_bacteria_3499.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1372_bacteria_3500.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1372_bacteria_3501.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1372_bacteria_3502.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1372_bacteria_3503.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1374_bacteria_3506.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1374_bacteria_3507.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1374_virus_2365.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1375_bacteria_3509.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1375_bacteria_3510.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1375_virus_2366.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1376_bacteria_3511.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1376_virus_2367.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1377_bacteria_3512.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1377_virus_2369.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1378_bacteria_3513.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1379_bacteria_3514.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person137_virus_281.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1380_bacteria_3515.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1381_bacteria_3516.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1381_bacteria_3517.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1381_virus_2375.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1383_bacteria_3521.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1383_virus_2377.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1384_bacteria_3522.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1385_bacteria_3524.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1385_virus_2380.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1387_virus_2382.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1388_bacteria_3529.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1389_bacteria_3531.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1389_virus_2387.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person138_virus_282.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1390_bacteria_3534.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1390_bacteria_3535.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1391_bacteria_3536.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1391_bacteria_3537.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1392_bacteria_3538.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1393_virus_2396.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1394_virus_2397.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1395_bacteria_3544.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1395_virus_2398.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1396_bacteria_3545.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1396_virus_2399.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1397_virus_2400.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1398_bacteria_3548.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1398_virus_2401.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1399_bacteria_3549.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1399_virus_2402.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person139_virus_283.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person13_bacteria_49.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person13_bacteria_50.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1400_bacteria_3550.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1400_bacteria_3551.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1400_bacteria_3553.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1400_bacteria_3554.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1401_bacteria_3555.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1402_virus_2405.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1403_bacteria_3557.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1403_bacteria_3559.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1403_virus_2406.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1404_bacteria_3561.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1405_bacteria_3564.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1405_bacteria_3566.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1405_bacteria_3567.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1405_bacteria_3571.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1405_bacteria_3573.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1405_virus_2408.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1406_bacteria_3574.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1406_bacteria_3575.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1406_virus_2409.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1407_virus_2410.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1408_bacteria_3579.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1408_bacteria_3581.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1408_virus_2411.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1409_bacteria_3583.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1409_bacteria_3585.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1409_virus_2413.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person140_virus_284.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person140_virus_285.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1411_bacteria_3591.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1411_bacteria_3593.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1411_bacteria_3598.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1411_bacteria_3599.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1411_bacteria_3601.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1411_bacteria_3602.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1411_bacteria_3603.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1411_bacteria_3604.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1411_bacteria_3607.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1411_bacteria_3609.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1411_bacteria_3610.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1411_virus_2415.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1412_bacteria_3612.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1413_bacteria_3613.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1413_bacteria_3615.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1413_bacteria_3617.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1413_bacteria_3620.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1413_virus_2422.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1413_virus_2423.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1414_bacteria_3627.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1414_bacteria_3628.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1414_virus_2424.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1415_bacteria_3629.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1415_virus_2425.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1416_virus_2427.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1417_bacteria_3635.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1418_bacteria_3636.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1418_bacteria_3637.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1418_bacteria_3638.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1418_bacteria_3639.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1418_bacteria_3643.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1418_virus_2429.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1419_bacteria_3645.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person141_virus_287.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1420_bacteria_3647.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1420_virus_2431.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1422_bacteria_3649.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1422_virus_2434.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1423_bacteria_3650.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1424_bacteria_3651.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1424_virus_2437.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1425_virus_2438.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1426_bacteria_3667.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1426_bacteria_3668.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1426_virus_2439.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1427_virus_2441.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1428_virus_2442.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1429_bacteria_3688.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1429_bacteria_3690.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1429_bacteria_3691.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1429_virus_2443.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person142_virus_288.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1430_bacteria_3693.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1430_bacteria_3694.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1430_bacteria_3695.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1430_bacteria_3696.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1430_bacteria_3697.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1430_virus_2444.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1431_bacteria_3698.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1432_bacteria_3699.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1433_bacteria_3701.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1433_bacteria_3704.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1433_bacteria_3705.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1433_virus_2447.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1436_bacteria_3711.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1436_bacteria_3712.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1438_bacteria_3715.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1438_bacteria_3718.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1438_bacteria_3721.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1438_virus_2452.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1439_bacteria_3722.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1439_virus_2453.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person143_virus_289.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1440_bacteria_3723.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1441_bacteria_3724.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1441_virus_2454.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1441_virus_2457.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1442_bacteria_3726.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1444_bacteria_3732.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1445_bacteria_3734.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1445_bacteria_3735.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1446_bacteria_3737.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1446_bacteria_3739.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1446_bacteria_3740.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1447_bacteria_3741.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1448_virus_2468.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1449_bacteria_3743.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1449_bacteria_3745.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1449_bacteria_3746.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1449_bacteria_3747.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1449_virus_2474.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1449_virus_2476.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1450_bacteria_3753.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1451_virus_2479.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1451_virus_2480.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1451_virus_2482.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1452_virus_2484.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1453_bacteria_3770.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1453_bacteria_3771.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1453_bacteria_3772.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1453_virus_2485.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1454_bacteria_3774.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1454_bacteria_3778.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1454_bacteria_3779.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1454_bacteria_3780.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1454_bacteria_3781.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1454_bacteria_3782.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1454_virus_2486.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1455_bacteria_3784.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1455_virus_2487.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1455_virus_2488.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1455_virus_2489.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1455_virus_2490.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1455_virus_2492.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1455_virus_2496.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1457_virus_2498.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1458_virus_2501.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1458_virus_2502.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1458_virus_2503.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1459_bacteria_3796.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1459_bacteria_3797.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1459_virus_2506.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person145_virus_294.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person145_virus_295.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1460_bacteria_3801.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1460_bacteria_3805.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1460_virus_2507.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1460_virus_2509.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1461_virus_2510.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1462_virus_2512.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1463_bacteria_3808.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1463_bacteria_3809.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1463_bacteria_3811.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1463_virus_2516.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1465_virus_2530.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1465_virus_2531.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1465_virus_2532.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1465_virus_2537.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1466_virus_2541.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1466_virus_2542.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1466_virus_2543.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1467_virus_2544.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1468_bacteria_3822.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1468_virus_2545.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1468_virus_2546.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1469_bacteria_3824.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1469_bacteria_3827.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1469_virus_2547.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person146_virus_296.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1470_bacteria_3829.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1470_bacteria_3830.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1471_bacteria_3831.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1471_virus_2549.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1472_bacteria_3833.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1472_bacteria_3834.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1472_virus_2550.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1473_bacteria_3836.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1473_virus_2551.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1473_virus_2553.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1474_bacteria_3837.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1474_virus_2556.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1474_virus_2557.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1475_virus_2558.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1476_bacteria_3842.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1476_bacteria_3843.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1476_virus_2560.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1477_virus_2561.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1478_bacteria_3848.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person147_virus_297.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1480_bacteria_3858.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1480_bacteria_3859.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1480_virus_2566.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1481_bacteria_3862.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1481_bacteria_3863.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1481_bacteria_3864.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1481_bacteria_3865.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1481_bacteria_3866.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1481_bacteria_3867.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1481_bacteria_3868.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1481_virus_2567.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1482_bacteria_3870.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1482_bacteria_3874.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1482_virus_2569.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1482_virus_2570.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1482_virus_2571.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1482_virus_2572.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1482_virus_2573.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1483_bacteria_3876.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1483_virus_2574.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1484_bacteria_3878.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1484_virus_2576.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1484_virus_2577.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1486_bacteria_3881.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1486_bacteria_3883.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1486_bacteria_3884.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1486_bacteria_3885.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1486_virus_2580.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1488_bacteria_3887.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1488_virus_2585.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1488_virus_2587.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1488_virus_2589.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1488_virus_2592.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1488_virus_2593.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1489_bacteria_3889.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1489_virus_2594.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person148_virus_298.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1490_bacteria_3891.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1490_virus_2596.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1491_bacteria_3892.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1491_bacteria_3893.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1491_virus_2597.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1492_bacteria_3894.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1492_virus_2599.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1493_bacteria_3895.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1493_bacteria_3896.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1493_bacteria_3897.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1493_bacteria_3898.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1493_bacteria_3899.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1494_bacteria_3901.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1494_virus_2601.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1495_virus_2603.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1496_bacteria_3905.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1496_bacteria_3906.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1496_bacteria_3907.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1496_bacteria_3908.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1496_bacteria_3909.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1496_bacteria_3910.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1496_bacteria_3911.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1496_virus_2605.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1496_virus_2606.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1497_bacteria_3912.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1497_virus_2607.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1499_bacteria_3915.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1499_virus_2609.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person149_virus_299.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person14_bacteria_51.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1500_bacteria_3916.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1500_virus_2610.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1501_virus_2611.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1502_bacteria_3922.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1502_bacteria_3923.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1502_bacteria_3924.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1502_bacteria_3925.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1502_bacteria_3927.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1502_bacteria_3928.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1502_bacteria_3929.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1502_virus_2612.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1503_virus_2613.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1504_bacteria_3931.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1504_virus_2614.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1505_virus_2615.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1506_bacteria_3933.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1506_virus_2616.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1507_bacteria_3935.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1507_bacteria_3942.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1507_bacteria_3943.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1507_bacteria_3944.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1507_bacteria_3945.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1507_bacteria_3946.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1507_bacteria_3947.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1507_bacteria_3948.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1508_bacteria_3949.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1509_bacteria_3951.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1509_virus_2621.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1510_virus_2628.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1510_virus_2629.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1511_bacteria_3955.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1512_bacteria_3958.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1512_virus_2631.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1513_bacteria_3962.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1513_virus_2632.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1514_bacteria_3964.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1514_virus_2633.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1516_virus_2643.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1517_bacteria_3968.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1517_virus_2644.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1518_bacteria_3969.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1518_virus_2645.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1519_bacteria_3970.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1519_virus_2646.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person151_virus_301.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person151_virus_302.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1520_bacteria_3971.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1520_virus_2647.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1521_virus_2649.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1522_bacteria_3977.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1522_virus_2651.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1523_bacteria_3979.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1523_bacteria_3980.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1524_bacteria_3983.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1524_bacteria_3984.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1524_virus_2658.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1525_bacteria_3985.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1525_virus_2659.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1526_bacteria_3986.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1526_virus_2660.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1527_bacteria_3988.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1527_bacteria_3989.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1527_bacteria_3990.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1527_virus_2661.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1528_bacteria_3991.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1528_bacteria_3996.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1528_virus_2662.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1529_virus_2663.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person152_virus_303.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1530_bacteria_4000.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1530_virus_2664.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1531_bacteria_4003.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1531_virus_2666.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1532_virus_2667.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1534_virus_2670.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1535_bacteria_4015.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1535_bacteria_4016.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1535_bacteria_4017.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1535_virus_2672.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1536_bacteria_4018.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1536_virus_2673.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1537_bacteria_4019.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1537_bacteria_4020.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1537_virus_2674.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1538_bacteria_4021.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1539_bacteria_4022.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1539_virus_2678.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1539_virus_2679.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person153_virus_304.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1540_bacteria_4023.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1540_virus_2680.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1541_virus_2681.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1542_bacteria_4029.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1542_virus_2683.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1543_virus_2684.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1544_bacteria_4033.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1544_bacteria_4035.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1544_bacteria_4037.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1544_bacteria_4038.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1544_virus_2685.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1545_bacteria_4041.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1545_bacteria_4042.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1546_bacteria_4044.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1546_bacteria_4045.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1546_virus_2687.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1547_virus_2688.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1548_bacteria_4048.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1548_virus_2689.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1549_bacteria_4050.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1549_virus_2690.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person154_virus_305.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person154_virus_306.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1550_bacteria_4051.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1550_virus_2691.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1551_bacteria_4053.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1551_bacteria_4054.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1551_virus_2692.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1552_bacteria_4055.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1554_bacteria_4057.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1554_virus_2696.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1555_bacteria_4058.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1555_bacteria_4059.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1555_bacteria_4060.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1556_bacteria_4061.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1556_bacteria_4062.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1556_virus_2699.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1557_bacteria_4063.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1557_bacteria_4065.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1558_bacteria_4066.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1559_bacteria_4067.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person155_virus_307.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1561_bacteria_4077.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1562_bacteria_4078.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1562_bacteria_4081.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1562_bacteria_4087.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1562_bacteria_4089.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1563_bacteria_4092.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1564_bacteria_4094.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1564_virus_2719.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1565_bacteria_4095.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1566_bacteria_4099.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1567_bacteria_4100.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1567_virus_2722.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1568_virus_2723.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person156_virus_308.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1571_bacteria_4108.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1571_bacteria_4110.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1571_virus_2728.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1574_bacteria_4118.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1575_bacteria_4119.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1576_bacteria_4120.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1576_bacteria_4121.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1576_bacteria_4122.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1576_bacteria_4124.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1576_bacteria_4126.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1576_bacteria_4127.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1576_bacteria_4128.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1576_bacteria_4129.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1576_virus_2734.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1577_virus_2735.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1579_bacteria_4133.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person157_virus_311.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1580_virus_2739.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1581_bacteria_4135.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1581_virus_2741.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1582_bacteria_4136.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1582_bacteria_4137.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1582_bacteria_4140.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1582_bacteria_4142.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1582_bacteria_4143.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1583_bacteria_4144.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1584_bacteria_4146.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1584_bacteria_4148.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1585_bacteria_4149.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1585_bacteria_4151.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1585_bacteria_4155.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1588_virus_2762.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1589_bacteria_4171.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1589_bacteria_4172.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1589_virus_2763.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person158_virus_312.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1590_bacteria_4174.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1590_bacteria_4175.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1590_bacteria_4176.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1590_virus_2764.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1591_bacteria_4177.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1591_virus_2765.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1592_bacteria_4178.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1592_virus_2766.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1593_virus_2767.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1594_bacteria_4182.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1594_virus_2768.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1595_bacteria_4183.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1595_virus_2771.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1596_bacteria_4184.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1597_bacteria_4187.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1597_bacteria_4188.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1597_bacteria_4189.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1597_bacteria_4190.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1597_bacteria_4191.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1597_bacteria_4192.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1597_bacteria_4193.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1597_bacteria_4194.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1598_bacteria_4195.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1598_bacteria_4197.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1598_bacteria_4198.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1599_bacteria_4200.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1599_bacteria_4201.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1599_virus_2775.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1599_virus_2776.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person15_bacteria_52.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1600_bacteria_4202.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1600_virus_2777.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1601_bacteria_4209.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1601_bacteria_4212.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1602_bacteria_4218.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1602_virus_2780.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1603_virus_2781.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1604_virus_2782.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1605_bacteria_4226.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1607_bacteria_4232.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1607_virus_2785.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1608_bacteria_4235.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1609_bacteria_4236.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1609_bacteria_4237.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1609_bacteria_4239.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1609_virus_2790.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1609_virus_2791.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person160_virus_316.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1610_bacteria_4240.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1611_bacteria_4241.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1613_bacteria_4247.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1614_bacteria_4248.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1615_bacteria_4249.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1616_bacteria_4251.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1617_bacteria_4254.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1617_bacteria_4255.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1617_bacteria_4256.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1618_bacteria_4258.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1619_bacteria_4261.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1619_bacteria_4262.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1619_bacteria_4266.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1619_bacteria_4267.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1619_bacteria_4268.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1619_bacteria_4269.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1619_bacteria_4270.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1619_bacteria_4271.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person161_virus_317.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1620_bacteria_4272.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1625_bacteria_4290.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1626_bacteria_4291.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1628_bacteria_4293.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1628_bacteria_4294.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1628_bacteria_4295.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1628_bacteria_4296.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1628_bacteria_4297.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1628_bacteria_4298.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1629_bacteria_4299.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person162_virus_319.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person162_virus_320.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person162_virus_321.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person162_virus_322.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1630_bacteria_4303.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1630_bacteria_4304.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1634_bacteria_4326.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1634_bacteria_4331.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1634_bacteria_4334.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1635_bacteria_4335.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1636_bacteria_4337.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1636_bacteria_4338.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1637_bacteria_4339.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1638_bacteria_4340.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1638_bacteria_4341.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1638_bacteria_4342.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1639_bacteria_4343.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1639_bacteria_4344.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1639_bacteria_4345.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1639_bacteria_4347.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1640_bacteria_4348.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1641_bacteria_4350.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1642_bacteria_4352.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1642_bacteria_4353.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1643_bacteria_4354.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1644_bacteria_4356.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1644_bacteria_4357.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1644_bacteria_4358.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1644_bacteria_4360.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1644_bacteria_4361.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1644_bacteria_4362.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1645_bacteria_4363.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1646_bacteria_4368.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1647_bacteria_4372.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1648_bacteria_4373.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1648_bacteria_4375.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1648_bacteria_4376.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1649_bacteria_4377.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1649_bacteria_4378.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1649_bacteria_4379.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1651_bacteria_4381.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1652_bacteria_4383.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1657_bacteria_4398.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1657_bacteria_4399.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1657_bacteria_4400.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1658_bacteria_4402.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1660_bacteria_4404.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1661_bacteria_4406.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1663_bacteria_4411.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1663_bacteria_4412.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1665_bacteria_4415.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1666_bacteria_4416.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1667_bacteria_4417.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1667_bacteria_4418.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1668_bacteria_4420.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1668_bacteria_4421.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1669_bacteria_4422.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1669_bacteria_4423.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1669_bacteria_4424.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1670_bacteria_4425.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1670_bacteria_4426.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1670_bacteria_4427.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1670_bacteria_4428.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1670_bacteria_4429.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1670_bacteria_4430.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1670_bacteria_4431.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1671_bacteria_4432.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1673_bacteria_4434.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1674_bacteria_4437.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1676_bacteria_4441.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1677_bacteria_4443.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1677_bacteria_4444.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1678_bacteria_4446.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1679_bacteria_4448.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1679_bacteria_4449.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1679_bacteria_4450.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1679_bacteria_4452.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1679_bacteria_4453.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1680_bacteria_4455.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1682_bacteria_4459.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1683_bacteria_4460.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1684_bacteria_4461.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1684_bacteria_4462.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1684_bacteria_4463.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1685_bacteria_4465.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1686_bacteria_4466.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1687_bacteria_4468.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1689_bacteria_4472.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1689_bacteria_4473.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1689_bacteria_4474.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1690_bacteria_4475.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1691_bacteria_4479.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1691_bacteria_4481.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1693_bacteria_4485.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1695_bacteria_4492.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1696_bacteria_4495.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1697_bacteria_4496.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1698_bacteria_4497.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1699_bacteria_4498.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person16_bacteria_53.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person16_bacteria_54.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person16_bacteria_55.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1700_bacteria_4500.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1700_bacteria_4502.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1701_bacteria_4504.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1702_bacteria_4506.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1702_bacteria_4508.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1702_bacteria_4509.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1702_bacteria_4510.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1702_bacteria_4511.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1705_bacteria_4515.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1706_bacteria_4516.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1707_bacteria_4520.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1708_bacteria_4521.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1709_bacteria_4522.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1709_bacteria_4523.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1709_bacteria_4524.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1710_bacteria_4525.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1710_bacteria_4526.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1711_bacteria_4527.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1712_bacteria_4529.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1713_bacteria_4530.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1715_bacteria_4532.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1716_bacteria_4533.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1717_bacteria_4534.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1717_bacteria_4536.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1718_bacteria_4538.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1718_bacteria_4540.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1719_bacteria_4541.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1719_bacteria_4542.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1719_bacteria_4544.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1720_bacteria_4545.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1721_bacteria_4546.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1722_bacteria_4547.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1723_bacteria_4548.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1724_bacteria_4549.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1725_bacteria_4550.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1725_bacteria_4551.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1726_bacteria_4552.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1728_bacteria_4555.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1728_bacteria_4556.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1729_bacteria_4557.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1730_bacteria_4558.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1730_bacteria_4559.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1731_bacteria_4563.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1732_bacteria_4564.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1733_bacteria_4566.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1735_bacteria_4570.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1737_bacteria_4573.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1739_bacteria_4576.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1740_bacteria_4579.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1744_bacteria_4583.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1745_bacteria_4584.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1746_bacteria_4585.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1748_bacteria_4588.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1749_bacteria_4590.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1751_bacteria_4592.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1753_bacteria_4594.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1756_bacteria_4598.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1757_bacteria_4599.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1758_bacteria_4600.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1760_bacteria_4602.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1761_bacteria_4603.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1763_bacteria_4606.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1764_bacteria_4607.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1765_bacteria_4608.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1770_bacteria_4613.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1770_bacteria_4614.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1771_bacteria_4615.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1777_bacteria_4622.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1779_bacteria_4626.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1784_bacteria_4631.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1787_bacteria_4634.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1790_bacteria_4638.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1796_bacteria_4644.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1799_bacteria_4647.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person17_bacteria_56.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1803_bacteria_4651.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1803_bacteria_4652.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1810_bacteria_4664.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1812_bacteria_4667.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1814_bacteria_4669.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1816_bacteria_4673.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1816_bacteria_4674.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1817_bacteria_4675.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1818_bacteria_4676.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1819_bacteria_4677.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1823_bacteria_4682.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1830_bacteria_4693.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1835_bacteria_4699.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1838_bacteria_4703.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1839_bacteria_4705.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1841_bacteria_4708.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1843_bacteria_4710.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1847_bacteria_4716.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1848_bacteria_4719.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1850_bacteria_4721.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1851_bacteria_4722.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1852_bacteria_4724.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1855_bacteria_4727.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1857_bacteria_4729.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1858_bacteria_4730.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1859_bacteria_4731.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1860_bacteria_4732.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1863_bacteria_4735.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1864_bacteria_4736.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1865_bacteria_4737.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1865_bacteria_4739.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1866_bacteria_4740.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1867_bacteria_4741.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1868_bacteria_4743.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1869_bacteria_4745.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1872_bacteria_4750.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1872_bacteria_4751.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1875_bacteria_4756.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1876_bacteria_4760.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1877_bacteria_4761.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1879_bacteria_4764.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1880_bacteria_4765.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1881_bacteria_4767.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1883_bacteria_4769.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1884_bacteria_4771.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1885_bacteria_4772.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1886_bacteria_4773.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1888_bacteria_4775.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1893_bacteria_4781.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1896_bacteria_4788.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1897_bacteria_4789.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person18_bacteria_57.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1901_bacteria_4795.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1903_bacteria_4797.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1904_bacteria_4798.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1905_bacteria_4801.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1906_bacteria_4803.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1907_bacteria_4806.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1908_bacteria_4811.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1910_bacteria_4814.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1911_bacteria_4815.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1912_bacteria_4816.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1912_bacteria_4817.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1916_bacteria_4821.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1917_bacteria_4823.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1918_bacteria_4825.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1921_bacteria_4828.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1922_bacteria_4830.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1923_bacteria_4831.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1924_bacteria_4832.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1924_bacteria_4833.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1926_bacteria_4835.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1927_bacteria_4836.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1927_bacteria_4837.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1929_bacteria_4839.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1930_bacteria_4841.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1931_bacteria_4842.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1932_bacteria_4843.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1933_bacteria_4844.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1934_bacteria_4846.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1935_bacteria_4847.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1935_bacteria_4848.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1935_bacteria_4849.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1935_bacteria_4850.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1936_bacteria_4852.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1937_bacteria_4853.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1938_bacteria_4854.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1940_bacteria_4859.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1940_bacteria_4861.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1940_bacteria_4862.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1941_bacteria_4863.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1942_bacteria_4865.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1943_bacteria_4868.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1944_bacteria_4869.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1945_bacteria_4872.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person19_bacteria_58.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person19_bacteria_59.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person19_bacteria_60.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person19_bacteria_61.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person19_bacteria_62.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person19_bacteria_63.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1_bacteria_1.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person1_bacteria_2.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person20_bacteria_64.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person20_bacteria_66.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person20_bacteria_67.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person20_bacteria_69.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person20_bacteria_70.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person21_bacteria_72.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person21_bacteria_73.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person22_bacteria_74.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person22_bacteria_76.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person22_bacteria_77.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person23_bacteria_100.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person23_bacteria_101.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person23_bacteria_102.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person23_bacteria_103.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person23_bacteria_104.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person23_bacteria_105.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person23_bacteria_106.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person23_bacteria_107.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person23_bacteria_78.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person23_bacteria_79.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person23_bacteria_80.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person23_bacteria_81.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person23_bacteria_82.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person23_bacteria_83.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person23_bacteria_84.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person23_bacteria_85.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person23_bacteria_86.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person23_bacteria_87.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person23_bacteria_88.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person23_bacteria_89.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person23_bacteria_90.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person23_bacteria_91.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person23_bacteria_92.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person23_bacteria_93.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person23_bacteria_94.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person23_bacteria_95.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person23_bacteria_96.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person23_bacteria_97.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person23_bacteria_98.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person23_bacteria_99.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person24_bacteria_108.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person24_bacteria_109.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person24_bacteria_110.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person24_bacteria_111.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person24_bacteria_112.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person253_bacteria_1152.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person253_bacteria_1153.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person253_bacteria_1154.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person253_bacteria_1155.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person253_bacteria_1156.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person253_bacteria_1157.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person255_bacteria_1160.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person255_bacteria_1161.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person255_bacteria_1162.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person255_bacteria_1165.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person255_bacteria_1175.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person255_bacteria_1182.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person255_bacteria_1188.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person255_virus_531.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person256_bacteria_1189.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person256_virus_537.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person257_bacteria_1191.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person257_bacteria_1193.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person257_bacteria_1194.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person257_bacteria_1195.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person257_bacteria_1196.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person257_bacteria_1197.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person257_bacteria_1199.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person257_bacteria_1200.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person257_virus_538.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person258_bacteria_1205.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person258_bacteria_1206.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person258_bacteria_1207.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person258_bacteria_1208.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person258_bacteria_1209.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person258_bacteria_1210.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person258_bacteria_1212.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person258_bacteria_1214.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person258_bacteria_1215.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person258_bacteria_1216.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person258_virus_539.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person259_bacteria_1217.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person259_bacteria_1219.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person259_bacteria_1220.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person259_virus_540.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person25_bacteria_113.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person25_bacteria_114.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person25_bacteria_115.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person25_bacteria_116.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person25_bacteria_117.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person25_bacteria_118.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person25_bacteria_119.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person25_bacteria_120.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person25_bacteria_121.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person260_bacteria_1222.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person260_bacteria_1223.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person260_bacteria_1224.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person260_virus_541.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person261_bacteria_1225.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person261_virus_543.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person262_bacteria_1226.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person262_virus_544.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person262_virus_545.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person263_bacteria_1227.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person263_virus_546.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person264_bacteria_1228.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person264_bacteria_1229.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person264_bacteria_1230.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person264_bacteria_1231.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person264_bacteria_1232.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person264_bacteria_1233.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person264_bacteria_1234.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person264_virus_547.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person265_bacteria_1235.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person265_bacteria_1236.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person265_virus_548.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person266_bacteria_1237.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person266_bacteria_1238.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person266_bacteria_1239.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person266_bacteria_1240.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person266_bacteria_1241.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person266_bacteria_1242.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person266_bacteria_1244.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person266_bacteria_1245.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person266_bacteria_1247.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person266_bacteria_1248.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person266_bacteria_1249.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person266_virus_549.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person267_bacteria_1250.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person267_bacteria_1251.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person267_bacteria_1252.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person267_bacteria_1253.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person267_virus_552.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person268_virus_553.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person269_virus_554.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person26_bacteria_122.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person26_bacteria_123.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person26_bacteria_124.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person26_bacteria_126.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person26_bacteria_127.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person26_bacteria_128.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person26_bacteria_129.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person26_bacteria_130.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person26_bacteria_131.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person26_bacteria_132.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person26_bacteria_133.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person270_virus_555.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person271_virus_556.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person272_virus_559.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person273_virus_561.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person273_virus_562.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person274_bacteria_1288.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person274_bacteria_1289.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person274_bacteria_1290.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person274_virus_563.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person275_bacteria_1291.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person275_bacteria_1293.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person275_bacteria_1294.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person275_virus_565.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person276_bacteria_1295.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person276_bacteria_1296.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person276_bacteria_1297.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person276_bacteria_1298.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person276_bacteria_1299.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person276_virus_569.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person277_bacteria_1300.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person277_bacteria_1301.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person277_bacteria_1302.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person277_bacteria_1303.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person277_bacteria_1304.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person277_bacteria_1305.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person277_bacteria_1306.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person277_bacteria_1307.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person277_virus_571.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person278_bacteria_1309.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person278_bacteria_1311.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person278_bacteria_1313.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person278_bacteria_1314.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person278_virus_572.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person278_virus_573.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person278_virus_574.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person278_virus_575.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person279_bacteria_1315.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person279_bacteria_1316.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person279_virus_576.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person27_bacteria_135.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person27_bacteria_136.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person27_bacteria_137.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person27_bacteria_138.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person280_bacteria_1318.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person280_bacteria_1320.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person280_bacteria_1321.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person280_bacteria_1322.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person280_virus_577.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person281_bacteria_1323.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person281_bacteria_1324.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person281_bacteria_1325.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person281_bacteria_1326.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person281_bacteria_1327.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person281_bacteria_1328.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person281_bacteria_1329.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person281_bacteria_1330.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person281_bacteria_1331.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person281_bacteria_1332.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person281_bacteria_1333.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person281_virus_578.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person282_virus_579.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person284_virus_582.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person286_virus_585.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person287_bacteria_1354.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person287_bacteria_1355.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person287_virus_586.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person288_virus_587.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person289_virus_593.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person28_bacteria_139.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person28_bacteria_141.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person28_bacteria_142.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person28_bacteria_143.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person290_bacteria_1372.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person290_virus_594.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person291_bacteria_1374.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person291_bacteria_1376.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person291_bacteria_1377.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person291_virus_596.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person292_bacteria_1378.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person292_virus_597.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person292_virus_598.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person292_virus_599.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person292_virus_600.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person292_virus_602.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person293_bacteria_1379.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person293_virus_604.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person293_virus_605.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person294_bacteria_1380.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person294_bacteria_1381.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person294_bacteria_1382.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person294_bacteria_1383.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person294_bacteria_1384.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person294_bacteria_1385.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person294_bacteria_1386.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person294_bacteria_1388.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person294_virus_606.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person294_virus_610.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person294_virus_611.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person295_bacteria_1389.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person295_bacteria_1390.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person295_virus_612.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person296_bacteria_1391.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person296_bacteria_1392.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person296_bacteria_1393.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person296_bacteria_1394.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person296_bacteria_1395.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person296_bacteria_1396.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person296_bacteria_1397.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person296_virus_613.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person297_bacteria_1400.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person297_bacteria_1404.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person297_virus_614.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person298_bacteria_1408.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person298_bacteria_1409.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person298_bacteria_1410.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person298_bacteria_1411.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person298_bacteria_1412.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person298_bacteria_1413.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person298_virus_617.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person298_virus_618.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person299_bacteria_1414.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person299_bacteria_1416.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person299_bacteria_1417.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person299_bacteria_1418.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person299_bacteria_1419.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person299_virus_620.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person29_bacteria_144.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person2_bacteria_3.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person2_bacteria_4.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person300_bacteria_1421.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person300_bacteria_1422.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person300_bacteria_1423.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person300_virus_621.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person301_bacteria_1424.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person301_bacteria_1427.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person301_bacteria_1428.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person301_bacteria_1429.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person301_virus_622.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person302_bacteria_1430.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person302_virus_623.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person303_bacteria_1431.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person303_virus_624.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person304_virus_625.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person305_bacteria_1435.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person305_bacteria_1436.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person305_bacteria_1437.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person305_virus_627.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person306_bacteria_1439.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person306_bacteria_1440.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person306_virus_628.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person307_bacteria_1441.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person307_bacteria_1442.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person307_virus_629.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person308_bacteria_1443.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person308_bacteria_1445.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person308_virus_630.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person309_bacteria_1447.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person309_bacteria_1449.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person309_virus_631.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person309_virus_632.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person30_bacteria_145.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person30_bacteria_146.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person30_bacteria_147.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person30_bacteria_148.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person30_bacteria_149.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person30_bacteria_150.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person30_bacteria_151.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person30_bacteria_152.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person30_bacteria_153.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person30_bacteria_154.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person30_bacteria_155.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person30_bacteria_156.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person30_bacteria_157.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person30_bacteria_158.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person310_bacteria_1450.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person310_bacteria_1451.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person310_virus_633.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person311_bacteria_1452.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person311_bacteria_1453.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person311_virus_634.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person312_bacteria_1454.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person312_bacteria_1455.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person312_bacteria_1456.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person312_virus_635.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person313_bacteria_1457.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person313_bacteria_1458.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person313_bacteria_1459.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person313_bacteria_1460.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person313_virus_637.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person314_bacteria_1461.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person314_bacteria_1462.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person314_virus_639.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person315_bacteria_1464.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person315_bacteria_1465.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person315_bacteria_1466.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person315_bacteria_1467.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person315_bacteria_1468.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person316_bacteria_1469.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person316_bacteria_1470.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person316_virus_641.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person317_bacteria_1471.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person317_bacteria_1473.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person317_virus_643.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person318_bacteria_1474.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person318_virus_644.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person319_bacteria_1475.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person319_bacteria_1476.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person319_bacteria_1477.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person319_bacteria_1478.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person319_bacteria_1479.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person319_bacteria_1480.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person319_virus_645.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person319_virus_646.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person31_bacteria_160.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person31_bacteria_161.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person31_bacteria_162.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person31_bacteria_163.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person31_bacteria_164.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person320_virus_647.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person321_bacteria_1483.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person321_bacteria_1484.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person321_bacteria_1485.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person321_bacteria_1486.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person321_bacteria_1487.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person321_bacteria_1488.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person321_bacteria_1489.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person321_virus_648.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person322_bacteria_1494.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person322_virus_655.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person323_virus_656.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person324_virus_658.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person325_bacteria_1497.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person325_bacteria_1498.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person325_bacteria_1500.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person325_bacteria_1501.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person325_bacteria_1502.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person325_virus_659.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person325_virus_660.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person325_virus_661.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person325_virus_664.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person325_virus_665.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person326_bacteria_1503.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person326_bacteria_1504.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person326_bacteria_1505.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person326_bacteria_1506.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person326_bacteria_1507.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person326_virus_666.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person326_virus_668.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person326_virus_670.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person326_virus_672.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person326_virus_673.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person326_virus_675.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person326_virus_677.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person327_bacteria_1508.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person327_bacteria_1509.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person327_virus_679.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person328_bacteria_1510.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person328_bacteria_1511.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person328_bacteria_1512.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person328_bacteria_1513.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person328_bacteria_1514.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person328_bacteria_1515.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person328_virus_681.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person329_virus_682.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person32_bacteria_165.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person32_bacteria_166.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person330_virus_683.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person331_bacteria_1526.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person331_bacteria_1527.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person331_bacteria_1528.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person331_bacteria_1529.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person331_bacteria_1530.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person331_virus_684.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person332_bacteria_1531.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person332_bacteria_1533.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person332_bacteria_1534.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person332_bacteria_1535.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person332_bacteria_1536.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person332_bacteria_1537.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person332_bacteria_1538.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person332_virus_685.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person333_bacteria_1539.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person333_bacteria_1540.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person333_virus_688.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person334_bacteria_1541.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person334_bacteria_1542.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person334_bacteria_1544.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person334_bacteria_1545.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person334_virus_689.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person335_virus_690.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person336_bacteria_1548.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person336_bacteria_1549.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person336_bacteria_1550.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person336_bacteria_1551.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person336_bacteria_1552.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person336_bacteria_1553.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person337_bacteria_1554.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person337_bacteria_1557.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person337_bacteria_1558.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person337_bacteria_1560.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person337_bacteria_1561.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person337_bacteria_1562.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person337_bacteria_1563.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person337_bacteria_1564.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person337_bacteria_1565.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person337_bacteria_1566.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person338_bacteria_1567.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person338_bacteria_1568.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person338_virus_694.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person339_bacteria_1572.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person339_bacteria_1573.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person339_bacteria_1574.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person339_virus_695.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person33_bacteria_169.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person33_bacteria_172.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person33_bacteria_173.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person33_bacteria_174.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person33_bacteria_175.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person340_bacteria_1575.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person340_virus_698.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person341_bacteria_1577.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person341_virus_699.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person342_virus_701.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person342_virus_702.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person343_bacteria_1583.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person343_bacteria_1584.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person343_virus_704.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person344_bacteria_1585.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person344_virus_705.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person346_bacteria_1590.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person346_virus_708.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person346_virus_709.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person347_bacteria_1594.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person347_bacteria_1595.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person347_bacteria_1597.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person347_bacteria_1599.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person348_bacteria_1601.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person348_bacteria_1602.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person348_bacteria_1603.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person348_bacteria_1604.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person348_virus_711.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person348_virus_714.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person348_virus_715.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person348_virus_716.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person348_virus_717.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person348_virus_719.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person348_virus_720.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person348_virus_721.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person348_virus_723.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person349_bacteria_1605.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person349_bacteria_1606.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person349_bacteria_1607.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person349_virus_724.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person34_bacteria_176.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person350_virus_725.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person351_bacteria_1617.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person351_bacteria_1619.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person351_bacteria_1620.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person351_bacteria_1621.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person351_bacteria_1622.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person351_bacteria_1623.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person351_bacteria_1624.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person351_virus_726.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person352_bacteria_1625.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person353_bacteria_1626.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person353_bacteria_1628.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person353_virus_728.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person354_bacteria_1632.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person354_bacteria_1633.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person354_bacteria_1634.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person354_bacteria_1635.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person354_virus_729.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person355_bacteria_1637.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person355_virus_730.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person355_virus_731.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person356_bacteria_1638.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person356_virus_733.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person357_bacteria_1639.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person357_bacteria_1640.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person357_virus_734.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person357_virus_735.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person357_virus_736.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person358_virus_737.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person359_bacteria_1642.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person359_bacteria_1643.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person359_bacteria_1644.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person359_bacteria_1645.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person359_bacteria_1646.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person359_virus_738.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person35_bacteria_178.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person35_bacteria_180.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person35_bacteria_181.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person360_bacteria_1647.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person360_virus_739.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person361_bacteria_1651.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person361_virus_740.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person362_bacteria_1652.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person362_virus_741.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person363_bacteria_1653.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person363_bacteria_1654.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person363_bacteria_1655.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person363_virus_742.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person364_bacteria_1656.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person364_bacteria_1657.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person364_bacteria_1658.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person364_bacteria_1659.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person364_bacteria_1660.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person364_virus_743.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person365_virus_745.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person366_bacteria_1664.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person366_virus_746.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person367_bacteria_1665.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person367_virus_747.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person368_bacteria_1666.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person368_bacteria_1667.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person368_bacteria_1668.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person368_bacteria_1672.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person368_bacteria_1678.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person368_virus_748.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person369_bacteria_1680.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person369_virus_750.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person36_bacteria_182.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person36_bacteria_183.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person36_bacteria_184.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person36_bacteria_185.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person370_bacteria_1687.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person370_bacteria_1688.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person370_bacteria_1689.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person370_bacteria_1690.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person370_bacteria_1691.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person370_bacteria_1692.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person370_virus_752.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person370_virus_753.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person371_bacteria_1694.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person371_bacteria_1695.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person371_bacteria_1696.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person371_bacteria_1698.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person371_bacteria_1699.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person371_bacteria_1700.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person371_bacteria_1701.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person371_bacteria_1702.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person371_bacteria_1703.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person371_virus_754.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person372_bacteria_1704.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person372_bacteria_1705.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person372_bacteria_1706.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person372_virus_755.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person373_bacteria_1707.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person373_bacteria_1708.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person373_bacteria_1709.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person373_virus_756.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person374_bacteria_1710.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person374_bacteria_1711.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person374_bacteria_1712.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person374_virus_757.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person375_bacteria_1713.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person375_virus_758.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person376_bacteria_1715.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person376_bacteria_1716.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person376_virus_759.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person377_bacteria_1717.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person377_bacteria_1718.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person377_virus_760.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person378_virus_761.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person379_bacteria_1721.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person379_bacteria_1722.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person379_virus_762.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person37_bacteria_186.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person37_bacteria_187.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person37_bacteria_188.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person37_bacteria_189.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person380_virus_763.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person381_bacteria_1730.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person381_bacteria_1731.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person382_bacteria_1737.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person382_bacteria_1738.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person382_bacteria_1739.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person382_bacteria_1740.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person382_bacteria_1741.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person382_bacteria_1742.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person382_bacteria_1745.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person382_bacteria_1746.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person383_bacteria_1747.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person383_bacteria_1748.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person383_bacteria_1749.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person383_bacteria_1750.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person383_bacteria_1751.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person383_bacteria_1752.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person383_bacteria_1753.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person383_bacteria_1754.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person383_virus_767.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person384_bacteria_1755.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person384_virus_769.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person385_bacteria_1765.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person385_bacteria_1766.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person385_virus_770.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person386_virus_771.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person387_bacteria_1769.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person387_bacteria_1770.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person387_bacteria_1772.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person387_virus_772.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person388_virus_775.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person388_virus_777.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person389_bacteria_1778.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person389_bacteria_1780.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person389_virus_778.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person38_bacteria_190.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person38_bacteria_191.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person38_bacteria_192.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person38_bacteria_193.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person38_bacteria_194.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person38_bacteria_195.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person38_bacteria_196.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person390_bacteria_1781.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person391_bacteria_1782.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person391_virus_781.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person392_bacteria_1783.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person392_bacteria_1784.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person392_bacteria_1785.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person392_bacteria_1786.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person392_bacteria_1787.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person392_virus_782.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person393_bacteria_1789.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person393_virus_784.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person394_bacteria_1791.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person394_bacteria_1792.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person394_virus_786.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person395_bacteria_1794.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person395_bacteria_1795.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person395_virus_788.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person396_bacteria_1796.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person396_virus_789.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person397_bacteria_1797.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person397_virus_790.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person398_bacteria_1799.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person398_bacteria_1801.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person399_bacteria_1804.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person399_bacteria_1805.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person399_bacteria_1806.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person399_virus_793.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person39_bacteria_198.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person39_bacteria_200.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person3_bacteria_10.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person3_bacteria_11.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person3_bacteria_12.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person3_bacteria_13.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person400_bacteria_1807.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person400_virus_794.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person401_bacteria_1808.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person401_virus_795.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person401_virus_797.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person401_virus_798.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person402_bacteria_1809.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person402_bacteria_1810.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person402_bacteria_1811.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person402_bacteria_1812.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person402_bacteria_1813.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person402_virus_799.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person402_virus_801.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person403_bacteria_1814.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person403_virus_803.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person405_bacteria_1817.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person405_virus_805.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person406_bacteria_1818.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person406_bacteria_1819.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person406_bacteria_1820.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person407_bacteria_1822.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person407_virus_811.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person407_virus_812.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person407_virus_814.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person408_bacteria_1823.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person408_virus_815.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person409_bacteria_1824.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person409_virus_816.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person409_virus_818.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person409_virus_820.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person40_bacteria_202.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person40_bacteria_203.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person40_bacteria_204.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person40_bacteria_205.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person410_bacteria_1825.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person410_virus_821.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person411_bacteria_1826.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person412_bacteria_1827.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person413_bacteria_1828.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person413_bacteria_1829.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person413_bacteria_1830.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person413_bacteria_1831.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person413_bacteria_1832.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person413_bacteria_1833.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person413_bacteria_1834.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person413_virus_844.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person414_bacteria_1835.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person414_virus_845.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person415_bacteria_1837.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person415_bacteria_1838.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person415_bacteria_1839.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person415_virus_847.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person416_bacteria_1840.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person416_virus_849.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person417_bacteria_1841.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person417_bacteria_1842.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person417_virus_850.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person418_bacteria_1843.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person418_virus_852.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person419_bacteria_1844.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person419_bacteria_1845.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person419_virus_855.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person419_virus_857.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person419_virus_859.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person419_virus_861.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person41_bacteria_206.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person41_bacteria_207.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person41_bacteria_208.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person41_bacteria_209.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person41_bacteria_210.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person41_bacteria_211.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person420_bacteria_1847.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person420_bacteria_1848.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person420_bacteria_1849.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person420_bacteria_1850.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person420_bacteria_1851.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person421_bacteria_1852.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person421_virus_866.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person422_bacteria_1853.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person422_virus_867.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person422_virus_868.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person423_bacteria_1854.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person423_bacteria_1855.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person423_bacteria_1856.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person423_bacteria_1857.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person423_bacteria_1858.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person423_virus_869.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person424_bacteria_1859.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person425_bacteria_1860.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person425_virus_871.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person426_bacteria_1861.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person426_bacteria_1862.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person426_bacteria_1863.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person426_virus_873.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person427_bacteria_1864.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person427_bacteria_1865.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person427_bacteria_1866.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person427_bacteria_1867.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person427_bacteria_1868.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person427_virus_875.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person428_bacteria_1869.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person428_virus_876.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person429_bacteria_1870.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person429_virus_877.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person430_bacteria_1871.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person430_virus_879.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person431_bacteria_1872.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person431_virus_880.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person432_virus_881.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person433_bacteria_1874.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person433_bacteria_1875.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person433_bacteria_1876.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person433_virus_882.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person434_bacteria_1877.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person434_virus_883.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person434_virus_884.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person435_bacteria_1879.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person435_virus_885.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person436_bacteria_1883.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person436_virus_886.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person437_bacteria_1884.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person437_bacteria_1885.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person437_bacteria_1886.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person437_bacteria_1887.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person437_bacteria_1888.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person437_virus_888.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person438_bacteria_1889.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person438_bacteria_1890.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person438_bacteria_1891.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person438_bacteria_1892.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person438_bacteria_1893.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person438_virus_889.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person439_bacteria_1895.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person439_virus_890.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person439_virus_891.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person43_bacteria_213.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person43_bacteria_216.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person440_bacteria_1897.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person440_bacteria_1898.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person440_virus_893.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person441_bacteria_1900.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person441_bacteria_1902.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person441_bacteria_1903.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person441_bacteria_1904.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person441_bacteria_1905.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person441_bacteria_1907.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person441_bacteria_1910.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person441_bacteria_1911.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person441_bacteria_1912.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person441_bacteria_1914.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person441_bacteria_1915.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person441_bacteria_1916.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person441_bacteria_1917.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person441_bacteria_1918.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person441_virus_894.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person441_virus_895.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person441_virus_896.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person441_virus_897.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person442_virus_898.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person442_virus_899.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person442_virus_900.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person442_virus_901.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person442_virus_902.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person442_virus_903.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person442_virus_904.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person442_virus_905.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person442_virus_906.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person443_bacteria_1923.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person443_bacteria_1924.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person443_bacteria_1926.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person443_virus_908.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person444_bacteria_1927.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person444_virus_911.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person445_bacteria_1928.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person445_bacteria_1929.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person445_bacteria_1930.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person445_virus_912.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person445_virus_913.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person445_virus_914.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person445_virus_915.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person445_virus_916.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person445_virus_917.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person445_virus_918.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person445_virus_919.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person446_bacteria_1931.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person446_virus_920.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person447_bacteria_1932.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person447_virus_921.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person447_virus_921_1.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person448_bacteria_1933.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person448_bacteria_1934.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person448_bacteria_1935.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person448_bacteria_1936.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person448_bacteria_1937.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person448_virus_922.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person449_bacteria_1938.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person449_bacteria_1939.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person449_bacteria_1940.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person44_bacteria_218.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person44_bacteria_219.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person450_bacteria_1941.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person450_virus_931.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person451_bacteria_1942.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person451_virus_932.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person452_bacteria_1943.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person453_virus_935.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person453_virus_936.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person454_bacteria_1945.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person454_virus_938.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person455_bacteria_1947.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person456_bacteria_1948.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person456_virus_943.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person457_bacteria_1949.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person457_virus_944.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person458_bacteria_1950.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person458_bacteria_1951.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person458_bacteria_1952.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person458_bacteria_1953.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person458_bacteria_1954.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person458_bacteria_1955.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person458_virus_945.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person459_bacteria_1956.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person459_bacteria_1957.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person459_virus_947.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person45_bacteria_220.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person45_bacteria_221.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person45_bacteria_222.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person460_bacteria_1958.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person460_virus_948.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person461_bacteria_1960.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person461_virus_949.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person461_virus_950.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person462_bacteria_1961.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person462_bacteria_1963.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person462_bacteria_1967.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person462_bacteria_1968.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person462_virus_951.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person463_bacteria_1971.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person463_virus_952.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person463_virus_953.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person464_bacteria_1974.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person464_bacteria_1975.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person464_virus_954.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person464_virus_956.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person465_bacteria_1976.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person465_bacteria_1977.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person465_bacteria_1979.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person465_bacteria_1980.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person465_bacteria_1981.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person465_bacteria_1982.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person465_virus_957.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person466_bacteria_1983.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person466_bacteria_1984.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person466_bacteria_1986.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person466_bacteria_1987.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person466_virus_960.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person467_bacteria_1988.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person467_bacteria_1989.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person467_virus_961.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person468_bacteria_1990.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person468_bacteria_1991.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person468_virus_963.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person469_bacteria_1992.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person469_bacteria_1993.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person469_bacteria_1994.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person469_bacteria_1995.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person469_virus_965.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person46_bacteria_224.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person46_bacteria_225.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person470_bacteria_1996.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person470_bacteria_1998.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person470_bacteria_1999.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person470_bacteria_2000.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person470_bacteria_2001.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person470_bacteria_2002.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person470_bacteria_2003.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person470_virus_966.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person471_bacteria_2004.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person471_bacteria_2005.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person471_bacteria_2006.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person471_virus_967.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person471_virus_968.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person472_bacteria_2007.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person472_bacteria_2008.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person472_bacteria_2010.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person472_bacteria_2014.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person472_bacteria_2015.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person472_virus_969.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person473_bacteria_2018.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person474_virus_971.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person475_bacteria_2020.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person475_bacteria_2021.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person475_bacteria_2022.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person475_bacteria_2023.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person475_bacteria_2024.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person475_bacteria_2025.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person475_virus_972.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person476_bacteria_2026.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person476_virus_973.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person477_bacteria_2028.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person477_bacteria_2029.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person477_bacteria_2030.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person477_bacteria_2031.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person478_bacteria_2032.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person478_bacteria_2035.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person478_virus_975.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person479_virus_978.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person47_bacteria_229.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person480_bacteria_2038.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person480_bacteria_2039.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person480_bacteria_2040.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person480_virus_981.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person480_virus_982.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person481_bacteria_2041.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person481_bacteria_2042.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person481_virus_983.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person482_bacteria_2043.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person482_bacteria_2044.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person482_bacteria_2045.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person482_virus_984.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person483_bacteria_2046.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person483_virus_985.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person484_virus_986.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person485_bacteria_2049.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person485_virus_988.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person486_bacteria_2051.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person486_bacteria_2052.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person486_bacteria_2053.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person486_bacteria_2054.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person486_virus_990.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person487_bacteria_2055.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person487_bacteria_2056.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person487_bacteria_2057.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person487_bacteria_2058.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person487_bacteria_2059.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person487_bacteria_2060.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person487_virus_991.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person488_bacteria_2061.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person488_bacteria_2062.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person488_virus_992.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person489_bacteria_2063.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person489_bacteria_2064.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person489_bacteria_2065.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person489_bacteria_2066.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person489_bacteria_2067.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person489_virus_994.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person489_virus_995.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person48_bacteria_230.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person48_bacteria_231.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person48_bacteria_232.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person48_bacteria_233.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person490_bacteria_2068.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person490_bacteria_2069.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person490_bacteria_2070.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person490_virus_996.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person491_bacteria_2071.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person491_bacteria_2073.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person491_bacteria_2075.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person491_bacteria_2080.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person491_bacteria_2081.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person491_bacteria_2082.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person491_virus_997.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person492_bacteria_2083.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person492_bacteria_2084.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person492_bacteria_2085.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person492_virus_998.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person493_bacteria_2086.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person493_bacteria_2087.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person493_virus_999.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person494_bacteria_2088.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person494_bacteria_2089.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person494_bacteria_2090.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person494_virus_1000.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person495_bacteria_2094.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person495_virus_1001.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person496_bacteria_2095.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person496_virus_1003.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person497_virus_1005.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person498_bacteria_2100.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person498_bacteria_2101.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person498_bacteria_2102.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person498_virus_1007.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person499_bacteria_2103.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person499_bacteria_2104.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person499_virus_1008.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person49_bacteria_235.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person49_bacteria_236.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person49_bacteria_237.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person4_bacteria_14.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person500_bacteria_2105.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person500_bacteria_2106.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person500_bacteria_2107.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person500_bacteria_2108.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person500_bacteria_2109.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person500_bacteria_2110.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person500_bacteria_2111.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person500_virus_1009.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person501_bacteria_2112.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person501_bacteria_2113.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person501_bacteria_2114.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person501_bacteria_2115.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person501_bacteria_2116.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person501_virus_1010.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person502_bacteria_2117.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person502_bacteria_2118.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person502_bacteria_2119.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person502_bacteria_2120.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person502_bacteria_2121.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person502_bacteria_2122.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person502_bacteria_2123.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person502_virus_1011.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person502_virus_1012.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person503_bacteria_2125.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person503_bacteria_2126.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person503_virus_1013.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person504_bacteria_2127.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person504_bacteria_2129.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person504_bacteria_2130.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person504_bacteria_2132.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person504_bacteria_2133.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person505_bacteria_2135.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person505_virus_1017.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person506_bacteria_2136.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person506_bacteria_2138.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person506_virus_1018.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person507_bacteria_2139.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person507_bacteria_2140.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person507_bacteria_2141.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person507_virus_1019.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person508_bacteria_2142.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person508_bacteria_2143.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person508_bacteria_2144.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person508_virus_1020.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person508_virus_1021.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person509_bacteria_2145.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person509_bacteria_2146.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person509_virus_1024.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person509_virus_1025.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person50_bacteria_238.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person510_bacteria_2147.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person510_bacteria_2148.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person510_bacteria_2149.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person510_bacteria_2150.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person510_virus_1026.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person511_bacteria_2152.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person511_bacteria_2153.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person511_virus_1027.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person512_bacteria_2154.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person512_bacteria_2155.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person512_virus_1029.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person513_virus_1030.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person514_bacteria_2184.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person514_virus_1031.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person515_bacteria_2185.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person515_bacteria_2186.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person515_bacteria_2187.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person515_bacteria_2188.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person515_bacteria_2189.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person515_bacteria_2190.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person515_virus_1032.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person516_bacteria_2191.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person516_bacteria_2192.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person516_virus_1033.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person517_bacteria_2196.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person517_virus_1034.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person517_virus_1035.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person518_bacteria_2197.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person518_bacteria_2198.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person518_bacteria_2199.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person518_bacteria_2200.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person518_virus_1036.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person519_virus_1038.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person51_bacteria_239.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person51_bacteria_240.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person51_bacteria_241.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person51_bacteria_242.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person51_bacteria_243.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person51_bacteria_244.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person51_bacteria_245.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person51_bacteria_246.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person51_bacteria_247.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person51_bacteria_248.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person520_bacteria_2203.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person520_bacteria_2204.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person520_bacteria_2205.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person520_virus_1039.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person521_virus_1040.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person522_bacteria_2210.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person522_bacteria_2211.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person522_virus_1041.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person523_virus_1043.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person524_virus_1045.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person525_bacteria_2216.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person525_bacteria_2217.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person525_bacteria_2218.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person525_bacteria_2220.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person525_virus_1046.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person526_bacteria_2221.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person527_bacteria_2225.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person527_bacteria_2226.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person527_virus_1048.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person528_bacteria_2227.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person528_virus_1049.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person529_bacteria_2228.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person529_bacteria_2229.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person529_bacteria_2230.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person529_virus_1050.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person52_bacteria_249.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person52_bacteria_251.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person530_bacteria_2231.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person530_bacteria_2233.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person530_virus_1052.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person531_bacteria_2235.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person531_bacteria_2236.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person531_bacteria_2237.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person531_bacteria_2238.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person531_bacteria_2239.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person531_bacteria_2240.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person531_bacteria_2241.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person531_bacteria_2242.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person531_virus_1053.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person532_virus_1054.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person533_bacteria_2245.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person533_bacteria_2250.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person533_virus_1055.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person534_bacteria_2251.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person534_bacteria_2252.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person534_bacteria_2253.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person534_bacteria_2254.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person534_virus_1061.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person535_bacteria_2255.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person535_bacteria_2256.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person535_virus_1062.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person536_bacteria_2257.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person536_bacteria_2258.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person536_bacteria_2259.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person536_bacteria_2260.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person536_virus_1064.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person536_virus_1065.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person537_bacteria_2261.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person537_bacteria_2262.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person537_bacteria_2263.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person537_bacteria_2264.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person537_bacteria_2265.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person537_bacteria_2266.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person537_virus_1067.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person538_bacteria_2268.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person538_virus_1068.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person539_bacteria_2269.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person539_bacteria_2270.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person539_virus_1069.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person53_bacteria_252.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person53_bacteria_253.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person53_bacteria_254.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person53_bacteria_255.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person540_bacteria_2271.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person540_bacteria_2272.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person540_bacteria_2273.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person540_virus_1070.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person541_bacteria_2274.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person541_bacteria_2275.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person541_virus_1071.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person542_bacteria_2276.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person542_virus_1072.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person543_bacteria_2279.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person543_bacteria_2280.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person543_bacteria_2281.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person543_bacteria_2282.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person543_bacteria_2283.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person543_bacteria_2284.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person543_virus_1073.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person544_bacteria_2286.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person544_virus_1074.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person544_virus_1075.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person544_virus_1076.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person544_virus_1078.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person544_virus_1079.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person544_virus_1080.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person545_bacteria_2287.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person545_bacteria_2288.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person545_bacteria_2289.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person545_bacteria_2290.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person545_virus_1081.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person546_virus_1085.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person547_bacteria_2292.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person547_bacteria_2294.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person547_bacteria_2296.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person547_virus_1086.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person548_bacteria_2297.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person548_bacteria_2298.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person548_bacteria_2299.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person548_bacteria_2300.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person548_bacteria_2301.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person548_bacteria_2302.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person548_virus_1088.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person549_bacteria_2303.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person549_bacteria_2304.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person549_bacteria_2305.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person549_bacteria_2306.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person549_bacteria_2307.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person549_virus_1089.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person54_bacteria_257.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person54_bacteria_258.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person550_bacteria_2308.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person550_bacteria_2309.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person550_virus_1090.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person551_bacteria_2310.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person551_bacteria_2311.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person551_virus_1091.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person552_bacteria_2313.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person552_bacteria_2315.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person552_virus_1092.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person553_bacteria_2316.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person553_bacteria_2317.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person553_virus_1093.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person554_bacteria_2320.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person554_bacteria_2321.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person554_bacteria_2322.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person554_bacteria_2323.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person554_virus_1094.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person555_bacteria_2325.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person556_bacteria_2326.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person556_virus_1096.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person557_bacteria_2327.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person557_virus_1097.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person558_bacteria_2328.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person558_virus_1098.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person559_bacteria_2329.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person559_virus_1099.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person55_bacteria_260.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person55_bacteria_261.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person55_bacteria_262.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person55_bacteria_263.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person55_bacteria_264.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person55_bacteria_265.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person55_bacteria_266.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person560_bacteria_2330.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person561_bacteria_2331.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person562_bacteria_2332.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person562_virus_1102.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person563_bacteria_2333.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person563_bacteria_2334.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person563_bacteria_2335.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person563_bacteria_2336.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person563_bacteria_2337.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person563_bacteria_2338.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person563_bacteria_2339.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person563_bacteria_2340.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person563_virus_1103.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person564_bacteria_2342.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person564_bacteria_2343.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person564_bacteria_2344.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person564_bacteria_2345.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person564_bacteria_2346.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person564_bacteria_2347.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person564_virus_1104.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person565_bacteria_2348.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person565_virus_1105.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person566_bacteria_2351.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person566_virus_1106.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person567_bacteria_2352.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person567_bacteria_2353.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person567_bacteria_2354.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person567_virus_1107.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person568_bacteria_2358.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person568_bacteria_2359.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person569_bacteria_2360.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person569_bacteria_2362.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person569_bacteria_2363.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person569_bacteria_2364.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person569_virus_1110.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person56_bacteria_267.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person56_bacteria_268.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person56_bacteria_269.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person570_bacteria_2365.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person570_virus_1112.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person571_bacteria_2367.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person571_virus_1114.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person572_bacteria_2368.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person573_bacteria_2369.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person573_virus_1116.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person574_bacteria_2370.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person574_bacteria_2371.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person574_bacteria_2372.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person574_bacteria_2373.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person574_virus_1118.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person575_bacteria_2374.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person575_virus_1119.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person576_bacteria_2375.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person576_bacteria_2376.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person576_virus_1120.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person577_bacteria_2378.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person577_virus_1121.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person578_bacteria_2379.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person578_virus_1122.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person579_bacteria_2381.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person579_bacteria_2382.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person579_bacteria_2383.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person579_bacteria_2384.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person579_bacteria_2386.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person579_virus_1123.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person57_bacteria_270.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person57_bacteria_271.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person580_bacteria_2387.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person580_bacteria_2388.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person580_bacteria_2389.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person581_bacteria_2390.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person581_bacteria_2392.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person581_bacteria_2393.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person581_bacteria_2394.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person581_bacteria_2395.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person581_bacteria_2400.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person581_virus_1125.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person582_bacteria_2403.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person582_bacteria_2404.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person582_bacteria_2405.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person583_bacteria_2406.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person583_bacteria_2408.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person583_bacteria_2409.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person583_virus_1127.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person584_virus_1128.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person585_bacteria_2411.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person585_bacteria_2412.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person585_bacteria_2413.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person585_bacteria_2414.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person585_bacteria_2415.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person585_bacteria_2416.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person585_virus_1129.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person586_bacteria_2417.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person586_bacteria_2418.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person586_bacteria_2420.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person586_virus_1130.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person587_bacteria_2421.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person588_bacteria_2422.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person588_bacteria_2423.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person588_virus_1134.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person588_virus_1135.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person589_bacteria_2424.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person589_bacteria_2425.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person58_bacteria_272.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person58_bacteria_273.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person58_bacteria_274.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person58_bacteria_275.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person58_bacteria_276.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person58_bacteria_277.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person58_bacteria_278.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person590_bacteria_2428.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person590_virus_1138.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person591_bacteria_2429.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person591_virus_1139.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person592_bacteria_2431.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person592_bacteria_2434.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person592_virus_1141.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person593_bacteria_2435.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person593_virus_1142.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person594_bacteria_2436.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person594_virus_1145.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person595_bacteria_2438.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person595_virus_1147.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person596_bacteria_2440.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person596_bacteria_2441.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person596_bacteria_2443.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person596_bacteria_2444.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person596_bacteria_2445.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person596_bacteria_2446.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person596_bacteria_2447.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person596_bacteria_2449.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person596_virus_1149.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person597_bacteria_2450.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person597_bacteria_2451.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person597_virus_1150.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person598_bacteria_2453.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person598_bacteria_2454.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person598_virus_1151.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person598_virus_1153.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person598_virus_1154.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person599_bacteria_2455.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person599_virus_1155.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person59_bacteria_279.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person59_bacteria_280.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person59_bacteria_281.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person59_bacteria_282.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person59_bacteria_283.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person59_bacteria_284.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person5_bacteria_15.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person5_bacteria_16.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person5_bacteria_17.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person5_bacteria_19.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person600_bacteria_2456.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person600_bacteria_2457.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person600_bacteria_2458.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person600_virus_1156.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person601_bacteria_2459.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person602_bacteria_2460.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person603_bacteria_2461.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person603_virus_1164.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person604_bacteria_2462.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person604_bacteria_2463.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person604_virus_1165.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person605_bacteria_2464.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person605_bacteria_2465.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person605_bacteria_2466.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person605_bacteria_2467.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person605_bacteria_2468.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person605_virus_1166.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person605_virus_1169.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person606_bacteria_2469.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person607_bacteria_2470.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person607_virus_1173.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person608_bacteria_2471.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person608_bacteria_2472.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person608_bacteria_2473.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person608_virus_1175.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person609_bacteria_2474.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person609_virus_1176.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person60_bacteria_285.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person60_bacteria_286.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person60_bacteria_287.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person610_bacteria_2475.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person610_virus_1177.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person611_bacteria_2476.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person612_bacteria_2477.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person612_bacteria_2478.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person612_virus_1179.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person613_bacteria_2479.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person613_virus_1181.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person614_bacteria_2480.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person614_bacteria_2481.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person614_bacteria_2483.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person614_virus_1183.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person615_virus_1184.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person616_bacteria_2487.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person616_virus_1186.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person617_bacteria_2488.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person617_virus_1187.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person618_bacteria_2489.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person618_virus_1189.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person619_bacteria_2490.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person619_bacteria_2491.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person619_virus_1190.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person61_bacteria_288.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person61_bacteria_289.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person61_bacteria_290.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person61_bacteria_291.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person61_bacteria_292.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person61_bacteria_293.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person61_bacteria_294.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person61_bacteria_295.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person61_bacteria_296.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person61_bacteria_297.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person620_bacteria_2492.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person620_virus_1191.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person620_virus_1192.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person621_virus_1194.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person621_virus_1195.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person622_bacteria_2494.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person622_virus_1196.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person623_bacteria_2495.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person623_bacteria_2496.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person623_virus_1197.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person624_bacteria_2497.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person624_virus_1198.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person625_bacteria_2499.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person625_bacteria_2500.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person625_virus_1199.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person626_bacteria_2502.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person626_virus_1202.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person627_virus_1204.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person628_bacteria_2505.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person628_virus_1206.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person629_bacteria_2506.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person629_bacteria_2507.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person629_bacteria_2508.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person629_bacteria_2509.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person629_bacteria_2510.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person629_virus_1207.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person62_bacteria_298.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person62_bacteria_299.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person62_bacteria_300.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person62_bacteria_301.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person62_bacteria_302.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person62_bacteria_303.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person630_bacteria_2512.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person630_bacteria_2513.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person630_bacteria_2514.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person630_bacteria_2515.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person630_bacteria_2516.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person630_virus_1209.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person632_bacteria_2520.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person632_bacteria_2521.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person632_virus_1211.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person633_bacteria_2522.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person633_virus_1213.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person634_bacteria_2525.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person635_bacteria_2526.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person636_bacteria_2527.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person636_virus_1217.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person637_bacteria_2528.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person637_bacteria_2529.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person637_virus_1218.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person639_virus_1220.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person63_bacteria_306.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person640_bacteria_2532.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person640_virus_1221.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person641_bacteria_2533.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person641_virus_1222.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person642_virus_1223.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person643_bacteria_2534.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person644_bacteria_2536.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person644_virus_1225.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person645_bacteria_2537.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person645_virus_1226.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person646_bacteria_2538.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person646_virus_1227.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person647_bacteria_2539.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person647_virus_1228.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person647_virus_1229.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person648_bacteria_2540.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person648_virus_1230.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person649_bacteria_2541.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person649_virus_1231.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person64_bacteria_310.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person64_bacteria_312.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person64_bacteria_316.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person64_bacteria_317.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person64_bacteria_318.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person64_bacteria_319.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person64_bacteria_320.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person650_bacteria_2542.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person650_virus_1232.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person651_bacteria_2543.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person652_bacteria_2544.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person652_virus_1234.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person653_bacteria_2545.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person653_virus_1235.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person654_bacteria_2546.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person655_bacteria_2547.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person656_bacteria_2548.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person656_virus_1238.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person657_bacteria_2549.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person657_virus_1240.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person658_bacteria_2550.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person658_virus_1241.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person659_bacteria_2551.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person659_virus_1243.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person65_bacteria_322.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person660_bacteria_2552.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person660_virus_1244.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person661_bacteria_2553.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person661_virus_1245.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person662_bacteria_2554.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person662_virus_1246.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person663_bacteria_2555.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person663_virus_1247.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person663_virus_1248.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person664_virus_1249.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person665_bacteria_2557.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person665_virus_1250.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person666_bacteria_2558.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person666_virus_1251.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person667_virus_1252.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person667_virus_1253.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person669_bacteria_2561.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person669_bacteria_2562.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person669_virus_1255.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person66_bacteria_323.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person66_bacteria_324.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person66_bacteria_325.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person66_bacteria_326.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person670_bacteria_2563.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person670_virus_1256.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person670_virus_1259.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person671_bacteria_2564.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person671_virus_1260.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person672_bacteria_2565.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person672_virus_1261.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person673_bacteria_2566.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person673_virus_1263.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person674_bacteria_2568.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person675_bacteria_2569.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person677_bacteria_2571.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person677_virus_1268.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person678_bacteria_2572.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person679_virus_1270.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person67_bacteria_328.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person67_bacteria_329.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person67_bacteria_330.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person67_bacteria_331.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person67_bacteria_332.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person67_bacteria_333.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person67_bacteria_334.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person680_bacteria_2575.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person681_bacteria_2576.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person681_virus_1272.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person682_virus_1273.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person683_bacteria_2578.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person684_bacteria_2580.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person684_virus_1275.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person685_bacteria_2581.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person687_bacteria_2583.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person688_bacteria_2584.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person688_virus_1281.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person688_virus_1282.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person689_bacteria_2585.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person689_bacteria_2586.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person68_bacteria_335.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person68_bacteria_336.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person68_bacteria_337.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person690_bacteria_2587.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person691_bacteria_2588.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person692_bacteria_2589.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person692_virus_1286.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person693_bacteria_2590.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person696_bacteria_2594.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person698_virus_1294.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person699_bacteria_2598.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person699_virus_1295.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person69_bacteria_338.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person6_bacteria_22.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person700_bacteria_2599.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person701_bacteria_2600.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person701_virus_1297.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person702_bacteria_2601.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person702_virus_1299.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person703_bacteria_2602.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person703_virus_1300.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person704_bacteria_2603.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person704_virus_1301.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person705_virus_1302.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person705_virus_1303.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person706_virus_1304.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person707_bacteria_2606.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person707_virus_1305.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person709_bacteria_2608.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person70_bacteria_341.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person70_bacteria_342.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person70_bacteria_343.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person70_bacteria_344.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person70_bacteria_345.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person70_bacteria_346.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person710_bacteria_2611.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person710_virus_1308.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person711_bacteria_2612.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person711_virus_1309.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person712_bacteria_2613.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person712_virus_1310.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person713_bacteria_2614.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person714_bacteria_2615.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person716_bacteria_2617.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person716_virus_1314.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person717_bacteria_2618.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person718_bacteria_2620.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person718_virus_1316.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person719_bacteria_2621.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person719_virus_1338.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person71_bacteria_347.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person71_bacteria_348.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person71_bacteria_349.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person71_bacteria_350.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person71_bacteria_351.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person720_bacteria_2622.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person720_virus_1339.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person721_bacteria_2623.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person721_virus_1340.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person722_virus_1341.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person723_bacteria_2625.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person723_virus_1342.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person724_bacteria_2626.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person724_virus_1343.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person724_virus_1344.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person725_bacteria_2627.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person726_bacteria_2628.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person727_bacteria_2629.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person727_virus_1347.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person728_bacteria_2630.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person72_bacteria_352.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person72_bacteria_353.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person72_bacteria_354.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person730_bacteria_2632.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person730_virus_1351.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person731_bacteria_2633.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person731_virus_1352.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person732_bacteria_2634.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person732_virus_1353.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person733_bacteria_2635.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person734_bacteria_2637.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person734_virus_1355.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person735_bacteria_2638.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person735_virus_1356.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person736_bacteria_2639.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person736_virus_1358.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person737_bacteria_2640.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person738_bacteria_2641.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person738_virus_1360.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person739_bacteria_2642.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person739_virus_1361.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person73_bacteria_355.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person73_bacteria_356.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person73_bacteria_357.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person73_bacteria_358.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person73_bacteria_359.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person73_bacteria_360.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person740_bacteria_2643.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person740_virus_1362.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person740_virus_1363.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person741_bacteria_2644.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person741_virus_1364.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person742_virus_1365.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person743_bacteria_2646.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person743_virus_1366.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person744_bacteria_2647.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person744_virus_1367.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person745_bacteria_2648.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person745_virus_1368.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person746_bacteria_2649.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person746_virus_1369.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person747_bacteria_2650.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person747_virus_1370.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person747_virus_1372.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person748_virus_1373.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person749_bacteria_2652.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person749_virus_1374.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person74_bacteria_361.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person74_bacteria_362.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person74_bacteria_363.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person750_bacteria_2653.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person751_bacteria_2654.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person752_virus_1377.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person753_bacteria_2656.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person753_virus_1378.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person754_virus_1379.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person755_bacteria_2659.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person755_virus_1380.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person755_virus_1382.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person756_bacteria_2660.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person757_bacteria_2661.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person757_virus_1385.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person758_bacteria_2662.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person759_bacteria_2663.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person759_virus_1387.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person75_bacteria_364.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person75_bacteria_365.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person75_bacteria_366.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person75_bacteria_367.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person75_bacteria_368.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person75_bacteria_369.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person760_bacteria_2664.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person760_virus_1388.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person761_bacteria_2665.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person761_virus_1389.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person762_virus_1390.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person763_bacteria_2667.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person763_virus_1391.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person764_bacteria_2668.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person764_virus_1392.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person765_bacteria_2669.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person765_virus_1393.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person766_bacteria_2670.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person767_bacteria_2671.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person768_bacteria_2672.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person768_virus_1396.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person769_bacteria_2673.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person76_bacteria_370.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person76_bacteria_371.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person76_bacteria_372.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person770_bacteria_2674.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person770_virus_1398.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person771_bacteria_2675.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person771_virus_1399.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person772_virus_1401.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person773_virus_1402.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person774_bacteria_2678.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person774_virus_1403.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person775_bacteria_2679.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person775_virus_1404.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person776_bacteria_2680.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person776_virus_1405.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person778_bacteria_2682.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person778_virus_1408.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person779_bacteria_2683.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person779_virus_1409.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person779_virus_1410.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person77_bacteria_374.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person77_bacteria_375.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person77_bacteria_376.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person77_bacteria_377.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person780_bacteria_2684.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person780_virus_1411.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person781_virus_1412.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person782_bacteria_2686.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person783_bacteria_2687.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person783_virus_1414.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person785_bacteria_2689.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person786_bacteria_2690.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person787_bacteria_2691.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person788_virus_1419.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person789_bacteria_2694.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person789_virus_1420.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person790_virus_1421.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person791_virus_1422.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person793_virus_1424.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person794_bacteria_2700.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person795_virus_1427.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person796_bacteria_2702.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person796_virus_1428.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person797_virus_1429.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person798_virus_1430.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person799_bacteria_2705.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person799_virus_1431.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person7_bacteria_24.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person7_bacteria_25.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person7_bacteria_28.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person7_bacteria_29.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person800_bacteria_2706.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person801_virus_1434.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person802_bacteria_2708.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person803_bacteria_2710.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person803_virus_1436.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person804_bacteria_2711.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person805_bacteria_2712.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person806_virus_1439.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person806_virus_1440.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person807_virus_1441.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person808_bacteria_2716.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person808_virus_1442.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person809_bacteria_2717.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person809_bacteria_2718.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person80_virus_150.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person810_bacteria_2719.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person810_virus_1445.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person810_virus_1446.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person811_bacteria_2721.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person811_virus_1447.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person813_bacteria_2723.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person813_bacteria_2724.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person813_virus_1449.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person814_bacteria_2725.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person815_bacteria_2726.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person816_bacteria_2727.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person817_bacteria_2728.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person818_bacteria_2729.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person819_bacteria_2730.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person819_virus_1455.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person81_virus_152.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person81_virus_153.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person820_bacteria_2731.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person820_virus_1456.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person823_virus_1459.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person825_bacteria_2736.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person826_bacteria_2737.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person826_virus_1462.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person827_bacteria_2738.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person829_bacteria_2740.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person82_virus_154.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person82_virus_155.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person830_bacteria_2741.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person830_virus_1466.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person831_bacteria_2742.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person832_bacteria_2743.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person832_virus_1468.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person833_virus_1469.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person834_bacteria_2747.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person834_bacteria_2748.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person835_bacteria_2749.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person835_bacteria_2750.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person835_virus_1472.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person836_bacteria_2752.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person836_virus_1473.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person837_bacteria_2753.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person837_bacteria_2754.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person837_virus_1475.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person838_virus_1476.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person839_bacteria_2757.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person83_virus_156.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person840_bacteria_2758.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person840_bacteria_2759.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person841_bacteria_2760.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person841_bacteria_2761.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person841_virus_1481.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person842_bacteria_2762.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person842_virus_1483.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person843_bacteria_2763.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person843_virus_1485.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person844_virus_1487.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person845_virus_1489.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person846_bacteria_2766.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person846_virus_1491.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person847_bacteria_2767.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person847_virus_1492.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person848_bacteria_2769.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person848_virus_1493.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person849_bacteria_2770.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person849_virus_1494.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person84_virus_157.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person850_bacteria_2771.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person851_virus_1496.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person852_virus_1497.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person853_bacteria_2774.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person853_bacteria_2775.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person853_virus_1498.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person854_bacteria_2776.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person855_bacteria_2777.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person855_virus_1500.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person858_bacteria_2780.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person859_virus_1504.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person860_virus_1505.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person861_virus_1506.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person862_bacteria_2784.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person862_virus_1507.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person863_bacteria_2785.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person863_virus_1508.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person864_virus_1509.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person866_bacteria_2788.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person866_virus_1511.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person867_bacteria_2789.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person867_virus_1512.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person868_virus_1513.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person868_virus_1514.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person86_virus_159.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person870_bacteria_2792.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person870_virus_1516.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person871_bacteria_2793.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person871_virus_1517.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person872_bacteria_2795.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person873_bacteria_2796.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person874_bacteria_2797.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person875_bacteria_2798.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person876_bacteria_2799.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person877_bacteria_2800.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person877_virus_1525.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person878_bacteria_2801.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person878_virus_1526.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person87_virus_160.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person880_bacteria_2804.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person880_virus_1529.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person881_bacteria_2805.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person881_virus_1531.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person882_bacteria_2806.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person883_bacteria_2807.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person883_virus_1533.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person884_bacteria_2808.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person884_virus_1534.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person885_bacteria_2809.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person886_bacteria_2810.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person886_virus_1536.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person887_bacteria_2811.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person888_bacteria_2812.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person888_virus_1538.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person889_bacteria_2813.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person88_virus_161.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person88_virus_163.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person88_virus_164.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person88_virus_165.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person88_virus_166.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person88_virus_167.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person890_bacteria_2814.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person890_virus_1540.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person891_virus_1541.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person892_bacteria_2817.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person893_bacteria_2818.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person894_bacteria_2819.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person894_virus_1546.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person895_bacteria_2820.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person895_virus_1547.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person896_bacteria_2821.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person896_virus_1548.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person897_bacteria_2822.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person898_bacteria_2823.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person898_virus_1552.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person899_virus_1553.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person89_virus_168.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person8_bacteria_37.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person900_virus_1554.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person901_virus_1555.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person902_bacteria_2827.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person903_bacteria_2828.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person904_bacteria_2829.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person905_bacteria_2830.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person905_virus_1561.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person906_bacteria_2831.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person906_virus_1562.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person907_bacteria_2832.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person907_virus_1563.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person908_virus_1564.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person909_bacteria_2834.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person909_virus_1565.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person90_virus_169.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person90_virus_170.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person911_bacteria_2836.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person911_virus_1567.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person912_bacteria_2837.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person913_bacteria_2838.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person913_virus_1570.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person914_bacteria_2839.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person914_virus_1571.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person915_virus_1572.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person916_bacteria_2841.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person917_bacteria_2842.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person918_bacteria_2843.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person918_virus_1575.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person919_bacteria_2844.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person919_virus_1576.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person920_bacteria_2845.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person920_virus_1577.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person921_bacteria_2846.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person921_virus_1578.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person922_bacteria_2847.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person923_bacteria_2848.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person924_bacteria_2849.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person924_virus_1581.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person925_bacteria_2850.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person925_virus_1582.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person926_virus_1583.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person927_bacteria_2852.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person927_virus_1584.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person928_virus_1586.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person929_bacteria_2854.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person929_virus_1588.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person929_virus_1589.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person92_virus_174.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person930_bacteria_2855.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person931_bacteria_2856.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person931_virus_1592.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person932_virus_1593.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person933_bacteria_2858.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person933_virus_1594.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person934_bacteria_2859.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person934_virus_1595.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person935_virus_1597.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person936_bacteria_2861.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person936_virus_1598.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person937_bacteria_2862.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person937_virus_1599.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person938_bacteria_2863.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person938_virus_1600.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person939_bacteria_2864.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person93_virus_175.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person940_bacteria_2865.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person940_virus_1602.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person940_virus_1604.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person940_virus_1605.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person940_virus_1607.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person940_virus_1609.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person941_virus_1610.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person942_bacteria_2867.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person942_virus_1611.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person943_bacteria_2868.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person944_bacteria_2869.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person945_bacteria_2870.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person945_virus_1616.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person946_bacteria_2871.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person947_bacteria_2872.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person947_virus_1618.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person949_bacteria_2874.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person949_virus_1620.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person94_virus_176.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person950_virus_1621.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person951_bacteria_2876.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person951_virus_1622.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person952_bacteria_2877.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person952_virus_1623.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person953_bacteria_2878.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person954_bacteria_2879.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person954_virus_1626.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person955_bacteria_2880.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person955_virus_1627.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person956_bacteria_2881.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person956_virus_1628.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person957_bacteria_2882.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person957_virus_1629.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person958_bacteria_2883.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person958_virus_1630.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person959_bacteria_2884.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person95_virus_177.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person960_bacteria_2885.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person960_virus_1633.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person961_bacteria_2886.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person961_virus_1634.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person962_bacteria_2887.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person962_virus_1635.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person963_bacteria_2888.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person963_virus_1636.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person964_bacteria_2889.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person964_virus_1637.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person965_bacteria_2890.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person965_virus_1638.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person966_bacteria_2891.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person966_virus_1639.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person967_bacteria_2892.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person967_virus_1640.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person968_bacteria_2893.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person968_virus_1642.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person969_bacteria_2894.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person969_virus_1643.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person96_virus_178.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person96_virus_179.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person970_bacteria_2895.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person970_virus_1644.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person971_bacteria_2896.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person972_bacteria_2897.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person972_virus_1646.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person973_virus_1647.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person974_bacteria_2899.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person974_virus_1649.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person975_virus_1650.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person976_bacteria_2901.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person976_virus_1651.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person977_bacteria_2902.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person977_virus_1652.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person978_bacteria_2904.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person978_virus_1653.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person979_bacteria_2905.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person979_virus_1654.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person97_virus_180.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person97_virus_181.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person980_bacteria_2906.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person980_virus_1655.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person981_bacteria_2907.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person981_bacteria_2908.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person981_virus_1657.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person982_bacteria_2909.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person982_virus_1658.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person983_bacteria_2910.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person983_virus_1660.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person984_bacteria_2911.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person985_bacteria_2912.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person986_bacteria_2913.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person987_bacteria_2914.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person988_bacteria_2915.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person988_virus_1666.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person989_virus_1667.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person98_virus_182.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person990_bacteria_2917.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person991_bacteria_2918.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person991_virus_1669.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person992_bacteria_2919.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person992_bacteria_2920.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person992_virus_1670.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person993_bacteria_2921.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person993_virus_1671.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person994_bacteria_2922.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person994_virus_1672.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person995_bacteria_2923.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person995_virus_1676.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person996_bacteria_2924.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person996_virus_1677.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person997_bacteria_2926.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person997_virus_1678.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person998_bacteria_2927.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person998_bacteria_2928.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person99_virus_183.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person9_bacteria_38.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person9_bacteria_39.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person9_bacteria_40.jpeg \n inflating: archive/chest_xray/train/PNEUMONIA/person9_bacteria_41.jpeg \n inflating: archive/chest_xray/val/NORMAL/NORMAL2-IM-1427-0001.jpeg \n inflating: archive/chest_xray/val/NORMAL/NORMAL2-IM-1430-0001.jpeg \n inflating: archive/chest_xray/val/NORMAL/NORMAL2-IM-1431-0001.jpeg \n inflating: archive/chest_xray/val/NORMAL/NORMAL2-IM-1436-0001.jpeg \n inflating: archive/chest_xray/val/NORMAL/NORMAL2-IM-1437-0001.jpeg \n inflating: archive/chest_xray/val/NORMAL/NORMAL2-IM-1438-0001.jpeg \n inflating: archive/chest_xray/val/NORMAL/NORMAL2-IM-1440-0001.jpeg \n inflating: archive/chest_xray/val/NORMAL/NORMAL2-IM-1442-0001.jpeg \n inflating: archive/chest_xray/val/PNEUMONIA/person1946_bacteria_4874.jpeg \n inflating: archive/chest_xray/val/PNEUMONIA/person1946_bacteria_4875.jpeg \n inflating: archive/chest_xray/val/PNEUMONIA/person1947_bacteria_4876.jpeg \n inflating: archive/chest_xray/val/PNEUMONIA/person1949_bacteria_4880.jpeg \n inflating: archive/chest_xray/val/PNEUMONIA/person1950_bacteria_4881.jpeg \n inflating: archive/chest_xray/val/PNEUMONIA/person1951_bacteria_4882.jpeg \n inflating: archive/chest_xray/val/PNEUMONIA/person1952_bacteria_4883.jpeg \n inflating: archive/chest_xray/val/PNEUMONIA/person1954_bacteria_4886.jpeg \n" ], [ "import warnings\r\nwarnings.filterwarnings('ignore')", "_____no_output_____" ], [ "import tensorflow as tf\r\nfrom tensorflow import keras", "_____no_output_____" ], [ "from keras.layers import Input, Lambda, Dense, Flatten", "_____no_output_____" ], [ "from keras.models import Model\r\nfrom keras.applications.vgg16 import VGG16\r\nfrom keras.applications.vgg16 import preprocess_input\r\nfrom keras.preprocessing import image\r\nfrom keras.preprocessing.image import ImageDataGenerator\r\nfrom keras.models import Sequential\r\nimport numpy as np\r\nfrom glob import glob\r\nimport matplotlib.pyplot as plt", "_____no_output_____" ], [ "IMAGE_SIZE = [224, 224]\r\n\r\ntrain_path = '/content/archive/chest_xray/train'\r\nvalid_path = '/content/archive/chest_xray/test'", "_____no_output_____" ], [ "vgg = VGG16(input_shape=IMAGE_SIZE + [3], weights='imagenet', include_top=False)", "Downloading data from https://storage.googleapis.com/tensorflow/keras-applications/vgg16/vgg16_weights_tf_dim_ordering_tf_kernels_notop.h5\n58892288/58889256 [==============================] - 0s 0us/step\n" ], [ "for layer in vgg.layers:\r\n layer.trainable = False", "_____no_output_____" ], [ "folders = glob('/content/archive/chest_xray/train/*')\r\nx = Flatten()(vgg.output)", "_____no_output_____" ], [ "prediction = Dense(len(folders), activation='softmax')(x)\r\n# create a model object\r\nmodel = Model(inputs=vgg.input, outputs=prediction)\r\n# view the structure of the model\r\nmodel.summary()", "Model: \"model_1\"\n_________________________________________________________________\nLayer (type) Output Shape Param # \n=================================================================\ninput_1 (InputLayer) [(None, 224, 224, 3)] 0 \n_________________________________________________________________\nblock1_conv1 (Conv2D) (None, 224, 224, 64) 1792 \n_________________________________________________________________\nblock1_conv2 (Conv2D) (None, 224, 224, 64) 36928 \n_________________________________________________________________\nblock1_pool (MaxPooling2D) (None, 112, 112, 64) 0 \n_________________________________________________________________\nblock2_conv1 (Conv2D) (None, 112, 112, 128) 73856 \n_________________________________________________________________\nblock2_conv2 (Conv2D) (None, 112, 112, 128) 147584 \n_________________________________________________________________\nblock2_pool (MaxPooling2D) (None, 56, 56, 128) 0 \n_________________________________________________________________\nblock3_conv1 (Conv2D) (None, 56, 56, 256) 295168 \n_________________________________________________________________\nblock3_conv2 (Conv2D) (None, 56, 56, 256) 590080 \n_________________________________________________________________\nblock3_conv3 (Conv2D) (None, 56, 56, 256) 590080 \n_________________________________________________________________\nblock3_pool (MaxPooling2D) (None, 28, 28, 256) 0 \n_________________________________________________________________\nblock4_conv1 (Conv2D) (None, 28, 28, 512) 1180160 \n_________________________________________________________________\nblock4_conv2 (Conv2D) (None, 28, 28, 512) 2359808 \n_________________________________________________________________\nblock4_conv3 (Conv2D) (None, 28, 28, 512) 2359808 \n_________________________________________________________________\nblock4_pool (MaxPooling2D) (None, 14, 14, 512) 0 \n_________________________________________________________________\nblock5_conv1 (Conv2D) (None, 14, 14, 512) 2359808 \n_________________________________________________________________\nblock5_conv2 (Conv2D) (None, 14, 14, 512) 2359808 \n_________________________________________________________________\nblock5_conv3 (Conv2D) (None, 14, 14, 512) 2359808 \n_________________________________________________________________\nblock5_pool (MaxPooling2D) (None, 7, 7, 512) 0 \n_________________________________________________________________\nflatten_1 (Flatten) (None, 25088) 0 \n_________________________________________________________________\ndense_1 (Dense) (None, 2) 50178 \n=================================================================\nTotal params: 14,764,866\nTrainable params: 50,178\nNon-trainable params: 14,714,688\n_________________________________________________________________\n" ], [ "model.compile(\r\n loss='categorical_crossentropy',\r\n optimizer='adam',\r\n metrics=['accuracy']\r\n)", "_____no_output_____" ], [ "from keras.preprocessing.image import ImageDataGenerator", "_____no_output_____" ], [ "train_datagen = ImageDataGenerator(rescale = 1./255,\r\n shear_range = 0.2,\r\n zoom_range = 0.2,\r\n horizontal_flip = True)\r\n\r\ntest_datagen = ImageDataGenerator(rescale = 1./255)\r\n\r\n\r\n\r\n\r\n# Make sure you provide the same target size as initialied for the image size\r\ntraining_set = train_datagen.flow_from_directory('/content/archive/chest_xray/train',\r\n target_size = (224, 224),\r\n batch_size = 10,\r\n class_mode = 'categorical')\r\n\r\n\r\n\r\n\r\ntest_set = test_datagen.flow_from_directory('/content/archive/chest_xray/test',\r\n target_size = (224, 224),\r\n batch_size = 10,\r\n class_mode = 'categorical')", "Found 5216 images belonging to 2 classes.\nFound 624 images belonging to 2 classes.\n" ], [ "r = model.fit_generator(\r\n training_set,\r\n validation_data=test_set,\r\n epochs=30,steps_per_epoch=len(training_set),\r\n validation_steps=len(test_set)\r\n)", "Epoch 1/30\n522/522 [==============================] - 108s 205ms/step - loss: 0.3084 - accuracy: 0.8912 - val_loss: 0.3777 - val_accuracy: 0.9103\nEpoch 2/30\n522/522 [==============================] - 108s 206ms/step - loss: 0.1601 - accuracy: 0.9485 - val_loss: 0.3799 - val_accuracy: 0.9054\nEpoch 3/30\n522/522 [==============================] - 108s 207ms/step - loss: 0.1191 - accuracy: 0.9605 - val_loss: 0.4871 - val_accuracy: 0.9022\nEpoch 4/30\n522/522 [==============================] - 108s 207ms/step - loss: 0.2038 - accuracy: 0.9426 - val_loss: 0.7985 - val_accuracy: 0.8718\nEpoch 5/30\n522/522 [==============================] - 106s 203ms/step - loss: 0.1456 - accuracy: 0.9632 - val_loss: 0.3993 - val_accuracy: 0.8926\nEpoch 6/30\n522/522 [==============================] - 105s 202ms/step - loss: 0.0971 - accuracy: 0.9669 - val_loss: 0.7351 - val_accuracy: 0.8798\nEpoch 7/30\n522/522 [==============================] - 105s 202ms/step - loss: 0.1128 - accuracy: 0.9695 - val_loss: 0.6090 - val_accuracy: 0.8974\nEpoch 8/30\n522/522 [==============================] - 103s 197ms/step - loss: 0.1683 - accuracy: 0.9587 - val_loss: 0.9952 - val_accuracy: 0.8734\nEpoch 9/30\n522/522 [==============================] - 104s 200ms/step - loss: 0.1429 - accuracy: 0.9606 - val_loss: 1.1234 - val_accuracy: 0.8702\nEpoch 10/30\n522/522 [==============================] - 104s 199ms/step - loss: 0.1644 - accuracy: 0.9636 - val_loss: 0.6492 - val_accuracy: 0.9071\nEpoch 11/30\n522/522 [==============================] - 104s 199ms/step - loss: 0.0994 - accuracy: 0.9714 - val_loss: 0.8677 - val_accuracy: 0.8958\nEpoch 12/30\n522/522 [==============================] - 106s 203ms/step - loss: 0.1470 - accuracy: 0.9669 - val_loss: 1.0083 - val_accuracy: 0.8718\nEpoch 13/30\n522/522 [==============================] - 107s 204ms/step - loss: 0.0682 - accuracy: 0.9807 - val_loss: 0.5825 - val_accuracy: 0.9119\nEpoch 14/30\n522/522 [==============================] - 108s 206ms/step - loss: 0.0820 - accuracy: 0.9769 - val_loss: 1.0674 - val_accuracy: 0.8670\nEpoch 15/30\n522/522 [==============================] - 109s 208ms/step - loss: 0.1028 - accuracy: 0.9744 - val_loss: 0.8836 - val_accuracy: 0.8878\nEpoch 16/30\n522/522 [==============================] - 109s 208ms/step - loss: 0.0616 - accuracy: 0.9832 - val_loss: 0.9991 - val_accuracy: 0.8734\nEpoch 17/30\n522/522 [==============================] - 107s 206ms/step - loss: 0.1249 - accuracy: 0.9676 - val_loss: 0.8446 - val_accuracy: 0.8990\nEpoch 18/30\n522/522 [==============================] - 109s 208ms/step - loss: 0.0800 - accuracy: 0.9808 - val_loss: 0.4918 - val_accuracy: 0.8990\nEpoch 19/30\n522/522 [==============================] - 109s 208ms/step - loss: 0.0793 - accuracy: 0.9754 - val_loss: 0.5303 - val_accuracy: 0.9038\nEpoch 20/30\n522/522 [==============================] - 109s 209ms/step - loss: 0.1026 - accuracy: 0.9750 - val_loss: 0.6707 - val_accuracy: 0.8766\nEpoch 21/30\n522/522 [==============================] - 107s 204ms/step - loss: 0.0995 - accuracy: 0.9770 - val_loss: 1.1745 - val_accuracy: 0.8830\nEpoch 22/30\n522/522 [==============================] - 110s 210ms/step - loss: 0.1134 - accuracy: 0.9751 - val_loss: 0.5603 - val_accuracy: 0.9327\nEpoch 23/30\n522/522 [==============================] - 110s 210ms/step - loss: 0.1049 - accuracy: 0.9749 - val_loss: 0.9143 - val_accuracy: 0.8974\nEpoch 24/30\n522/522 [==============================] - 110s 211ms/step - loss: 0.0623 - accuracy: 0.9831 - val_loss: 0.7359 - val_accuracy: 0.9199\nEpoch 25/30\n522/522 [==============================] - 110s 210ms/step - loss: 0.0570 - accuracy: 0.9827 - val_loss: 0.5417 - val_accuracy: 0.9295\nEpoch 26/30\n522/522 [==============================] - 108s 207ms/step - loss: 0.0687 - accuracy: 0.9801 - val_loss: 1.0377 - val_accuracy: 0.8942\nEpoch 27/30\n522/522 [==============================] - 110s 210ms/step - loss: 0.1590 - accuracy: 0.9693 - val_loss: 1.1372 - val_accuracy: 0.8814\nEpoch 28/30\n522/522 [==============================] - 110s 210ms/step - loss: 0.0820 - accuracy: 0.9796 - val_loss: 0.6963 - val_accuracy: 0.8910\nEpoch 29/30\n522/522 [==============================] - 111s 212ms/step - loss: 0.0902 - accuracy: 0.9787 - val_loss: 0.6777 - val_accuracy: 0.9279\nEpoch 30/30\n522/522 [==============================] - 110s 211ms/step - loss: 0.0775 - accuracy: 0.9825 - val_loss: 0.8432 - val_accuracy: 0.9231\n" ], [ "import numpy as np", "_____no_output_____" ], [ "model.save('chest_xray.h5')", "_____no_output_____" ], [ "img=image.load_img('/content/archive/chest_xray/val/NORMAL/NORMAL2-IM-1437-0001.jpeg',target_size=(224,224))", "_____no_output_____" ], [ "x=image.img_to_array(img) #convert an image into array", "_____no_output_____" ], [ "x=np.expand_dims(x, axis=0)", "_____no_output_____" ], [ "img_data=preprocess_input(x)", "_____no_output_____" ], [ "classes=model.predict(img_data)", "_____no_output_____" ], [ "result=classes[0][0]", "_____no_output_____" ], [ "if result>0.5:\r\n print(\"Result is Normal\")\r\nelse:\r\n print(\"Person is Affected By PNEUMONIA\")", "Result is Normal\n" ], [ "", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
4a0ca3ac314c164c8c6f43c439e9d40ef0fa47bc
6,969
ipynb
Jupyter Notebook
tossing/Physical_regularization_tossing.ipynb
physicslearning/PhysicsNAS
9f9690ce064d1eca4a1f3f89cc761c484e7e594a
[ "MIT" ]
9
2019-10-19T02:47:52.000Z
2021-02-28T08:40:21.000Z
tossing/Physical_regularization_tossing.ipynb
PhysicsNAS/PhysicsNAS
9f9690ce064d1eca4a1f3f89cc761c484e7e594a
[ "MIT" ]
null
null
null
tossing/Physical_regularization_tossing.ipynb
PhysicsNAS/PhysicsNAS
9f9690ce064d1eca4a1f3f89cc761c484e7e594a
[ "MIT" ]
3
2019-10-02T08:21:03.000Z
2021-04-19T03:14:52.000Z
28.561475
104
0.477687
[ [ [ "# Library", "_____no_output_____" ] ], [ [ "import numpy as np\nimport torch\nimport torch.nn as nn\n\nfrom utils import *\nfrom dataset import TossingDataset\nfrom torch.utils.data import DataLoader", "_____no_output_____" ] ], [ [ "# Model", "_____no_output_____" ] ], [ [ "class NaiveMLP(nn.Module):\n\n def __init__(self, in_traj_num, pre_traj_num):\n super(NaiveMLP, self).__init__()\n self.hidden_dim = 128\n self.fc_1 = nn.Sequential(\n nn.Linear(in_traj_num * 2, self.hidden_dim),\n nn.ReLU(inplace=True),\n nn.Linear(self.hidden_dim, self.hidden_dim),\n nn.ReLU(inplace=True),\n )\n self.fc_out = nn.Linear(self.hidden_dim, pre_traj_num * 2)\n\n def forward(self, x):\n x = self.fc_1(x)\n x = self.fc_out(x)\n\n return x", "_____no_output_____" ], [ "def train_model(model, train_loader, test_loader, num_epochs, optimizer, scheduler, criterion):\n # Training the Model\n min_test_dif = float('inf')\n epoch_loss = []\n for epoch in range(num_epochs):\n batch_loss = []\n for i, data in enumerate(train_loader):\n \n # get the inputs\n inputs = data['current_locs_gt']\n locs_gt = data['future_locs_gt']\n\n inputs = inputs.cuda()\n locs_gt = locs_gt.cuda()\n\n # zero the parameter gradients\n optimizer.zero_grad()\n\n # forward + backward + optimize\n outputs = net(inputs)\n \n loss = criterion(outputs, locs_gt, inputs)\n \n loss.backward()\n optimizer.step()\n \n batch_loss.append(loss.item())\n\n # Results every epoch\n cur_epoch_loss = sum(batch_loss) / len(batch_loss)\n \n # Scheduler\n scheduler.step(cur_epoch_loss)\n \n # Test the network\n train_dif = test_model(model, train_loader)\n test_dif = test_model(model, test_loader)\n \n # Print the result\n print('Epoch: %d Train Loss: %.03f Train Dif: %.03f Test Dif: %.03f' \n % (epoch, cur_epoch_loss, train_dif, test_dif))\n epoch_loss.append(cur_epoch_loss)\n \n if min_test_dif > test_dif:\n min_test_dif = test_dif\n print('Best')\n \n return epoch_loss\n\ndef test_model(model, test_loader):\n # Test the Model\n model.eval()\n \n batch_loss = []\n for i, data in enumerate(test_loader):\n\n # get the inputs\n inputs = data['current_locs_gt']\n locs_gt = data['future_locs_gt']\n\n inputs = inputs.cuda()\n locs_gt = locs_gt.cuda()\n\n outputs = net(inputs)\n loss = get_mean_distance(locs_gt, outputs)\n batch_loss.append(loss.item())\n\n # Results every epoch\n cur_epoch_loss = sum(batch_loss) / len(batch_loss)\n \n model.train()\n \n return cur_epoch_loss\n\ndef get_mean_distance(locs_a, locs_b):\n vector_len = locs_a.shape[1]\n x_a = locs_a[:, :vector_len // 2]\n y_a = locs_a[:, vector_len // 2:]\n x_b = locs_b[:, :vector_len // 2]\n y_b = locs_b[:, vector_len // 2:]\n \n dif_x = (x_a - x_b) ** 2\n dif_y = (y_a - y_b) ** 2\n \n dif = dif_x + dif_y\n \n return torch.mean(torch.sqrt(dif))", "_____no_output_____" ], [ "#################### Hyperparameters ####################\nnum_epochs = 50000\nlearning_rate = 0.001\nweight_decay = 0\nin_frames_num = 3\npre_frames_num = 15\nfactor = 0.95\npatience = 40\nbatch_size = 16\n#################### Hyperparameters ####################\nnet = NaiveMLP(in_traj_num=3, pre_traj_num=15).cuda()\ncriterion = PhysicalRegularization()\n\ntrain_set = TossingDataset(\n './dataset/r1_k0.2/train', \n in_traj_num=3, \n pre_traj_num=15,\n sample_num=32\n)\n\ntest_set = TossingDataset(\n './dataset/r1_k0.2/test', \n in_traj_num=3,\n pre_traj_num=15\n)\n\nprint(len(train_set), len(test_set))\n\ntrain_loader = DataLoader(train_set, batch_size=batch_size, shuffle=True)\ntest_loader = DataLoader(test_set, batch_size=len(test_set), shuffle=False)\n\noptimizer = torch.optim.Adam(net.parameters(), lr=learning_rate, weight_decay=weight_decay)\n\nscheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(\n optimizer, \n mode='min', \n factor=factor, \n patience=patience, \n verbose=True, \n threshold=1e-3\n)\n\ntrain_loss = train_model(\n net, \n train_loader, \n test_loader, \n num_epochs, \n optimizer, \n scheduler, \n criterion\n)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ] ]
4a0cb8a6f62ebe9d53e8de9178c4a5fa6b0cd88d
510,598
ipynb
Jupyter Notebook
pyflightdata examples.ipynb
sk7/pyflightdata
93528434a3330db835e4fd204b75a7b174ee9727
[ "MIT" ]
null
null
null
pyflightdata examples.ipynb
sk7/pyflightdata
93528434a3330db835e4fd204b75a7b174ee9727
[ "MIT" ]
null
null
null
pyflightdata examples.ipynb
sk7/pyflightdata
93528434a3330db835e4fd204b75a7b174ee9727
[ "MIT" ]
null
null
null
50.93755
187
0.414277
[ [ [ "# MIT License\n#\n# Copyright (c) 2019 Hari Allamraju\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n", "_____no_output_____" ] ], [ [ "# pyflightdata examples\n\nThis document lists a few examples to show the basic usage of pyflightdata. This does not show all the potential uses of the data we get from the API.\n\nPlease note that this is not an official API and we do not endorse or recommend any commercial usage of this API to make large scale mass requests.\n\nAlso the API may break from time to time as the pages and their structure change at the underlying websites. For now this is only flightradar24.com but we might add more sites soon.", "_____no_output_____" ] ], [ [ "from pyflightdata import FlightData", "_____no_output_____" ], [ "api=FlightData()", "_____no_output_____" ], [ "api.get_countries()[:5]", "_____no_output_____" ], [ "api.get_airlines()[:5]", "_____no_output_____" ], [ "api.get_airports('India')[10:15]", "_____no_output_____" ], [ "#pass the airline-code from get_airlines\napi.get_fleet('emirates-ek-uae')", "_____no_output_____" ], [ "#pass airline-code from get_airlines to see all current live flights\napi.get_flights('AI1')[:10]", "_____no_output_____" ], [ "api.get_history_by_flight_number('AI101')[-5:]", "_____no_output_____" ], [ "api.get_history_by_tail_number('9V-SMA')[-5:]", "_____no_output_____" ], [ "api.get_info_by_tail_number('9V-SMA')", "_____no_output_____" ], [ "api.get_airport_arrivals('sin')", "_____no_output_____" ], [ "api.get_airport_departures('sin')", "_____no_output_____" ], [ "api.get_airport_details('sin')", "_____no_output_____" ] ] ]
[ "code", "markdown", "code" ]
[ [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
4a0cfc4c52145983324a8528267a63da5522bb70
145,184
ipynb
Jupyter Notebook
2 - Data Analysis with Python/Module 2 - Data Wrangling/1 - code/data-wrangling.ipynb
joaopaulo164/Data-Science-with-Python
eff0240f97c150e65e12a295e47b5dee2d1bdbf7
[ "MIT" ]
null
null
null
2 - Data Analysis with Python/Module 2 - Data Wrangling/1 - code/data-wrangling.ipynb
joaopaulo164/Data-Science-with-Python
eff0240f97c150e65e12a295e47b5dee2d1bdbf7
[ "MIT" ]
null
null
null
2 - Data Analysis with Python/Module 2 - Data Wrangling/1 - code/data-wrangling.ipynb
joaopaulo164/Data-Science-with-Python
eff0240f97c150e65e12a295e47b5dee2d1bdbf7
[ "MIT" ]
null
null
null
37.808333
8,704
0.492561
[ [ [ "<center>\n <img src=\"https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-DA0101EN-SkillsNetwork/labs/Module%202/images/IDSNlogo.png\" width=\"300\" alt=\"cognitiveclass.ai logo\" />\n</center>\n\n# Data Wrangling\n\nEstimated time needed: **30** minutes\n\n## Objectives\n\nAfter completing this lab you will be able to:\n\n* Handle missing values\n* Correct data format\n* Standardize and normalize data\n", "_____no_output_____" ], [ "<h2>Table of Contents</h2>\n\n<div class=\"alert alert-block alert-info\" style=\"margin-top: 20px\">\n<ul>\n <li><a href=\"https://#identify_handle_missing_values\">Identify and handle missing values</a>\n <ul>\n <li><a href=\"https://#identify_missing_values\">Identify missing values</a></li>\n <li><a href=\"https://#deal_missing_values\">Deal with missing values</a></li>\n <li><a href=\"https://#correct_data_format\">Correct data format</a></li>\n </ul>\n </li>\n <li><a href=\"https://#data_standardization\">Data standardization</a></li>\n <li><a href=\"https://#data_normalization\">Data normalization (centering/scaling)</a></li>\n <li><a href=\"https://#binning\">Binning</a></li>\n <li><a href=\"https://#indicator\">Indicator variable</a></li>\n</ul>\n\n</div>\n\n<hr>\n", "_____no_output_____" ], [ "<h2>What is the purpose of data wrangling?</h2>\n", "_____no_output_____" ], [ "Data wrangling is the process of converting data from the initial format to a format that may be better for analysis.\n", "_____no_output_____" ], [ "<h3>What is the fuel consumption (L/100k) rate for the diesel car?</h3>\n", "_____no_output_____" ], [ "<h3>Import data</h3>\n<p>\nYou can find the \"Automobile Dataset\" from the following link: <a href=\"https://archive.ics.uci.edu/ml/machine-learning-databases/autos/imports-85.data?utm_medium=Exinfluencer&utm_source=Exinfluencer&utm_content=000026UJ&utm_term=10006555&utm_id=NA-SkillsNetwork-Channel-SkillsNetworkCoursesIBMDeveloperSkillsNetworkDA0101ENSkillsNetwork20235326-2021-01-01\">https://archive.ics.uci.edu/ml/machine-learning-databases/autos/imports-85.data</a>. \nWe will be using this dataset throughout this course.\n</p>\n", "_____no_output_____" ], [ "<h4>Import pandas</h4> \n", "_____no_output_____" ] ], [ [ "import pandas as pd\nimport matplotlib.pylab as plt", "_____no_output_____" ] ], [ [ "<h2>Reading the dataset from the URL and adding the related headers</h2>\n", "_____no_output_____" ], [ "First, we assign the URL of the dataset to \"filename\".\n", "_____no_output_____" ], [ "This dataset was hosted on IBM Cloud object. Click <a href=\"https://cocl.us/corsera_da0101en_notebook_bottom?utm_medium=Exinfluencer&utm_source=Exinfluencer&utm_content=000026UJ&utm_term=10006555&utm_id=NA-SkillsNetwork-Channel-SkillsNetworkCoursesIBMDeveloperSkillsNetworkDA0101ENSkillsNetwork20235326-2021-01-01\">HERE</a> for free storage.\n", "_____no_output_____" ] ], [ [ "filename = \"https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-DA0101EN-SkillsNetwork/labs/Data%20files/auto.csv\"", "_____no_output_____" ] ], [ [ "Then, we create a Python list <b>headers</b> containing name of headers.\n", "_____no_output_____" ] ], [ [ "headers = [\"symboling\",\"normalized-losses\",\"make\",\"fuel-type\",\"aspiration\", \"num-of-doors\",\"body-style\",\n \"drive-wheels\",\"engine-location\",\"wheel-base\", \"length\",\"width\",\"height\",\"curb-weight\",\"engine-type\",\n \"num-of-cylinders\", \"engine-size\",\"fuel-system\",\"bore\",\"stroke\",\"compression-ratio\",\"horsepower\",\n \"peak-rpm\",\"city-mpg\",\"highway-mpg\",\"price\"]", "_____no_output_____" ] ], [ [ "Use the Pandas method <b>read_csv()</b> to load the data from the web address. Set the parameter \"names\" equal to the Python list \"headers\".\n", "_____no_output_____" ] ], [ [ "df = pd.read_csv(filename, names = headers)", "_____no_output_____" ] ], [ [ "Use the method <b>head()</b> to display the first five rows of the dataframe.\n", "_____no_output_____" ] ], [ [ "# To see what the data set looks like, we'll use the head() method.\ndf.head()", "_____no_output_____" ] ], [ [ "As we can see, several question marks appeared in the dataframe; those are missing values which may hinder our further analysis.\n\n<div>So, how do we identify all those missing values and deal with them?</div> \n\n<b>How to work with missing data?</b>\n\nSteps for working with missing data:\n\n<ol>\n <li>Identify missing data</li>\n <li>Deal with missing data</li>\n <li>Correct data format</li>\n</ol>\n", "_____no_output_____" ], [ "<h2 id=\"identify_handle_missing_values\">Identify and handle missing values</h2>\n\n<h3 id=\"identify_missing_values\">Identify missing values</h3>\n<h4>Convert \"?\" to NaN</h4>\nIn the car dataset, missing data comes with the question mark \"?\".\nWe replace \"?\" with NaN (Not a Number), Python's default missing value marker for reasons of computational speed and convenience. Here we use the function: \n <pre>.replace(A, B, inplace = True) </pre>\nto replace A by B.\n", "_____no_output_____" ] ], [ [ "import numpy as np\n\n# replace \"?\" to NaN\ndf.replace(\"?\", np.nan, inplace = True)\ndf.head(5)", "_____no_output_____" ] ], [ [ "<h4>Evaluating for Missing Data</h4>\n\nThe missing values are converted by default. We use the following functions to identify these missing values. There are two methods to detect missing data:\n\n<ol>\n <li><b>.isnull()</b></li>\n <li><b>.notnull()</b></li>\n</ol>\nThe output is a boolean value indicating whether the value that is passed into the argument is in fact missing data.\n", "_____no_output_____" ] ], [ [ "missing_data = df.isnull()\nmissing_data.head(5)", "_____no_output_____" ] ], [ [ "\"True\" means the value is a missing value while \"False\" means the value is not a missing value.\n", "_____no_output_____" ], [ "<h4>Count missing values in each column</h4>\n<p>\nUsing a for loop in Python, we can quickly figure out the number of missing values in each column. As mentioned above, \"True\" represents a missing value and \"False\" means the value is present in the dataset. In the body of the for loop the method \".value_counts()\" counts the number of \"True\" values. \n</p>\n", "_____no_output_____" ] ], [ [ "for column in missing_data.columns.values.tolist():\n print(column)\n print (missing_data[column].value_counts())\n print(\"\") ", "symboling\nFalse 205\nName: symboling, dtype: int64\n\nnormalized-losses\nFalse 164\nTrue 41\nName: normalized-losses, dtype: int64\n\nmake\nFalse 205\nName: make, dtype: int64\n\nfuel-type\nFalse 205\nName: fuel-type, dtype: int64\n\naspiration\nFalse 205\nName: aspiration, dtype: int64\n\nnum-of-doors\nFalse 203\nTrue 2\nName: num-of-doors, dtype: int64\n\nbody-style\nFalse 205\nName: body-style, dtype: int64\n\ndrive-wheels\nFalse 205\nName: drive-wheels, dtype: int64\n\nengine-location\nFalse 205\nName: engine-location, dtype: int64\n\nwheel-base\nFalse 205\nName: wheel-base, dtype: int64\n\nlength\nFalse 205\nName: length, dtype: int64\n\nwidth\nFalse 205\nName: width, dtype: int64\n\nheight\nFalse 205\nName: height, dtype: int64\n\ncurb-weight\nFalse 205\nName: curb-weight, dtype: int64\n\nengine-type\nFalse 205\nName: engine-type, dtype: int64\n\nnum-of-cylinders\nFalse 205\nName: num-of-cylinders, dtype: int64\n\nengine-size\nFalse 205\nName: engine-size, dtype: int64\n\nfuel-system\nFalse 205\nName: fuel-system, dtype: int64\n\nbore\nFalse 201\nTrue 4\nName: bore, dtype: int64\n\nstroke\nFalse 201\nTrue 4\nName: stroke, dtype: int64\n\ncompression-ratio\nFalse 205\nName: compression-ratio, dtype: int64\n\nhorsepower\nFalse 203\nTrue 2\nName: horsepower, dtype: int64\n\npeak-rpm\nFalse 203\nTrue 2\nName: peak-rpm, dtype: int64\n\ncity-mpg\nFalse 205\nName: city-mpg, dtype: int64\n\nhighway-mpg\nFalse 205\nName: highway-mpg, dtype: int64\n\nprice\nFalse 201\nTrue 4\nName: price, dtype: int64\n\n" ] ], [ [ "Based on the summary above, each column has 205 rows of data and seven of the columns containing missing data:\n\n<ol>\n <li>\"normalized-losses\": 41 missing data</li>\n <li>\"num-of-doors\": 2 missing data</li>\n <li>\"bore\": 4 missing data</li>\n <li>\"stroke\" : 4 missing data</li>\n <li>\"horsepower\": 2 missing data</li>\n <li>\"peak-rpm\": 2 missing data</li>\n <li>\"price\": 4 missing data</li>\n</ol>\n", "_____no_output_____" ], [ "<h3 id=\"deal_missing_values\">Deal with missing data</h3>\n<b>How to deal with missing data?</b>\n\n<ol>\n <li>Drop data<br>\n a. Drop the whole row<br>\n b. Drop the whole column\n </li>\n <li>Replace data<br>\n a. Replace it by mean<br>\n b. Replace it by frequency<br>\n c. Replace it based on other functions\n </li>\n</ol>\n", "_____no_output_____" ], [ "Whole columns should be dropped only if most entries in the column are empty. In our dataset, none of the columns are empty enough to drop entirely.\nWe have some freedom in choosing which method to replace data; however, some methods may seem more reasonable than others. We will apply each method to many different columns:\n\n<b>Replace by mean:</b>\n\n<ul>\n <li>\"normalized-losses\": 41 missing data, replace them with mean</li>\n <li>\"stroke\": 4 missing data, replace them with mean</li>\n <li>\"bore\": 4 missing data, replace them with mean</li>\n <li>\"horsepower\": 2 missing data, replace them with mean</li>\n <li>\"peak-rpm\": 2 missing data, replace them with mean</li>\n</ul>\n\n<b>Replace by frequency:</b>\n\n<ul>\n <li>\"num-of-doors\": 2 missing data, replace them with \"four\". \n <ul>\n <li>Reason: 84% sedans is four doors. Since four doors is most frequent, it is most likely to occur</li>\n </ul>\n </li>\n</ul>\n\n<b>Drop the whole row:</b>\n\n<ul>\n <li>\"price\": 4 missing data, simply delete the whole row\n <ul>\n <li>Reason: price is what we want to predict. Any data entry without price data cannot be used for prediction; therefore any row now without price data is not useful to us</li>\n </ul>\n </li>\n</ul>\n", "_____no_output_____" ], [ "<h4>Calculate the mean value for the \"normalized-losses\" column </h4>\n", "_____no_output_____" ] ], [ [ "avg_norm_loss = df[\"normalized-losses\"].astype(\"float\").mean(axis=0)\nprint(\"Average of normalized-losses:\", avg_norm_loss)", "Average of normalized-losses: 122.0\n" ] ], [ [ "<h4>Replace \"NaN\" with mean value in \"normalized-losses\" column</h4>\n", "_____no_output_____" ] ], [ [ "df[\"normalized-losses\"].replace(np.nan, avg_norm_loss, inplace=True)", "_____no_output_____" ] ], [ [ "<h4>Calculate the mean value for the \"bore\" column</h4>\n", "_____no_output_____" ] ], [ [ "avg_bore=df['bore'].astype('float').mean(axis=0)\nprint(\"Average of bore:\", avg_bore)", "Average of bore: 3.3297512437810943\n" ] ], [ [ "<h4>Replace \"NaN\" with the mean value in the \"bore\" column</h4>\n", "_____no_output_____" ] ], [ [ "df[\"bore\"].replace(np.nan, avg_bore, inplace=True)", "_____no_output_____" ] ], [ [ "<div class=\"alert alert-danger alertdanger\" style=\"margin-top: 20px\">\n<h1> Question #1: </h1>\n\n<b>Based on the example above, replace NaN in \"stroke\" column with the mean value.</b>\n\n</div>\n", "_____no_output_____" ] ], [ [ "# Write your code below and press Shift+Enter to execute \navg_stroke=df['stroke'].astype('float').mean(axis=0)\nprint(\"Average of stroke:\", avg_bore)\ndf[\"stroke\"].replace(np.nan, avg_stroke, inplace=True)", "Average of stroke: 3.3297512437810943\n" ] ], [ [ "<details><summary>Click here for the solution</summary>\n\n```python\n#Calculate the mean vaule for \"stroke\" column\navg_stroke = df[\"stroke\"].astype(\"float\").mean(axis = 0)\nprint(\"Average of stroke:\", avg_stroke)\n\n# replace NaN by mean value in \"stroke\" column\ndf[\"stroke\"].replace(np.nan, avg_stroke, inplace = True)\n```\n\n</details>\n", "_____no_output_____" ], [ "<h4>Calculate the mean value for the \"horsepower\" column</h4>\n", "_____no_output_____" ] ], [ [ "avg_horsepower = df['horsepower'].astype('float').mean(axis=0)\nprint(\"Average horsepower:\", avg_horsepower)", "Average horsepower: 104.25615763546799\n" ] ], [ [ "<h4>Replace \"NaN\" with the mean value in the \"horsepower\" column</h4>\n", "_____no_output_____" ] ], [ [ "df['horsepower'].replace(np.nan, avg_horsepower, inplace=True)", "_____no_output_____" ] ], [ [ "<h4>Calculate the mean value for \"peak-rpm\" column</h4>\n", "_____no_output_____" ] ], [ [ "avg_peakrpm=df['peak-rpm'].astype('float').mean(axis=0)\nprint(\"Average peak rpm:\", avg_peakrpm)", "Average peak rpm: 5125.369458128079\n" ] ], [ [ "<h4>Replace \"NaN\" with the mean value in the \"peak-rpm\" column</h4>\n", "_____no_output_____" ] ], [ [ "df['peak-rpm'].replace(np.nan, avg_peakrpm, inplace=True)", "_____no_output_____" ] ], [ [ "To see which values are present in a particular column, we can use the \".value_counts()\" method:\n", "_____no_output_____" ] ], [ [ "df['num-of-doors'].value_counts()", "_____no_output_____" ] ], [ [ "We can see that four doors are the most common type. We can also use the \".idxmax()\" method to calculate the most common type automatically:\n", "_____no_output_____" ] ], [ [ "df['num-of-doors'].value_counts().idxmax()", "_____no_output_____" ] ], [ [ "The replacement procedure is very similar to what we have seen previously:\n", "_____no_output_____" ] ], [ [ "#replace the missing 'num-of-doors' values by the most frequent \ndf[\"num-of-doors\"].replace(np.nan, \"four\", inplace=True)", "_____no_output_____" ] ], [ [ "Finally, let's drop all rows that do not have price data:\n", "_____no_output_____" ] ], [ [ "# simply drop whole row with NaN in \"price\" column\ndf.dropna(subset=[\"price\"], axis=0, inplace=True)\n\n# reset index, because we droped two rows\ndf.reset_index(drop=True, inplace=True)", "_____no_output_____" ], [ "df.head()", "_____no_output_____" ] ], [ [ "<b>Good!</b> Now, we have a dataset with no missing values.\n", "_____no_output_____" ], [ "<h3 id=\"correct_data_format\">Correct data format</h3>\n<b>We are almost there!</b>\n<p>The last step in data cleaning is checking and making sure that all data is in the correct format (int, float, text or other).</p>\n\nIn Pandas, we use:\n\n<p><b>.dtype()</b> to check the data type</p>\n<p><b>.astype()</b> to change the data type</p>\n", "_____no_output_____" ], [ "<h4>Let's list the data types for each column</h4>\n", "_____no_output_____" ] ], [ [ "df.dtypes", "_____no_output_____" ] ], [ [ "<p>As we can see above, some columns are not of the correct data type. Numerical variables should have type 'float' or 'int', and variables with strings such as categories should have type 'object'. For example, 'bore' and 'stroke' variables are numerical values that describe the engines, so we should expect them to be of the type 'float' or 'int'; however, they are shown as type 'object'. We have to convert data types into a proper format for each column using the \"astype()\" method.</p> \n", "_____no_output_____" ], [ "<h4>Convert data types to proper format</h4>\n", "_____no_output_____" ] ], [ [ "df[[\"bore\", \"stroke\"]] = df[[\"bore\", \"stroke\"]].astype(\"float\")\ndf[[\"normalized-losses\"]] = df[[\"normalized-losses\"]].astype(\"int\")\ndf[[\"price\"]] = df[[\"price\"]].astype(\"float\")\ndf[[\"peak-rpm\"]] = df[[\"peak-rpm\"]].astype(\"float\")", "_____no_output_____" ] ], [ [ "<h4>Let us list the columns after the conversion</h4>\n", "_____no_output_____" ] ], [ [ "df.dtypes", "_____no_output_____" ] ], [ [ "<b>Wonderful!</b>\n\nNow we have finally obtained the cleaned dataset with no missing values with all data in its proper format.\n", "_____no_output_____" ], [ "<h2 id=\"data_standardization\">Data Standardization</h2>\n<p>\nData is usually collected from different agencies in different formats.\n(Data standardization is also a term for a particular type of data normalization where we subtract the mean and divide by the standard deviation.)\n</p>\n\n<b>What is standardization?</b>\n\n<p>Standardization is the process of transforming data into a common format, allowing the researcher to make the meaningful comparison.\n</p>\n\n<b>Example</b>\n\n<p>Transform mpg to L/100km:</p>\n<p>In our dataset, the fuel consumption columns \"city-mpg\" and \"highway-mpg\" are represented by mpg (miles per gallon) unit. Assume we are developing an application in a country that accepts the fuel consumption with L/100km standard.</p>\n<p>We will need to apply <b>data transformation</b> to transform mpg into L/100km.</p>\n", "_____no_output_____" ], [ "<p>The formula for unit conversion is:<p>\nL/100km = 235 / mpg\n<p>We can do many mathematical operations directly in Pandas.</p>\n", "_____no_output_____" ] ], [ [ "df.head()", "_____no_output_____" ], [ "# Convert mpg to L/100km by mathematical operation (235 divided by mpg)\ndf['city-L/100km'] = 235/df[\"city-mpg\"]\n\n# check your transformed data \ndf.head()", "_____no_output_____" ] ], [ [ "<div class=\"alert alert-danger alertdanger\" style=\"margin-top: 20px\">\n<h1> Question #2: </h1>\n\n<b>According to the example above, transform mpg to L/100km in the column of \"highway-mpg\" and change the name of column to \"highway-L/100km\".</b>\n\n</div>\n", "_____no_output_____" ] ], [ [ "# Write your code below and press Shift+Enter to execute \n# transform mpg to L/100km by mathematical operation (235 divided by mpg)\ndf[\"highway-mpg\"] = 235/df[\"highway-mpg\"]\n\n# rename column name from \"highway-mpg\" to \"highway-L/100km\"\ndf.rename(columns={'highway-mpg':'highway-L/100km'}, inplace=True)\n\n# check your transformed data \ndf.head()", "_____no_output_____" ] ], [ [ "<details><summary>Click here for the solution</summary>\n\n```python\n# transform mpg to L/100km by mathematical operation (235 divided by mpg)\ndf[\"highway-mpg\"] = 235/df[\"highway-mpg\"]\n\n# rename column name from \"highway-mpg\" to \"highway-L/100km\"\ndf.rename(columns={'\"highway-mpg\"':'highway-L/100km'}, inplace=True)\n\n# check your transformed data \ndf.head()\n\n```\n\n</details>\n", "_____no_output_____" ], [ "<h2 id=\"data_normalization\">Data Normalization</h2>\n\n<b>Why normalization?</b>\n\n<p>Normalization is the process of transforming values of several variables into a similar range. Typical normalizations include scaling the variable so the variable average is 0, scaling the variable so the variance is 1, or scaling the variable so the variable values range from 0 to 1.\n</p>\n\n<b>Example</b>\n\n<p>To demonstrate normalization, let's say we want to scale the columns \"length\", \"width\" and \"height\".</p>\n<p><b>Target:</b> would like to normalize those variables so their value ranges from 0 to 1</p>\n<p><b>Approach:</b> replace original value by (original value)/(maximum value)</p>\n", "_____no_output_____" ] ], [ [ "# replace (original value) by (original value)/(maximum value)\ndf['length'] = df['length']/df['length'].max()\ndf['width'] = df['width']/df['width'].max()", "_____no_output_____" ] ], [ [ "<div class=\"alert alert-danger alertdanger\" style=\"margin-top: 20px\">\n<h1> Question #3: </h1>\n\n<b>According to the example above, normalize the column \"height\".</b>\n\n</div>", "_____no_output_____" ] ], [ [ "# Write your code below and press Shift+Enter to execute \ndf['height'] = df['height']/df['height'].max()\n\n# show the scaled columns\ndf[[\"length\",\"width\",\"height\"]].head()", "_____no_output_____" ] ], [ [ "<details><summary>Click here for the solution</summary>\n\n```python\ndf['height'] = df['height']/df['height'].max() \n\n# show the scaled columns\ndf[[\"length\",\"width\",\"height\"]].head()\n\n\n```\n\n</details>\n", "_____no_output_____" ], [ "Here we can see we've normalized \"length\", \"width\" and \"height\" in the range of \\[0,1].\n", "_____no_output_____" ], [ "<h2 id=\"binning\">Binning</h2>\n<b>Why binning?</b>\n<p>\n Binning is a process of transforming continuous numerical variables into discrete categorical 'bins' for grouped analysis.\n</p>\n\n<b>Example: </b>\n\n<p>In our dataset, \"horsepower\" is a real valued variable ranging from 48 to 288 and it has 59 unique values. What if we only care about the price difference between cars with high horsepower, medium horsepower, and little horsepower (3 types)? Can we rearrange them into three ‘bins' to simplify analysis? </p>\n\n<p>We will use the pandas method 'cut' to segment the 'horsepower' column into 3 bins.</p>\n", "_____no_output_____" ], [ "<h3>Example of Binning Data In Pandas</h3>\n", "_____no_output_____" ], [ "Convert data to correct format:\n", "_____no_output_____" ] ], [ [ "df[\"horsepower\"]=df[\"horsepower\"].astype(int, copy=True)", "_____no_output_____" ] ], [ [ "Let's plot the histogram of horsepower to see what the distribution of horsepower looks like.\n", "_____no_output_____" ] ], [ [ "%matplotlib inline\nimport matplotlib as plt\nfrom matplotlib import pyplot\nplt.pyplot.hist(df[\"horsepower\"])\n\n# set x/y labels and plot title\nplt.pyplot.xlabel(\"horsepower\")\nplt.pyplot.ylabel(\"count\")\nplt.pyplot.title(\"horsepower bins\")", "_____no_output_____" ] ], [ [ "<p>We would like 3 bins of equal size bandwidth so we use numpy's <code>linspace(start_value, end_value, numbers_generated</code> function.</p>\n<p>Since we want to include the minimum value of horsepower, we want to set start_value = min(df[\"horsepower\"]).</p>\n<p>Since we want to include the maximum value of horsepower, we want to set end_value = max(df[\"horsepower\"]).</p>\n<p>Since we are building 3 bins of equal length, there should be 4 dividers, so numbers_generated = 4.</p>\n", "_____no_output_____" ], [ "We build a bin array with a minimum value to a maximum value by using the bandwidth calculated above. The values will determine when one bin ends and another begins.\n", "_____no_output_____" ] ], [ [ "bins = np.linspace(min(df[\"horsepower\"]), max(df[\"horsepower\"]), 4)\nbins", "_____no_output_____" ] ], [ [ "We set group names:\n", "_____no_output_____" ] ], [ [ "group_names = ['Low', 'Medium', 'High']", "_____no_output_____" ] ], [ [ "We apply the function \"cut\" to determine what each value of `df['horsepower']` belongs to.\n", "_____no_output_____" ] ], [ [ "df['horsepower-binned'] = pd.cut(df['horsepower'], bins, labels=group_names, include_lowest=True )\ndf[['horsepower','horsepower-binned']].head(20)", "_____no_output_____" ] ], [ [ "Let's see the number of vehicles in each bin:\n", "_____no_output_____" ] ], [ [ "df[\"horsepower-binned\"].value_counts()", "_____no_output_____" ] ], [ [ "Let's plot the distribution of each bin:\n", "_____no_output_____" ] ], [ [ "%matplotlib inline\nimport matplotlib as plt\nfrom matplotlib import pyplot\npyplot.bar(group_names, df[\"horsepower-binned\"].value_counts())\n\n# set x/y labels and plot title\nplt.pyplot.xlabel(\"horsepower\")\nplt.pyplot.ylabel(\"count\")\nplt.pyplot.title(\"horsepower bins\")", "_____no_output_____" ] ], [ [ "<p>\n Look at the dataframe above carefully. You will find that the last column provides the bins for \"horsepower\" based on 3 categories (\"Low\", \"Medium\" and \"High\"). \n</p>\n<p>\n We successfully narrowed down the intervals from 59 to 3!\n</p>\n", "_____no_output_____" ], [ "<h3>Bins Visualization</h3>\nNormally, a histogram is used to visualize the distribution of bins we created above. \n", "_____no_output_____" ] ], [ [ "%matplotlib inline\nimport matplotlib as plt\nfrom matplotlib import pyplot\n\n\n# draw historgram of attribute \"horsepower\" with bins = 3\nplt.pyplot.hist(df[\"horsepower\"], bins = 3)\n\n# set x/y labels and plot title\nplt.pyplot.xlabel(\"horsepower\")\nplt.pyplot.ylabel(\"count\")\nplt.pyplot.title(\"horsepower bins\")", "_____no_output_____" ] ], [ [ "The plot above shows the binning result for the attribute \"horsepower\".\n", "_____no_output_____" ], [ "<h2 id=\"indicator\">Indicator Variable (or Dummy Variable)</h2>\n<b>What is an indicator variable?</b>\n<p>\n An indicator variable (or dummy variable) is a numerical variable used to label categories. They are called 'dummies' because the numbers themselves don't have inherent meaning. \n</p>\n\n<b>Why we use indicator variables?</b>\n\n<p>\n We use indicator variables so we can use categorical variables for regression analysis in the later modules.\n</p>\n<b>Example</b>\n<p>\n We see the column \"fuel-type\" has two unique values: \"gas\" or \"diesel\". Regression doesn't understand words, only numbers. To use this attribute in regression analysis, we convert \"fuel-type\" to indicator variables.\n</p>\n\n<p>\n We will use pandas' method 'get_dummies' to assign numerical values to different categories of fuel type. \n</p>\n", "_____no_output_____" ] ], [ [ "df.columns", "_____no_output_____" ] ], [ [ "Get the indicator variables and assign it to data frame \"dummy_variable\\_1\":\n", "_____no_output_____" ] ], [ [ "dummy_variable_1 = pd.get_dummies(df[\"fuel-type\"])\ndummy_variable_1.head()", "_____no_output_____" ] ], [ [ "Change the column names for clarity:\n", "_____no_output_____" ] ], [ [ "dummy_variable_1.rename(columns={'gas':'fuel-type-gas', 'diesel':'fuel-type-diesel'}, inplace=True)\ndummy_variable_1.head()", "_____no_output_____" ] ], [ [ "In the dataframe, column 'fuel-type' has values for 'gas' and 'diesel' as 0s and 1s now.\n", "_____no_output_____" ] ], [ [ "# merge data frame \"df\" and \"dummy_variable_1\" \ndf = pd.concat([df, dummy_variable_1], axis=1)\n\n# drop original column \"fuel-type\" from \"df\"\ndf.drop(\"fuel-type\", axis = 1, inplace=True)", "_____no_output_____" ], [ "df.head()", "_____no_output_____" ] ], [ [ "The last two columns are now the indicator variable representation of the fuel-type variable. They're all 0s and 1s now.\n", "_____no_output_____" ], [ "<div class=\"alert alert-danger alertdanger\" style=\"margin-top: 20px\">\n<h1> Question #4: </h1>\n\n<b>Similar to before, create an indicator variable for the column \"aspiration\"</b>\n\n</div>\n", "_____no_output_____" ] ], [ [ "# Write your code below and press Shift+Enter to execute \n# get indicator variables of aspiration and assign it to data frame \"dummy_variable_2\"\ndummy_variable_2 = pd.get_dummies(df['aspiration'])\n\n# change column names for clarity\ndummy_variable_2.rename(columns={'std':'aspiration-std', 'turbo': 'aspiration-turbo'}, inplace=True)\n\n# show first 5 instances of data frame \"dummy_variable_1\"\ndummy_variable_2.head()", "_____no_output_____" ] ], [ [ "<details><summary>Click here for the solution</summary>\n\n```python\n# get indicator variables of aspiration and assign it to data frame \"dummy_variable_2\"\ndummy_variable_2 = pd.get_dummies(df['aspiration'])\n\n# change column names for clarity\ndummy_variable_2.rename(columns={'std':'aspiration-std', 'turbo': 'aspiration-turbo'}, inplace=True)\n\n# show first 5 instances of data frame \"dummy_variable_1\"\ndummy_variable_2.head()\n\n\n```\n\n</details>\n", "_____no_output_____" ], [ " <div class=\"alert alert-danger alertdanger\" style=\"margin-top: 20px\">\n<h1> Question #5: </h1>\n\n<b>Merge the new dataframe to the original dataframe, then drop the column 'aspiration'.</b>\n\n</div>\n", "_____no_output_____" ] ], [ [ "# Write your code below and press Shift+Enter to execute \n# merge the new dataframe to the original datafram\ndf = pd.concat([df, dummy_variable_2], axis=1)\n\n# drop original column \"aspiration\" from \"df\"\ndf.drop('aspiration', axis = 1, inplace=True)", "_____no_output_____" ] ], [ [ "<details><summary>Click here for the solution</summary>\n\n```python\n# merge the new dataframe to the original datafram\ndf = pd.concat([df, dummy_variable_2], axis=1)\n\n# drop original column \"aspiration\" from \"df\"\ndf.drop('aspiration', axis = 1, inplace=True)\n\n\n```\n\n</details>\n", "_____no_output_____" ], [ "Save the new csv:\n", "_____no_output_____" ] ], [ [ "df.to_csv('clean_df.csv')", "_____no_output_____" ] ], [ [ "### Thank you for completing this lab!\n\n## Author\n\n<a href=\"https://www.linkedin.com/in/joseph-s-50398b136/?utm_medium=Exinfluencer&utm_source=Exinfluencer&utm_content=000026UJ&utm_term=10006555&utm_id=NA-SkillsNetwork-Channel-SkillsNetworkCoursesIBMDeveloperSkillsNetworkDA0101ENSkillsNetwork20235326-2021-01-01\" target=\"_blank\">Joseph Santarcangelo</a>\n\n### Other Contributors\n\n<a href=\"https://www.linkedin.com/in/mahdi-noorian-58219234/?utm_medium=Exinfluencer&utm_source=Exinfluencer&utm_content=000026UJ&utm_term=10006555&utm_id=NA-SkillsNetwork-Channel-SkillsNetworkCoursesIBMDeveloperSkillsNetworkDA0101ENSkillsNetwork20235326-2021-01-01\" target=\"_blank\">Mahdi Noorian PhD</a>\n\nBahare Talayian\n\nEric Xiao\n\nSteven Dong\n\nParizad\n\nHima Vasudevan\n\n<a href=\"https://www.linkedin.com/in/fiorellawever/?utm_medium=Exinfluencer&utm_source=Exinfluencer&utm_content=000026UJ&utm_term=10006555&utm_id=NA-SkillsNetwork-Channel-SkillsNetworkCoursesIBMDeveloperSkillsNetworkDA0101ENSkillsNetwork20235326-2021-01-01\" target=\"_blank\">Fiorella Wenver</a>\n\n<a href=\"https:// https://www.linkedin.com/in/yi-leng-yao-84451275/ \" target=\"_blank\" >Yi Yao</a>.\n\n## Change Log\n\n| Date (YYYY-MM-DD) | Version | Changed By | Change Description |\n| ----------------- | ------- | ---------- | ----------------------------------- |\n| 2020-10-30 | 2.2 | Lakshmi | Changed URL of csv |\n| 2020-09-09 | 2.1 | Lakshmi | Updated Indicator Variables section |\n| 2020-08-27 | 2.0 | Lavanya | Moved lab to course repo in GitLab |\n\n<hr>\n\n## <h3 align=\"center\"> © IBM Corporation 2020. All rights reserved. <h3/>\n", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ] ]
4a0cfc900dbfce4b184ba5cdee28b628ea22f6b8
67,453
ipynb
Jupyter Notebook
notebooks/monte_carlo_dev/test_oil_capacity.ipynb
MIDOSS/analysis-rachael
c4a3082eca53b49e358e86a6e623a359ca6668be
[ "Apache-2.0" ]
null
null
null
notebooks/monte_carlo_dev/test_oil_capacity.ipynb
MIDOSS/analysis-rachael
c4a3082eca53b49e358e86a6e623a359ca6668be
[ "Apache-2.0" ]
3
2020-07-03T17:07:04.000Z
2020-07-07T16:09:53.000Z
notebooks/monte_carlo_dev/test_oil_capacity.ipynb
MIDOSS/analysis-rachael
c4a3082eca53b49e358e86a6e623a359ca6668be
[ "Apache-2.0" ]
null
null
null
191.084986
18,088
0.899545
[ [ [ "import numpy\nimport matplotlib.pyplot as plt", "_____no_output_____" ] ], [ [ "## Plot up tanker fuel capacity by vessel length", "_____no_output_____" ] ], [ [ "# SuezMax: 5986.7 m3 (4,025/130 m3 for HFO/diesel)\n# Aframax: 2,984 m3 (2,822/162 for HFO/diesel)\n# Handymax as 1,956 m3 (1,826/130 m3 for HFO/diesel)\n# Small Tanker: 740 m3 (687/53 for HFO/diesel)\n \n# SuezMax (281 m)\n# Aframax (201-250 m)\n# Handymax (182 m)\n# Small Tanker (< 150 m)\n\ntanker_size_classes = [\n 'SuezMax (251-300 m)', \n 'Aframax (201-250 m)', \n 'Handymax (151-200 m)', \n 'Small Tanker (< 150 m)'\n]\nfuel_hfo_to_diesel = [\n 4025/130, 2822/162, 1826/130, 687/53\n]\ncapacity = numpy.array([\n 740000, 1956000, 2984000, 5986000.7, \n])\nlength = numpy.array([108.5, 182, 247.24, 281])", "_____no_output_____" ], [ "coef3 = numpy.polyfit(length, capacity, 3)", "_____no_output_____" ], [ "fit = (\n coef3[3] + \n coef3[2]*length + \n coef3[1]*numpy.power(length,2) + \n coef3[0]*numpy.power(length,3)\n)", "_____no_output_____" ], [ "numpy.array(fit.tolist())", "_____no_output_____" ], [ "test_length = range(50, 320, 25)\nfit = (\n coef3[3] + \n coef3[2]*test_length + \n coef3[1]*numpy.power(test_length,2) + \n coef3[0]*numpy.power(test_length,3)\n)", "_____no_output_____" ], [ "## plot fit\nfig1 = plt.figure() \nax1 = fig1.add_subplot(111) \nax1.scatter(length[:], capacity[:],50) \nax1.plot(test_length, fit) \nplt.xlabel('tanker length (m)',fontsize=12)\nplt.ylabel('tanker fuel capacity (liters)',fontsize=12)\nplt.show()", "_____no_output_____" ] ], [ [ "## plot up tank barge oil capacity \nfrom values in our [MMSI spreadsheet](https://docs.google.com/spreadsheets/d/1dlT0JydkFG43LorqgtHle5IN6caRYjf_3qLrUYqANDY/edit#gid=591561201)", "_____no_output_____" ] ], [ [ "harley_cargo_legths = [\n 65.3796, 73.4568,\n 73.4568,73.4568,\n 74.676, 83.8962,\n 85.0392, 86.868,\n 90.678, 108.5088, \n 114.3, 128.4732,\n 128.7018, 128.7018, \n 130.5306, 130.5306,\n 130.5306\n]\n\nharley_cargo_capacity = [\n 2544952.93, 5159066.51, \n 5195793.20, 5069714.13,\n 3973955.05, 3461689.27,\n 6197112.22, 7685258.62,\n 4465075.16, 5609803.16,\n 12652106.22, 12791381.46,\n 13315412.50, 13315412.50,\n 13041790.71, 13009356.75,\n 13042744.65\n]\n\nharley_volume_per_hold = [\n 254495.293, 573229.6122,\n 577310.3556, 563301.57,\n 397395.505, 247263.5193, \n 476700.94, 548947.0443,\n 744179.1933, 560980.316,\n 903721.8729, 913670.1043, \n 1109617.708, 1109617.708, \n 931556.4793, 929239.7679,\n 931624.6179\n]\n\nC = numpy.polyfit(\n harley_cargo_legths, \n harley_cargo_capacity, \n 3\n) \n\ntest_length = range(65,135,5)\nharley_cargo_fit = ( \n C[3] + C[2]*test_length + \n C[1]*numpy.power(test_length,2) + \n C[0]*numpy.power(test_length,3)\n)\n\n\n## plot fit\nfig2 = plt.figure() \nax1 = fig2.add_subplot(111) \nax1.scatter(harley_cargo_legths[:], harley_cargo_capacity[:],50) \nax1.plot(test_length, harley_cargo_fit) \nplt.xlabel('cargo tank length (m)',fontsize=12)\nplt.ylabel('cargo tank capacity (liters)',fontsize=12)\nplt.show()\n\n## plot volume per hold\nfig3 = plt.figure()\nax1 = fig3.add_subplot(111) \nax1.scatter(harley_cargo_legths[:], harley_volume_per_hold[:],50) \nplt.xlabel('cargo tank length (m)',fontsize=12)\nplt.ylabel('cargo volume per hold (liters)',fontsize=12)\nplt.show()", "_____no_output_____" ], [ "test_length", "_____no_output_____" ] ], [ [ "### plot up tug barge fuel capacity\nfrom values in our [MMSI spreadsheet](https://docs.google.com/spreadsheets/d/1dlT0JydkFG43LorqgtHle5IN6caRYjf_3qLrUYqANDY/edit#gid=591561201)", "_____no_output_____" ] ], [ [ "tug_length = [\n 33.92424, 33.92424,\n 33.92424, 32.06496,\n 38.34384, 41.4528,\n 41.45\n]\ntug_fuel_capacity = [\n 101383.00, 383776.22,\n 378541.00, 302832.80,\n 545099.04, 567811.50,\n 300000.00\n]\n\n## plot fit\nfig4 = plt.figure() \nax1 = fig4.add_subplot(111) \nax1.scatter(tug_length[:], tug_fuel_capacity[:],50) \nplt.xlabel('tug length (m)',fontsize=12)\nplt.ylabel('tug fuel capacity (liters)',fontsize=12)\nplt.show()\n\n", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ] ]
4a0cfe62922a4d5a8d10341bc133f5c57fec64e7
123,185
ipynb
Jupyter Notebook
dog_app.ipynb
TheGeekiestOne/Dog-Breed-CNN-Classifier
2bae38288f58cb0a53a3dcf062eab9a7ba90a941
[ "MIT" ]
null
null
null
dog_app.ipynb
TheGeekiestOne/Dog-Breed-CNN-Classifier
2bae38288f58cb0a53a3dcf062eab9a7ba90a941
[ "MIT" ]
null
null
null
dog_app.ipynb
TheGeekiestOne/Dog-Breed-CNN-Classifier
2bae38288f58cb0a53a3dcf062eab9a7ba90a941
[ "MIT" ]
null
null
null
101.721718
72,220
0.818257
[ [ [ "# Convolutional Neural Networks\n\n## Project: Write an Algorithm for a Dog Identification App \n\n---\n\nIn this notebook, some template code has already been provided for you, and you will need to implement additional functionality to successfully complete this project. You will not need to modify the included code beyond what is requested. Sections that begin with **'(IMPLEMENTATION)'** in the header indicate that the following block of code will require additional functionality which you must provide. Instructions will be provided for each section, and the specifics of the implementation are marked in the code block with a 'TODO' statement. Please be sure to read the instructions carefully! \n\n> **Note**: Once you have completed all of the code implementations, you need to finalize your work by exporting the Jupyter Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to **File -> Download as -> HTML (.html)**. Include the finished document along with this notebook as your submission.\n\nIn addition to implementing code, there will be questions that you must answer which relate to the project and your implementation. Each section where you will answer a question is preceded by a **'Question X'** header. Carefully read each question and provide thorough answers in the following text boxes that begin with **'Answer:'**. Your project submission will be evaluated based on your answers to each of the questions and the implementation you provide.\n\n>**Note:** Code and Markdown cells can be executed using the **Shift + Enter** keyboard shortcut. Markdown cells can be edited by double-clicking the cell to enter edit mode.\n\nThe rubric contains _optional_ \"Stand Out Suggestions\" for enhancing the project beyond the minimum requirements. If you decide to pursue the \"Stand Out Suggestions\", you should include the code in this Jupyter notebook.\n\n\n\n---\n### Why We're Here \n\nIn this notebook, you will make the first steps towards developing an algorithm that could be used as part of a mobile or web app. At the end of this project, your code will accept any user-supplied image as input. If a dog is detected in the image, it will provide an estimate of the dog's breed. If a human is detected, it will provide an estimate of the dog breed that is most resembling. The image below displays potential sample output of your finished project (... but we expect that each student's algorithm will behave differently!). \n\n![Sample Dog Output](images/sample_dog_output.png)\n\nIn this real-world setting, you will need to piece together a series of models to perform different tasks; for instance, the algorithm that detects humans in an image will be different from the CNN that infers dog breed. There are many points of possible failure, and no perfect algorithm exists. Your imperfect solution will nonetheless create a fun user experience!\n\n### The Road Ahead\n\nWe break the notebook into separate steps. Feel free to use the links below to navigate the notebook.\n\n* [Step 0](#step0): Import Datasets\n* [Step 1](#step1): Detect Humans\n* [Step 2](#step2): Detect Dogs\n* [Step 3](#step3): Create a CNN to Classify Dog Breeds (from Scratch)\n* [Step 4](#step4): Create a CNN to Classify Dog Breeds (using Transfer Learning)\n* [Step 5](#step5): Write your Algorithm\n* [Step 6](#step6): Test Your Algorithm\n\n---\n<a id='step0'></a>\n## Step 0: Import Datasets\n\nMake sure that you've downloaded the required human and dog datasets:\n* Download the [dog dataset](https://s3-us-west-1.amazonaws.com/udacity-aind/dog-project/dogImages.zip). Unzip the folder and place it in this project's home directory, at the location `/dogImages`. \n\n* Download the [human dataset](https://s3-us-west-1.amazonaws.com/udacity-aind/dog-project/lfw.zip). Unzip the folder and place it in the home directory, at location `/lfw`. \n\n*Note: If you are using a Windows machine, you are encouraged to use [7zip](http://www.7-zip.org/) to extract the folder.*\n\nIn the code cell below, we save the file paths for both the human (LFW) dataset and dog dataset in the numpy arrays `human_files` and `dog_files`.", "_____no_output_____" ] ], [ [ "import numpy as np\nfrom glob import glob\n\n# load filenames for human and dog images\nhuman_files = np.array(glob(\"lfw/*/*\"))\ndog_files = np.array(glob(\"dogImages/*/*/*\"))\n\n# print number of images in each dataset\nprint('There are %d total human images.' % len(human_files))\nprint('There are %d total dog images.' % len(dog_files))", "There are 13233 total human images.\nThere are 8351 total dog images.\n" ] ], [ [ "<a id='step1'></a>\n## Step 1: Detect Humans\n\nIn this section, we use OpenCV's implementation of [Haar feature-based cascade classifiers](http://docs.opencv.org/trunk/d7/d8b/tutorial_py_face_detection.html) to detect human faces in images. \n\nOpenCV provides many pre-trained face detectors, stored as XML files on [github](https://github.com/opencv/opencv/tree/master/data/haarcascades). We have downloaded one of these detectors and stored it in the `haarcascades` directory. In the next code cell, we demonstrate how to use this detector to find human faces in a sample image.", "_____no_output_____" ] ], [ [ "import cv2 \nimport matplotlib.pyplot as plt \n%matplotlib inline \n\n# extract pre-trained face detector\nface_cascade = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_alt.xml')\n\n# load color (BGR) image\nimg = cv2.imread(human_files[0])\n# convert BGR image to gzrayscale\ngray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n# find faces in image\nfaces = face_cascade.detectMultiScale(gray)\n\n# print number of faces detected in the image\nprint('Number of faces detected:', len(faces))\n\n# get bounding box for each detected face\nfor (x,y,w,h) in faces:\n # add bounding box to color image\n cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)\n \n# convert BGR image to RGB for plotting\ncv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n\n# display the image, along with bounding box\nplt.imshow(cv_rgb)\nplt.show()", "Number of faces detected: 1\n" ] ], [ [ "Before using any of the face detectors, it is standard procedure to convert the images to grayscale. The `detectMultiScale` function executes the classifier stored in `face_cascade` and takes the grayscale image as a parameter. \n\nIn the above code, `faces` is a numpy array of detected faces, where each row corresponds to a detected face. Each detected face is a 1D array with four entries that specifies the bounding box of the detected face. The first two entries in the array (extracted in the above code as `x` and `y`) specify the horizontal and vertical positions of the top left corner of the bounding box. The last two entries in the array (extracted here as `w` and `h`) specify the width and height of the box.\n\n### Write a Human Face Detector\n\nWe can use this procedure to write a function that returns `True` if a human face is detected in an image and `False` otherwise. This function, aptly named `face_detector`, takes a string-valued file path to an image as input and appears in the code block below.", "_____no_output_____" ] ], [ [ "# returns \"True\" if face is detected in image stored at img_path\ndef face_detector(img_path):\n img = cv2.imread(img_path)\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n faces = face_cascade.detectMultiScale(gray)\n return len(faces) > 0", "_____no_output_____" ] ], [ [ "### (IMPLEMENTATION) Assess the Human Face Detector\n\n__Question 1:__ Use the code cell below to test the performance of the `face_detector` function. \n- What percentage of the first 100 images in `human_files` have a detected human face? \n- What percentage of the first 100 images in `dog_files` have a detected human face? \n\nIdeally, we would like 100% of human images with a detected face and 0% of dog images with a detected face. You will see that our algorithm falls short of this goal, but still gives acceptable performance. We extract the file paths for the first 100 images from each of the datasets and store them in the numpy arrays `human_files_short` and `dog_files_short`.", "_____no_output_____" ], [ "__Answer:__ \n(You can print out your results and/or write your percentages in this cell)", "_____no_output_____" ] ], [ [ "from tqdm import tqdm\n\nhuman_files_short = human_files[:100]\ndog_files_short = dog_files[:100]\n\n#-#-# Do NOT modify the code above this line. #-#-#\n\n## TODO: Test the performance of the face_detector algorithm \n## on the images in human_files_short and dog_files_short.\n\ndef face_detector_accuracy(face_array):\n face_detected=0\n for faces in face_array:\n face_flag=face_detector(faces)\n if face_flag==True:\n face_detected += 1\n return face_detected/len(face_array)*100\nprint('Human faces detected by Percentage in humans:', face_detector_accuracy(human_files_short)) \nprint('Hhuman faces detected by Percentage in dogs:', face_detector_accuracy(dog_files_short))", "Human faces detected by Percentage in humans: 96.0\nHhuman faces detected by Percentage in dogs: 18.0\n" ] ], [ [ "We suggest the face detector from OpenCV as a potential way to detect human images in your algorithm, but you are free to explore other approaches, especially approaches that make use of deep learning :). Please use the code cell below to design and test your own face detection algorithm. If you decide to pursue this _optional_ task, report performance on `human_files_short` and `dog_files_short`.", "_____no_output_____" ] ], [ [ "### (Optional) \n### TODO: Test performance of another face detection algorithm.\n### Feel free to use as many code cells as needed.", "_____no_output_____" ] ], [ [ "---\n<a id='step2'></a>\n## Step 2: Detect Dogs\n\nIn this section, we use a [pre-trained model](http://pytorch.org/docs/master/torchvision/models.html) to detect dogs in images. \n\n### Obtain Pre-trained VGG-16 Model\n\nThe code cell below downloads the VGG-16 model, along with weights that have been trained on [ImageNet](http://www.image-net.org/), a very large, very popular dataset used for image classification and other vision tasks. ImageNet contains over 10 million URLs, each linking to an image containing an object from one of [1000 categories](https://gist.github.com/yrevar/942d3a0ac09ec9e5eb3a). ", "_____no_output_____" ] ], [ [ "import torch\nimport torchvision.models as models\n\n# define VGG16 model\nVGG16 = models.vgg16(pretrained=True)\n\n# check if CUDA is available\nuse_cuda = torch.cuda.is_available()\n\n# move model to GPU if CUDA is available\nif use_cuda:\n VGG16 = VGG16.cuda()", "Downloading: \"https://download.pytorch.org/models/vgg16-397923af.pth\" to C:\\Users\\The Geekiest One/.cache\\torch\\checkpoints\\vgg16-397923af.pth\n100%|███████████████████████████████████████████████████████████████████████████████| 528M/528M [00:27<00:00, 20.1MB/s]\n" ] ], [ [ "Given an image, this pre-trained VGG-16 model returns a prediction (derived from the 1000 possible categories in ImageNet) for the object that is contained in the image.", "_____no_output_____" ], [ "### (IMPLEMENTATION) Making Predictions with a Pre-trained Model\n\nIn the next code cell, you will write a function that accepts a path to an image (such as `'dogImages/train/001.Affenpinscher/Affenpinscher_00001.jpg'`) as input and returns the index corresponding to the ImageNet class that is predicted by the pre-trained VGG-16 model. The output should always be an integer between 0 and 999, inclusive.\n\nBefore writing the function, make sure that you take the time to learn how to appropriately pre-process tensors for pre-trained models in the [PyTorch documentation](http://pytorch.org/docs/stable/torchvision/models.html).", "_____no_output_____" ] ], [ [ "from PIL import Image\nimport torchvision.transforms as transforms\n\n# Set PIL to be tolerant of image files that are truncated.\nfrom PIL import ImageFile\nImageFile.LOAD_TRUNCATED_IMAGES = True\n\ndef VGG16_predict(img_path):\n '''\n Use pre-trained VGG-16 model to obtain index corresponding to \n predicted ImageNet class for image at specified path\n \n Args:\n img_path: path to an image\n \n Returns:\n Index corresponding to VGG-16 model's prediction\n '''\n \n ## TODO: Complete the function.\n ## Load and pre-process an image from the given img_path\n ## Return the *index* of the predicted class for that image\n image = Image.open(img_path)\n mean=[0.485, 0.456, 0.406]\n std=[0.229, 0.224, 0.225]\n image_transforms = transforms.Compose([transforms.Resize(256),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize(mean,std)])\n image_tensor = image_transforms(image)\n image_tensor.unsqueeze_(0)\n if use_cuda:\n image_tensor=image_tensor.cuda()\n output = VGG16(image_tensor)\n _,classes= torch.max(output,dim=1)\n return classes.item() # predicted class index", "_____no_output_____" ] ], [ [ "### (IMPLEMENTATION) Write a Dog Detector\n\nWhile looking at the [dictionary](https://gist.github.com/yrevar/942d3a0ac09ec9e5eb3a), you will notice that the categories corresponding to dogs appear in an uninterrupted sequence and correspond to dictionary keys 151-268, inclusive, to include all categories from `'Chihuahua'` to `'Mexican hairless'`. Thus, in order to check to see if an image is predicted to contain a dog by the pre-trained VGG-16 model, we need only check if the pre-trained model predicts an index between 151 and 268 (inclusive).\n\nUse these ideas to complete the `dog_detector` function below, which returns `True` if a dog is detected in an image (and `False` if not).", "_____no_output_____" ] ], [ [ "### returns \"True\" if a dog is detected in the image stored at img_path\ndef dog_detector(img_path):\n ## TODO: Complete the function.\n class_dog=VGG16_predict(img_path)\n return class_dog >= 151 and class_dog <=268 # true/false", "_____no_output_____" ] ], [ [ "### (IMPLEMENTATION) Assess the Dog Detector\n\n__Question 2:__ Use the code cell below to test the performance of your `dog_detector` function. \n- What percentage of the images in `human_files_short` have a detected dog? \n- What percentage of the images in `dog_files_short` have a detected dog?", "_____no_output_____" ], [ "__Answer:__ \n", "_____no_output_____" ] ], [ [ "### TODO: Test the performance of the dog_detector function\n### on the images in human_files_short and dog_files_short.\nfrom tqdm import tqdm\n\nhuman_files_short = human_files[:100]\ndog_files_short = dog_files[:100]\n\n\ndog_percentage_human = 0\ndog_percentage_dog = 0\nfor i in tqdm(range(100)):\n dog_percentage_human += int (dog_detector(human_files_short[i]))\n dog_percentage_dog += int (dog_detector(dog_files_short[i]))\nprint ('Dog Percentage in Human dataset:{} % \\t Dog Percentage in Dog Dataset:{} %'.format(dog_percentage_human,dog_percentage_dog))", "100%|████████████████████████████████████████████████████████████████████████████████| 100/100 [00:05<00:00, 17.33it/s]" ] ], [ [ "We suggest VGG-16 as a potential network to detect dog images in your algorithm, but you are free to explore other pre-trained networks (such as [Inception-v3](http://pytorch.org/docs/master/torchvision/models.html#inception-v3), [ResNet-50](http://pytorch.org/docs/master/torchvision/models.html#id3), etc). Please use the code cell below to test other pre-trained PyTorch models. If you decide to pursue this _optional_ task, report performance on `human_files_short` and `dog_files_short`.", "_____no_output_____" ] ], [ [ "### (Optional) \n### TODO: Report the performance of another pre-trained network.\n### Feel free to use as many code cells as needed.\n\nresnet50 = models.resnet50(pretrained=True)\nif use_cuda:\n resnet50.cuda()\ndef resnet50_predict(img_path):\n image = Image.open(img_path)\n mean=[0.485, 0.456, 0.406]\n std=[0.229, 0.224, 0.225]\n image_transforms = transforms.Compose([transforms.Resize(256),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n transforms.Normalize(mean,std)])\n image_tensor = image_transforms(image)\n image_tensor.unsqueeze_(0)\n if use_cuda:\n image_tensor=image_tensor.cuda()\n resnet50.eval()\n output = resnet50(image_tensor)\n _,classes = torch.max(output,dim=1)\n return classes.item()", "Downloading: \"https://download.pytorch.org/models/resnet50-19c8e357.pth\" to C:\\Users\\The Geekiest One/.cache\\torch\\checkpoints\\resnet50-19c8e357.pth\n100%|█████████████████████████████████████████████████████████████████████████████| 97.8M/97.8M [00:04<00:00, 22.8MB/s]\n" ], [ "def resnet50_dog_detector(image_path):\n class_idx = resnet50_predict(image_path)\n return class_idx >= 151 and class_idx <=268", "_____no_output_____" ], [ "\nfrom tqdm import tqdm\n\nhuman_files_short = human_files[:1000]\ndog_files_short = dog_files[:10000]\n\ndog_percentage_human = 0\ndog_percentage_dog = 0\nfor i in tqdm(range(1000)):\n dog_percentage_human += int (resnet50_dog_detector(human_files_short[i]))\n dog_percentage_dog += int (resnet50_dog_detector(dog_files_short[i]))\nprint ('Dog Percentage in Human dataset:{} % \\t Dog Percentage in Dog Dataset:{} %'.format(dog_percentage_human,dog_percentage_dog))", "100%|██████████████████████████████████████████████████████████████████████████████| 1000/1000 [01:12<00:00, 13.84it/s]" ], [ "\nfrom tqdm import tqdm\n\nhuman_files_short = human_files[:100]\ndog_files_short = dog_files[:100]\n\ndog_percentage_human = 0\ndog_percentage_dog = 0\nfor i in tqdm(range(100)):\n dog_percentage_human += int (resnet50_dog_detector(human_files_short[i]))\n dog_percentage_dog += int (resnet50_dog_detector(dog_files_short[i]))\nprint ('Dog Percentage in Human dataset:{} % \\t Dog Percentage in Dog Dataset:{} %'.format(dog_percentage_human,dog_percentage_dog))", "100%|████████████████████████████████████████████████████████████████████████████████| 100/100 [00:05<00:00, 18.02it/s]" ] ], [ [ "---\n<a id='step3'></a>\n## Step 3: Create a CNN to Classify Dog Breeds (from Scratch)\n\nNow that we have functions for detecting humans and dogs in images, we need a way to predict breed from images. In this step, you will create a CNN that classifies dog breeds. You must create your CNN _from scratch_ (so, you can't use transfer learning _yet_!), and you must attain a test accuracy of at least 10%. In Step 4 of this notebook, you will have the opportunity to use transfer learning to create a CNN that attains greatly improved accuracy.\n\nWe mention that the task of assigning breed to dogs from images is considered exceptionally challenging. To see why, consider that *even a human* would have trouble distinguishing between a Brittany and a Welsh Springer Spaniel. \n\nBrittany | Welsh Springer Spaniel\n- | - \n<img src=\"images/Brittany_02625.jpg\" width=\"100\"> | <img src=\"images/Welsh_springer_spaniel_08203.jpg\" width=\"200\">\n\nIt is not difficult to find other dog breed pairs with minimal inter-class variation (for instance, Curly-Coated Retrievers and American Water Spaniels). \n\nCurly-Coated Retriever | American Water Spaniel\n- | -\n<img src=\"images/Curly-coated_retriever_03896.jpg\" width=\"200\"> | <img src=\"images/American_water_spaniel_00648.jpg\" width=\"200\">\n\n\nLikewise, recall that labradors come in yellow, chocolate, and black. Your vision-based algorithm will have to conquer this high intra-class variation to determine how to classify all of these different shades as the same breed. \n\nYellow Labrador | Chocolate Labrador | Black Labrador\n- | -\n<img src=\"images/Labrador_retriever_06457.jpg\" width=\"150\"> | <img src=\"images/Labrador_retriever_06455.jpg\" width=\"240\"> | <img src=\"images/Labrador_retriever_06449.jpg\" width=\"220\">\n\nWe also mention that random chance presents an exceptionally low bar: setting aside the fact that the classes are slightly imabalanced, a random guess will provide a correct answer roughly 1 in 133 times, which corresponds to an accuracy of less than 1%. \n\nRemember that the practice is far ahead of the theory in deep learning. Experiment with many different architectures, and trust your intuition. And, of course, have fun!\n\n### (IMPLEMENTATION) Specify Data Loaders for the Dog Dataset\n\nUse the code cell below to write three separate [data loaders](http://pytorch.org/docs/stable/data.html#torch.utils.data.DataLoader) for the training, validation, and test datasets of dog images (located at `dogImages/train`, `dogImages/valid`, and `dogImages/test`, respectively). You may find [this documentation on custom datasets](http://pytorch.org/docs/stable/torchvision/datasets.html) to be a useful resource. If you are interested in augmenting your training and/or validation data, check out the wide variety of [transforms](http://pytorch.org/docs/stable/torchvision/transforms.html?highlight=transform)!", "_____no_output_____" ] ], [ [ "\nimport numpy as np\nfrom glob import glob\nfrom tqdm import tqdm\nfrom tqdm import tqdm\nimport cv2\ndef get_train_set_info():\n dog_files_train = np.array(glob(\"/data/dog_images/train/*/*\"))\n mean = np.array([0.,0.,0.])\n std = np.array([0.,0.,0.])\n for i in tqdm(range(len(dog_files_train))):\n image=cv2.imread(dog_files_train[i])\n image = cv2.cvtColor(image,cv2.COLOR_BGR2RGB)\n image = image/255.0\n mean[0] += np.mean(image[:,:,0])\n mean[1] += np.mean(image[:,:,1])\n mean[2] += np.mean(image[:,:,2])\n std[0] += np.std(image[:,:,0])\n std[1] += np.std(image[:,:,1])\n std[2] += np.std(image[:,:,2])\n mean = mean/len(dog_files_train)\n std = std/len(dog_files_train)\n return mean,std", "_____no_output_____" ], [ "mean_train_set,std_train_set = [0.487,0.467,0.397],[0.235,0.23,0.23]", "_____no_output_____" ], [ "import torch\nfrom torchvision import datasets,transforms\nfrom torch.utils.data import DataLoader\n### TODO: Write data loaders for training, validation, and test sets\n## Specify appropriate transforms, and batch_sizes\ntrain_dir ='/data/dog_images/train'\nvalid_dir = '/data/dog_images/valid'\ntest_dir = '/data/dog_images/test'\ntrain_transforms = transforms.Compose([transforms.RandomResizedCrop(256),\n transforms.ColorJitter(saturation=0.2),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize(mean_train_set,std_train_set)])\nvalid_test_transforms= transforms.Compose([transforms.Resize(300),\n transforms.CenterCrop(256),\n transforms.ToTensor(),\n transforms.Normalize(mean_train_set,std_train_set)])\n\ntrain_dataset = datasets.ImageFolder(train_dir,transform=train_transforms)\nvalid_dataset = datasets.ImageFolder(valid_dir,transform=valid_test_transforms)\ntest_dataset = datasets.ImageFolder(test_dir,transform=valid_test_transforms)\n\ntrainloader = DataLoader(train_dataset,batch_size=32,shuffle=True)\nvalidloader = DataLoader(valid_dataset,batch_size=32,shuffle=False)\ntestloader = DataLoader(test_dataset,batch_size=32,shuffle=False)\n\nloaders_scratch={}\nloaders_scratch['train'] = trainloader\nloaders_scratch['valid'] = validloader\nloaders_scratch['test'] = testloader\nuse_cuda = torch.cuda.is_available()", "_____no_output_____" ] ], [ [ "**Question 3:** Describe your chosen procedure for preprocessing the data. \n- How does your code resize the images (by cropping, stretching, etc)? What size did you pick for the input tensor, and why?\n- Did you decide to augment the dataset? If so, how (through translations, flips, rotations, etc)? If not, why not?\n", "_____no_output_____" ], [ "**Answer**:", "_____no_output_____" ], [ "### (IMPLEMENTATION) Model Architecture\n\nCreate a CNN to classify dog breed. Use the template in the code cell below.", "_____no_output_____" ] ], [ [ "import torch.nn as nn\nimport torch.nn.functional as F\n\n# define the CNN architecture\nclass Net(nn.Module):\n ### TODO: choose an architecture, and complete the class\n def __init__(self):\n super(Net, self).__init__()\n ## Define layers of a CNN\n \n def forward(self, x):\n ## Define forward behavior\n return x\n\n#-#-# You do NOT have to modify the code below this line. #-#-#\n\n# instantiate the CNN\nmodel_scratch = Net()\n\n# move tensors to GPU if CUDA is available\nif use_cuda:\n model_scratch.cuda()", "_____no_output_____" ] ], [ [ "__Question 4:__ Outline the steps you took to get to your final CNN architecture and your reasoning at each step. ", "_____no_output_____" ], [ "__Answer:__ ", "_____no_output_____" ], [ "### (IMPLEMENTATION) Specify Loss Function and Optimizer\n\nUse the next code cell to specify a [loss function](http://pytorch.org/docs/stable/nn.html#loss-functions) and [optimizer](http://pytorch.org/docs/stable/optim.html). Save the chosen loss function as `criterion_scratch`, and the optimizer as `optimizer_scratch` below.", "_____no_output_____" ] ], [ [ "import torch.optim as optim\n\n### TODO: select loss function\ncriterion_scratch = None\n\n### TODO: select optimizer\noptimizer_scratch = None", "_____no_output_____" ] ], [ [ "### (IMPLEMENTATION) Train and Validate the Model\n\nTrain and validate your model in the code cell below. [Save the final model parameters](http://pytorch.org/docs/master/notes/serialization.html) at filepath `'model_scratch.pt'`.", "_____no_output_____" ] ], [ [ "# the following import is required for training to be robust to truncated images\nfrom PIL import ImageFile\nImageFile.LOAD_TRUNCATED_IMAGES = True\n\ndef train(n_epochs, loaders, model, optimizer, criterion, use_cuda, save_path):\n \"\"\"returns trained model\"\"\"\n # initialize tracker for minimum validation loss\n valid_loss_min = np.Inf \n \n for epoch in range(1, n_epochs+1):\n # initialize variables to monitor training and validation loss\n train_loss = 0.0\n valid_loss = 0.0\n \n ###################\n # train the model #\n ###################\n model.train()\n for batch_idx, (data, target) in enumerate(loaders['train']):\n # move to GPU\n if use_cuda:\n data, target = data.cuda(), target.cuda()\n ## find the loss and update the model parameters accordingly\n ## record the average training loss, using something like\n ## train_loss = train_loss + ((1 / (batch_idx + 1)) * (loss.data - train_loss))\n \n ###################### \n # validate the model #\n ######################\n model.eval()\n for batch_idx, (data, target) in enumerate(loaders['valid']):\n # move to GPU\n if use_cuda:\n data, target = data.cuda(), target.cuda()\n ## update the average validation loss\n\n \n # print training/validation statistics \n print('Epoch: {} \\tTraining Loss: {:.6f} \\tValidation Loss: {:.6f}'.format(\n epoch, \n train_loss,\n valid_loss\n ))\n \n ## TODO: save the model if validation loss has decreased\n \n # return trained model\n return model\n\n\n# train the model\nmodel_scratch = train(100, loaders_scratch, model_scratch, optimizer_scratch, \n criterion_scratch, use_cuda, 'model_scratch.pt')\n\n# load the model that got the best validation accuracy\nmodel_scratch.load_state_dict(torch.load('model_scratch.pt'))", "_____no_output_____" ] ], [ [ "### (IMPLEMENTATION) Test the Model\n\nTry out your model on the test dataset of dog images. Use the code cell below to calculate and print the test loss and accuracy. Ensure that your test accuracy is greater than 10%.", "_____no_output_____" ] ], [ [ "def test(loaders, model, criterion, use_cuda):\n\n # monitor test loss and accuracy\n test_loss = 0.\n correct = 0.\n total = 0.\n\n model.eval()\n for batch_idx, (data, target) in enumerate(loaders['test']):\n # move to GPU\n if use_cuda:\n data, target = data.cuda(), target.cuda()\n # forward pass: compute predicted outputs by passing inputs to the model\n output = model(data)\n # calculate the loss\n loss = criterion(output, target)\n # update average test loss \n test_loss = test_loss + ((1 / (batch_idx + 1)) * (loss.data - test_loss))\n # convert output probabilities to predicted class\n pred = output.data.max(1, keepdim=True)[1]\n # compare predictions to true label\n correct += np.sum(np.squeeze(pred.eq(target.data.view_as(pred))).cpu().numpy())\n total += data.size(0)\n \n print('Test Loss: {:.6f}\\n'.format(test_loss))\n\n print('\\nTest Accuracy: %2d%% (%2d/%2d)' % (\n 100. * correct / total, correct, total))\n\n# call test function \ntest(loaders_scratch, model_scratch, criterion_scratch, use_cuda)", "_____no_output_____" ] ], [ [ "---\n<a id='step4'></a>\n## Step 4: Create a CNN to Classify Dog Breeds (using Transfer Learning)\n\nYou will now use transfer learning to create a CNN that can identify dog breed from images. Your CNN must attain at least 60% accuracy on the test set.\n\n### (IMPLEMENTATION) Specify Data Loaders for the Dog Dataset\n\nUse the code cell below to write three separate [data loaders](http://pytorch.org/docs/master/data.html#torch.utils.data.DataLoader) for the training, validation, and test datasets of dog images (located at `dogImages/train`, `dogImages/valid`, and `dogImages/test`, respectively). \n\nIf you like, **you are welcome to use the same data loaders from the previous step**, when you created a CNN from scratch.", "_____no_output_____" ] ], [ [ "## TODO: Specify data loaders\n", "_____no_output_____" ] ], [ [ "### (IMPLEMENTATION) Model Architecture\n\nUse transfer learning to create a CNN to classify dog breed. Use the code cell below, and save your initialized model as the variable `model_transfer`.", "_____no_output_____" ] ], [ [ "import torchvision.models as models\nimport torch.nn as nn\n\n## TODO: Specify model architecture \n\n\nif use_cuda:\n model_transfer = model_transfer.cuda()", "_____no_output_____" ] ], [ [ "__Question 5:__ Outline the steps you took to get to your final CNN architecture and your reasoning at each step. Describe why you think the architecture is suitable for the current problem.", "_____no_output_____" ], [ "__Answer:__ \n", "_____no_output_____" ], [ "### (IMPLEMENTATION) Specify Loss Function and Optimizer\n\nUse the next code cell to specify a [loss function](http://pytorch.org/docs/master/nn.html#loss-functions) and [optimizer](http://pytorch.org/docs/master/optim.html). Save the chosen loss function as `criterion_transfer`, and the optimizer as `optimizer_transfer` below.", "_____no_output_____" ] ], [ [ "criterion_transfer = None\noptimizer_transfer = None", "_____no_output_____" ] ], [ [ "### (IMPLEMENTATION) Train and Validate the Model\n\nTrain and validate your model in the code cell below. [Save the final model parameters](http://pytorch.org/docs/master/notes/serialization.html) at filepath `'model_transfer.pt'`.", "_____no_output_____" ] ], [ [ "# train the model\nmodel_transfer = # train(n_epochs, loaders_transfer, model_transfer, optimizer_transfer, criterion_transfer, use_cuda, 'model_transfer.pt')\n\n# load the model that got the best validation accuracy (uncomment the line below)\n#model_transfer.load_state_dict(torch.load('model_transfer.pt'))", "_____no_output_____" ] ], [ [ "### (IMPLEMENTATION) Test the Model\n\nTry out your model on the test dataset of dog images. Use the code cell below to calculate and print the test loss and accuracy. Ensure that your test accuracy is greater than 60%.", "_____no_output_____" ] ], [ [ "test(loaders_transfer, model_transfer, criterion_transfer, use_cuda)", "_____no_output_____" ] ], [ [ "### (IMPLEMENTATION) Predict Dog Breed with the Model\n\nWrite a function that takes an image path as input and returns the dog breed (`Affenpinscher`, `Afghan hound`, etc) that is predicted by your model. ", "_____no_output_____" ] ], [ [ "### TODO: Write a function that takes a path to an image as input\n### and returns the dog breed that is predicted by the model.\n\n# list of class names by index, i.e. a name can be accessed like class_names[0]\nclass_names = [item[4:].replace(\"_\", \" \") for item in data_transfer['train'].classes]\n\ndef predict_breed_transfer(img_path):\n # load the image and return the predicted breed\n return None", "_____no_output_____" ] ], [ [ "---\n<a id='step5'></a>\n## Step 5: Write your Algorithm\n\nWrite an algorithm that accepts a file path to an image and first determines whether the image contains a human, dog, or neither. Then,\n- if a __dog__ is detected in the image, return the predicted breed.\n- if a __human__ is detected in the image, return the resembling dog breed.\n- if __neither__ is detected in the image, provide output that indicates an error.\n\nYou are welcome to write your own functions for detecting humans and dogs in images, but feel free to use the `face_detector` and `dog_detector` functions developed above. You are __required__ to use your CNN from Step 4 to predict dog breed. \n\nSome sample output for our algorithm is provided below, but feel free to design your own user experience!\n\n![Sample Human Output](images/sample_human_output.png)\n\n\n### (IMPLEMENTATION) Write your Algorithm", "_____no_output_____" ] ], [ [ "### TODO: Write your algorithm.\n### Feel free to use as many code cells as needed.\n\ndef run_app(img_path):\n ## handle cases for a human face, dog, and neither\n \n", "_____no_output_____" ] ], [ [ "---\n<a id='step6'></a>\n## Step 6: Test Your Algorithm\n\nIn this section, you will take your new algorithm for a spin! What kind of dog does the algorithm think that _you_ look like? If you have a dog, does it predict your dog's breed accurately? If you have a cat, does it mistakenly think that your cat is a dog?\n\n### (IMPLEMENTATION) Test Your Algorithm on Sample Images!\n\nTest your algorithm at least six images on your computer. Feel free to use any images you like. Use at least two human and two dog images. \n\n__Question 6:__ Is the output better than you expected :) ? Or worse :( ? Provide at least three possible points of improvement for your algorithm.", "_____no_output_____" ], [ "__Answer:__ (Three possible points for improvement)", "_____no_output_____" ] ], [ [ "## TODO: Execute your algorithm from Step 6 on\n## at least 6 images on your computer.\n## Feel free to use as many code cells as needed.\n\n## suggested code, below\nfor file in np.hstack((human_files[:3], dog_files[:3])):\n run_app(file)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ] ]
4a0d16fd6024fe4ac4e99fd88239ef8e18fb9c4b
756
ipynb
Jupyter Notebook
P A quation 2.ipynb
Bhaven96/python-assignment
4013327e08cb1ec8627dafbc5a65f38fbf7b0d89
[ "MIT" ]
null
null
null
P A quation 2.ipynb
Bhaven96/python-assignment
4013327e08cb1ec8627dafbc5a65f38fbf7b0d89
[ "MIT" ]
null
null
null
P A quation 2.ipynb
Bhaven96/python-assignment
4013327e08cb1ec8627dafbc5a65f38fbf7b0d89
[ "MIT" ]
null
null
null
18.9
52
0.503968
[ [ [ "word = input(\"Input a word to reverse: \")\n\nfor char in range(len(word) - 1, -1, -1):\n print(word[char], end=\"\")\nprint(\"\\n\")\n", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code" ] ]
4a0d197b28163d010607d15129bb11ba1526dd64
12,639
ipynb
Jupyter Notebook
Labs/Lab6/Unix_Programming_Refresher.ipynb
kfollette/AST337-Fall2017
2411475578db339c819b6f104e2c3495afc21a7f
[ "MIT" ]
2
2017-08-31T05:01:54.000Z
2017-10-20T13:44:51.000Z
Labs/Lab6/Unix_Programming_Refresher.ipynb
kfollette/AST337-Fall2017
2411475578db339c819b6f104e2c3495afc21a7f
[ "MIT" ]
null
null
null
Labs/Lab6/Unix_Programming_Refresher.ipynb
kfollette/AST337-Fall2017
2411475578db339c819b6f104e2c3495afc21a7f
[ "MIT" ]
null
null
null
23.580224
695
0.562782
[ [ [ "## Appendix 1: Optional Refresher on the Unix Environment", "_____no_output_____" ], [ "### A1.1) A Quick Unix Overview\nIn Jupyter, many of the same Unix commands we use to navigate in the regular terminal can be used. (However, this is not true when we write standalone code outside Jupyter.) As a quick refresher, try each of the following:", "_____no_output_____" ] ], [ [ "ls", "_____no_output_____" ], [ "pwd ", "_____no_output_____" ], [ "cd 2017oct04 ", "_____no_output_____" ] ], [ [ "We're in a new folder now, so issue commands in the next two cells to look at the folder content and list your current path:", "_____no_output_____" ] ], [ [ "ls", "_____no_output_____" ], [ "pwd", "_____no_output_____" ] ], [ [ "Now test out a few more things. In the blank cells below, try the following and discuss in your group what each does:\n", "_____no_output_____" ] ], [ [ "ls M52*fit", "_____no_output_____" ], [ "ls M52-001*fit", "_____no_output_____" ], [ "ls *V*", "_____no_output_____" ] ], [ [ "What does the asterisk symbol * do?\n\n**Answer:** Is a placeholder (wildcard) for some text in a file/folder name. ", "_____no_output_____" ], [ "Now, return to where you started, by moving up a directory:\n\n(one directory up from where you are is denoted with `..`, while the current directory is denoted with `.`)", "_____no_output_____" ] ], [ [ "cd .. ", "_____no_output_____" ] ], [ [ "### A1.2) A few more helpful commands\n\n#### `mkdir` to *make* a new *dir*ectory: \n`mkdir new_project_name`\n\n#### `cp` to copy a file: \n`cp existingfile newfilename` \nor \n`cp existingfile newlocation`\n\n#### `mv` to move or rename a file: \n`mv old_filename_oldlocation old_filename_newlocation` \nor \n`mv old_filename_oldlocation new_filename_oldlocation`\n\n#### `rm` to *PERMANENTLY* delete (remove) a file... (use with caution): \n`rm file_I_will_never_see_again`\n\n#### In the six cells below:\n\n(1) Make a new directory, called `temporary`\n\n(2) Go into that new directory\n\n(3) Move the file test_file.txt from the original directory above (`../test_file.txt`) into your current location using the `.`\n\n(4) Create a copy of test_file.txt with a new, different filename of your choice.\n\n(5) Delete the original test_file.txt\n\n(6) Go back up into the original location where this notebook is located.", "_____no_output_____" ] ], [ [ "# Make a new directory, \"temporary\"\n", "_____no_output_____" ], [ "# Move into temporary\n", "_____no_output_____" ], [ "# Move the test_file.txt into this current location\n", "_____no_output_____" ], [ "# Create a copy of the test_file.txt, name the copy however you like\n", "_____no_output_____" ], [ "# Delete the original test_file.txt\n", "_____no_output_____" ], [ "# Change directories to original location of notebook.\n", "_____no_output_____" ] ], [ [ "If all went according to plan, the following command should show three directories, a zip file, a .png file, this notebook, and the Lab6 notebook:", "_____no_output_____" ] ], [ [ "ls", "_____no_output_____" ] ], [ [ "And the following command should show the contents of the `temporary` folder, so only your new text file (a copy of test_file.txt, which is now gone forever) within it:", "_____no_output_____" ] ], [ [ "ls ./temporary/", "_____no_output_____" ] ], [ [ "\n## Appendix 2: Optional Refresher on Conditional Statements and Iteration\n\n### A2.1) Conditional Statements\nThe use of tests or _conditions_ to evaluate variables, values, etc., is a fundamental programming tool. Try executing each of the cells below:", "_____no_output_____" ] ], [ [ "2 < 5", "_____no_output_____" ], [ "3 > 7", "_____no_output_____" ], [ "x = 11", "_____no_output_____" ], [ "x > 10", "_____no_output_____" ], [ "2 * x < x ", "_____no_output_____" ], [ "3.14 <= 3.14 # <= means less than or equal to; >= means greater than or equal to", "_____no_output_____" ], [ "42 == 42", "_____no_output_____" ], [ "3e8 != 3e9 # != means \"not equal to\"", "_____no_output_____" ], [ "type(True)", "_____no_output_____" ] ], [ [ "You see that conditions are either `True` or `False` (with no quotes!) These are the only possible Boolean values (named after 19th century mathematician George Boole). In Python, the name Boolean is shortened to the type `bool`. It is the type of the results of true-false conditions or tests.\n\nNow try executing the following two cells at least twice over, with inputs 50 and then 80.", "_____no_output_____" ] ], [ [ "temperature = float(input('What is the temperature in Fahrenheit? '))", "_____no_output_____" ], [ "if temperature > 70:\n print('Wear shorts.')\nelse:\n print('Wear long pants.')", "_____no_output_____" ] ], [ [ "The four lines in the previous cell are an if-else statement. There are two indented blocks: One comes right after the `if` heading in line 1 and is executed when the condition in the `if` heading is _true_. This is followed by an `else:` in line 3, followed by another indented block that is only execued when the original condition is _false_. In an if-else statement, exactly one of the two possible indented blocks is executed.", "_____no_output_____" ], [ "### A2.2) Iteration\nAnother important component in our arsenal of programming tools is iteration. Iteration means performing an operation repeatedly. We can execute a very simple example at the command line. Let's make a list of objects as follows:", "_____no_output_____" ] ], [ [ "names = ['Henrietta', 'Annie', 'Jocelyn', 'Vera']", "_____no_output_____" ], [ "for n in names:\n print('There are ' + str(len(n)) + ' letters in ' + n)", "_____no_output_____" ] ], [ [ "This is an example of a for loop. The way a for loop works is a follows. We start with a list of objects -- in this example a list of strings, but it could be anything -- and then we say for variable in list:, followed by a block of code. The code inside the block will be executed once for every item in the list, and when it is executed the variable will be set equal to the appropriate list item. In this example, the list names had four objects in it, each a string. Thus the print statement inside the loop was executed four times. The first time it was executed, the variable n was set equal to `Henrietta`. The second time n was set equal to `Annie`, then `Jocelyn`, then `Vera`.\n\nOne of the most common types of loop is where you want to loop over numbers: 0, 1, 2, 3, .... To handle loops of this sort, python provides a simple command to construct a list of numbers to iterate over, called range. The command range(n) produces a list of numbers from 0 to n-1. For example:\n", "_____no_output_____" ] ], [ [ "for i in range(5):\n print(i)", "_____no_output_____" ] ], [ [ "There are also other ways of iterating, which may be more convenient depending on what you're trying to do. A very common one is the while loop, which does exactly what it sounds like it should: it loops until some condition is met. For example:", "_____no_output_____" ] ], [ [ "i = 0 # This starts the initial value off at zero\n\nwhile i < 11:\n print(i)\n i = i + 3 # This adds three to the value of i, then goes back to the line #3 to check if the condition is met", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
4a0d22cc2b82f07e610fe5f808e1d3271b162d12
17,444
ipynb
Jupyter Notebook
pretrained-model/stt/hubert/export/conformer-base-ctc.ipynb
ishine/malaya-speech
fd34afc7107af1656dff4b3201fa51dda54fde18
[ "MIT" ]
null
null
null
pretrained-model/stt/hubert/export/conformer-base-ctc.ipynb
ishine/malaya-speech
fd34afc7107af1656dff4b3201fa51dda54fde18
[ "MIT" ]
null
null
null
pretrained-model/stt/hubert/export/conformer-base-ctc.ipynb
ishine/malaya-speech
fd34afc7107af1656dff4b3201fa51dda54fde18
[ "MIT" ]
null
null
null
29.616299
300
0.565983
[ [ [ "import os\n\nos.environ['CUDA_VISIBLE_DEVICES'] = ''", "_____no_output_____" ], [ "from malaya_speech.train.model import hubert, ctc\nfrom malaya_speech.train.model.conformer.model import Model as ConformerModel\nimport malaya_speech\nimport tensorflow as tf\nimport numpy as np\nimport json\nfrom glob import glob\nimport string", "_____no_output_____" ], [ "unique_vocab = [''] + list(\n string.ascii_lowercase + string.digits\n) + [' ']\nlen(unique_vocab)", "_____no_output_____" ], [ "X = tf.compat.v1.placeholder(tf.float32, [None, None], name = 'X_placeholder')\nX_len = tf.compat.v1.placeholder(tf.int32, [None], name = 'X_len_placeholder')", "_____no_output_____" ], [ "training = True\n\nclass Encoder:\n def __init__(self, config):\n self.config = config\n self.encoder = ConformerModel(**self.config)\n\n def __call__(self, x, input_mask, training = True):\n return self.encoder(x, training = training)", "_____no_output_____" ], [ "config_conformer = malaya_speech.config.conformer_base_encoder_config\nconfig_conformer['subsampling']['type'] = 'none'\nconfig_conformer['dropout'] = 0.0\nencoder = Encoder(config_conformer)\ncfg = hubert.HuBERTConfig(\n extractor_mode='layer_norm',\n dropout=0.0,\n attention_dropout=0.0,\n encoder_layerdrop=0.0,\n dropout_input=0.0,\n dropout_features=0.0,\n final_dim=256,\n)\nmodel = hubert.Model(cfg, encoder, ['pad', 'eos', 'unk'] + [str(i) for i in range(100)])\nr = model(X, padding_mask = X_len, features_only = True, mask = False)\nlogits = tf.layers.dense(r['x'], len(unique_vocab) + 1)\nseq_lens = tf.reduce_sum(\n tf.cast(tf.logical_not(r['padding_mask']), tf.int32), axis = 1\n)", "WARNING:tensorflow:From /home/husein/malaya-speech/malaya_speech/train/model/hubert/model.py:59: The name tf.get_variable is deprecated. Please use tf.compat.v1.get_variable instead.\n\nWARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/resource_variable_ops.py:1630: calling BaseResourceVariable.__init__ (from tensorflow.python.ops.resource_variable_ops) with constraint is deprecated and will be removed in a future version.\nInstructions for updating:\nIf using Keras pass *_constraint arguments to layers.\nWARNING:tensorflow:From <ipython-input-7-91db1bb7c21c>:16: dense (from tensorflow.python.layers.core) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse keras.layers.Dense instead.\nWARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/layers/core.py:187: Layer.apply (from tensorflow.python.keras.engine.base_layer) is deprecated and will be removed in a future version.\nInstructions for updating:\nPlease use `layer.__call__` method instead.\n" ], [ "logits = tf.transpose(logits, [1, 0, 2])\nlogits = tf.identity(logits, name = 'logits')\nseq_lens = tf.identity(seq_lens, name = 'seq_lens')", "_____no_output_____" ], [ "sess = tf.Session()\nsess.run(tf.global_variables_initializer())\nvar_list = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES)\nsaver = tf.train.Saver(var_list = var_list)\nsaver.restore(sess, 'hubert-conformer-base-ctc-char/model.ckpt-2000000')", "INFO:tensorflow:Restoring parameters from hubert-conformer-base-ctc-char/model.ckpt-2000000\n" ], [ "saver = tf.train.Saver()\nsaver.save(sess, 'output-hubert-conformer-base-ctc/model.ckpt')", "_____no_output_____" ], [ "strings = ','.join(\n [\n n.name\n for n in tf.get_default_graph().as_graph_def().node\n if ('Variable' in n.op\n or 'gather' in n.op.lower()\n or 'placeholder' in n.name\n or 'logits' in n.name\n or 'seq_lens' in n.name)\n and 'adam' not in n.name\n and 'global_step' not in n.name\n and 'Assign' not in n.name\n and 'ReadVariableOp' not in n.name\n and 'Gather' not in n.name\n ]\n)\nstrings.split(',')", "_____no_output_____" ], [ "def freeze_graph(model_dir, output_node_names):\n\n if not tf.gfile.Exists(model_dir):\n raise AssertionError(\n \"Export directory doesn't exists. Please specify an export \"\n 'directory: %s' % model_dir\n )\n\n checkpoint = tf.train.get_checkpoint_state(model_dir)\n input_checkpoint = checkpoint.model_checkpoint_path\n\n absolute_model_dir = '/'.join(input_checkpoint.split('/')[:-1])\n output_graph = absolute_model_dir + '/frozen_model.pb'\n clear_devices = True\n with tf.Session(graph = tf.Graph()) as sess:\n saver = tf.train.import_meta_graph(\n input_checkpoint + '.meta', clear_devices = clear_devices\n )\n saver.restore(sess, input_checkpoint)\n output_graph_def = tf.graph_util.convert_variables_to_constants(\n sess,\n tf.get_default_graph().as_graph_def(),\n output_node_names.split(','),\n )\n with tf.gfile.GFile(output_graph, 'wb') as f:\n f.write(output_graph_def.SerializeToString())\n print('%d ops in the final graph.' % len(output_graph_def.node))", "_____no_output_____" ], [ "freeze_graph('output-hubert-conformer-base-ctc', strings)", "INFO:tensorflow:Restoring parameters from output-hubert-conformer-base-ctc/model.ckpt\nWARNING:tensorflow:From <ipython-input-12-9a7215a4e58a>:23: convert_variables_to_constants (from tensorflow.python.framework.graph_util_impl) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse `tf.compat.v1.graph_util.convert_variables_to_constants`\nWARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/framework/graph_util_impl.py:277: extract_sub_graph (from tensorflow.python.framework.graph_util_impl) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse `tf.compat.v1.graph_util.extract_sub_graph`\nINFO:tensorflow:Froze 575 variables.\nINFO:tensorflow:Converted 575 variables to const ops.\n9451 ops in the final graph.\n" ], [ "def load_graph(frozen_graph_filename):\n with tf.gfile.GFile(frozen_graph_filename, 'rb') as f:\n graph_def = tf.GraphDef()\n graph_def.ParseFromString(f.read())\n \n with tf.Graph().as_default() as graph:\n tf.import_graph_def(graph_def)\n \n return graph", "_____no_output_____" ], [ "files = [\n 'speech/record/savewav_2020-11-26_22-36-06_294832.wav',\n 'speech/record/savewav_2020-11-26_22-40-56_929661.wav',\n 'speech/record/675.wav',\n 'speech/record/664.wav',\n 'speech/example-speaker/husein-zolkepli.wav',\n 'speech/example-speaker/mas-aisyah.wav',\n 'speech/example-speaker/khalil-nooh.wav',\n 'speech/example-speaker/shafiqah-idayu.wav',\n 'speech/khutbah/wadi-annuar.wav',\n]\n\nys = [malaya_speech.load(f)[0] for f in files]\npadded, lens = malaya_speech.padding.sequence_1d(ys, return_len = True)", "_____no_output_____" ], [ "g = load_graph('output-hubert-conformer-base-ctc/frozen_model.pb')", "_____no_output_____" ], [ "input_nodes = [\n 'X_placeholder',\n 'X_len_placeholder',\n]\noutput_nodes = [\n 'logits',\n 'seq_lens',\n]\ninputs = {n: g.get_tensor_by_name(f'import/{n}:0') for n in input_nodes}\noutputs = {n: g.get_tensor_by_name(f'import/{n}:0') for n in output_nodes}", "_____no_output_____" ], [ "test_sess = tf.Session(graph = g)", "_____no_output_____" ], [ "r = test_sess.run(outputs['logits'], feed_dict = {inputs['X_placeholder']: padded, \n inputs['X_len_placeholder']: lens})", "_____no_output_____" ], [ "from tensorflow.tools.graph_transforms import TransformGraph", "_____no_output_____" ], [ "transforms = ['add_default_attributes',\n 'remove_nodes(op=Identity, op=CheckNumerics, op=Dropout)',\n 'fold_batch_norms',\n 'fold_old_batch_norms',\n 'quantize_weights(fallback_min=-10, fallback_max=10)',\n 'strip_unused_nodes',\n 'sort_by_execution_order']\n\npb = 'output-hubert-conformer-base-ctc/frozen_model.pb'\n\ninput_graph_def = tf.GraphDef()\nwith tf.gfile.FastGFile(pb, 'rb') as f:\n input_graph_def.ParseFromString(f.read())\n\ntransformed_graph_def = TransformGraph(input_graph_def, \n input_nodes,\n output_nodes, transforms)\n \nwith tf.gfile.GFile(f'{pb}.quantized', 'wb') as f:\n f.write(transformed_graph_def.SerializeToString())", "WARNING:tensorflow:From <ipython-input-21-45fa588a41e4>:12: FastGFile.__init__ (from tensorflow.python.platform.gfile) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse tf.gfile.GFile.\n" ], [ "g = load_graph('output-hubert-conformer-large-ctc/frozen_model.pb.quantized')", "_____no_output_____" ], [ "!tar -czvf output-hubert-conformer-base-ctc-v2.tar.gz output-hubert-conformer-base-ctc", "output-hubert-conformer-base-ctc/\noutput-hubert-conformer-base-ctc/model.ckpt.index\noutput-hubert-conformer-base-ctc/model.ckpt.data-00000-of-00001\noutput-hubert-conformer-base-ctc/frozen_model.pb.quantized\noutput-hubert-conformer-base-ctc/checkpoint\noutput-hubert-conformer-base-ctc/model.ckpt.meta\noutput-hubert-conformer-base-ctc/frozen_model.pb\n" ], [ "b2_application_key_id = os.environ['b2_application_key_id']\nb2_application_key = os.environ['b2_application_key']", "_____no_output_____" ], [ "from b2sdk.v1 import *\ninfo = InMemoryAccountInfo()\nb2_api = B2Api(info)\napplication_key_id = b2_application_key_id\napplication_key = b2_application_key\nb2_api.authorize_account(\"production\", application_key_id, application_key)\nfile_info = {'how': 'good-file'}\nb2_bucket = b2_api.get_bucket_by_name('malaya-speech-model')", "_____no_output_____" ], [ "key = 'output-hubert-conformer-base-ctc-v2.tar.gz'\noutPutname = \"pretrained/output-hubert-conformer-base-ctc-v2.tar.gz\"\nb2_bucket.upload_local_file(\n local_file=key,\n file_name=outPutname,\n file_infos=file_info,\n)", "_____no_output_____" ], [ "file = 'output-hubert-conformer-base-ctc/frozen_model.pb'\noutPutname = 'speech-to-text-ctc-v2/hubert-conformer/model.pb'\nb2_bucket.upload_local_file(\n local_file=file,\n file_name=outPutname,\n file_infos=file_info,\n)", "_____no_output_____" ], [ "file = 'output-hubert-conformer-base-ctc/frozen_model.pb.quantized'\noutPutname = 'speech-to-text-ctc-v2/hubert-conformer-quantized/model.pb'\nb2_bucket.upload_local_file(\n local_file=file,\n file_name=outPutname,\n file_infos=file_info,\n)", "_____no_output_____" ], [ "!rm -rf output-hubert-conformer-base-ctc output-hubert-conformer-base-ctc-v2.tar.gz", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
4a0d2d0ba9c12c60c1f7bd01ab798116bbd7e7fb
50,867
ipynb
Jupyter Notebook
2020-07-10 UCSD MSTP/2020-07-10_05_MSTP Class Project.ipynb
g2nb/workshop-notebooks
1e22f9569438dd509f3148959ca5b87d78ea5157
[ "BSD-3-Clause" ]
null
null
null
2020-07-10 UCSD MSTP/2020-07-10_05_MSTP Class Project.ipynb
g2nb/workshop-notebooks
1e22f9569438dd509f3148959ca5b87d78ea5157
[ "BSD-3-Clause" ]
null
null
null
2020-07-10 UCSD MSTP/2020-07-10_05_MSTP Class Project.ipynb
g2nb/workshop-notebooks
1e22f9569438dd509f3148959ca5b87d78ea5157
[ "BSD-3-Clause" ]
1
2022-01-12T20:17:50.000Z
2022-01-12T20:17:50.000Z
33.509223
845
0.555213
[ [ [ "# Class Project\n## GenePattern Single Cell Analysis Workshop ", "_____no_output_____" ], [ "<div class=\"alert alert-info\">\n<p class=\"lead\"> Instructions <i class=\"fa fa-info-circle\"></i></p>\nLog in to GenePettern with your credentials.\n</div>", "_____no_output_____" ] ], [ [ "# Requires GenePattern Notebook: pip install genepattern-notebook\nimport gp\nimport genepattern\n\n# Username and password removed for security reasons.\ngenepattern.display(genepattern.session.register(\"https://cloud.genepattern.org/gp\", \"\", \"\"))", "_____no_output_____" ] ], [ [ "For this project, we will use data from the Human Cell Atlas, for the project [Single cell transcriptome analysis of human pancreas reveals transcriptional signatures of aging and somatic mutation patterns](https://data.humancellatlas.org/explore/projects/cddab57b-6868-4be4-806f-395ed9dd635a/m/expression-matrices). This project, and a few others, are available on the Human Cell Atlas Data Browser and you can experiment with finding other available studies on its [Explore Data Page](https://data.humancellatlas.org/explore/projects?filter=%5B%7B%22facetName%22%3A%22genusSpecies%22%2C%22terms%22%3A%5B%22Homo+sapiens%22%5D%7D%2C%7B%22facetName%22%3A%22organ%22%2C%22terms%22%3A%5B%22pancreas%22%5D%7D%5D), in this case the link (above) will pre-filter for Human Pancreas datasets to make it easy to find the experiment we will use.\n\nFrom [the project page](https://data.humancellatlas.org/explore/projects/cddab57b-6868-4be4-806f-395ed9dd635a/m/expression-matrices), we can obtain the link to the file which contains the RNA-Seq data in the MTX format:\nhttps://data.humancellatlas.org/project-assets/project-matrices/cddab57b-6868-4be4-806f-395ed9dd635a.homo_sapiens.mtx.zip \n", "_____no_output_____" ], [ "<div class=\"alert alert-info\">\n<p class=\"lead\"> Instructions <i class=\"fa fa-info-circle\"></i></p>\n<ol> \n <li>Drag or Copy/Paste the link to the <code>mtx.zip</code> file (above) into the <code>url*</code> parameter below.</li>\n <li>Click 'Run'</li>\n\n</div>", "_____no_output_____" ] ], [ [ "import os \nimport shutil\nimport urllib.request\nimport subprocess\nimport rpy2\n%load_ext nbtools.r_support\n\[email protected]_ui(description=\"Setup the R and Python environments for the rest of this notebook. Downloads the example dataset to the notebook server.\", \n parameters={\"url\":{\"name\":\"url\"},\n \"output_var\": {\"name\":\"folder\",\"default\":\"folder\",\"hide\":\"true\"}\n })\ndef download_MTX_zip(url):\n %load_ext rpy2.ipython\n print(\"Retrieving input data...\") \n base_name = 'temp_data.mtx.zip'\n os.makedirs('data/input_data/unzipped_data', exist_ok=True)\n urllib.request.urlretrieve(url, f'data/input_data/{base_name}')\n subprocess.run([\"unzip\", f\"data/input_data/\"+f\"{base_name}\",\"-d\",f\"data/input_data/unzipped_data/\"])\n folder = os.listdir(\"data/input_data/unzipped_data/\")[0]\n folder = os.path.join(\"data/input_data/unzipped_data\",folder)\n \n # cache the last downloaded copy if its a repeat (just in case)\n unzipPath = \"data/input_data/unzipped_data/downloaded_MTX_folder\"\n if os.path.exists(unzipPath):\n if os.path.exists(unzipPath + \"_PREVIOUS\"):\n shutil.rmtree(unzipPath + \"_PREVIOUS\")\n print(\"Saving old copy of the data as \"+unzipPath + \"_PREVIOUS\")\n os.rename(unzipPath, unzipPath + \"_PREVIOUS\"); \n \n os.rename(folder,\"data/input_data/unzipped_data/downloaded_MTX_folder\")\n folder = 'data/input_data/unzipped_data/downloaded_MTX_folder'\n print(f'Data unzipped to: {folder}')\n print(\"Done.\")\n return folder", "/opt/conda/envs/python3.7/lib/python3.7/site-packages/rpy2/robjects/pandas2ri.py:14: FutureWarning: pandas.core.index is deprecated and will be removed in a future version. The public classes are available in the top-level namespace.\n from pandas.core.index import Index as PandasIndex\n" ] ], [ [ "Now we have a copy of the project data as a zipped MTX file on our GenePattern Notebook server. We need to unzip it so that Seurat can read the MTX file.\n\n\n<div class=\"alert alert-info\">\n<p class=\"lead\"> Instructions <i class=\"fa fa-info-circle\"></i></p>\n \nInput here the directory where your data resides. If you used default parameters, it should be in `data/input_data/unzipped_data/downloaded_MTX_folder`\n</div>", "_____no_output_____" ] ], [ [ "%%r_build_ui { \"name\": \"Setup Seurat Objects\", \"parameters\": { \"data_dir\":{\"name\":\"data_dir\",},\"output_var\": { \"hide\": \"True\" } } }\n\nsetupR <- function(data_dir){\n \n write(\"Loading libraries...\", stdout())\n suppressMessages(library(Seurat))\n suppressMessages(library(scater))\n # Load the dataset\n write(c(\"Reading data from\",data_dir), stdout())\n suppressMessages(pbmc.data <- Read10X(data.dir = data_dir))\n \n # Initialize the Seurat object with the raw (non-normalized data).\n write(\"Loadig data into Seurat...\", stdout())\n pbmc <- CreateSeuratObject(counts = pbmc.data, project = \"pbmc3k\", min.cells = 3, min.features = 200)\n write(\"Done with this step.\", stdout())\n return(pbmc)\n}\nsuppressMessages(pbmc <- setupR(data_dir))", "_____no_output_____" ] ], [ [ "As in the example earlier today, we will want to filter the dataset based on the mitochondrial QC metrics. To make this sort of filtering easy we will add the metrics directly into the Seurat object.\n\n<div class=\"alert alert-info\">\n<p class=\"lead\"> Instructions <i class=\"fa fa-info-circle\"></i></p>\n \nClick `Run` to add mitochondrial QC metrics.\n</div>", "_____no_output_____" ] ], [ [ "%%r_build_ui { \"name\": \"Add Mitochondrial QC Metrics\", \"parameters\": { \"column_name\": { \"type\": \"string\", \"default\":\"percent.mt\" },\"pattern\": { \"type\": \"string\", \"default\":\"MT-\" }, \"output_var\": { \"hide\": \"True\" } } }\n\nset_mito_qc <- function(colName, pat) {\n write(\"Calculating the frequency of mitochondrial genes...\", stdout())\n pattern <- paste(\"^\", trimws(pat, which = \"both\"), sep=\"\")\n \n # The [[ operator can add columns to object metadata. This is a great place to stash QC stats\n pbmc[[colName]] <- PercentageFeatureSet(pbmc, pattern = pattern)\n write(\"Done!\", stdout())\n return(pbmc)\n}\n\n\nsuppressMessages(pbmc <- set_mito_qc(column_name, pattern))", "_____no_output_____" ] ], [ [ "<div class=\"alert alert-info\">\n<p class=\"lead\"> Instructions <i class=\"fa fa-info-circle\"></i></p>\n\nPlot the three features (nFeature_RNA, nCount_RNA, and percent.mt) to decide which filters to use in the next step.\n</div>", "_____no_output_____" ] ], [ [ "%%r_build_ui -w 800 { \"width\": 10, \"height\": 300, \"name\": \"Triple Violin Plot\", \"parameters\": { \"first_feature\": { \"type\": \"string\", \"default\":\"nFeature_RNA\" }, \"second_feature\":{ \"type\": \"string\", \"default\":\"nCount_RNA\"}, \"third_feature\": { \"type\": \"string\", \"default\":\"percent.mt\" }, \"output_var\":{\"hide\":\"True\"} } }\n# Visualize QC metrics as a violin plot\n#VlnPlot(pbmc, features = c(first_feature, second_feature, third_feature), ncol = 3)\ntripleViolin <- function(first, second, third){\n \n feats <- c(first, second, third)\n plot(VlnPlot(pbmc, features = feats, ncol = 3, combine=TRUE), fig.height=5, fig.width=15)\n return(\"\")\n}\n\ntripleViolin(first_feature, second_feature, third_feature)", "_____no_output_____" ] ], [ [ "<div class=\"alert alert-info\">\n<p class=\"lead\"> Instructions <i class=\"fa fa-info-circle\"></i></p>\n\nBased on the three violin plots above, input which filters to apply to the data.\n</div>", "_____no_output_____" ] ], [ [ "%%r_build_ui { \"name\": \"Subset Data\", \"parameters\": { \"min_n_features\": { \"type\": \"number\", \"default\":\"200\" },\"max_n_features\": { \"type\": \"number\", \"default\":\"9000\" },\"max_percent_mitochondrial\": { \"type\": \"number\", \"default\":\"50\" }, \"output_var\": { \"hide\": \"True\" } } }\n\nmy_subset <- function(min_n_features, max_n_features, max_percent_mitochondrial){\n# print(pbmc)\n pbmc <- subset(pbmc, subset = nFeature_RNA > min_n_features & nFeature_RNA < max_n_features & percent.mt < max_percent_mitochondrial)\n# print(pbmc)\n write('filtering done!', stdout())\n return(pbmc)\n}\n\npbmc <- my_subset(min_n_features, max_n_features, max_percent_mitochonrial)", "_____no_output_____" ] ], [ [ "<div class=\"alert alert-info\">\n<p class=\"lead\"> Instructions <i class=\"fa fa-info-circle\"></i></p>\nClick run to apply a log-normalization and scaling of the data.\n</div>", "_____no_output_____" ] ], [ [ "\n%%r_build_ui { \"name\": \"Normalize\", \"parameters\": { \"method\": { \"type\": \"string\", \"default\":\"LogNormalize\" },\"scale_factor\": { \"type\": \"number\", \"default\":\"10000\" }, \"output_var\": { \"hide\": \"True\" } } }\n\nnorm_pbmc <- function(meth, scale){\n write(\"Normalizing data...\", stdout())\n invisible(pbmc <- NormalizeData(pbmc, normalization.method = meth, scale.factor = scale, verbose = F))\n write('Normalization done!', stdout())\n return(pbmc)\n}\n\npbmc <- norm_pbmc(method, scale_factor)", "_____no_output_____" ] ], [ [ "<div class=\"alert alert-info\">\n<p class=\"lead\"> Instructions <i class=\"fa fa-info-circle\"></i></p>\nClick run to show genes which are highly variable in this experiment. Take note of these genes as they may be helpful in downstream analyses.\n</div>", "_____no_output_____" ] ], [ [ "%%r_build_ui { \"name\": \"Feature Selection\", \"parameters\": { \"method\": { \"type\": \"string\", \"default\":\"vst\",\"hide\":\"True\" },\"num_features\": { \"type\": \"number\", \"default\":\"2000\" }, \"num_to_label\":{\"type\": \"number\", \"default\": \"10\", \"description\": \"label the top N features in the plot.\"}, \"output_var\": { \"hide\": \"True\" } } }\n#%%R -w 800 -h 450\n\nfeat_sel_plot <- function(meth, nFeat, nLabel){\n write(\"Identifying variable features...\", stdout())\n invisible(capture.output(pbmc <- FindVariableFeatures(pbmc, selection.method = meth, nfeatures = nFeat, \n verbose=F)))\n write(\"Done!\", stdout())\n\n # Identify the 10 most highly variable genes\n top10 <- head(VariableFeatures(pbmc), nLabel)\n\n # plot variable features with and without labels\n invisible(capture.output(plot1 <- VariableFeaturePlot(pbmc)))\n invisible(capture.output(plot2 <- LabelPoints(plot = plot1, points = top10, repel = TRUE)))\n print(plot2)\n #plot(CombinePlots(plots = list(plot1, plot2)))\n return(pbmc)\n}\n\npbmc <- feat_sel_plot(method, num_features, num_to_label)", "_____no_output_____" ] ], [ [ "<div class=\"alert alert-info\">\n<p class=\"lead\"> Instructions <i class=\"fa fa-info-circle\"></i></p>\nClick run to compute PCA.\n</div>", "_____no_output_____" ] ], [ [ "%%r_build_ui {\"name\": \"Compute PCA\", \"parameters\": {\"output_var\":{\"hide\": \"True\"}}}\nmyscale <- function(pbmc){\n write(\"Scaling data...\", stdout())\n all.genes <- rownames(pbmc)\n invisible(capture.output(pbmc <- ScaleData(pbmc, features = all.genes, verbose = F)))\n write('Done scaling data!', stdout())\n \n feats <- VariableFeatures(object = pbmc, verbose = F)\n pbmc <- RunPCA(pbmc, features = feats, nfeatures.print=5, verbose=F)\n write('Done computing PCA. Elbow plot below.', stdout())\n \n plot(ElbowPlot(pbmc))\n \n return(pbmc)\n}\npbmc <- myscale(pbmc)", "_____no_output_____" ] ], [ [ "Now that the PCA results have been added to the Seurat object, we want to save it again so that we can run the SeuratClustering module on the GenePattern server. \n\n", "_____no_output_____" ], [ "#### Why do we run Seurat Clustering on the GenePattern server instead of in this Notebook directly?\n*expand this cell to see the hidden answer*", "_____no_output_____" ], [ "Performing UMAP or TSNE takes more memory and CPU cycles than the simpler analyses we have been doing directly in this notebook. By sending these to the GenePattern module, we can use the cluster behind GenePattern which has machines with more CPU and memory than our local notebook server for the few seconds or minutes the analysis requires, and not the hours that the notebook might be in use, reducing our compute costs while making the analysis run faster.", "_____no_output_____" ], [ "#### Save and upload the Seurat object", "_____no_output_____" ], [ "\n<div class=\"alert alert-info\">\n<p class=\"lead\"> Instructions <i class=\"fa fa-info-circle\"></i></p>\nClick 'Run' to save the Seurat object as an RDS file.\n</div>", "_____no_output_____" ] ], [ [ "%%r_build_ui {\"name\":\"Save preprocessed dataset\", \"parameters\": { \"file_name\": {\"default\":\"Seurat_preprocessed.rds\"}, \"output_var\": {\"hide\": \"True\"} }}\nsave_it <- function(fileName){\n write('Saving file to the notebook workspace. This may take a while (this file may be about 1 GB in size)...', stdout())\n saveRDS(pbmc, file = fileName)\n print(\"Saved file!\")\n return(pbmc)\n}\nsave_it(file_name)", "_____no_output_____" ] ], [ [ "<div class=\"alert alert-info\">\n<p class=\"lead\"> Instructions <i class=\"fa fa-info-circle\"></i></p>\nClick 'Run' to upload the RDS file to the GenePattern server.\n</div>\n<div class=\"well well-sm\">\n<b>Note:</b> Note: This can potentially take a long time as the RDS file is nearly 1GB in size. A pre-generated file is available below if this takes too long or fails.\n</div>\n\n", "_____no_output_____" ] ], [ [ "@nbtools.build_ui(name=\"Upload file to GenePattern Server\", parameters={\n \"file\": {\n \"name\": \"File to upload:\",\n \"default\":\"Seurat_preprocessed.rds\"\n },\n \"output_var\": {\n \"name\": \"results\",\n \"description\": \"\",\n \"default\": \"quantification_source\",\n \"hide\": True\n }\n})\ndef load_file(file):\n import genepattern\n uio = nbtools.UIOutput()\n display(uio)\n size = os.path.getsize(file)\n print(f'This file size is {round(size/1e6)} MB, it may take a while to upload.')\n uio.status = \"Uploading...\"\n uploaded_file = genepattern.session.get(0).upload_file(file_name=os.path.basename(file),file_path=file)\n uio.status = \"Uploaded!\"\n display(nbtools.UIOutput(files=[uploaded_file.get_url()]))\n return()", "_____no_output_____" ] ], [ [ "### Pre-generated RDS file\n*Expand this cell to access a pre-generated rds file if the save & upload is taking too long*", "_____no_output_____" ], [ "<div class=\"alert alert-info\">\n<p class=\"lead\"> Instructions <i class=\"fa fa-info-circle\"></i></p>\nIf the above steps are taking too long (save+upload), feel free to use this file for illustrative purposes. You will need to run the cell below.\n</div>", "_____no_output_____" ] ], [ [ "display(nbtools.UIOutput(text='Feel free to use this pre-generated RDS file to save time and/or disk space.',\n files=['https://datasets.genepattern.org/data/module_support_files/SeuratClustering/Seurat_preprocessed_prebaked.rds']))", "_____no_output_____" ] ], [ [ "## Seurat Clustering", "_____no_output_____" ], [ "Now we will cluster our pancreas data using umap.\n<div class=\"alert alert-info\">\n<p class=\"lead\"> Instructions <i class=\"fa fa-info-circle\"></i></p>\n <ol>\n <li>Select your RDS file (or the pre-baked one) from the `input seurat rds file*` dropdown.</li>\n <li>Select `umap` for the `reduction` parameter.</li>\n <li>Leave all the other parameters at their defaults (or experiment with them!).</li>\n <li>Click 'Run' to start the analysis.</li>\n </ol>\n</div>", "_____no_output_____" ] ], [ [ "seuratclustering_task = gp.GPTask(genepattern.session.get(0), 'urn:lsid:broad.mit.edu:cancer.software.genepattern.module.analysis:00408')\nseuratclustering_job_spec = seuratclustering_task.make_job_spec()\nseuratclustering_job_spec.set_parameter(\"input.seurat.rds.file\", \"\")\nseuratclustering_job_spec.set_parameter(\"output.filename\", \"<input.seurat.rds.file_basename>.clustered\")\nseuratclustering_job_spec.set_parameter(\"maximum_dimension\", \"10\")\nseuratclustering_job_spec.set_parameter(\"resolution\", \"0.5\")\nseuratclustering_job_spec.set_parameter(\"reduction\", \"umap\")\nseuratclustering_job_spec.set_parameter(\"job.memory\", \"2 Gb\")\nseuratclustering_job_spec.set_parameter(\"job.queue\", \"gp-cloud-default\")\nseuratclustering_job_spec.set_parameter(\"job.cpuCount\", \"1\")\nseuratclustering_job_spec.set_parameter(\"job.walltime\", \"02:00:00\")\ngenepattern.display(seuratclustering_task)", "_____no_output_____" ] ], [ [ "# Visualize Seurat results", "_____no_output_____" ], [ "#### pre-baked Results\n\nIf your SeuratClustering module is taking too long, you can use our pre-generated results instead of waiting for your analysis to complete.\n\n*Expand this cell to access pre-generated SeuratClustering results instead of the results from your analysis*", "_____no_output_____" ], [ "<div class=\"alert alert-info\">\n<p class=\"lead\"> Instructions <i class=\"fa fa-info-circle\"></i></p>\n \nThe cell below (Job #199267) can be used to access the pre-baked results.\n- Note: if you wish to use it, make sure you run it (e.g., click on the play symbol ⏯ next to it)\n</div>", "_____no_output_____" ] ], [ [ "job199267 = gp.GPJob(genepattern.session.get(0), 199267)\ngenepattern.display(job199267)", "_____no_output_____" ] ], [ [ "<div class=\"alert alert-info\">\n<p class=\"lead\"> Instructions <i class=\"fa fa-info-circle\"></i></p>\nDownload the CSV file.\n</div>", "_____no_output_____" ], [ "## Download files from GPServer\n\nSince we ran the clustering on the GenePattern server instead of the notebook, now we will bring them back down to the notebook server so that we can visualize them within the notebook. We need to download both the CSV and the RDS files.", "_____no_output_____" ], [ "<div class=\"alert alert-info\">\n<p class=\"lead\"> Instructions <i class=\"fa fa-info-circle\"></i></p>\n \nTo download the CSV file, choose from the dropdown menu the CSV file that the SeuratClustering module outputs (it should end with `*.clustered.csv`)\n\n- Alternatively, chose the CSV file which includes the term `prebaked` in it.\n</div>\n<div class=\"well well-sm\">\n<b>Note:</b> This takes ~ 1 second.\n</div>", "_____no_output_____" ] ], [ [ "import os\n\nDownloadJobResultFile_description = \"Download file from a GenePattern module job result.\"\nDownloadJobResultFile_parameters = {\"file\": {\"type\": \"file\", \"kinds\": [\"csv\", \"rds\"]}, \"output_var\": {\"hide\": True}} \n \ndef DownloadJobResultFile(file):\n # extract job number and file name from url\n job_num = file.split(\"/\")[-2]\n remote_file_name = file.split(\"/\")[-1]\n \n # get the job based on the job number passed as the second argument\n job = gp.GPJob(genepattern.get_session(0), job_num)\n\n # fetch a specific file from the job\n remote_file = job.get_file(remote_file_name)\n \n uio = nbtools.UIOutput(text=file)\n display(uio)\n uio.status = \"Downloading...\"\n \n File_Name = os.path.basename(file)\n\n response = remote_file.open()\n CHUNK = 16 * 1024\n with open(File_Name, 'wb') as f:\n while True:\n chunk = response.read(CHUNK)\n if not chunk:\n break\n f.write(chunk)\n uio.status = \"Downloaded!\"\n print(File_Name)\n display(nbtools.UIOutput(files=[File_Name]))\n \ngenepattern.GPUIBuilder(DownloadJobResultFile, collapse=False,\n name='Download File From GenePattern Server',\n description=DownloadJobResultFile_description,\n parameters=DownloadJobResultFile_parameters)", "_____no_output_____" ] ], [ [ "<div class=\"alert alert-info\">\n<p class=\"lead\"> Instructions <i class=\"fa fa-info-circle\"></i></p>\n \nTo download the RDS file, choose from the dropdown menu the CSV file that the SeuratClustering module outputs (it should end with `*.clustered.rds`)\n\n- Alternatively, chose the RDS file which includes the term `prebaked` in it.\n</div>\n<div class=\"well well-sm\">\n<b>Note:</b> This takes about 30 seconds on a <i>high speed</i> connnection, please be patient.\n</div>", "_____no_output_____" ] ], [ [ "genepattern.GPUIBuilder(DownloadJobResultFile, collapse=False,\n name='Download File From GenePattern Server',\n description=DownloadJobResultFile_description,\n parameters=DownloadJobResultFile_parameters)", "_____no_output_____" ] ], [ [ "## Load data into notebook", "_____no_output_____" ], [ "<div class=\"alert alert-info\">\n<p class=\"lead\"> Instructions <i class=\"fa fa-info-circle\"></i></p>\n \nClick 'Run' to load the results you just downloaded.\n- Note: make sure you type the name of the files downloaded in the two steps above.\n</div>", "_____no_output_____" ] ], [ [ "%%r_build_ui {\"name\":\"Load dataset with clustering\", \"parameters\": {\"RDS_url\":{\"name\":\"RDS file\",\"default\":\"Seurat_preprocessed.clustered.rds.rds\",'type':\"file\"}, \"CSV_url\":{\"name\":\"CSV_file\",\"type\":\"file\",\"default\":\"Seurat_preprocessed.clustered.rds.csv\"}, \"output_var\": {\"hide\": \"True\"} }}\n\nload_markers <- function(CSV_url) {\n write(\"Loading cluster markers into notebook...\", stdout())\n markers <- read.csv(CSV_url)\n write(\"Done!\", stdout())\n return(markers)\n}\nload_it <- function(RDS_url){\n write(\"Loading clustering results into notebook...\", stdout())\n pbmc <- readRDS(file = RDS_url)\n write(\"Loaded file!\", stdout())\n return(pbmc)\n}\nsuppressWarnings(markers <- load_markers(CSV_url))\npbmc <- load_it(RDS_url)", "_____no_output_____" ] ], [ [ "<div class=\"alert alert-info\">\n<p class=\"lead\"> Instructions <i class=\"fa fa-info-circle\"></i></p>\nClick 'Run' to plot the results of the umap clustering.\n</div>", "_____no_output_____" ] ], [ [ "%%r_build_ui {\"name\": \"Visualize clusters\", \"parameters\": {\"output_var\": {\"hide\": \"True\"}}}\nlibrary(Seurat)\ndo_dim_plot <- function() {\n plot(DimPlot(pbmc, reduction = \"umap\"))\n return(\"\")\n}\ndo_dim_plot()", "_____no_output_____" ] ], [ [ "We want to see which genes are markers for the clusters we see above. Lets look at the markers\n\n<div class=\"alert alert-info\">\n<p class=\"lead\"> Instructions <i class=\"fa fa-info-circle\"></i></p>\n<ol> \n <li>Select one of the clusters (e.g. 1,2,3).</li>\n <li>Click 'Run' to show the top markers for a cluster.</li>\n </ol>\n</div>", "_____no_output_____" ] ], [ [ "%%r_build_ui {\"name\": \"Print top cluster markers\", \"parameters\": {\"cluster_number\": {}, \"output_var\": {\"hide\": \"True\"}}}\nprint_top_markers <- function(cluster_number) {\n return(head(markers[markers$cluster==cluster_number,], n = 5))\n}\nprint_top_markers(cluster_number)", "_____no_output_____" ] ], [ [ "And now lets look at the gene expression for one of these markers.\n\n<div class=\"alert alert-info\">\n<p class=\"lead\"> Instructions <i class=\"fa fa-info-circle\"></i></p>\n<ol> \n <li>Enter the gene name for a cluster marker (e.g., PDIA2, CLPS).</li>\n <li>Click 'Run' to show a violin plot of its gene expression.</li>\n <li>Repeat as desired for several marker genes.</li>\n </ol>\n</div>", "_____no_output_____" ] ], [ [ "%%r_build_ui {\"name\": \"Violin plot of gene expression\", \"parameters\": {\"gene\": {}, \"output_var\": {\"hide\": \"True\"}}}\ndo_violin <- function(gene) {\n plot(VlnPlot(pbmc, features = c(gene), slot = \"counts\", log = TRUE))\n return(\"\")\n}\ndo_violin(gene)", "_____no_output_____" ] ], [ [ "And now lets look at the gene expression for this marker across all clusters.\n\n<div class=\"alert alert-info\">\n<p class=\"lead\"> Instructions <i class=\"fa fa-info-circle\"></i></p>\n<ol> \n <li>Enter the gene name for a cluster marker.</li>\n <li>Click 'Run'.</li>\n </ol>\n</div>", "_____no_output_____" ] ], [ [ "%%r_build_ui {\"name\": \"Expression of gene across all clusters\", \"parameters\": {\"gene\": {}, \"output_var\": {\"hide\": \"True\"}}}\ndo_umap_gene <- function(gene) {\n plot(FeaturePlot(pbmc, features = c(gene)))\n return(\"\")\n}\ndo_umap_gene(gene)", "_____no_output_____" ] ], [ [ "<div class=\"well well-sm\">\n \nFinally, take a look at a few different genes, some suggestions are: MMP7, and MMP2.\n- Crawford, Howard C et al. “Matrix metalloproteinase-7 is expressed by pancreatic cancer precursors and regulates acinar-to-ductal metaplasia in exocrine pancreas.” The Journal of clinical investigation vol. 109,11 (2002): 1437-44. doi:10.1172/JCI15051\n- Jakubowska, et al. “Expressions of Matrix Metalloproteinases 2, 7, and 9 in Carcinogenesis of Pancreatic Ductal Adenocarcinoma.” Disease Markers, Hindawi, 26 June 2016, www.hindawi.com/journals/dm/2016/9895721/.\n \n</div>", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
4a0d2eb72b0293a9585010e436a11a2471f79310
9,409
ipynb
Jupyter Notebook
agents/.ipynb_checkpoints/NN_qlearn_cartpole-checkpoint.ipynb
Rhushabh1/Mini-AI-Games
a9478c1e8bb93ffecdc247b0cf3ba7e3416ff095
[ "MIT" ]
null
null
null
agents/.ipynb_checkpoints/NN_qlearn_cartpole-checkpoint.ipynb
Rhushabh1/Mini-AI-Games
a9478c1e8bb93ffecdc247b0cf3ba7e3416ff095
[ "MIT" ]
null
null
null
agents/.ipynb_checkpoints/NN_qlearn_cartpole-checkpoint.ipynb
Rhushabh1/Mini-AI-Games
a9478c1e8bb93ffecdc247b0cf3ba7e3416ff095
[ "MIT" ]
null
null
null
35.2397
252
0.533638
[ [ [ "import gym\nimport random\nimport numpy as np\nimport time\nimport tensorflow.compat.v1 as tf\ntf.disable_v2_behavior()\nfrom gym.envs.registration import registry, register\nfrom IPython.display import clear_output", "WARNING:tensorflow:From /home/rhushabh/.local/lib/python3.8/site-packages/tensorflow/python/compat/v2_compat.py:96: disable_resource_variables (from tensorflow.python.ops.variable_scope) is deprecated and will be removed in a future version.\nInstructions for updating:\nnon-resource variables are not supported in the long term\n" ], [ "try:\n register(\n id='FrozenLakeNoSlip-v0',\n entry_point='gym.envs.toy_text:FrozenLakeEnv',\n kwargs={'map_name' : '4x4', 'is_slippery' : False},\n max_episode_steps=100,\n reward_threshold=0.70, # optimum = 0.74\n )\nexcept:\n pass\n\nenv_name = 'FrozenLakeNoSlip-v0'\nenv = gym.make(env_name)\nprint(env.observation_space)\nprint(env.action_space)", "Discrete(16)\nDiscrete(4)\n" ], [ "class Agent():\n def __init__(self, env):\n self.is_discrete = type(env.action_space == gym.spaces.discrete.Discrete)\n \n if self.is_discrete:\n self.action_size = env.action_space.n\n print(\"action size\", self.action_size)\n else:\n self.action_low = env.action_space.low\n self.action_high = env.action_space.high\n self.action_shape = env.action_space.shape\n print(\"action range\", self.action_low, self.action_high)\n \n def get_action(self, state):\n if self.is_discrete:\n action = random.choice(range(self.action_size))\n else:\n action = np.random.uniform(self.action_low, \n self.action_high, \n self.action_shape)\n# pole_angle = state[2]\n# action = 0 if pole_angle<0 else 1\n return action", "_____no_output_____" ], [ "class QNAgent(Agent):\n def __init__(self, env, discount_rate=0.97, learning_rate=0.01):\n super().__init__(env)\n self.state_size = env.observation_space.n\n print(\"state size\", self.state_size)\n \n self.eps = 1.0\n self.discount_rate = discount_rate\n self.learning_rate = learning_rate\n self.build_model()\n \n self.sess = tf.Session()\n self.sess.run(tf.global_variables_initializer())\n \n def build_model(self):\n tf.reset_default_graph()\n self.state_in = tf.placeholder(tf.int32, shape=[1])\n self.action_in = tf.placeholder(tf.int32, shape=[1])\n self.target_in = tf.placeholder(tf.float32, shape=[1])\n \n self.state = tf.one_hot(self.state_in, depth=self.state_size)\n self.action = tf.one_hot(self.action_in, depth=self.action_size)\n \n self.q_state = tf.layers.dense(self.state, units=self.action_size, name='q_table')\n self.q_action = tf.reduce_sum(tf.multiply(self.q_state, self.action), axis=1)\n \n self.loss = tf.reduce_sum(tf.square(self.target_in - self.q_action))\n self.optimizer = tf.train.AdamOptimizer(self.learning_rate).minimize(self.loss)\n \n def get_action(self, state):\n q_state = self.sess.run(self.q_state, feed_dict={self.state_in: [state]})\n action_greedy = np.argmax(q_state)\n action_random = super().get_action(state) \n return action_random if random.random() < self.eps else action_greedy\n \n def train(self, experience):\n state, action, next_state, reward, done = [[exp] for exp in experience]\n \n q_next = self.sess.run(self.q_state, feed_dict={self.state_in: next_state})\n q_next[done] = np.zeros([self.action_size])\n q_target = reward + self.discount_rate * np.max(q_next)\n \n feed = {self.state_in: state, self.action_in: action, self.target_in: q_target}\n self.sess.run(self.optimizer, feed_dict=feed)\n \n if experience[4]:\n self.eps = self.eps * 0.99\n \n def __del__(self):\n self.sess.close()\n \nagent = QNAgent(env) ", "action size 4\nstate size 16\n" ], [ "total_reward = 0\nfor ep in range(100):\n state = env.reset()\n done = False\n while not done:\n action = agent.get_action(state)\n next_state, reward, done, info = env.step(action)\n agent.train((state, action, next_state, reward, done))\n state = next_state\n total_reward += reward\n \n print(\"s\", state, \"a\", action)\n print(\"Episode: {}, Total Reward: {}, eps: {}\".format(ep, total_reward, agent.eps))\n env.render()\n with tf.variable_scope('q_table', reuse=True):\n weights = agent.sess.run(tf.get_variable(\"kernel\"))\n print(weights)\n time.sleep(0.05)\n clear_output(wait=True)\n \nenv.close()", "s 15 a 2\nEpisode: 99, Total Reward: 94.0, eps: 0.04904089407128576\n (Right)\nSFFF\nFHFH\nFFFH\nHFF\u001b[41mG\u001b[0m\n[[ 0.14308797 0.24822079 0.37045413 0.20545048]\n [ 0.13916846 -0.49372488 0.31665617 0.0581756 ]\n [ 0.09553888 0.1108096 0.30186507 0.10175668]\n [ 0.04884319 -0.30793354 0.15975532 -0.10328578]\n [ 0.16683719 0.27409965 -0.45249024 0.2195665 ]\n [-0.16810209 0.12941182 0.2716092 -0.5109889 ]\n [-0.5111402 -0.02730454 -0.45570606 0.24242021]\n [-0.26480454 -0.27236882 0.3914525 0.36197883]\n [ 0.14835835 -0.6129192 0.45827687 0.24370404]\n [ 0.1668269 0.2679096 0.4857323 -0.60761076]\n [ 0.21030821 0.35645518 -0.40255424 0.14535761]\n [-0.47490662 0.12705368 -0.12166277 -0.33817655]\n [ 0.38481516 0.33966404 -0.2220841 -0.47996986]\n [ 0.0207003 0.2411671 0.51648754 -0.07092325]\n [ 0.2616676 0.36289978 0.54491043 0.31746033]\n [ 0.14607841 -0.07755956 0.17504698 -0.01494348]]\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code" ] ]
4a0d478265733c0224b6f60525e4fdf307197617
81,184
ipynb
Jupyter Notebook
07_sparkml_and_bqml/logistic_regression.ipynb
AcornPublishing/google-cloud-platform
b46869fda79667af37bdd8aed6b0de63db504ebd
[ "ECL-2.0", "Apache-2.0" ]
1
2019-10-18T11:54:38.000Z
2019-10-18T11:54:38.000Z
07_sparkml_and_bqml/logistic_regression.ipynb
kalyanipande-tudip/data-science-on-gcp
c21863a828175b8893abf28ff903199c951f7f0c
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
07_sparkml_and_bqml/logistic_regression.ipynb
kalyanipande-tudip/data-science-on-gcp
c21863a828175b8893abf28ff903199c951f7f0c
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
96.762813
27,258
0.788197
[ [ [ "<h1> Logistic Regression using Spark ML </h1>\n\nSet up bucket", "_____no_output_____" ] ], [ [ "BUCKET='cloud-training-demos-ml' # CHANGE ME\n\nos.environ['BUCKET'] = BUCKET", "_____no_output_____" ], [ "# Create spark session\n\nfrom pyspark.sql import SparkSession\nfrom pyspark import SparkContext\n\nsc = SparkContext('local', 'logistic')\nspark = SparkSession \\\n .builder \\\n .appName(\"Logistic regression w/ Spark ML\") \\\n .getOrCreate()\n\nprint spark\nprint sc", "<pyspark.sql.session.SparkSession object at 0x7f36a5e228d0>\n<SparkContext master=yarn appName=pyspark-shell>\n" ], [ "from pyspark.mllib.classification import LogisticRegressionWithLBFGS\nfrom pyspark.mllib.regression import LabeledPoint", "_____no_output_____" ] ], [ [ "<h2> Read dataset </h2>", "_____no_output_____" ] ], [ [ "traindays = spark.read \\\n .option(\"header\", \"true\") \\\n .csv('gs://{}/flights/trainday.csv'.format(BUCKET))\ntraindays.createOrReplaceTempView('traindays')", "_____no_output_____" ], [ "spark.sql(\"SELECT * from traindays LIMIT 5\").show()", "+----------+------------+\n| FL_DATE|is_train_day|\n+----------+------------+\n|2015-01-01| True|\n|2015-01-04| True|\n|2015-01-05| True|\n|2015-01-07| True|\n|2015-01-08| True|\n+----------+------------+\n\n" ], [ "from pyspark.sql.types import StringType, FloatType, StructType, StructField\n\nheader = 'FL_DATE,UNIQUE_CARRIER,AIRLINE_ID,CARRIER,FL_NUM,ORIGIN_AIRPORT_ID,ORIGIN_AIRPORT_SEQ_ID,ORIGIN_CITY_MARKET_ID,ORIGIN,DEST_AIRPORT_ID,DEST_AIRPORT_SEQ_ID,DEST_CITY_MARKET_ID,DEST,CRS_DEP_TIME,DEP_TIME,DEP_DELAY,TAXI_OUT,WHEELS_OFF,WHEELS_ON,TAXI_IN,CRS_ARR_TIME,ARR_TIME,ARR_DELAY,CANCELLED,CANCELLATION_CODE,DIVERTED,DISTANCE,DEP_AIRPORT_LAT,DEP_AIRPORT_LON,DEP_AIRPORT_TZOFFSET,ARR_AIRPORT_LAT,ARR_AIRPORT_LON,ARR_AIRPORT_TZOFFSET,EVENT,NOTIFY_TIME'\n\ndef get_structfield(colname):\n if colname in ['ARR_DELAY', 'DEP_DELAY', 'DISTANCE', 'TAXI_OUT']:\n return StructField(colname, FloatType(), True)\n else:\n return StructField(colname, StringType(), True)\n\nschema = StructType([get_structfield(colname) for colname in header.split(',')])", "_____no_output_____" ], [ "inputs = 'gs://{}/flights/tzcorr/all_flights-00000-*'.format(BUCKET) # 1/30th; you may have to change this to find a shard that has training data\n#inputs = 'gs://{}/flights/tzcorr/all_flights-*'.format(BUCKET) # FULL\nflights = spark.read\\\n .schema(schema)\\\n .csv(inputs)\n\n# this view can now be queried ...\nflights.createOrReplaceTempView('flights')", "_____no_output_____" ] ], [ [ "<h2> Clean up </h2>", "_____no_output_____" ] ], [ [ "trainquery = \"\"\"\nSELECT\n f.*\nFROM flights f\nJOIN traindays t\nON f.FL_DATE == t.FL_DATE\nWHERE\n t.is_train_day == 'True'\n\"\"\"\ntraindata = spark.sql(trainquery)", "_____no_output_____" ], [ "print traindata.head(2) # if this is empty, try changing the shard you are using.", "[Row(FL_DATE=u'2015-11-26', UNIQUE_CARRIER=u'B6', AIRLINE_ID=u'20409', CARRIER=u'B6', FL_NUM=u'1447', ORIGIN_AIRPORT_ID=u'12197', ORIGIN_AIRPORT_SEQ_ID=u'1219702', ORIGIN_CITY_MARKET_ID=u'31703', ORIGIN=u'HPN', DEST_AIRPORT_ID=u'15304', DEST_AIRPORT_SEQ_ID=u'1530402', DEST_CITY_MARKET_ID=u'33195', DEST=u'TPA', CRS_DEP_TIME=u'2015-11-26T19:10:00', DEP_TIME=u'2015-11-26T19:14:00', DEP_DELAY=4.0, TAXI_OUT=13.0, WHEELS_OFF=u'2015-11-26T19:27:00', WHEELS_ON=u'2015-11-26T21:37:00', TAXI_IN=u'5.00', CRS_ARR_TIME=u'2015-11-26T22:03:00', ARR_TIME=u'2015-11-26T21:42:00', ARR_DELAY=-21.0, CANCELLED=u'0.00', CANCELLATION_CODE=None, DIVERTED=u'0.00', DISTANCE=1032.0, DEP_AIRPORT_LAT=u'41.06694444', DEP_AIRPORT_LON=u'-73.70750000', DEP_AIRPORT_TZOFFSET=u'-18000.0', ARR_AIRPORT_LAT=u'27.97555556', ARR_AIRPORT_LON=u'-82.53333333', ARR_AIRPORT_TZOFFSET=u'-18000.0', EVENT=None, NOTIFY_TIME=None), Row(FL_DATE=u'2015-11-26', UNIQUE_CARRIER=u'B6', AIRLINE_ID=u'20409', CARRIER=u'B6', FL_NUM=u'1454', ORIGIN_AIRPORT_ID=u'14843', ORIGIN_AIRPORT_SEQ_ID=u'1484304', ORIGIN_CITY_MARKET_ID=u'34819', ORIGIN=u'SJU', DEST_AIRPORT_ID=u'11697', DEST_AIRPORT_SEQ_ID=u'1169704', DEST_CITY_MARKET_ID=u'32467', DEST=u'FLL', CRS_DEP_TIME=u'2015-11-26T23:25:00', DEP_TIME=u'2015-11-26T23:36:00', DEP_DELAY=11.0, TAXI_OUT=11.0, WHEELS_OFF=u'2015-11-26T23:47:00', WHEELS_ON=u'2015-11-27T02:12:00', TAXI_IN=u'7.00', CRS_ARR_TIME=u'2015-11-27T02:11:00', ARR_TIME=u'2015-11-27T02:19:00', ARR_DELAY=8.0, CANCELLED=u'0.00', CANCELLATION_CODE=None, DIVERTED=u'0.00', DISTANCE=1046.0, DEP_AIRPORT_LAT=u'18.43944444', DEP_AIRPORT_LON=u'-66.00222222', DEP_AIRPORT_TZOFFSET=u'-14400.0', ARR_AIRPORT_LAT=u'26.07166667', ARR_AIRPORT_LON=u'-80.14972222', ARR_AIRPORT_TZOFFSET=u'-18000.0', EVENT=None, NOTIFY_TIME=None)]\n" ], [ "traindata.describe().show()", "+-------+----------+--------------+------------------+-------+------------------+------------------+---------------------+---------------------+------+------------------+-------------------+-------------------+----+-------------------+-------------------+------------------+------------------+-------------------+-------------------+-----------------+-------------------+-------------------+------------------+--------------------+-----------------+--------------------+-----------------+------------------+------------------+--------------------+------------------+------------------+--------------------+-----+-----------+\n|summary| FL_DATE|UNIQUE_CARRIER| AIRLINE_ID|CARRIER| FL_NUM| ORIGIN_AIRPORT_ID|ORIGIN_AIRPORT_SEQ_ID|ORIGIN_CITY_MARKET_ID|ORIGIN| DEST_AIRPORT_ID|DEST_AIRPORT_SEQ_ID|DEST_CITY_MARKET_ID|DEST| CRS_DEP_TIME| DEP_TIME| DEP_DELAY| TAXI_OUT| WHEELS_OFF| WHEELS_ON| TAXI_IN| CRS_ARR_TIME| ARR_TIME| ARR_DELAY| CANCELLED|CANCELLATION_CODE| DIVERTED| DISTANCE| DEP_AIRPORT_LAT| DEP_AIRPORT_LON|DEP_AIRPORT_TZOFFSET| ARR_AIRPORT_LAT| ARR_AIRPORT_LON|ARR_AIRPORT_TZOFFSET|EVENT|NOTIFY_TIME|\n+-------+----------+--------------+------------------+-------+------------------+------------------+---------------------+---------------------+------+------------------+-------------------+-------------------+----+-------------------+-------------------+------------------+------------------+-------------------+-------------------+-----------------+-------------------+-------------------+------------------+--------------------+-----------------+--------------------+-----------------+------------------+------------------+--------------------+------------------+------------------+--------------------+-----+-----------+\n| count| 9559| 9559| 9559| 9559| 9559| 9559| 9559| 9559| 9559| 9559| 9559| 9559|9559| 9559| 9533| 9533| 9531| 9531| 9527| 9527| 9559| 9527| 9514| 9559| 31| 9559| 9559| 9559| 9559| 9559| 9559| 9559| 9559| 0| 0|\n| mean| null| null|19854.703630086828| null| 2609.077937022701| 12652.85406423266| 1265288.2625797677| 31715.02761795167| null|12585.991526310283| 1258602.0389162046| 31682.230986504863|null| null| null|2.6588691912304627|14.627845976287903| null| null|7.149889786921381| null| null|-4.238385537103216|0.003243017051992886| null|0.001464588346061...| 869.220002092269|35.918674925542206|-94.73029416819357| -21903.546396066533| 35.94444581049187|-94.47358455185994| -21806.75802908254| null| null|\n| stddev| null| null|402.70507420771446| null|2053.3431814617616|1522.4049784934023| 152240.17071675116| 1276.3603481399443| null|1543.5954555365124| 154359.19877849414| 1280.0838349094581|null| null| null|29.729841487731417| 7.282754066063705| null| null|4.979740156733318| null| null|32.565523694571986| 0.05685805211885097| null|0.038243905845130204|617.1870728197283| 6.320118789761992| 19.16114616034329| 4869.836503663976|6.2752435684194845|19.090188990683455| 4865.578774855603| null| null|\n| min|2015-11-26| AA| 19393| AA| 1| 10135| 1013503| 30070| ABE| 10135| 1013503| 30070| ABE|2015-11-26T05:55:00|2015-11-26T05:58:00| -31.0| 2.0|2015-11-26T06:13:00|2015-11-26T09:41:00| 1.00|2015-11-26T10:02:00|2015-11-26T09:49:00| -62.0| 0.00| A| 0.00| 31.0| -14.33000000| -101.70583333| -14400.0| -14.33000000| -100.74583333| -14400.0| null| null|\n| max|2015-11-27| WN| 21171| WN| 999| 15991| 1599102| 35991| YAK| 15991| 1599102| 35991| YAK|2015-11-28T10:25:00|2015-11-28T10:03:00| 1631.0| 133.0|2015-11-28T10:16:00|2015-11-28T15:45:00| 93.00|2015-11-29T06:54:00|2015-11-28T15:59:00| 1638.0| 1.00| B| 1.00| 4983.0| 71.28472222| -99.46166667| 0| 71.28472222| -99.68194444| 0| null| null|\n+-------+----------+--------------+------------------+-------+------------------+------------------+---------------------+---------------------+------+------------------+-------------------+-------------------+----+-------------------+-------------------+------------------+------------------+-------------------+-------------------+-----------------+-------------------+-------------------+------------------+--------------------+-----------------+--------------------+-----------------+------------------+------------------+--------------------+------------------+------------------+--------------------+-----+-----------+\n\n" ] ], [ [ "Note that the counts for the various columns are all different; We have to remove NULLs in the delay variables (these correspond to canceled or diverted flights).", "_____no_output_____" ], [ "<h2> Logistic regression </h2>", "_____no_output_____" ] ], [ [ "trainquery = \"\"\"\nSELECT\n DEP_DELAY, TAXI_OUT, ARR_DELAY, DISTANCE\nFROM flights f\nJOIN traindays t\nON f.FL_DATE == t.FL_DATE\nWHERE\n t.is_train_day == 'True' AND\n f.dep_delay IS NOT NULL AND \n f.arr_delay IS NOT NULL\n\"\"\"\ntraindata = spark.sql(trainquery)\ntraindata.describe().show()", "+-------+------------------+-----------------+------------------+-----------------+\n|summary| DEP_DELAY| TAXI_OUT| ARR_DELAY| DISTANCE|\n+-------+------------------+-----------------+------------------+-----------------+\n| count| 9514| 9514| 9514| 9514|\n| mean|2.6394786630229135|14.62528904771915|-4.238385537103216|870.8421273912129|\n| stddev|29.693248310855065| 7.28500427136442|32.565523694571986| 617.509578518596|\n| min| -31.0| 2.0| -62.0| 31.0|\n| max| 1631.0| 133.0| 1638.0| 4983.0|\n+-------+------------------+-----------------+------------------+-----------------+\n\n" ], [ "trainquery = \"\"\"\nSELECT\n DEP_DELAY, TAXI_OUT, ARR_DELAY, DISTANCE\nFROM flights f\nJOIN traindays t\nON f.FL_DATE == t.FL_DATE\nWHERE\n t.is_train_day == 'True' AND\n f.CANCELLED == '0.00' AND \n f.DIVERTED == '0.00'\n\"\"\"\ntraindata = spark.sql(trainquery)\ntraindata.describe().show()", "+-------+------------------+-----------------+------------------+-----------------+\n|summary| DEP_DELAY| TAXI_OUT| ARR_DELAY| DISTANCE|\n+-------+------------------+-----------------+------------------+-----------------+\n| count| 9514| 9514| 9514| 9514|\n| mean|2.6394786630229135|14.62528904771915|-4.238385537103216|870.8421273912129|\n| stddev|29.693248310855065| 7.28500427136442|32.565523694571986| 617.509578518596|\n| min| -31.0| 2.0| -62.0| 31.0|\n| max| 1631.0| 133.0| 1638.0| 4983.0|\n+-------+------------------+-----------------+------------------+-----------------+\n\n" ], [ "def to_example(fields):\n return LabeledPoint(\\\n float(fields['ARR_DELAY'] < 15), #ontime? \\\n [ \\\n fields['DEP_DELAY'], \\\n fields['TAXI_OUT'], \\\n fields['DISTANCE'], \\\n ])", "_____no_output_____" ], [ "examples = traindata.rdd.map(to_example)", "_____no_output_____" ], [ "lrmodel = LogisticRegressionWithLBFGS.train(examples, intercept=True)\nprint lrmodel.weights,lrmodel.intercept", "[-0.162365742978,-0.160228517204,3.75487291939e-05] 5.95703978472\n" ], [ "print lrmodel.predict([6.0,12.0,594.0])\nprint lrmodel.predict([36.0,12.0,594.0])", "1\n0\n" ], [ "lrmodel.clearThreshold()\nprint lrmodel.predict([6.0,12.0,594.0])\nprint lrmodel.predict([36.0,12.0,594.0])", "0.956161192349\n0.143248721331\n" ], [ "lrmodel.setThreshold(0.7) # cancel if prob-of-ontime < 0.7\nprint lrmodel.predict([6.0,12.0,594.0])\nprint lrmodel.predict([36.0,12.0,594.0])", "1\n0\n" ] ], [ [ "<h2> Predict with the model </h2>\n\nFirst save the model", "_____no_output_____" ] ], [ [ "!gsutil -m rm -r gs://$BUCKET/flights/sparkmloutput/model", "_____no_output_____" ], [ "MODEL_FILE='gs://' + BUCKET + '/flights/sparkmloutput/model'", "_____no_output_____" ], [ "lrmodel.save(sc, MODEL_FILE)\nprint '{} saved'.format(MODEL_FILE)", "_____no_output_____" ], [ "lrmodel = 0\nprint lrmodel", "0\n" ] ], [ [ "Now retrieve the model", "_____no_output_____" ] ], [ [ "from pyspark.mllib.classification import LogisticRegressionModel\nlrmodel = LogisticRegressionModel.load(sc, MODEL_FILE)\nlrmodel.setThreshold(0.7)", "_____no_output_____" ], [ "print lrmodel.predict([36.0,12.0,594.0])", "0\n" ], [ "print lrmodel.predict([8.0,4.0,594.0])", "1\n" ] ], [ [ "<h2> Examine the model behavior </h2>\n\nFor dep_delay=20 and taxiout=10, how does the distance affect prediction?", "_____no_output_____" ] ], [ [ "lrmodel.clearThreshold() # to make the model produce probabilities\nprint lrmodel.predict([20, 10, 500])", "0.755139551394\n" ], [ "import matplotlib.pyplot as plt\nimport seaborn as sns\nimport pandas as pd\nimport numpy as np\ndist = np.arange(10, 2000, 10)\nprob = [lrmodel.predict([20, 10, d]) for d in dist]", "_____no_output_____" ], [ "sns.set_style(\"whitegrid\")\nax = plt.plot(dist, prob)\nplt.xlabel('distance (miles)')\nplt.ylabel('probability of ontime arrival')", "_____no_output_____" ], [ "delay = np.arange(-20, 60, 1)\nprob = [lrmodel.predict([d, 10, 500]) for d in delay]\nax = plt.plot(delay, prob)\nplt.xlabel('departure delay (minutes)')\nplt.ylabel('probability of ontime arrival')", "_____no_output_____" ] ], [ [ "<h2> Evaluate model </h2>\n\nEvaluate on the test data", "_____no_output_____" ] ], [ [ "inputs = 'gs://{}/flights/tzcorr/all_flights-00001-*'.format(BUCKET) # you may have to change this to find a shard that has test data\nflights = spark.read\\\n .schema(schema)\\\n .csv(inputs)\nflights.createOrReplaceTempView('flights')\ntestquery = trainquery.replace(\"t.is_train_day == 'True'\",\"t.is_train_day == 'False'\")\nprint testquery", "\nSELECT\n DEP_DELAY, TAXI_OUT, ARR_DELAY, DISTANCE\nFROM flights f\nJOIN traindays t\nON f.FL_DATE == t.FL_DATE\nWHERE\n t.is_train_day == 'False' AND\n f.CANCELLED == '0.00' AND \n f.DIVERTED == '0.00'\n\n" ], [ "testdata = spark.sql(testquery)\nexamples = testdata.rdd.map(to_example)", "_____no_output_____" ], [ "testdata.describe().show() # if this is empty, change the shard you are using", "+-------+-----------------+------------------+------------------+-----------------+\n|summary| DEP_DELAY| TAXI_OUT| ARR_DELAY| DISTANCE|\n+-------+-----------------+------------------+------------------+-----------------+\n| count| 31721| 31721| 31721| 31721|\n| mean|22.06188329497809|17.100438195517164|18.437785694019734|861.5131301030863|\n| stddev|55.27263492541411| 9.92470074434109| 58.42307362543692| 623.824325676582|\n| min| -43.0| 1.0| -65.0| 31.0|\n| max| 1239.0| 140.0| 1214.0| 4983.0|\n+-------+-----------------+------------------+------------------+-----------------+\n\n" ], [ "def eval(labelpred):\n cancel = labelpred.filter(lambda (label, pred): pred < 0.7)\n nocancel = labelpred.filter(lambda (label, pred): pred >= 0.7)\n corr_cancel = cancel.filter(lambda (label, pred): label == int(pred >= 0.7)).count()\n corr_nocancel = nocancel.filter(lambda (label, pred): label == int(pred >= 0.7)).count()\n \n cancel_denom = cancel.count()\n nocancel_denom = nocancel.count()\n if cancel_denom == 0:\n cancel_denom = 1\n if nocancel_denom == 0:\n nocancel_denom = 1\n return {'total_cancel': cancel.count(), \\\n 'correct_cancel': float(corr_cancel)/cancel_denom, \\\n 'total_noncancel': nocancel.count(), \\\n 'correct_noncancel': float(corr_nocancel)/nocancel_denom \\\n }\n\n# Evaluate model\nlrmodel.clearThreshold() # so it returns probabilities\nlabelpred = examples.map(lambda p: (p.label, lrmodel.predict(p.features)))\nprint 'All flights:'\nprint eval(labelpred)\n\n# keep only those examples near the decision threshold\nprint 'Flights near decision threshold:'\nlabelpred = labelpred.filter(lambda (label, pred): pred > 0.65 and pred < 0.75)\nprint eval(labelpred)", "All flights:\n{'correct_cancel': 0.8220530174844896, 'total_noncancel': 21083, 'correct_noncancel': 0.938765830289807, 'total_cancel': 10638}\nFlights near decision threshold:\n{'correct_cancel': 0.30975143403441685, 'total_noncancel': 461, 'correct_noncancel': 0.7700650759219089, 'total_cancel': 523}\n" ] ], [ [ "Copyright 2019 Google Inc. Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ] ]
4a0d4aad0754eeca6ea53ed4a56afa6457fe288a
170,767
ipynb
Jupyter Notebook
notebook/mobility_cdmx.ipynb
jballesterosc/mobility-covid19
29bfe39a8f17f40ac92f6956c2784427ec63a65a
[ "MIT" ]
2
2020-11-29T04:15:19.000Z
2022-03-02T15:49:04.000Z
notebook/mobility_cdmx.ipynb
jballesterosc/mobility-covid19
29bfe39a8f17f40ac92f6956c2784427ec63a65a
[ "MIT" ]
null
null
null
notebook/mobility_cdmx.ipynb
jballesterosc/mobility-covid19
29bfe39a8f17f40ac92f6956c2784427ec63a65a
[ "MIT" ]
2
2020-11-18T05:22:48.000Z
2020-11-19T03:05:49.000Z
824.961353
165,183
0.723454
[ [ [ "import pandas as pd\nimport warnings\nimport altair as alt\nfrom urllib import request\nimport json\n\n", "_____no_output_____" ], [ "# fetch & enable a Spanish timeFormat locale.\nwith request.urlopen('https://raw.githubusercontent.com/d3/d3-time-format/master/locale/es-ES.json') as f:\n es_time_format = json.load(f)\nalt.renderers.set_embed_options(timeFormatLocale=es_time_format)\n\n#warnings.filterwarnings('ignore')\n\ndf = pd.read_csv ('https://www.gstatic.com/covid19/mobility/Global_Mobility_Report.csv')", "_____no_output_____" ], [ "country = 'Mexico'\nregion = 'Mexico City'\nsub_df = df[(df['country_region']== country) & (df['sub_region_1']==region)]\nsub_df.loc[:,'date'] = pd.to_datetime(sub_df.loc[:,'date'])\n# Change date here\nsub_df = sub_df[(sub_df['date'] > '2020-02-15') & (sub_df['date'] < '2020-11-17')]\nsub_df = sub_df.sort_values('date', ascending=True)\n", "_____no_output_____" ], [ "%run urban_theme.py\n\nretail_recretation = alt.Chart(sub_df).mark_line(size=1).encode(\n alt.X('date:T', title = \" \"),\n alt.Y('retail_and_recreation_percent_change_from_baseline:Q', title = \" \"),\n).properties(\n title = \"Lugares de ocio\",\n width = 450,\n height = 250\n)\n\ngrocery_pharmacy = alt.Chart(sub_df).mark_line(size=1).encode(\n alt.X('date:T', title = \" \"),\n alt.Y('grocery_and_pharmacy_percent_change_from_baseline:Q', title = \" \"),\n).properties(\n title = \"Mercados y farmacias\",\n width = 450,\n height = 250\n)\n\nparks = alt.Chart(sub_df).mark_line(size=1).encode(\n alt.X('date:T', title = \" \"),\n alt.Y('parks_percent_change_from_baseline:Q', title = \" \")\n).properties(\n title = \"Parques y playas\",\n width = 450,\n height = 250\n)\n\n\ntransit = alt.Chart(sub_df).mark_line(size=1).encode(\n alt.X('date:T', title = \" \"),\n alt.Y('transit_stations_percent_change_from_baseline:Q', title = \" \")\n).properties(\n title = \"Transporte público\",\n width = 450,\n height = 250\n)\n\nworkplaces = alt.Chart(sub_df).mark_line(size=1).encode(\n alt.X('date:T', title = \" \"),\n alt.Y('workplaces_percent_change_from_baseline:Q', title = \" \")\n).properties(\n title = \"Lugares de trabajo\",\n width = 450,\n height = 250\n)\n\nresidential = alt.Chart(sub_df).mark_line(size=1).encode(\n alt.X('date:T', title = \" \"),\n alt.Y('residential_percent_change_from_baseline:Q', title = \" \")\n).properties(\n title = \"Residenciales\",\n width = 450,\n height = 250\n)\n", "_____no_output_____" ], [ "par1 = retail_recretation | grocery_pharmacy | parks\npar2 = transit | workplaces | residential\n\nmobility = par1 & par2", "_____no_output_____" ], [ "# Title of the concatened grpah\nmobility_1 = mobility.properties(\n title={\n \"text\":[\"Movilidad en CDMX\"],\n \"subtitle\": [\"Datos del 15 de febrero al 15 de noviembre de 2020.\", \" \"],\n }\n)", "_____no_output_____" ], [ "#Add footer\n\nalt.concat(mobility_1).properties(\n title=alt.TitleParams(\n ['Fuente: Elaboración propia con datos del COVID-19 Community Mobility Reports de Google.', 'Jay Ballesteros (@jballesterosc_)'],\n baseline='bottom',\n orient='bottom',\n anchor='end',\n fontWeight='normal',\n fontSize=12\n )\n)", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code" ] ]
4a0d54f1f2ba8ade46c98607fc38d08f8e8b5bc1
845,729
ipynb
Jupyter Notebook
notebooks/turian_models.ipynb
mbatchkarov/ExpLosion
705039ec5f77c4203c98487f80d74b9d1f4fd501
[ "BSD-3-Clause" ]
1
2015-10-21T08:53:55.000Z
2015-10-21T08:53:55.000Z
notebooks/turian_models.ipynb
mbatchkarov/ExpLosion
705039ec5f77c4203c98487f80d74b9d1f4fd501
[ "BSD-3-Clause" ]
null
null
null
notebooks/turian_models.ipynb
mbatchkarov/ExpLosion
705039ec5f77c4203c98487f80d74b9d1f4fd501
[ "BSD-3-Clause" ]
null
null
null
791.881086
225,550
0.934593
[ [ [ "%cd ~/NetBeansProjects/ExpLosion/\nfrom notebooks.common_imports import *\nfrom gui.output_utils import *\nfrom gui.user_code import pairwise_significance_exp_ids\n\nquery = {'expansions__decode_handler': 'SignifiedOnlyFeatureHandler',\n 'expansions__vectors__dimensionality': 100,\n 'expansions__vectors__rep': 0,\n 'expansions__vectors__unlabelled': 'turian'}", "/Volumes/LocalDataHD/m/mm/mmb28/NetBeansProjects/ExpLosion\n" ], [ "ids = Experiment.objects.filter(**query).values_list('id', flat=True)\nprint('ids are', ids)\ndf = dataframe_from_exp_ids(ids, {'Algorithm':'expansions__vectors__algorithm', \n 'Composer':'expansions__vectors__composer',\n 'Features': 'document_features_tr'})\n", "ids are [38, 39, 40, 41, 42]\nFeatures has 2500 values\nAccuracy has 2500 values\nfolds has 2500 values\nComposer has 2500 values\nAlgorithm has 2500 values\n" ], [ "ids = list(ids.values_list('id', flat=True))\nfor eid in ids + [1]:\n exp = Experiment.objects.get(id=eid)\n mean, low, high, _ = get_ci(eid)\n print('%s & %.2f$\\pm$%.2f \\\\\\\\'%(exp.expansions.vectors.composer, mean, (high-low)/2))", "Add & 0.24$\\pm$0.01 \\\\\nMult & 0.24$\\pm$0.01 \\\\\nLeft & 0.23$\\pm$0.01 \\\\\nRight & 0.21$\\pm$0.01 \\\\\nSocher & 0.24$\\pm$0.01 \\\\\nrandom_neigh & 0.22$\\pm$0.01 \\\\\n" ], [ "pairwise_significance_exp_ids(zip(ids, [1]*len(ids)), name_format=['expansions__vectors__composer'])", "Running significance for (38, 1)\nRunning significance for (39, 1)\nRunning significance for (40, 1)\nRunning significance for (41, 1)\nRunning significance for (42, 1)\n" ], [ "df.head()", "_____no_output_____" ], [ "def f1(x):\n return '%1.2f' % x\n\n# ddf = df.drop('folds', axis=1).groupby(['Composer', 'k']).agg([np.mean, np.std])\n# ddf.columns = ddf.columns.droplevel(0)#.reset_index()\n# ddf['Accuracy'] = ddf['mean'].map(f1) + \"$\\pm$\" + ddf['std'].map(f1)\n# ddf = ddf.drop(['mean', 'std'], axis=1).reset_index()\n# print(ddf.pivot_table(values='Accuracy', index='k', \n# columns='Composer', aggfunc=lambda x: x).to_latex(escape=False))\n\nddf = df.drop(['folds', 'Algorithm'], axis=1).groupby(['Composer', 'Features']).agg('mean').reset_index() # no need to drop unwanted columns\nres = ddf.pivot_table(values='Accuracy', index='Composer', columns='Features')\nprint(res.to_latex(float_format=f1, na_rep='N/A'))\nres.T", "\\begin{tabular}{lr}\n\\toprule\nFeatures & J+N+AN+NN \\\\\n\\midrule\nComposer & \\\\\nAdd & 0.24 \\\\\nLeft & 0.23 \\\\\nMult & 0.24 \\\\\nRight & 0.21 \\\\\nSocher & 0.24 \\\\\n\\bottomrule\n\\end{tabular}\n\n" ], [ "del res.index.name\ndel res.columns.name\nfor c in res.columns:\n print(res[[c]].to_latex(float_format=f1, na_rep='N/A'))\nres[[c]]", "\\begin{tabular}{lr}\n\\toprule\n{} & J+N+AN+NN \\\\\n\\midrule\nAdd & 0.24 \\\\\nLeft & 0.23 \\\\\nMult & 0.24 \\\\\nRight & 0.21 \\\\\nSocher & 0.24 \\\\\n\\bottomrule\n\\end{tabular}\n\n" ] ], [ [ "# Compare to word2vec qualitatively ", "_____no_output_____" ] ], [ [ "from discoutils.thesaurus_loader import Vectors\nfrom discoutils.tokens import DocumentFeature", "_____no_output_____" ], [ "v1 = Vectors.from_tsv('../FeatureExtractionToolkit/socher_vectors/turian_unigrams.h5')\nv1.init_sims(n_neighbors=25)", "_____no_output_____" ], [ "v2 = Vectors.from_tsv('../FeatureExtractionToolkit/word2vec_vectors/word2vec-wiki-15perc.unigr.strings.rep0')\nv2.init_sims(n_neighbors=25)", "_____no_output_____" ], [ "\ndef compare_neighbours(vectors, names, words=[], n_neighbours=5):\n if not words:\n words = random.sample([x for x in vectors[0].keys() if not x.count('_')], 10)\n words_clean = [DocumentFeature.from_string(w).tokens[0].text for w in words]\n data = []\n for w, w_clearn in zip(words, words_clean):\n this_row = []\n for v in vectors:\n neigh = v.get_nearest_neighbours(w)\n # remove neigh with the same PoS (for turian)\n new_neigh = []\n for n, _ in neigh:\n n1 = DocumentFeature.from_string(n).tokens[0].text\n# print(n, n1)\n if n1 not in new_neigh:\n if n1 != w_clearn:\n new_neigh.append(n1)\n# print(new_neigh)\n if neigh:\n this_row.append(', '.join(n for n in new_neigh[:n_neighbours]))\n else:\n this_row.append(None)\n data.append(this_row)\n return pd.DataFrame(data, index=words_clean, columns=names)", "_____no_output_____" ], [ "# bunch of random words contained in both\nwords = 'andrade/N giant/J seize/V fundamental/J affidavit/N claim/V sikh/N rest/V israel/N arrow/N preventative/J torrential/J'.split()\ndf = compare_neighbours([v1, v2], ['turian', 'w2v'], words, n_neighbours=5)\ndf.to_csv('turian_vs_w2v.csv')\ndf", "_____no_output_____" ], [ "print(pd.DataFrame(df.turian).to_latex())", "\\begin{tabular}{ll}\n\\toprule\n{} & turian \\\\\n\\midrule\nandrade & aslam, rahman, aguirre, weinstein, chandra \\\\\ngiant & monopoly, retailer, group, utility, unit \\\\\nseize & dissolve, renew, suppress, restore, donate \\\\\nfundamental & inflationary, external, structural, speculativ... \\\\\naffidavit & organization, affair, squad, essay, audience \\\\\nclaim & request, link, plan, challenge, drive \\\\\nsikh & gambian, tutsi, bugging, zairean, rioting \\\\\nrest & size, duration, bottom, end, depth \\\\\nisrael & beijing, washington, bonn, pakistan, russia \\\\\narrow & atlantic, mississippi, mall, iberian, caribbean \\\\\npreventative & periodic, disgrace, compensatory, conclusive, ... \\\\\ntorrential & intermittent, severe, persistent, gusty, planting \\\\\n\\bottomrule\n\\end{tabular}\n\n" ], [ "print(pd.DataFrame(df['w2v']).to_latex())", "\\begin{tabular}{ll}\n\\toprule\n{} & w2v \\\\\n\\midrule\nandrade & souza, camilo, vives, leopoldo, barros \\\\\ngiant & gigantic, legless, man-eating, serpentine, horned \\\\\nseize & capture, re-take, attack, demoralise, crush \\\\\nfundamental & principle, epistemic, objective, indeterminism... \\\\\naffidavit & testimony, al-arian, subpoena, demjanjuk, minkow \\\\\nclaim & allege, assert, believe, suggest, acknowledge \\\\\nsikh & sikhs, hindus, shi'ite, hindu, shiite \\\\\nrest & dais, keep, gorge, gibbet, parihaka \\\\\nisrael & iran, palestine, al-sadr, gush, salafi \\\\\narrow & bullet, quiver, gauntlet, upturned, sword \\\\\npreventative & preventive, prophylactic, life-saving, high-ri... \\\\\ntorrential & downpour, monsoonal, rainstorm, freezing, sleet \\\\\n\\bottomrule\n\\end{tabular}\n\n" ] ], [ [ "# How many words of each PoS type are there in turian's unigrams\nCode below largely copied from `socher_vectors.py`", "_____no_output_____" ] ], [ [ "from scipy.io import loadmat\nmat = loadmat('../FeatureExtractionToolkit/socher_vectors/vars.normalized.100.mat')\nwords = [w[0] for w in mat['words'].ravel()]", "_____no_output_____" ], [ "import nltk\nfrom nltk import WordNetLemmatizer\nimport string\nfrom collections import defaultdict\n\nlmtzr = WordNetLemmatizer()\nclean_to_dirty = defaultdict(list) # canonical -> [non-canonical]\ndirty_to_clean = dict() # non-canonical -> canonical\nto_keep = set() # which non-canonical forms forms we will keep\n# todo this can be done based on frequency or something\n\nfor w in words:\n if set(w).intersection(set(string.punctuation).union(set('0123456789'))):\n # not a real word- contains digits or punctuation\n continue\n\n lemma = lmtzr.lemmatize(w.lower())\n clean_to_dirty[lemma].append(w)\n dirty_to_clean[w] = lemma\n\n# decide which of possibly many non-canonical forms with the same lemma to keep\n# prefer shorter and lowercased non-canonical forms\nfor lemma, dirty_list in clean_to_dirty.items():\n if len(dirty_list) > 1:\n best_lemma = min(dirty_list, key=lambda w: (len(w), not w.islower()))\n else:\n best_lemma = dirty_list[0]\n to_keep.add(best_lemma)", "_____no_output_____" ], [ "pos_tagged = [nltk.pos_tag([w]) for w in to_keep]", "_____no_output_____" ], [ "from collections import defaultdict\npos_coarsification_map = defaultdict(lambda: \"UNK\")\npos_coarsification_map.update({\"JJ\": \"J\",\n \"JJN\": \"J\",\n \"JJS\": \"J\",\n \"JJR\": \"J\",\n\n \"VB\": \"V\",\n \"VBD\": \"V\",\n \"VBG\": \"V\",\n \"VBN\": \"V\",\n \"VBP\": \"V\",\n \"VBZ\": \"V\",\n\n \"NN\": \"N\",\n \"NNS\": \"N\",\n \"NNP\": \"N\",\n \"NPS\": \"N\",\n \"NP\": \"N\",\n\n \"RB\": \"RB\",\n \"RBR\": \"RB\",\n \"RBS\": \"RB\",\n\n \"DT\": \"DET\",\n \"WDT\": \"DET\",\n\n \"IN\": \"CONJ\",\n \"CC\": \"CONJ\",\n\n \"PRP\": \"PRON\",\n \"PRP$\": \"PRON\",\n \"WP\": \"PRON\",\n \"WP$\": \"PRON\",\n\n \".\": \"PUNCT\",\n \":\": \"PUNCT\",\n \":\": \"PUNCT\",\n \"\": \"PUNCT\",\n \"'\": \"PUNCT\",\n \"\\\"\": \"PUNCT\",\n \"'\": \"PUNCT\",\n \"-LRB-\": \"PUNCT\",\n \"-RRB-\": \"PUNCT\"})", "_____no_output_____" ], [ "pos_tags = [pos_coarsification_map[x[0][1]] for x in pos_tagged]", "_____no_output_____" ], [ "from collections import Counter\nCounter(pos_tags)", "_____no_output_____" ] ], [ [ "# Let's look at the embeddings ", "_____no_output_____" ] ], [ [ "from sklearn.manifold import TSNE\nfrom sklearn.preprocessing import normalize\nsns.set_style('white')\n\ndef draw_tsne_embeddings(v):\n # pairs of words from Mikolov et al (2013)- Distributed word reprs and their compositionality\n # ignored some pairs that do not have a vectors\n words = 'china/N beijing/N russia/N moscow/N japan/N tokyo/N turkey/N ankara/N france/N \\\n paris/N italy/N rome/N greece/N athens/N germany/N berlin/N portugal/N lisbon/N spain/N madrid/N'.split()\n mat = np.vstack([v.get_vector(w).A for w in words])\n reduced = TSNE(init='pca').fit_transform(normalize(mat))\n# ax = plt.fig\n plt.scatter(reduced[:, 0], reduced[:, 1]);\n\n # point labels\n for i, txt in enumerate(words):\n plt.annotate(txt, (reduced[i, 0], reduced[i, 1]), fontsize=20);\n\n # lines between country-capital pairs\n for i in range(len(words)):\n if i %2 != 0:\n continue\n plt.plot([reduced[i, 0], reduced[i+1, 0]],\n [reduced[i, 1], reduced[i+1, 1]], alpha=0.5, color='black')\n \n # remove all junk from plot\n sns.despine(left=True, bottom=True)\n plt.gca().xaxis.set_major_locator(plt.NullLocator())\n plt.gca().yaxis.set_major_locator(plt.NullLocator())", "_____no_output_____" ], [ "v = Vectors.from_tsv('../FeatureExtractionToolkit/word2vec_vectors/word2vec-wiki-100perc.unigr.strings.rep0') # look very good \ndraw_tsne_embeddings(v)\nplt.savefig('plot-mikolov-tsne-w2v-wiki.pdf', format='pdf', dpi=300, bbox_inches='tight', pad_inches=0.1)", "_____no_output_____" ], [ "v = Vectors.from_tsv('../FeatureExtractionToolkit/word2vec_vectors/word2vec-gigaw-100perc.unigr.strings.rep0') # ok \ndraw_tsne_embeddings(v)\nplt.savefig('plot-mikolov-tsne-w2v-gigaw.pdf', format='pdf', dpi=300, bbox_inches='tight', pad_inches=0.1)", "_____no_output_____" ], [ "v = Vectors.from_tsv('../FeatureExtractionToolkit/socher_vectors/turian_unigrams.h5') # terrible\ndraw_tsne_embeddings(v)\nplt.savefig('plot-mikolov-tsne-turian.pdf', format='pdf', dpi=300, bbox_inches='tight', pad_inches=0.1)", "_____no_output_____" ], [ "v = Vectors.from_tsv('../FeatureExtractionToolkit/glove/vectors.miro.h5') # terrible\ndraw_tsne_embeddings(v)\nplt.savefig('plot-mikolov-tsne-glove-wiki.pdf', format='pdf', dpi=300, bbox_inches='tight', pad_inches=0.1)", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ] ]
4a0d5e81954182a9d85ed5350d1fc02ccd40b9b6
17,123
ipynb
Jupyter Notebook
tutorial.ipynb
NINFA-UFES/ESPset
57886936cfe787ada76aec42fe46a668ca507335
[ "MIT" ]
null
null
null
tutorial.ipynb
NINFA-UFES/ESPset
57886936cfe787ada76aec42fe46a668ca507335
[ "MIT" ]
null
null
null
tutorial.ipynb
NINFA-UFES/ESPset
57886936cfe787ada76aec42fe46a668ca507335
[ "MIT" ]
null
null
null
52.363914
8,328
0.677043
[ [ [ "# Load Dataset", "_____no_output_____" ], [ "## loading spectrum", "_____no_output_____" ] ], [ [ "import numpy as np\n\nsignals = np.loadtxt('data/spectrum.csv', delimiter=';')\nsignals.shape", "_____no_output_____" ] ], [ [ "## loading labels and features", "_____no_output_____" ] ], [ [ "import pandas as pd\nimport seaborn as sns\n\nfeatures = pd.read_csv('data/features.csv',sep=';', index_col='id')\nlabels = features['label']\nesp_id = features['esp_id']\nlabels.hist();\nfeatures.head()", "_____no_output_____" ] ], [ [ "# Cross-validation on models applied to ICTAI2016 features", "_____no_output_____" ] ], [ [ "from sklearn.ensemble import RandomForestClassifier\nfrom sklearn.model_selection import cross_validate, StratifiedKFold\nfrom PredefinedKFold import PredefinedKFold\n\nICTAI2016_features = ['a', 'b', 'real_rotation_hz', 'peak1x', 'peak2x', 'rms(freq-1,freq+1)',\n 'median(freq-1,freq+1)', 'median(3,5)']\n\nX = features[ICTAI2016_features]\n\nrf = RandomForestClassifier(n_estimators=100, max_features=5)", "_____no_output_____" ] ], [ [ "## cross-validation using ESP group", "_____no_output_____" ] ], [ [ "sampler = PredefinedKFold(n_rounds=1) # run 1 round only.\nscores = cross_validate(rf, X, labels, groups=esp_id, scoring='f1_macro', cv=sampler)\nscores['test_score']", "_____no_output_____" ] ], [ [ "## cross-validation using StratifiedKFold", "_____no_output_____" ] ], [ [ "sampler = StratifiedKFold(n_splits=4, shuffle=True) # run 1 round only.\nscores = cross_validate(rf, X, labels, groups=esp_id, scoring='f1_macro', cv=sampler)\nscores['test_score']", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
4a0d70c68979d2c14a675e65185a8778694b52ba
30,089
ipynb
Jupyter Notebook
topics/15_lussen.ipynb
misja/programmeren
9abf7fae0b810f1a09d97d7ea18936766913c5df
[ "MIT" ]
4
2020-09-03T09:12:59.000Z
2021-12-15T23:15:45.000Z
topics/15_lussen.ipynb
misja/programmeren
9abf7fae0b810f1a09d97d7ea18936766913c5df
[ "MIT" ]
40
2020-09-07T06:15:16.000Z
2021-12-13T22:01:41.000Z
topics/15_lussen.ipynb
misja/programmeren
9abf7fae0b810f1a09d97d7ea18936766913c5df
[ "MIT" ]
4
2021-02-01T20:02:57.000Z
2021-08-10T09:08:39.000Z
17.57535
337
0.429027
[ [ [ "# Lussen\n\nLooping `for` a `while`", "_____no_output_____" ], [ "## `for` lussen", "_____no_output_____" ] ], [ [ "for i in [0, 1, 2]:\n print(\"i is\", i)", "i is 0\ni is 1\ni is 2\n" ], [ "for i in range(0, 3):\n print(\"i is\", i)", "i is 0\ni is 1\ni is 2\n" ], [ "for x in [10, 15, 2020]:\n print(\"x is\", x)", "x is 10\nx is 15\nx is 2020\n" ] ], [ [ "```python\nfor i in ...:\n print(\"Gefeliciteerd\")\n```", "_____no_output_____" ], [ "Hoe kan dit 10 keer worden uitgevoerd? Hier is een reeks aan oplossingen mogelijk...", "_____no_output_____" ] ], [ [ "for i in range(10):\n print(\"Gefeliciteerd!\")", "Gefeliciteerd!\nGefeliciteerd!\nGefeliciteerd!\nGefeliciteerd!\nGefeliciteerd!\nGefeliciteerd!\nGefeliciteerd!\nGefeliciteerd!\nGefeliciteerd!\nGefeliciteerd!\n" ] ], [ [ "## `for` fun(cties)", "_____no_output_____" ] ], [ [ "def fun1():\n for i in range(0, 3):\n print(\"i is\", i)\n return", "_____no_output_____" ], [ "def fun2():\n for i in range(0, 3):\n print(\"i is\", i)\n return", "_____no_output_____" ] ], [ [ "## Meer `for`", "_____no_output_____" ] ], [ [ "def fun1B():\n for i in range(1, 6):\n if i % 2 == 0:\n print(\"i is\", i)\n return", "_____no_output_____" ], [ "fun1B()", "i is 2\n" ], [ "def fun2B():\n for i in range(1, 6):\n if i % 2 == 0:\n print(\"i is\", i)\n return", "_____no_output_____" ], [ "fun2B()", "_____no_output_____" ], [ "def fun3B():\n for i in range(1,6):\n if i % 2 == 0:\n print(\"i is\", i)\n return", "_____no_output_____" ], [ "fun3B()", "i is 2\ni is 4\n" ] ], [ [ "```python\ndef fun3B():\n for i in range(1,6):\n if i % 2 == 0:\n print(\"i is\", i)\nreturn\n```", "_____no_output_____" ], [ "![SyntaxError return](images/15/syntax_error_return.png)", "_____no_output_____" ], [ "## Hmmm\n\nIteratieve oplossingen\n\nBlokken herhalen tot een conditie is bereikt, lussen!", "_____no_output_____" ], [ "Bereken de faculteit van een getal\n\n```asm\n00 read r1\n01 setn r13 1\n02 jeqzn r1 6\n03 mul r13 r13 r1\n04 addn r1 -1\n05 jumpn 02\n06 write r13\n07 halt\n```", "_____no_output_____" ], [ "- `02` tot `r1` gelijk is aan 0 ...\n- `03` vermenigvuldig `r13` met `r1` en overschrijf `r13` met het resultaat\n- `04` verminder `r1` met 1\n- `05` herhaal", "_____no_output_____" ], [ "### Hmmm denken in Python", "_____no_output_____" ], [ "```python\ndef fac(x): # 00 read r1\n result = 1 # 01 setn r13 1\n while x != 0: # 02 jeqzn r1 6\n result *= x # 03 mul r13 r13 r1\n x -= 1 # 04 addn r1 -1\n # 05 jumpn 02\n return result # 06 write r13\n # 07 halt\n```", "_____no_output_____" ], [ "We hebben nu de voordelen van *expliciete* lussen én op zichzelf staande functies!", "_____no_output_____" ], [ "### Recursieve versie", "_____no_output_____" ] ], [ [ "def fac(x):\n \"\"\"faculty, recursive version\n \"\"\"\n if x == 0:\n return 1\n else:\n return x * fac(x - 1)", "_____no_output_____" ] ], [ [ "```asm\n00 read r1\n01 setn r15 42\n02 call r14 5\n03 jump 21\n04 nop\n05 jnezn r1 8\n06 setn r13 1\n07 jumpr r14\n08 storer r1 r15\n09 addn r15 1\n10 storer r14 r15\n11 addn r15 1\n12 addn r1 -1\n13 call r14 5\n14 addn r15 -1\n15 loadr r14 r15\n16 addn r15 -1\n17 loadr r1 r15\n18 mul r13 r13 r1\n19 jumpr r14\n20 nop\n21 write r13\n22 halt\n```", "_____no_output_____" ], [ "## Iteratief ontwerp\n\nLussen! Variabelen!", "_____no_output_____" ], [ "`for`\n\n```python\nfor x in [40, 41, 42]:\n print(x)\n```", "_____no_output_____" ], [ "`while`\n\n```python\nx = 42\nwhile x > 0:\n print(x)\n x -= 1\n```", "_____no_output_____" ], [ "Variabelen\n\n```python\nx = 41\nx += 1 # addn r1 1\n```", "_____no_output_____" ], [ "### Variabelen\n\nVariëren!", "_____no_output_____" ], [ "```python\nage = 41\n```", "_____no_output_____" ], [ "```python\nage = age + 1\n```", "_____no_output_____" ], [ "Wat hetzelfde is als ...", "_____no_output_____" ], [ "```python\nage += 1\n```", "_____no_output_____" ], [ "### In het kort", "_____no_output_____" ], [ "```python\nhwToGo = 7\nhwToGo = hwToGo - 1\n```", "_____no_output_____" ], [ "```python\nhwToGo -= 1\n```", "_____no_output_____" ], [ "```python\ntotal = 21000000\ntotal = total * 2\n```", "_____no_output_____" ], [ "```python\ntotal *= 2\n```", "_____no_output_____" ], [ "```python\nu235 = 84000000000000000;\nu235 = u235 / 2\n```", "_____no_output_____" ], [ "```python\nu235 /= 2\n```", "_____no_output_____" ], [ "## `for`!", "_____no_output_____" ], [ "```python\nfor x in [2, 4, 6, 8]:\n print(\"x is\", x)\n\nprint(\"Done!\")\n```", "_____no_output_____" ], [ "### Stap voor stap", "_____no_output_____" ], [ "1. ken elk element toe aan `x` \n\n```python\nfor x in [2, 4, 6, 8]:\n```", "_____no_output_____" ], [ "2. de BODY of BLOCK gebruikt de waarde van `x`\n3. en vervolg de lus met de het volgende element\n\n```python\n print(\"x is\", x)\n```", "_____no_output_____" ], [ "4. code na de lus wordt wordt pas uitgevoerd als de lus klaar is!\n\n```python\nprint(\"Done!\")\n```", "_____no_output_____" ], [ "### Faculteit met `for`", "_____no_output_____" ] ], [ [ "def fac(n):\n result = 1 # not the result yet!\n\n for i in range(1, n + 1): # range start at 0, add one!\n result *= i # result = result * i\n\n return result # return the result", "_____no_output_____" ], [ "fac(5)", "_____no_output_____" ] ], [ [ "## Quiz", "_____no_output_____" ], [ "```python\nx = 0\n\nfor i in range(4):\n x += 10\n\nprint(x)\n```\n\nWat wordt geprint voor `x`?", "_____no_output_____" ], [ "### Oplossing\n\n`40`", "_____no_output_____" ], [ "```python\nS = \"time to think this over! \"\nresult = \"\"\n\nfor i in range(len(S)):\n if S[i - 1] == \" \":\n result += S[i]\n\nprint(result)\n```\n\nWat wordt geprint voor `result`?", "_____no_output_____" ], [ "### Oplossing\n\n`'tttto'`\n\n| `result` | `S[i - 1]` | `S[i]` | `i` |\n|----------|------------|--------|-----|\n| `'t'` | `' '` | `'t'` | `0` |\n| | `'t'` | `'i'` | `1` |\n| | `'i'` | `'m'` | `2` |\n| | `'m'` | `'e'` | `3` |\n| | `'e'` | `' '` | `4` |\n| `'tt'` | `' '` | `'t'` | `5` |\n| | `'t'` | `'o'` | `6` |\n| | `'o'` | `' '` | `7` |\n| `'ttt'` | `' '` | `'t'` | `8` |", "_____no_output_____" ], [ "## Twee typen `for`\n\nElementen versus index", "_____no_output_____" ], [ "### Op basis van element ", "_____no_output_____" ], [ "```python\nL = [3, 15, 17, 7]\n\nfor x in L:\n print(x)\n```", "_____no_output_____" ], [ "```python\nS = \"een fijne lus\"\n\nfor c in S:\n print(c)\n```", "_____no_output_____" ], [ "### Op basis van index", "_____no_output_____" ], [ "```python\nL = [3, 15, 17, 7]\n\nfor i in range(len(L)):\n print(L[i])\n```", "_____no_output_____" ], [ "```python\nS = \"een fijne lus\"\n\nfor i in range(len(S)):\n print(S[i])\n```", "_____no_output_____" ], [ "Let op, het is niet heel gewoon om in lussen te printen, maar is wel heel nuttig voor debuggen!", "_____no_output_____" ], [ "### Welke van de twee?\n\nElementen: eenvoudiger\n\nIndices: flexibeler\n", "_____no_output_____" ], [ "Denk aan het \"time to think this over! \" voorbeeld, in de lus kon op basis van de index steeds \"terug\" worden gekeken in de string met `S[i - 1]`!", "_____no_output_____" ], [ "### Of ... beide?\n\nIndex én element? Met de ingebouwde functie [`enumerate`](https://docs.python.org/3/library/functions.html#enumerate)", "_____no_output_____" ] ], [ [ "L = [3, 15, 17, 7]\n\nfor i, x in enumerate(L):\n print(\"index\", i, \"element\", x)", "index 0 element 3\nindex 1 element 15\nindex 2 element 17\nindex 3 element 7\n" ] ], [ [ "Misschien ben je `enumerate` al eens tegengekomen? De kans is in ieder geval groot als je op het net gaat zoeken, we staan er om deze reden even bij stil.", "_____no_output_____" ], [ "### Een klein uitstapje\n\nWelkom bij de cursus Advanced Python!", "_____no_output_____" ] ], [ [ "a, b = [1, 2]\n\nprint(a)\nprint(b)", "1\n2\n" ] ], [ [ "Deze techniek heet \"tuple unpacking\". Misschien heb je de term \"tuple\" al eens gehoord (of misschien gezien in een foutmelding!). Een tuple is een type dat we niet verder gaan behandelen maar zie het als een list met een vaste lengte (een list heeft géén vaste lengte, je kan daar elementen aan toevoegen en van vewijderen).\n\nEen tuple heeft hetzelfde gedrag als een list en wordt vaak \"onzichtbaar\" toegepast door Python, bijvoorbeeld", "_____no_output_____" ] ], [ [ "x = 3, 4", "_____no_output_____" ], [ "type(x)", "_____no_output_____" ], [ "x", "_____no_output_____" ] ], [ [ "### Vraag\n\n```python\na = 1\nb = 2\n```\n\nWelke handeling(en) zijn nodig om de waarden om te draaien, zodat `a` gelijk is aan `b` en `b` gelijk aan `a`?", "_____no_output_____" ], [ "Stel, je hebt een kopje koffie en een kopje water, hoe kan je de inhoud de kopjes omwisselen?", "_____no_output_____" ] ], [ [ "a, b = b, a\n\nprint(a)\nprint(b)", "2\n1\n" ] ], [ [ "Python maakt het jou makkelijk, geen derde variabele is nodig voor een wisseling!", "_____no_output_____" ], [ "### `LoL`'s uitpakken\n\n`enumerate` geeft een `LoL` terug!", "_____no_output_____" ], [ "Hoewel, technisch gezien is het een `LoT`, een List of Tuples ...", "_____no_output_____" ] ], [ [ "W = [[5, \"jan\"], [12, \"feb\"], [15, \"mar\"]]\n\nfor temp, month in W:\n print(\"month\", month, \"avg temp\", temp)", "month jan avg temp 5\nmonth feb avg temp 12\nmonth mar avg temp 15\n" ] ], [ [ "Een alternatieve benadering\n\n```python\nfor x in W:\n temp, month = x\n print(\"month\", month, \"avg temp\", temp)\n```", "_____no_output_____" ], [ "## Extreme lussen", "_____no_output_____" ], [ "```python\nguess = 42\n\nprint(\"It keeps on\")\n\nwhile guess == 42:\n print(\"going and\")\n\nprint(\"Phew! I'm done!\")\n```\n\nWat doet deze lus?", "_____no_output_____" ], [ "## `while` lussen", "_____no_output_____" ], [ "Een lus tot een bepaalde **conditie** is bereikt.", "_____no_output_____" ], [ "Tests?\n\n- `42 == 42`\n- `guess > 42`\n- ...", "_____no_output_____" ], [ "### Ontsnappen", "_____no_output_____" ] ], [ [ "import random\n\nguess = 0 # starting value, not the final or desired value!\n\nwhile guess != 42: # test to see if we keep looping\n print('Help! Let me out!')\n guess = random.choice([41, 42, 43]) # watch out for infinite loops!\n\nprint('At last!') # after the loop ends", "Help! Let me out!\nHelp! Let me out!\nHelp! Let me out!\nHelp! Let me out!\nAt last!\n" ] ], [ [ "### Simulatie\n\n```python\ndef guess(hidden):\n \"\"\"De computer raadt een geheim getal\n \"\"\"\n comp_guess = choice(list(range(100))) # [0, ..., 99]\n \n print(\"Ik koos\", comp_guess) # print de keus\n time.sleep(0.5) # pauzeer een halve seconde\n \n if comp_guess == hidden: # base case, eindelijk...\n print(\"Gevonden!\") # de computer is blij :)\n return 1 # poging\n else: # recursive case\n return 1 + guess(hidden) # volgende poging!\n```", "_____no_output_____" ] ], [ [ "from random import choice\n\ndef escape(hidden):\n guess = 0\n count = 0\n \n while guess != hidden:\n guess = choice(range(100))\n count += 1\n\n return count", "_____no_output_____" ], [ "LC = [escape(42) for i in range(1000)]", "_____no_output_____" ] ], [ [ "Bekijk de eerste 10 resutaten", "_____no_output_____" ] ], [ [ "LC[:10]", "_____no_output_____" ] ], [ [ "Het snelst geraden", "_____no_output_____" ] ], [ [ "min(LC)", "_____no_output_____" ] ], [ [ "Het minste geluk", "_____no_output_____" ] ], [ [ "max(LC)", "_____no_output_____" ] ], [ [ "Gemiddeld aantal keren", "_____no_output_____" ] ], [ [ "sum(LC)/len(LC)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
4a0d7e32fc3acdcaea43d7eee4d124262535c824
3,730
ipynb
Jupyter Notebook
Homework 1.ipynb
hubieva-a/lab2.1
ddb23fecb2fd1669d4c8c53eb22c434371d1abcb
[ "MIT" ]
null
null
null
Homework 1.ipynb
hubieva-a/lab2.1
ddb23fecb2fd1669d4c8c53eb22c434371d1abcb
[ "MIT" ]
null
null
null
Homework 1.ipynb
hubieva-a/lab2.1
ddb23fecb2fd1669d4c8c53eb22c434371d1abcb
[ "MIT" ]
null
null
null
24.064516
277
0.550402
[ [ [ "# Домашнее задание №5", "_____no_output_____" ], [ "### Задание №1 (1,5 балла)\n\nСоздайте два массива: в первом должны быть четные числа от 2 до 12 включительно, а в другом числа 7, 11, 15, 18, 23, 29.", "_____no_output_____" ], [ "$1.$ Сложите массивы и возведите элементы получившегося массива в квадрат:", "_____no_output_____" ] ], [ [ "import numpy as np\na = np.array([2, 4, 6, 8, 10, 12])\nb = np.array([7, 11, 15, 18, 23, 29])\nc = a + b\nc = c * c\nprint(c)", "[ 81 225 441 676 1089 1681]\n" ] ], [ [ "$2.$ Выведите все элементы из первого массива, которые стоят на тех местах, где элементы второго массива больше 12 и дают остаток 3 при делении на 5.", "_____no_output_____" ] ], [ [ "ind_b = np.logical_and(b>12, b%5==3)\nprint(ind_b)\nprint(a[3])\nprint(a[4])", "[False False False True True False]\n8\n10\n" ] ], [ [ "*3.* Для первого массива найдите остатки от деления на 2, а для второго --- на 3. Для каждого получившегося массива выведите его уникальные значения (см. семинар).", "_____no_output_____" ] ], [ [ "m = a%2\nn = b%3\nprint(m)\nprint(n)", "[0 0 0 0 0 0]\n[1 2 0 0 2 2]\n" ] ], [ [ "### Задание №2 (1,5 балла)\n\nНайдите интересный для вас датасет. Например, можно выбрать датасет [тут](http://data.un.org/Explorer.aspx) или [тут](https://hls.harvard.edu/library/research/find-a-database/). Если выскакивают ошибки при считывании таблицы, попробуйте их погуглить и решить проблему!\n\n1. Рассчитайте подходящие описательные статистики для признаков объектов в выбранном датасете\n2. Проанализируйте и прокомментируйте содержательно получившиеся результаты\n - недостаточно написать фразы формата \"Средний возраст = 60, а минимальный = 20\", следует дать пояснение, что это значит и какие выводы можно сделать в рамках датасета\n3. Все комментарии оформляйте строго в ячейках формата Markdown\n - для этого надо в выпадающем окошке сверху для текущей ячейки сменить тип Code на Markdown\n ![](https://i.imgur.com/vl7Fmg9.png)", "_____no_output_____" ] ], [ [ "# YOUR CODE", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
4a0d9b64db769bb5f6130d58ba53a1f0ed4038b5
301,137
ipynb
Jupyter Notebook
ADM-HW2.ipynb
Alessio-Galimi/ADM-HW4
e406577bf716bb48b8c4652d98babbdceb0e0483
[ "MIT" ]
null
null
null
ADM-HW2.ipynb
Alessio-Galimi/ADM-HW4
e406577bf716bb48b8c4652d98babbdceb0e0483
[ "MIT" ]
null
null
null
ADM-HW2.ipynb
Alessio-Galimi/ADM-HW4
e406577bf716bb48b8c4652d98babbdceb0e0483
[ "MIT" ]
null
null
null
109.18673
46,740
0.856955
[ [ [ "import numpy as np \nimport pandas as pd \nimport gc\nimport matplotlib.pyplot as plt\nimport seaborn as sns", "_____no_output_____" ] ], [ [ "#### <font color='darkblue'> Doing these exercises, we had to be very careful about managing the RAM of our personal computers. We had to run this code with the 8gb RAM of our computers. So we tried to delete each dataframe as soon as we didn't need it anymore, and we also used the gc.collect() function. For every exercise, we uploaded only the part we needed from the main dataset.</font>", "_____no_output_____" ], [ "### <font color='purple'>Question 1:</font>\n#### <font color='purple'>A marketing funnel describes your customer’s journey with your e-commerce. It may involve different stages, beginning when someone learns about your business, when he/she visits your website for the first time, to the purchasing stage, marketing funnels map routes to conversion and beyond. Suppose your funnel involves just three simple steps: 1) view, 2) cart, 3) purchase. Which is the rate of complete funnels?</font>", "_____no_output_____" ] ], [ [ "chunks_oct = pd.read_csv('2019-Oct.csv',chunksize=1000000, header='infer',usecols=[\"event_type\",\n\"product_id\",\"user_id\"])\n\nchunks_nov = pd.read_csv('2019-Nov.csv',chunksize=1000000, header='infer',usecols=[\"event_type\",\n\"product_id\",\"user_id\"])\n\ndataset=pd.DataFrame()\nfor chunk in chunks_oct:\n chunk = chunk[chunk[\"event_type\"]!=\"view\"]\n dataset= pd.concat([dataset,chunk])\nfor chunk in chunks_nov:\n chunk = chunk[chunk[\"event_type\"]!=\"view\"]\n dataset= pd.concat([dataset,chunk])", "_____no_output_____" ], [ "# rate of complete funnels :\n# In order to have a complete funnel, we need a certain user to execute a \"purchase\" action after having executed\n# a \"cart\" action. The \"view\" action has obviously happened before, so there is no need to consider it. This is why we will \n# work with a database containing only the \"purchase\" and \"cart\" actions. We will count one complete funnel everytime a \n# user performs a \"purchase\" action on a product, but only if the same user previously performed a \"cart\" action on the same\n# product.\n\nx=dataset.groupby([\"user_id\",\"product_id\"]) # we group the actions of the same user on the same product\n\ncomplete_funnels=0\nfor name,group in x:\n cart=0\n purchase=0\n for i in range(group.shape[0]):\n event = group.iloc[i][\"event_type\"]\n if event == \"cart\":\n cart=cart+1\n elif event == \"purchase\" and cart>purchase: #we accept a \"purchase\" only if a \"cart\" event has happened before\n purchase=purchase+1\n complete_funnels=complete_funnels+purchase\n\ncomplete_funnels", "_____no_output_____" ] ], [ [ "### <font color='purple'>Question 1:</font>\n#### <font color='purple'>What’s the operation users repeat more on average within a session? Produce a plot that shows the average number of times users perform each operation (view/removefromchart etc etc).</font>", "_____no_output_____" ] ], [ [ "dataset=pd.DataFrame()", "_____no_output_____" ], [ "df_oct = pd.read_csv('2019-Oct.csv', header='infer',usecols=[ \"event_type\",\"user_session\"])", "_____no_output_____" ], [ "gc.collect()", "_____no_output_____" ], [ "df_nov = pd.read_csv('2019-Nov.csv', header='infer',usecols=[ \"event_type\",\"user_session\"])", "_____no_output_____" ], [ "dataset= pd.concat([df_oct,df_nov])", "_____no_output_____" ], [ "dataset.info()", "<class 'pandas.core.frame.DataFrame'>\nInt64Index: 109950743 entries, 0 to 67501978\nData columns (total 2 columns):\n # Column Dtype \n--- ------ ----- \n 0 event_type object\n 1 user_session object\ndtypes: object(2)\nmemory usage: 2.5+ GB\n" ], [ "n_session = dataset['user_session'].nunique() # we calculate the total number of sessions", "_____no_output_____" ], [ "actions = dataset['event_type'].value_counts() # we calculate the number of each action", "_____no_output_____" ], [ "avg_actions = actions/n_session", "_____no_output_____" ], [ "avg_actions.values", "_____no_output_____" ], [ "import matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set(style=\"darkgrid\")\nfig, ax = plt.subplots()\nfig.set_size_inches(5.7, 6.27)\nax = sns.barplot(avg_actions.index,avg_actions.values)\nax.set(xlabel=' Operations', ylabel='Avg. performs')\nplt.title(\" Average number of times users perform each operation in a session\")\nplt.show()", "_____no_output_____" ] ], [ [ "#### <font color='blue'>As expected, the \"view\" actions are way more common than the \"cart\" and \"purchase\" actions.</font>", "_____no_output_____" ], [ "### <font color='purple'>Question 1:</font>\n#### <font color='purple'>How many times, on average, a user views a product before adding it to the cart?</font>", "_____no_output_____" ] ], [ [ "dataset=pd.DataFrame()", "_____no_output_____" ], [ "df_oct = pd.read_csv('2019-Oct.csv', header='infer',usecols=[ \"event_type\"])", "_____no_output_____" ], [ "df_nov = pd.read_csv('2019-Nov.csv', header='infer',usecols=[ \"event_type\"])", "_____no_output_____" ], [ "dataset= pd.concat([df_oct,df_nov])", "_____no_output_____" ], [ "actions['view']/actions['cart']", "_____no_output_____" ] ], [ [ "### <font color='purple'>Question 1:</font> \n#### <font color='purple'>What’s the probability that products added once to the cart are effectively bought?</font> ", "_____no_output_____" ] ], [ [ "# We need to calculate in which percentage a \"cart\" action actually becomes a \"complete funnel\". Again, we consider \n# that the \"view\" event has obviously happened before.\nprint(\"Percentage probability that products added once to the cart are effectively bought:\")\ncomplete_funnels/actions['cart']*100", "Percentage probability that products added once to the cart are effectively bought:\n" ] ], [ [ "### <font color='purple'>Question 1:</font> \n#### <font color='purple'>What’s the average time an item stays in the cart before being removed?</font> ", "_____no_output_____" ] ], [ [ "# For this question, we will work with a database which doesn't contain the \"view\" actions. Since there is no\n# \"remove_from_cart\" event_type, we will calculate the average time difference between the first \"cart\" action of a user\n# on a product and the first \"purchase\" action, since purchasing the item removes it from the cart\ndataset=pd.DataFrame()\nchunks_oct = pd.read_csv('2019-Oct.csv',chunksize=1000000, header='infer',usecols=[\"event_time\", \"event_type\",\n\"product_id\",\"user_id\"])\nchunks_nov = pd.read_csv('2019-Nov.csv',chunksize=1000000, header='infer',usecols=[\"event_time\", \"event_type\",\n\"product_id\",\"user_id\"])\n\nfor chunk in chunks_oct:\n chunk = chunk[chunk[\"event_type\"]!=\"view\"]\n chunk[\"event_time\"]= pd.to_datetime(chunk[\"event_time\"])\n dataset= pd.concat([dataset,chunk])\nfor chunk in chunks_nov:\n chunk = chunk[chunk[\"event_type\"]!=\"view\"]\n chunk[\"event_time\"]= pd.to_datetime(chunk[\"event_time\"])\n dataset= pd.concat([dataset,chunk])", "_____no_output_____" ], [ "z=dataset.groupby([\"user_id\",\"product_id\"]) # we group the actions of the same user on the same product\ntot_time=list() # the \"time passed between the first \"cart\" and a \"purchase\"\nfor name,group in z:\n added= False # this condition will turn True when the product is added for the first time by the user\n bought = False # this condition will turn True when the product is bought by the user\n for i in range(group.shape[0]):\n event = group.iloc[i][\"event_type\"]\n if event == \"cart\" and not added:\n add_time= group.iloc[i][\"event_time\"]\n added=True # the product has been added to the cart\n elif event==\"purchase\" and added and not bought:\n buy_time= group.iloc[i][\"event_time\"]\n bought= True # the product has been bought\n elif bought and added:\n break # we already found the first \"cart\" and the purchase time for this user and this product, so we can go to the next product/user\n if bought and added:\n tot_time.append(buy_time-add_time)\ntot_time=np.array(tot_time)\ncounter=0\ny=pd.to_timedelta(0)\nwhile len(tot_time)>=1000: \n x=tot_time[:1000]\n tot_time=tot_time[1001:]\n y=y+x.mean()\n counter=counter+1\naverage_time=y/counter", "_____no_output_____" ], [ "average_time", "_____no_output_____" ] ], [ [ "#### <font color='blue'>On average, when a user adds a product in the cart, it will take almost 8 hours and an half for him to decide to actually buy the product</font>", "_____no_output_____" ], [ "### <font color='purple'>Question 1:</font> \n#### <font color='purple'>How much time passes on average between the first view time and a purchase/addition to cart?</font>", "_____no_output_____" ] ], [ [ "dataset_oct=pd.DataFrame()\ndataset_nov=pd.DataFrame()\ndataset=pd.DataFrame()\ngc.collect()\nprint(\"Free the memory\")", "Free the memory\n" ] ], [ [ "#### <font color='darkblue'>For this exercise, we had to find a way to reduce the dataset in order to run the code just by using the 8gb ram of our personal computers. We decided to focus our analysis only on products with an high price. The reason for this is that we are looking for the average time between the first view time and a purchase/addition to cart. If the user sees a product with a low price and he is interested in it, he probably adds the product, or purchases it, as soon as he sees it. If he isn't interested, he simply won't add the product. So the average time between first view and a purchase/add to cart it's not really meaningful for products with a low price. Instead, when an user sees an high price product, even if he is interested in it, he will need some time to think about it. Understanding how much time the user needs to decide to buy the high price product or not is interesting for the company, because during that time the company might try to convince the user with, for example, a little discount. </font>", "_____no_output_____" ] ], [ [ "chunks_oct = pd.read_csv('2019-Oct.csv',chunksize=1000000, header='infer',usecols=[\"event_time\", \"event_type\",\"price\",\n\"product_id\",\"user_id\"])\n\nchunks_nov = pd.read_csv('2019-Nov.csv',chunksize=1000000, header='infer',usecols=[\"event_time\", \"event_type\",\"price\",\n\"product_id\",\"user_id\"])\n\nfor chunk in chunks_oct:\n chunk = chunk[chunk[\"price\"]>500]\n chunk[\"event_time\"]= pd.to_datetime(chunk[\"event_time\"])\n dataset= pd.concat([dataset,chunk])\nfor chunk in chunks_nov:\n chunk = chunk[chunk[\"price\"]>500]\n chunk[\"event_time\"]= pd.to_datetime(chunk[\"event_time\"])\n dataset= pd.concat([dataset,chunk])", "_____no_output_____" ], [ "dataset.info()", "<class 'pandas.core.frame.DataFrame'>\nInt64Index: 18480132 entries, 2 to 67501978\nData columns (total 5 columns):\n # Column Dtype \n--- ------ ----- \n 0 event_time datetime64[ns, UTC]\n 1 event_type object \n 2 product_id int64 \n 3 price float64 \n 4 user_id int64 \ndtypes: datetime64[ns, UTC](1), float64(1), int64(2), object(1)\nmemory usage: 846.0+ MB\n" ], [ "z=dataset.groupby([\"product_id\",\"user_id\"]) # we group the actions of the same user on the same product\ntot_time=list() # a list of the \"time passed between the first view and a purchase/addition to cart\"\nfor name,group in z:\n seen= False # this condition will turn True when the product is seen for the first time by the user\n added = False # this condition will turn True when the product is bought or added to the cart by the user\n for i in range(group.shape[0]):\n event = group.iloc[i][\"event_type\"]\n if event == \"view\" and not seen:\n view_time= group.iloc[i][\"event_time\"]\n seen=True # the product has been seen\n elif event!=\"view\" and seen and not added:\n add_time= group.iloc[i][\"event_time\"]\n added= True # the product has been bought/added to the cart\n elif seen and added:\n break # we already found the first view time and the cart/purchase time for this user and this product, so we can go to the next product/user\n if seen and added:\n tot_time.append(add_time-view_time)\ntot_time=np.array(tot_time)\ncounter=0\ny=pd.to_timedelta(0)\nwhile len(tot_time)>=1000: \n x=tot_time[:1000]\n tot_time=tot_time[1001:]\n y=y+x.mean()\n counter=counter+1\naverage_time=y/counter", "_____no_output_____" ], [ "average_time", "_____no_output_____" ] ], [ [ "#### <font color='darkblue'> As expected, when a user sees an expensive product which he is interested in , he needs some time to think about the purchase, almost 3 days. </font>", "_____no_output_____" ] ], [ [ "dataset_oct=pd.DataFrame()\ndataset_nov=pd.DataFrame()\ngc.collect()\nprint(\"Free the memory\")", "_____no_output_____" ] ], [ [ "### <font color='purple'>Question 2:</font> \n##### <font color='purple'>What are the categories of the most trending products overall? For each month visualize this information through a plot showing the number of sold products per category.</font>", "_____no_output_____" ] ], [ [ "import pandas as pd \ndataset=pd.DataFrame()\ndataset_oct=pd.DataFrame()\ndataset_nov=pd.DataFrame()", "_____no_output_____" ], [ "## reading data for October 2019:\ndf_oct = pd.read_csv('2019-Oct.csv', header='infer',usecols=[\"event_type\",\"category_code\"])", "_____no_output_____" ], [ "dataset_oct=df_oct[df_oct['category_code'].notna()] # eliminating missing data", "_____no_output_____" ], [ "dataset_oct=dataset_oct[dataset_oct.event_type=='purchase'] # we are looking for the \"purchase\" actions", "_____no_output_____" ], [ "dataset_oct.info # we check our work", "_____no_output_____" ], [ "# extracting category section from category_code data\ndataset_oct_cat=dataset_oct\ndataset_oct_cat['category_code']=dataset_oct_cat['category_code'].str.split('.').str[0]", "_____no_output_____" ], [ "dataset_oct.info", "_____no_output_____" ], [ "import matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set(style=\"darkgrid\")\nfig, ax = plt.subplots()\nfig.set_size_inches(13.7, 6.27)\nx=dataset_oct_cat.groupby('category_code').category_code.count().nlargest(10) # we are looking for the top 10\nax = sns.barplot(x.index,x.values)\nax.set(xlabel=' categories for October', ylabel='# rate')\nplt.title(\" Most Visited Categories For October\")\nplt.show()", "_____no_output_____" ], [ "# reading data for November 2019 \ndf_nov = pd.read_csv('2019-Nov.csv', header='infer',usecols=[\"event_type\",\"category_code\"])", "_____no_output_____" ], [ "dataset_nov=df_nov[df_nov['category_code'].notna()] # eliminating missing data", "_____no_output_____" ], [ "dataset_nov=dataset_nov[dataset_nov.event_type=='purchase'] # we are looking for the \"purchase\" actions", "_____no_output_____" ], [ "dataset_nov.info # we check the data", "_____no_output_____" ], [ "# extracting category section from category_code data\ndataset_nov_cat=dataset_nov \ndataset_nov_cat['category_code']=dataset_nov_cat['category_code'].str.split('.').str[0] ", "_____no_output_____" ], [ "# November\n# We look for the top 10 categories by sales\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set(style=\"darkgrid\")\nfig, ax = plt.subplots()\nfig.set_size_inches(13.7, 6.27)\nx=dataset_nov_cat.groupby('category_code').category_code.count().nlargest(10)\nax = sns.barplot(x.index,x.values)\nax.set(xlabel=' categories for November', ylabel='# rate')\nplt.title(\" Most Visited Categories For November\")\nplt.show()", "_____no_output_____" ] ], [ [ "#### <font color='blue'>In both months, \"Electronics\" is the most visited category by a wide margin.</font>", "_____no_output_____" ] ], [ [ "import gc\ngc.collect()\n", "_____no_output_____" ] ], [ [ "### <font color='purple'>Question 2:</font> \n##### <font color='purple'>plot the most visited subcategories for each month</font> ", "_____no_output_____" ] ], [ [ "dataset_oct1=df_oct[df_oct['category_code'].notna()] # eliminating missing data", "_____no_output_____" ], [ "oct_view=dataset_oct1[dataset_oct1.event_type=='view'] # extracting data with event_type= view\n", "_____no_output_____" ], [ "# we will extract the subcategory from the \"category_code\" column. We consider as \"subcategory\" the last part of the\n# \"category_column\" string.", "_____no_output_____" ], [ "oct_view_subcat=oct_view", "_____no_output_____" ], [ "oct_view_subcat['category_code']=oct_view_subcat['category_code'].str.split('.').str[-1]", "_____no_output_____" ], [ "## October ", "_____no_output_____" ], [ "sns.set(style=\"darkgrid\")\nfig, ax = plt.subplots()\nfig.set_size_inches(13.7, 6.27)\nx=oct_view_subcat.groupby('category_code').category_code.count().nlargest(10)\nax = sns.barplot(x.index,x.values)\nax.set(xlabel='subcategories for October', ylabel='# rate')\nax.set_xticklabels(ax.get_xticklabels(), rotation=45)\nplt.title(\" Most Visited Subcategories For October\")\nplt.show()", "_____no_output_____" ], [ "import gc\ngc.collect()\nprint(\"Free the memory\")", "Free the memory\n" ], [ "dataset_nov1=df_nov[df_nov['category_code'].notna()] ", "_____no_output_____" ], [ "nov_view=dataset_nov1[dataset_nov1.event_type=='view'] # extracting data with event_type= view", "_____no_output_____" ], [ "nov_view_subcat=nov_view ", "_____no_output_____" ], [ "nov_view_subcat['category_code']=nov_view_subcat['category_code'].str.split('.').str[-1]", "_____no_output_____" ], [ "# November\n# We look for the top 10 categories by sales\nsns.set(style=\"darkgrid\")\nfig, ax = plt.subplots()\nfig.set_size_inches(13.7, 6.27)\nx=nov_view_subcat.groupby('category_code').category_code.count().nlargest(10) # temp variable\nax = sns.barplot(x.index,x.values)\nax.set(xlabel=' subcategories for November ', ylabel='# rate')\nax.set_xticklabels(ax.get_xticklabels(), rotation=45)\nplt.title(\" Most Visited Subcategories For November\") \nplt.show()", "_____no_output_____" ] ], [ [ "#### <font color='blue'>In both months, \"Smartphone\" is the most visited subcategory by a wide margin. \"Smartphone\" is a subcategory of \"Electronics\", which is the most visited category</font>", "_____no_output_____" ] ], [ [ "dataset_nov=pd.DataFrame()\ngc.collect()\nprint(\"Free the memory\")", "Free the memory\n" ] ], [ [ "### <font color='purple'>What are the 10 most sold products per category in each month?</font>", "_____no_output_____" ] ], [ [ "## OCTOBER 2019 :", "_____no_output_____" ], [ "col_list1=[\"product_id\"] # we aim to add column of product_id to previous loaded data ", "_____no_output_____" ], [ "a= pd.read_csv('2019-Oct.csv', sep=',',usecols=col_list1) # use it as temporary variable because we want concat it", "_____no_output_____" ], [ "df_oct_m=pd.concat([df_oct,a],axis=1) # concatenate the extra column", "_____no_output_____" ], [ "data_oct=df_oct_m[df_oct_m['category_code'].notna()]", "_____no_output_____" ], [ "data_oct=data_oct[data_oct.event_type=='purchase']", "_____no_output_____" ], [ "data_oct_cat=data_oct # to avoid miss indexing\ndata_oct_cat['category_code']=data_oct_cat['category_code'].str.split('.').str[0]", "_____no_output_____" ], [ "categories_oct = data_oct_cat.groupby('category_code') \nfor name, group in categories_oct:\n x= group.groupby(\"product_id\").product_id.count().nlargest(10)\n print(name)\n print(x)\n print(\"\")", "accessories\nproduct_id\n18300155 63\n18300021 34\n52900016 31\n28300780 24\n49800017 23\n28300432 21\n18300595 17\n18300214 16\n18300496 16\n28400774 16\nName: product_id, dtype: int64\n\napparel\nproduct_id\n28718083 72\n28715756 46\n28712682 45\n28715827 40\n28715757 39\n28717034 39\n28703609 38\n28715829 38\n28716983 38\n54900011 37\nName: product_id, dtype: int64\n\nappliances\nproduct_id\n3700926 1675\n3600661 1482\n3600163 1017\n3600666 877\n2900536 831\n3601405 768\n3601485 627\n2701657 566\n3601244 559\n3701134 543\nName: product_id, dtype: int64\n\nauto\nproduct_id\n6000094 785\n4700478 411\n5701128 382\n6000227 360\n5701166 304\n4700630 300\n4700589 235\n6000229 214\n6000004 206\n5700518 165\nName: product_id, dtype: int64\n\ncomputers\nproduct_id\n1307310 1003\n1307073 864\n1307366 722\n1307067 651\n1306650 649\n1307074 416\n1307188 378\n1307187 356\n1306359 350\n1307350 324\nName: product_id, dtype: int64\n\nconstruction\nproduct_id\n19200005 404\n4000169 272\n12300396 267\n30000048 181\n12400121 123\n4000170 116\n12300394 113\n19200010 113\n12300066 111\n30000055 97\nName: product_id, dtype: int64\n\ncountry_yard\nproduct_id\n27600022 10\n27600080 8\n30500001 6\n30500002 5\n30500003 5\n27600165 4\n30500022 3\n27600024 2\n27600150 2\n27600218 2\nName: product_id, dtype: int64\n\nelectronics\nproduct_id\n1004856 28944\n1004767 21806\n1004833 12697\n1005115 12543\n4804056 12381\n1004870 10615\n1002544 10549\n1004249 9090\n1004836 7691\n1005105 7293\nName: product_id, dtype: int64\n\nfurniture\nproduct_id\n14701435 207\n17200570 200\n13201002 133\n17200651 130\n7101172 98\n7900440 94\n7100133 84\n14701260 77\n14701406 72\n14701532 70\nName: product_id, dtype: int64\n\nkids\nproduct_id\n7004492 209\n7004508 127\n7002254 123\n12100045 106\n7005751 102\n7004509 82\n8900305 82\n7005059 76\n12100230 66\n12100513 60\nName: product_id, dtype: int64\n\nmedicine\nproduct_id\n25800005 106\n25800007 90\n25800003 45\n25800001 23\n25800002 11\n25800006 10\n25800014 6\n25800019 6\n25800004 5\n25800000 3\nName: product_id, dtype: int64\n\nsport\nproduct_id\n12202301 62\n12201562 61\n26900073 50\n12200545 35\n12201563 33\n12202338 33\n26900059 33\n26900065 30\n27000036 28\n12202300 25\nName: product_id, dtype: int64\n\nstationery\nproduct_id\n12900125 9\n53400013 8\n12900132 7\n12901271 7\n12900110 5\n12900360 5\n12901426 5\n12900085 4\n12900181 4\n12900186 4\nName: product_id, dtype: int64\n\n" ], [ "## November 2019:\n", "_____no_output_____" ], [ "b= pd.read_csv('2019-Nov.csv', sep=',',usecols=col_list1) # we aim to add column od product_id to previous loaded data ", "_____no_output_____" ], [ "df_nov_m=pd.concat([df_nov,a],axis=1) # concatenate the extracted column", "_____no_output_____" ], [ "data_nov=df_nov_m[df_nov_m['category_code'].notna()] # eliminating missing values", "_____no_output_____" ], [ "data_nov=data_nov[data_nov.event_type=='purchase']", "_____no_output_____" ], [ "data_nov_cat=data_nov \ndata_nov_cat['category_code']=data_nov_cat['category_code'].str.split('.').str[0]", "_____no_output_____" ], [ "categories_nov = data_nov_cat.groupby('category_code') \nfor name, group in categories_nov:\n x= group.groupby(\"product_id\").product_id.count().nlargest(10)\n print(name)\n print(x)\n print(\"\")", "accessories\nproduct_id\n1004856.0 16\n1004767.0 12\n1004249.0 11\n1005115.0 9\n1005105.0 7\n1002544.0 6\n4804056.0 6\n1004565.0 5\n1004836.0 5\n1004870.0 5\nName: product_id, dtype: int64\n\napparel\nproduct_id\n1004856.0 95\n1005115.0 84\n1004767.0 79\n1002544.0 49\n1004833.0 43\n1005105.0 41\n1004249.0 37\n1004870.0 37\n4804056.0 36\n5100816.0 34\nName: product_id, dtype: int64\n\nappliances\nproduct_id\n1004856.0 602\n1004767.0 550\n1005115.0 503\n1004833.0 348\n1004249.0 301\n1004870.0 271\n4804056.0 271\n1002544.0 269\n1005105.0 257\n5100816.0 252\nName: product_id, dtype: int64\n\nauto\nproduct_id\n1004856.0 60\n1005115.0 59\n1004767.0 48\n1004833.0 40\n1004249.0 35\n4804056.0 33\n1005105.0 27\n1004739.0 26\n5100816.0 26\n1004741.0 24\nName: product_id, dtype: int64\n\ncomputers\nproduct_id\n1004856.0 212\n1004767.0 186\n1005115.0 155\n1004870.0 108\n1004249.0 106\n1004833.0 101\n1002544.0 86\n4804056.0 86\n1005105.0 82\n1004741.0 81\nName: product_id, dtype: int64\n\nconstruction\nproduct_id\n1004856.0 52\n1004767.0 43\n1005115.0 42\n1002544.0 28\n1004833.0 26\n1004249.0 24\n1004741.0 24\n1004836.0 23\n1004873.0 23\n1005105.0 23\nName: product_id, dtype: int64\n\ncountry_yard\nproduct_id\n1004767.0 2\n1002544.0 1\n1003899.0 1\n1004386.0 1\n1004402.0 1\n1004777.0 1\n1004836.0 1\n1004848.0 1\n1004956.0 1\n1005007.0 1\nName: product_id, dtype: int64\n\nelectronics\nproduct_id\n1004856.0 3120\n1004767.0 2745\n1005115.0 2310\n1004249.0 1461\n1004833.0 1426\n1004870.0 1426\n1005105.0 1332\n4804056.0 1306\n1002544.0 1291\n5100816.0 1178\nName: product_id, dtype: int64\n\nfurniture\nproduct_id\n1004767.0 72\n1004856.0 70\n1005115.0 54\n1004870.0 46\n4804056.0 38\n1005105.0 34\n5100816.0 32\n1004249.0 31\n1004739.0 30\n1004741.0 29\nName: product_id, dtype: int64\n\nkids\nproduct_id\n1004856.0 32\n1005115.0 26\n1004249.0 24\n1004767.0 21\n1005105.0 16\n1004741.0 15\n1002544.0 14\n1004750.0 13\n1004836.0 13\n4804056.0 13\nName: product_id, dtype: int64\n\nmedicine\nproduct_id\n1004856.0 4\n1004767.0 3\n1004741.0 2\n1004768.0 2\n1005105.0 2\n4802036.0 2\n1002528.0 1\n1002547.0 1\n1003304.0 1\n1003312.0 1\nName: product_id, dtype: int64\n\nsport\nproduct_id\n1004856.0 16\n1004767.0 9\n1005115.0 7\n1002544.0 6\n1004833.0 6\n1004750.0 5\n1005160.0 5\n5100816.0 5\n1003306.0 4\n1004665.0 4\nName: product_id, dtype: int64\n\nstationery\nproduct_id\n1004836.0 3\n1004870.0 3\n1002544.0 2\n1005105.0 2\n1005124.0 2\n1307054.0 2\n5100816.0 2\n1003285.0 1\n1003527.0 1\n1003751.0 1\nName: product_id, dtype: int64\n\n" ], [ "dataset=pd.DataFrame()\ndataset_oct=pd.DataFrame()\ndataset_nov=pd.DataFrame()\ngc.collect()\nprint(\"Free the memory\")", "Free the memory\n" ] ], [ [ "### <font color='purple'>Question 3:</font> \n##### <font color='purple'>For each category, what’s the brand whose prices are higher on average?</font> ", "_____no_output_____" ] ], [ [ "# We look for the average price of every brand\ndataset=pd.DataFrame()\ndataset_oct=pd.DataFrame()\ndataset_nov=pd.DataFrame()\nchunks_oct = pd.read_csv('2019-Oct.csv',chunksize=1000000, header='infer',usecols=[\"event_type\",\"category_code\",\"brand\",\"price\"])\nchunks_nov = pd.read_csv('2019-Nov.csv',chunksize=1000000, header='infer',usecols=[\"event_type\",\"category_code\",\"brand\",\"price\"])\nfor chunk in chunks_oct:\n chunk=chunk[chunk[\"category_code\"].notna()] \n chunk = chunk[chunk[\"event_type\"]==\"purchase\"]\n chunk['category_code'] = chunk['category_code'].str.split('.').str[0]\n dataset= pd.concat([dataset,chunk])\nfor chunk in chunks_nov:\n chunk=chunk[chunk[\"category_code\"].notna()] \n chunk = chunk[chunk[\"event_type\"]==\"purchase\"]\n chunk['category_code'] = chunk['category_code'].str.split('.').str[0]\n dataset= pd.concat([dataset,chunk])\n\nbrand_group=dataset.groupby(['category_code','brand']).agg(m_price=('price','mean'))\nbrand_agg=brand_group['m_price'].groupby('category_code',group_keys=False)\nbrand_agg.nlargest(1) # for each category, we show the brand with the highest average price", "_____no_output_____" ] ], [ [ "### <font color='purple'>Question 3:</font> \n##### <font color='purple'>Write a function that asks the user a category in input and returns a plot indicating the average price of the products sold by the brand.</font>", "_____no_output_____" ] ], [ [ "# We ask the user a category in input. We will give as output a list of the average prices of each brand which belongs to that category\ndef category_prices(name=input()):\n return brand_agg.get_group(name)\ncategory_prices()", "electronics\n" ] ], [ [ "### <font color='purple'>Question 3:</font> \n##### <font color='purple'>Find, for each category, the brand with the highest average price. Return all the results in ascending order by price.</font> \n", "_____no_output_____" ] ], [ [ "brand_agg.nlargest(1).sort_values()", "_____no_output_____" ], [ "dataset=pd.DataFrame()\ndataset_oct=pd.DataFrame()\ndataset_nov=pd.DataFrame()\ngc.collect()\nprint(\"Free the memory\")", "Free the memory\n" ] ], [ [ "### <font color='purple'>Question 4:</font> \n##### <font color='purple'>How much does each brand earn per month?</font> ", "_____no_output_____" ] ], [ [ "dataset=pd.DataFrame()\ndataset_oct=pd.DataFrame()\ndataset_nov=pd.DataFrame()\n", "_____no_output_____" ], [ "df_oct = pd.read_csv('2019-Oct.csv', header='infer',usecols=[\"event_type\",\"brand\",\"price\"])", "_____no_output_____" ], [ "df_nov = pd.read_csv('2019-Nov.csv', header='infer',usecols=[\"event_type\",\"brand\",\"price\"])", "_____no_output_____" ], [ "#Categorizing \ndataset_oct = df_oct[df_oct[\"event_type\"]==\"purchase\"]", "_____no_output_____" ], [ "dataset_nov = df_nov[df_nov[\"event_type\"]==\"purchase\"]", "_____no_output_____" ], [ "print(\"October revenues\")\ndataset_oct.groupby('brand').price.sum() # we calculate the revenue of each brand", "October revenues\n" ], [ "print(\"November revenues\")\ndataset_nov.groupby('brand').price.sum() # we calculate the revenue of each brand", "November revenues\n" ] ], [ [ "### <font color='purple'>Question 4:</font> \n##### <font color='purple'>Write a function that given the name of a brand in input returns, for each month, its profit.</font>", "_____no_output_____" ] ], [ [ "def profit_brand(Name=input()):\n oct_profit=dataset_oct[dataset_oct.brand==Name].price.sum() # we calculate the revenue of the brand for October\n nov_profit=dataset_nov[dataset_nov.brand==Name].price.sum() # we calculate the revenue of the brand for November\n return oct_profit, nov_profit\nprofit_brand()", "apple\n" ] ], [ [ "### <font color='purple'>Question 4:</font>\n##### <font color='purple'>Is the average price of products of different brands significantly different?</font>", "_____no_output_____" ] ], [ [ "# We consider the average price of all the products by the same brand as the \"brand price\". \n# We calculate the difference between the maximum and the minimum brand price, and the average between the brand prices.", "_____no_output_____" ], [ "dataset=pd.concat([dataset_oct,dataset_nov])", "_____no_output_____" ], [ "avg_brand_price=dataset.groupby([\"brand\"]).price.mean()\nranges=avg_brand_price.max()-avg_brand_price.min()", "_____no_output_____" ], [ "avg_brand_price.mean()", "_____no_output_____" ], [ "print(\"The difference between the maximum and the minimum brand price is: \", ranges)\nprint(\"The average between the brand prices is: \",avg_brand_price.mean())", "The difference between the maximum and the minimum brand price is: 1991.4299999999998\nThe average between the brand prices is: 158.5258799823834\n" ] ], [ [ "## <font color='purple'>Question 4:</font> \n##### <font color='purple'>Using the function you just created, find the top 3 brands that have suffered the biggest losses in earnings between one month and the next, specifing both the loss percentage and the 2 months</font> ", "_____no_output_____" ] ], [ [ "# We are working only with the datasets from November and October, so the loss is to be considered as happened between these\n# two months\nprint(\"Top 3 brands that have suffered the biggest losses in earnings between October 2019 and November 2019:\")\n(((dataset_nov.groupby('brand').price.sum()-dataset_oct.groupby('brand').price.sum())/dataset_oct.groupby('brand')\n.price.sum() )*100 ) .sort_values(ascending=True).head(3)\n ", "Top 3 brands that have suffered the biggest losses in earnings between October 2019 and November 2019:\n" ] ], [ [ "## <font color='purple'>Question 5:</font>\n##### <font color='purple'>In what part of the day is your store most visited? Knowing which days of the week or even which hours of the day shoppers are likely to visit your online store and make a purchase may help you improve your strategies. Create a plot that for each day of the week shows the hourly average of visitors your store has.</font>", "_____no_output_____" ] ], [ [ "dataset=pd.DataFrame()\ndataset_oct=pd.DataFrame()\ndataset_nov=pd.DataFrame()\ngc.collect()\nprint(\"Free the memory\")", "Free the memory\n" ], [ "# we load data of October 2019 just for the 2 columns we need \ndf_oct = pd.read_csv('2019-Oct.csv', header='infer',usecols=[\"event_time\", \"event_type\"]) ", "_____no_output_____" ], [ "# we load data of November 2019 just for the 2 columns we need\ndf_nov = pd.read_csv('2019-Nov.csv', header='infer',usecols=[\"event_time\", \"event_type\"]) ", "_____no_output_____" ], [ "dataset= pd.concat([df_oct,df_nov]) # concatenate data ", "_____no_output_____" ], [ "# we are looking for the \"view\" actions\ndataset_view= dataset[dataset.event_type=='view'] ", "_____no_output_____" ], [ "# we change the \"event_time\" column to datetime format \ndataset_view[\"event_time\"]= pd.to_datetime(dataset_view[\"event_time\"])", "_____no_output_____" ], [ "# We show the top 3 hours for \"views\" on the site\ndataset_view.groupby([dataset_view.event_time.dt.hour , dataset_view.event_type]).event_type.count().nlargest(3)", "_____no_output_____" ], [ "dataset_purchase= dataset[dataset.event_type=='purchase'] # observing just \"purchase\" event ", "_____no_output_____" ], [ "# we change the \"event_time\" column to datetime format \ndataset_purchase[\"event_time\"]= pd.to_datetime(dataset_purchase[\"event_time\"]) ", "_____no_output_____" ], [ "# We show the top 3 hours for \"purchases\" on the site\ndataset_purchase.groupby([dataset_purchase.event_time.dt.hour , dataset_purchase.event_type]).event_type.count().nlargest(3)", "_____no_output_____" ] ], [ [ "#### <font color='blue'>We can see that the afternoon hours are the ones with the most visitors on the site, but the favourite hours for purchasing products are the morning hours</font>\n", "_____no_output_____" ] ], [ [ "gc.collect()", "_____no_output_____" ], [ "# now we count the views for each day of the week\ntot_views_daily=dataset_view.groupby([dataset_view.event_time.dt.dayofweek,dataset_view.event_type]).event_type.count()", "_____no_output_____" ], [ "avg_views_daily=tot_views_daily/24\navg_views_daily.rename({0:\"Monday\", 1:\"Tuesday\", 2:\"Wednesday\", 3:\"Thursday\", 4:\"Friday\", 5:\"Saturday\", 6:\"Sunday\"}, inplace=True)", "_____no_output_____" ], [ "sns.set(style=\"darkgrid\")\nfig, ax = plt.subplots()\nfig.set_size_inches(14.7, 5.27)\nax = sns.barplot(avg_views_daily.index,avg_views_daily.values)\nax.set(xlabel=' Days of the week ', ylabel='Average Hourly Views')\nax.set_xticklabels(ax.get_xticklabels(), rotation=45)\nplt.title(\" verage Hourly Views Per Day Of The Week\") \nplt.show()", "_____no_output_____" ] ], [ [ "#### <font color='blue'>As expected, Friday, Saturday and Sunday are the days with the most visitors on the site</font>\n", "_____no_output_____" ], [ "### <font color='purple'>Question 6:</font>\n##### <font color='purple'>The conversion rate of a product is given by the number of times a product has been bought over the number of times it has been visited. What's the conversion rate of your online store? Find the overall conversion rate of your store.</font>", "_____no_output_____" ] ], [ [ "dataset=pd.DataFrame()\ndataset_oct=pd.DataFrame()\ndataset_nov=pd.DataFrame()", "_____no_output_____" ], [ "dataset_oct = pd.read_csv('2019-Oct.csv', header='infer',usecols=[\"event_type\"])", "_____no_output_____" ], [ "dataset_nov = pd.read_csv('2019-Nov.csv', header='infer',usecols=[\"event_type\"])", "_____no_output_____" ], [ "dataset= pd.concat([dataset_oct,dataset_nov])", "_____no_output_____" ], [ "# increase free space of RAM\ndataset_oct=pd.DataFrame()\ndataset_nov=pd.DataFrame()", "_____no_output_____" ], [ "# We need the calculate the rate between how many times the products are \n# buyed and how many times the products are visited", "_____no_output_____" ], [ "tot_views= dataset[\"event_type\"][dataset[\"event_type\"]==\"view\"].count() # total number of views\ntot_purchases= dataset[\"event_type\"][dataset[\"event_type\"]==\"purchase\"].count() # total number of purchases\nconversion_rate= tot_purchases/tot_views # conversion rate of the online store\nprint(\"conversion_rate =\",conversion_rate)", "conversion_rate = 0.01590817944828352\n" ] ], [ [ "### <font color='purple'>Question 6:</font>\n#### <font color='purple'>Plot the number of purchases of each category and show the conversion rate of each category in decreasing order.</font>", "_____no_output_____" ] ], [ [ "dataset=pd.DataFrame()\ndataset_oct=pd.DataFrame()\ndataset_nov=pd.DataFrame()\ngc.collect()\nprint(\"Free the memory\")", "Free the memory\n" ], [ "dataset_oct = pd.read_csv('2019-Oct.csv', header='infer',usecols=[\"event_type\",\"category_code\"])", "_____no_output_____" ], [ "dataset_nov = pd.read_csv('2019-Nov.csv', header='infer',usecols=[\"event_type\",\"category_code\"])", "_____no_output_____" ], [ "dataset_oct['category_code'] = dataset_oct['category_code'].str.split('.').str[0] # we extract the category\n# the category is the first part of the \"category_code\" string", "_____no_output_____" ], [ "dataset_nov['category_code'] = dataset_nov['category_code'].str.split('.').str[0] ", "_____no_output_____" ], [ "dataset=pd.concat([dataset_oct,dataset_nov])", "_____no_output_____" ], [ "views_dataset=dataset[dataset[\"event_type\"]==\"view\"] ", "_____no_output_____" ], [ "purchase_dataset=dataset[dataset[\"event_type\"]==\"purchase\"] ", "_____no_output_____" ], [ "total_ourchased_cat=purchase_dataset.groupby(\"category_code\").category_code.count().sort_values(ascending=False)", "_____no_output_____" ], [ "total_ourchased_cat.values", "_____no_output_____" ], [ "sns.set(style=\"darkgrid\")\nfig, ax = plt.subplots()\nfig.set_size_inches(13.7, 6.27)\nax = sns.barplot( total_ourchased_cat.index , total_ourchased_cat.values )\nax.set(ylabel=' #rate ', xlabel='Category')\nax.set_xticklabels(ax.get_xticklabels(), rotation=45)\nplt.title(\" Number Of Purchases Per Category\") \nplt.show()", "_____no_output_____" ] ], [ [ "#### <font color='blue'> We can see that the \"electronics\" category is the one with the highest number of purchases by a wide margin. This was expected, since \"electronics\" is also the most visited category</font>", "_____no_output_____" ] ], [ [ "# we show the conversion rate of each category in decreasing order\n(purchase_dataset.groupby(\"category_code\").event_type.count()/views_dataset.groupby(\"category_code\").event_type.count()).sort_values(ascending=False)", "_____no_output_____" ] ], [ [ "#### <font color='blue'> The \"electronics\" category also has the best conversion rate. At the second place we find \"medicine\". This makes sense because medicines are something users look for when they actually need them, so there is a good chance that a user who is looking for medicines on the site will also buy a medicine. </font>", "_____no_output_____" ], [ "### <font color='purple'>Question 7:</font>\n#### <font color='purple'>The Pareto principle states that for many outcomes roughly 80% of consequences come from 20% of the causes. Also known as 80/20 rule, in e-commerce simply means that most of your business, around 80%, likely comes from about 20% of your customers.Prove that the pareto principle applies to your store.</font>", "_____no_output_____" ] ], [ [ "dataset=pd.DataFrame()\ndataset_oct=pd.DataFrame()\ndataset_nov=pd.DataFrame()\ngc.collect()\nprint(\"Free the memory\")", "Free the memory\n" ], [ "dataset_oct = pd.read_csv('2019-Oct.csv', header='infer',usecols=[\"event_type\",\"price\",\"user_id\"])\ndataset_nov = pd.read_csv('2019-Nov.csv', header='infer',usecols=[\"event_type\",\"price\",\"user_id\"])\ndataset_oct = dataset_oct[dataset_oct[\"event_type\"]==\"purchase\"]\ndataset_nov = dataset_nov[dataset_nov[\"event_type\"]==\"purchase\"]\ndataset= pd.concat([dataset_oct,dataset_nov])", "_____no_output_____" ], [ "# We want to prove that the top 20% of our customers are responsible for at least the 80% of our total revenues\n# We calculate the total revenues\ntot_revenues=dataset[\"price\"].sum()\n\n# We calculate the total number of costumers\ncustomers=dataset[\"user_id\"].nunique()\n\n# We calculate the revenues coming from the top 20% of customers\ntop20_revenues = dataset.groupby(\"user_id\").price.sum().sort_values(ascending=False).head(customers//5).sum()\n\nprint(\"Percentage of the total revenues coming from the top 20% customers:\")\n(top20_revenues/tot_revenues)*100", "Percentage of the total revenues coming from the top 20% customers:\n" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ] ]
4a0d9d1a1aecd8cb54cd8fdaba3f1a97e3328379
272,160
ipynb
Jupyter Notebook
ExtractingData.ipynb
jojordan3/Public-Health-and-Education
0abb8073576e13111d67cf6cbdf20956c8b5c253
[ "MIT" ]
null
null
null
ExtractingData.ipynb
jojordan3/Public-Health-and-Education
0abb8073576e13111d67cf6cbdf20956c8b5c253
[ "MIT" ]
null
null
null
ExtractingData.ipynb
jojordan3/Public-Health-and-Education
0abb8073576e13111d67cf6cbdf20956c8b5c253
[ "MIT" ]
null
null
null
43.029249
946
0.281691
[ [ [ "# Here I will deal mostly with extracting data from PDF files\n\n### In accompanying scripts, I convert SAS and mutli-sheet Excel files into csv files for easy use in pandas using sas7bdat and pandas itself", "_____no_output_____" ] ], [ [ "# Necessary imports\nimport csv\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\nimport openpyxl\nimport pandas as pd\nimport pdfplumber\nimport PyPDF2\nimport re\nimport tabula\n#import sas7bdat\nfrom openpyxl import load_workbook\nfrom pathlib import Path\nfrom copy import deepcopy\nfrom tabula import read_pdf", "_____no_output_____" ] ], [ [ "##### Possibly handy functions", "_____no_output_____" ] ], [ [ "def normalize_whitespace(s, replace):\n if isinstance(s, str):\n return re.sub(r'\\s+', replace, s)\n else:\n return s\n\ndef convert_multisheet(filepath, csv_path=''):\n prefix = Path(filepath).stem\n wb = load_workbook(filepath)\n sheets = wb.get_sheet_names()\n for sheet in sheets[1:]:\n df = wb[sheet]\n with open(f'{csv_path}{prefix}{sheet}.csv', 'w', newline='') as csvfile:\n c = csv.writer(csvfile)\n data =[]\n for row in df.rows:\n data.append([cell.value for cell in row])\n c.writerows(data)\n print(f'{prefix}{sheet}.csv file written')", "_____no_output_____" ] ], [ [ "##### Probably useful definitions", "_____no_output_____" ] ], [ [ "boroughs_ = {\n 'Manhattan': ['1','MN', 100, 12],\n 'Brooklyn': ['3', 'BK', 300, 18],\n 'Bronx': ['2', 'BX', 200, 12],\n 'Queens': ['4', 'QN', 400, 14],\n 'Staten Island': ['5', 'SI', 500, 3]\n}\n\nborough_labels = {'Manhattan': [],\n 'Brooklyn': [],\n 'Bronx': [],\n 'Queens': [],\n 'Staten Island': []}\n\nfor borough, abbr in boroughs_.items():\n for n in range(1, abbr[2]+1):\n if n < 10:\n n = f'0{n}'\n borough_labels[borough].append(f'{abbr[1]}{n}')", "_____no_output_____" ] ], [ [ "# First Collection Round", "_____no_output_____" ], [ "#### All the years for which specific files are available and their corresponding file naming formats", "_____no_output_____" ] ], [ [ "CHP_years = [2018, 2015] # {year}_CHP_all_data.csv, {year}_Cause_of_premature_death_data.csv\nCHS_years = range(2002, 2018) # chs{year}_public.csv\nCD_years = range(1999, 2015) # cd{year}.csv\nCDall_years = range(1999, 2015) # cdall_{2digityear}.csv\nPov_years = range(2005, 2017) # NYCgov_Poverty_Measure_Data__{year}_.csv\nChild_years = range(2007, 2018) # AnnualReport{year}.pdf\nYRBSS_years = range(2003, 2019, 2) # All archived in file sadc_2017_district.dat", "_____no_output_____" ] ], [ [ "### Youth Risk Behavior Surveilance System Data", "_____no_output_____" ] ], [ [ "# Borough names get cut off\nboroughs = {\n 'State': 'StatenIsland',\n 'Queen': 'Queens',\n 'Manha': 'Manhattan',\n 'Brook': 'Brooklyn' \n}\n\nfor year in YRBSS_years:\n with open('sadc_2017_district.dat', 'r') as source:\n data = ''\n for line in source:\n # It's a national survey, so we extract the NYC-related data\n # Metadata specified in which years NYC participated\n if 'Borough' in line and f' {year} ' in line:\n data += line\n with open('tmp', 'w') as tmp:\n tmp.write(data)\n # File is fixed-width formatted\n df = pd.read_fwf('tmp', header=None)\n # These columns pertain to state, city, and other classifying data I'm not\n # interested in\n df.drop(columns=[0, 1, 2, 4, 5], inplace=True)\n \n # Replacing cut-off borough names mentioned above\n df[3].replace(to_replace=boroughs, inplace=True)\n \n # Nan values are represented as periods...\n df.replace(to_replace='.', value=np.nan, inplace=True)\n df.to_csv(f'data/youthriskbehavior{year}.csv')", "_____no_output_____" ] ], [ [ "## Find all the PDF files", "_____no_output_____" ] ], [ [ "allfiles = os.listdir('data/NYCDataSources')\npdffiles = [filename for filename in allfiles if filename.endswith('.pdf')]", "_____no_output_____" ], [ "pdffiles", "_____no_output_____" ] ], [ [ "### Investigate first the Infant Mortality PDF", "_____no_output_____" ] ], [ [ "file = pdffiles[0]\n\n# Obtained from looking at the pdf\n# Tried using multi-indexing for the columns, but tabula\n# could not properly parse the headings\ncolumns = ['CommunityDistrict', 'Neighborhoods',\n '2013-2015 InfantMortalityRate',\n '2013-2015 NeonatalMortalityRate',\n '2014-2016 InfantMortalityRate',\n '2014-2016 NeonatalMortalityRate',\n '2015-2017 InfantMortalityRate',\n '2015-2017 NeonatalMortalityRate']\n\n# For this, I manually determined the area and column boundaries\ndf = read_pdf(file, lattice=True, guess=False, area=[126, 55, 727, 548],\n columns=[111, 247, 297, 348, 399, 449, 499],\n pandas_options={'header': None, 'names': columns})\ndf.dropna(inplace=True)\n\ndf.to_csv(f'data/{file[:-3]}csv', index=False)", "_____no_output_____" ] ], [ [ "### Investigate next the Child Abuse and Neglect Report", "_____no_output_____" ] ], [ [ "file = pdffiles[-1]\n\n# Again tried using multi-indexing for the columns,\n# but again resorted to manually specifying column names\ncolumns = ['CommunityDistrict',\n '2015 AbuseNeglectCases',\n '2015 AbuseNeglectChildren',\n '2015 AbuseNeglectIndication',\n '2016 AbuseNeglectCases',\n '2016 AbuseNeglectChildren',\n '2016 AbuseNeglectIndication',\n '2017 AbuseNeglectCases',\n '2017 AbuseNeglectChildren',\n '2017 AbuseNeglectIndication',\n '2018 AbuseNeglectCases',\n '2018 AbuseNeglectChildren',\n '2018 AbuseNeglectIndication']\n\n# And manually determining the area needed\ndf = read_pdf(file, pages='all', guess=False, area=[111, 18, 459, 765],\n pandas_options={'header': None})\n# drop \"rank\" columns\ndf.drop(columns=[2,6,10,14], inplace=True)\n# tabula put some NaN rows in there just for the fun of it\ndf.dropna(inplace=True)\ndf.columns = columns\ndf.to_csv(f'data/{file[:-3]}csv', index=False)", "_____no_output_____" ] ], [ [ "### Investigate the \"AnnualReports\" -- Child Welfare and Child Services (Foster Care) Reports", "_____no_output_____" ], [ "This was an attempt at automating the creation of the column names. Only later did I find out that the vast majority of the boroughs and years were missing many (but not all) of the columns that were straight zeroes down the line...", "_____no_output_____" ] ], [ [ "file = pdffiles[5]\n\n# Each row of headers ia actually read in as a two-row df\ndf1 = read_pdf(file, pages=19, guess=False, stream=True,\n area=[56, 249, 80, 726],\n columns=[278, 312, 344, 376, 414.8, 446, 483, 517, 552, 586, 622, 657, 695],\n pandas_options={'header': None})\ndf2 = read_pdf(file, pages=19, guess=False, stream=True,\n area=[104, 249, 126, 731],\n columns=[278, 312, 344, 376, 414.8, 446, 483, 517, 552, 586, 622, 657, 695],\n pandas_options={'header': None})\ndf3 = read_pdf(file, pages=19, guess=False, stream=True,\n area=[154, 249, 176, 342],\n columns=[279.57, 313],\n pandas_options={'header': None})\n\ndf4 = pd.concat([df1, df2, df3], axis=1, ignore_index=True)\n\n# Here is where the top and bottom rows are combined to create a whole df\ndef combine_labels(col):\n '''\n Takes in the top and bottom row of the df and ensures the new\n column name is of the format 'FosterCareLength({X}yrs-<{Y}yrs)'\n '''\n if col[0][-1] != '-':\n col[0] += '-'\n new_label = f'FosterCareLength({col[0]}{col[1]})'\n return re.sub(r'\\s+', '', new_label)\n\nCWlabels = df4.apply(lambda col: combine_labels(col), axis=0).values.tolist()\nCWlabels.append('TotalReunifications')\nCWlabels.insert(26, 'FosterCareLength(13yrs-<13.5yrs)') # Missing in this particular ds\nFClabels = ['TotalPlacements', 'PlacementWithin36mos', '%PlacementsWithin36mos']\n\n# Because of the lack of consistency, I opted to keep the high-frequency (shorter-term)\n# labels and just make sure to get a total for all <18yrs\nCWlabels_std = CWlabels[:10]", "_____no_output_____" ], [ "def get_areas(num_words, words, labels):\n '''\n Must be used in conjunction with pdfplumber. pdfplumber's,\n word objects have coordinates, which will be useful with tabula's\n read_pdf function.\n '''\n # Initializations\n start = -1\n areas = []\n \n # Run through each word in succession, checking if it matches \n # one of the borough's labels\n while start < num_words - 1:\n start += 1\n top = None\n left = None\n bottom = None\n right = None\n df_label = ''\n word = words[start]\n for first in labels:\n # When we find a match, note the top and left coordinates\n # (as the label will be the index)\n if word['text'] == first:\n top = word['top']\n left = word['x0']\n prev_word = words[start-1]\n found = False\n # Run through each borough label in reverse order, to\n # catch the first instance of the highest label for the\n # borough\n for last in reversed(labels):\n # Start from word following the one we matched previously\n # to reduce redundancy\n for end in range(start+1, num_words):\n word2 = words[end]\n # When the word is found note the bottom and right\n # coordinates\n if word2['text'] == last:\n bottom = word2['bottom']\n prev_line = words[end-1]\n right = prev_line['x1']\n # Also include some tagging for easier manipulation\n # when reading and formatting the dataframes\n if 'Total' in prev_word['text']:\n df_label = 'total'\n elif r'%' in prev_line['text']:\n df_label = 'FC'\n # So we can break the outside loop\n found = True\n # So we don't repeat reading sections\n start = end\n break\n # Breaking the outside loop\n if found:\n break\n try:\n # Give some wiggle room by adding and subtracting from coordinates\n area = [float(top)-0.5, float(left)-2, float(bottom)+0.5, float(right)+5]\n except:\n # To help debug\n print(top, left, bottom, right, word, prev_word, word2, prev_line)\n raise\n areas.append([[df_label, word['text'], word2['text']], area])\n # Break the final for loop to return to our controlled while loop\n # at the appropriate 'start' value\n break\n return areas", "_____no_output_____" ], [ "def get_tables(year):\n '''\n Uses get_areas to return the page numbers, labels, and related areas\n for each borough.\n '''\n # Initializations\n borough_dfs = {'Manhattan': {},\n 'Brooklyn': {},\n 'Bronx': {},\n 'Queens': {},\n 'Staten Island': {}}\n file = f'AnnualReport{year}.pdf'\n i = 0\n \n with pdfplumber.open(file) as pdf:\n # Loop through the pages, keep track of page number as it\n # will be used by tabula--which starts numeration at 1\n for page in pdf.pages:\n i += 1\n # Gets all the text from a page as a single string -- easy to check\n # for inclusion of substrings\n text = page.extract_text()\n # Gets all the 'words' as 'word objects' which includes the \n # text of the word, and the upper, lower, left, and right coordinates\n # for use in get_areas\n words = page.extract_words()\n num_words = len(words)\n \n for borough, labels in borough_labels.items():\n if any(label in text for label in labels):\n areas = get_areas(num_words, words, labels)\n borough_dfs[borough][str(i)] = areas\n return borough_dfs", "_____no_output_____" ], [ "# Initialize dict for misfits (to be able to debug after-the-fact)\nstrays = {}\n# Initialize dict we will actually use to create the larger df\nyear_dfs = {}\nfor year in range(2007, 2018):\n borough_dfs = get_tables(year)\n year_dfs[str(year)] = borough_dfs", "_____no_output_____" ], [ "# Take a peek\nyear_dfs", "_____no_output_____" ] ], [ [ "##### The 2017 right-bounding coordinates for pages 17 and 18 can't be correct. Let's change them to 721.", "_____no_output_____" ] ], [ [ "latest = year_dfs['2017']\nfor borough, dfs in latest.items():\n try:\n info = dfs['18'][0]\n page = 18\n except:\n info = dfs['17'][0]\n page = 17\n area = info[1]\n area[3] = 721", "_____no_output_____" ], [ "def get_borough_df(file, borough, df_pages, year, strays):\n '''\n Function to get a unified borough-wide df from each year.\n Adds to strays if necessary.\n '''\n # Initialization\n to_merge = []\n first = True\n k = 0\n # dfs is a dictionary with keys that are the page numbers\n # and values that are the objects returned by get_areas\n for i, info in df_pages.items():\n page = int(i)\n # Just to keep track of same borough appearing twice on one page\n j = 0\n for each in info:\n j += 1\n k += 1\n df_label = each[0][0]\n begin = each[0][1]\n end = each[0][2]\n area = each[1]\n # tabula doing its work\n df = read_pdf(file, pages=page, guess=False, area=area,\n pandas_options={'header': None, 'index_col': 0})\n try:\n n_cols = df.shape[1] - 1\n except:\n print(f'could not READ {borough}{year}_{i}{j}')\n # For the dfs labeled 'total', I am only interested in the last column,\n # the rest are sparse. If parents/family are unable to regain custody\n # of the child after a few years, it is unlikely they will ever do so.\n if df_label == 'total':\n try:\n df = df.iloc[:, -1]\n srs = df.rename(f'{year}TotalReunifications')\n except:\n print(f'could not RENAME TotalReunifications {borough}{year}_{i}{j}')\n strays[borough+str(year)+'_'+i+str(j)] = df\n continue\n else:\n to_merge.append(srs)\n continue\n # For the label 'FC', these are children returning to foster care--with\n # a focus on those returning within the last 3 years\n elif df_label == 'FC' or (year != '2007' and k == 1):\n try:\n df.drop(columns=[1], inplace=True)\n df.columns = [f'{year}{FC}' for FC in FClabels]\n except:\n print(f'could not RENAME FC {borough}{year}_{i}{j}')\n strays[borough+str(year)+'_'+i+str(j)] = df\n continue\n else:\n to_merge.append(df)\n continue\n elif not first:\n print(f'DROPPED {borough}{year}_{i}{j}')\n strays[borough+str(year)+'_'+i+str(j)] = df\n continue\n elif df[2].isnull().sum() > 1:\n try:\n df[2] = df.apply(lambda row: [\n n for n in row[1].split(' ') if n.isnumeric()], axis=1)\n except:\n print(f'could not COPY infant data {borough}{year}_{i}{j}')\n strays[borough+str(year)+'_'+i+str(j)] = df\n continue\n if end == borough_labels[borough][-1]:\n first = False\n df.drop(columns=[1], inplace=True)\n try:\n df = df.iloc[:, :10]\n df.columns = [f'{year}{CW}' for CW in CWlabels_std]\n except:\n print(f'could not RENAME {borough}{year}_{i}{j}')\n strays[borough+str(year)+'_'+i+str(j)] = df\n continue\n else:\n to_merge.append(df)\n try:\n df = pd.concat(to_merge, axis=1, join='outer', sort=True)\n except:\n print(f'unable to MERGE {year} {borough}')\n strays[borough+str(year)] = to_merge\n return None, strays\n return df, strays", "_____no_output_____" ], [ "# Initialization\ny_to_merge = []\n\n# year_dfs is a dict with years as keys and objects returned by get_tables\n# as values\nfor year, borough_dfs in year_dfs.items():\n file = f'AnnualReport{year}.pdf'\n b_to_merge = []\n\n # Those objects are also a dict with keys as borough names and values\n # as dicts with keys of page numbers and values of df info as returned\n # by get_areas\n for borough, df_pages in borough_dfs.items():\n b_df, strays = get_borough_df(file, borough, df_pages, year, strays)\n b_to_merge.append(b_df)\n try:\n df = pd.concat(b_to_merge, axis=0, join='outer', sort=True)\n except:\n print(f'unable to merge ALL of {year}')\n strays[str(year)] = b_to_merge\n else:\n y_to_merge.append(df)\n\ndf = pd.concat(y_to_merge, axis=1, join='outer', sort=True)\ndf.to_csv(f'data/ChildWelfare.csv', index=True)", "DROPPED Manhattan Manhattan2007_231\nDROPPED Brooklyn Brooklyn2007_212\nDROPPED Bronx Bronx2007_201\nDROPPED Queens Queens2007_242\nDROPPED Staten Island Staten Island2007_252\nDROPPED Manhattan Manhattan2008_241\nDROPPED Brooklyn Brooklyn2008_222\nDROPPED Bronx Bronx2008_211\nDROPPED Queens Queens2008_252\nDROPPED Staten Island Staten Island2008_262\nDROPPED Manhattan Manhattan2009_241\nDROPPED Brooklyn Brooklyn2009_222\nDROPPED Bronx Bronx2009_211\nDROPPED Queens Queens2009_252\nDROPPED Staten Island Staten Island2009_262\nDROPPED Manhattan Manhattan2010_241\nDROPPED Brooklyn Brooklyn2010_222\nDROPPED Bronx Bronx2010_211\nDROPPED Queens Queens2010_252\nDROPPED Staten Island Staten Island2010_262\nunable to merge ALL of 2012\n" ] ], [ [ "#### Everything that got dropped was supposed to.", "_____no_output_____" ], [ "#### First I'll look into why the 2012 merge failed", "_____no_output_____" ] ], [ [ "bad_year = strays['2012']\nfor df in bad_year:\n print(df.index, df.columns)\n print(len(df.columns))", "Index(['MN01', 'MN02', 'MN03', 'MN04', 'MN05', 'MN06', 'MN07', 'MN08', 'MN09',\n 'MN10', 'MN11', 'MN12'],\n dtype='object') Index(['2012TotalPlacements', '2012PlacementWithin36mos',\n '2012%PlacementsWithin36mos', '2012FosterCareLength(losgr-<6mo.)',\n '2012FosterCareLength(6mo-<1yr)', '2012FosterCareLength(1yr-<1.5yrs)',\n '2012FosterCareLength(1.5yrs-<2yrs)',\n '2012FosterCareLength(2yrs-<2.5yrs)',\n '2012FosterCareLength(2.5yrs-<3yrs)',\n '2012FosterCareLength(3yrs-<3.5yrs)',\n '2012FosterCareLength(3.5yrs-<4yrs)',\n '2012FosterCareLength(4yrs-<4.5yrs)',\n '2012FosterCareLength(4.5yrs-<5yrs)',\n '2012FosterCareLength(losgr-<6mo.)', '2012FosterCareLength(6mo-<1yr)',\n '2012FosterCareLength(1yr-<1.5yrs)',\n '2012FosterCareLength(1.5yrs-<2yrs)',\n '2012FosterCareLength(2yrs-<2.5yrs)',\n '2012FosterCareLength(2.5yrs-<3yrs)',\n '2012FosterCareLength(3yrs-<3.5yrs)',\n '2012FosterCareLength(3.5yrs-<4yrs)',\n '2012FosterCareLength(4yrs-<4.5yrs)',\n '2012FosterCareLength(4.5yrs-<5yrs)', '2012TotalReunifications'],\n dtype='object')\n24\nIndex(['BK01', 'BK02', 'BK03', 'BK04', 'BK05', 'BK06', 'BK07', 'BK08', 'BK09',\n 'BK10', 'BK11', 'BK12', 'BK13', 'BK14', 'BK15', 'BK16', 'BK17', 'BK18'],\n dtype='object', name=0) Index(['2012TotalPlacements', '2012PlacementWithin36mos',\n '2012%PlacementsWithin36mos', '2012FosterCareLength(losgr-<6mo.)',\n '2012FosterCareLength(6mo-<1yr)', '2012FosterCareLength(1yr-<1.5yrs)',\n '2012FosterCareLength(1.5yrs-<2yrs)',\n '2012FosterCareLength(2yrs-<2.5yrs)',\n '2012FosterCareLength(2.5yrs-<3yrs)',\n '2012FosterCareLength(3yrs-<3.5yrs)',\n '2012FosterCareLength(3.5yrs-<4yrs)',\n '2012FosterCareLength(4yrs-<4.5yrs)',\n '2012FosterCareLength(4.5yrs-<5yrs)', '2012TotalReunifications'],\n dtype='object')\n14\nIndex(['BX01', 'BX02', 'BX03', 'BX04', 'BX05', 'BX06', 'BX07', 'BX08', 'BX09',\n 'BX10', 'BX11', 'BX12'],\n dtype='object', name=0) Index(['2012TotalPlacements', '2012PlacementWithin36mos',\n '2012%PlacementsWithin36mos', '2012FosterCareLength(losgr-<6mo.)',\n '2012FosterCareLength(6mo-<1yr)', '2012FosterCareLength(1yr-<1.5yrs)',\n '2012FosterCareLength(1.5yrs-<2yrs)',\n '2012FosterCareLength(2yrs-<2.5yrs)',\n '2012FosterCareLength(2.5yrs-<3yrs)',\n '2012FosterCareLength(3yrs-<3.5yrs)',\n '2012FosterCareLength(3.5yrs-<4yrs)',\n '2012FosterCareLength(4yrs-<4.5yrs)',\n '2012FosterCareLength(4.5yrs-<5yrs)', '2012TotalReunifications'],\n dtype='object')\n14\nIndex(['QN01', 'QN02', 'QN03', 'QN04', 'QN05', 'QN06', 'QN07', 'QN08', 'QN09',\n 'QN10', 'QN11', 'QN12', 'QN13', 'QN14'],\n dtype='object', name=0) Index(['2012TotalPlacements', '2012PlacementWithin36mos',\n '2012%PlacementsWithin36mos', '2012FosterCareLength(losgr-<6mo.)',\n '2012FosterCareLength(6mo-<1yr)', '2012FosterCareLength(1yr-<1.5yrs)',\n '2012FosterCareLength(1.5yrs-<2yrs)',\n '2012FosterCareLength(2yrs-<2.5yrs)',\n '2012FosterCareLength(2.5yrs-<3yrs)',\n '2012FosterCareLength(3yrs-<3.5yrs)',\n '2012FosterCareLength(3.5yrs-<4yrs)',\n '2012FosterCareLength(4yrs-<4.5yrs)',\n '2012FosterCareLength(4.5yrs-<5yrs)', '2012TotalReunifications'],\n dtype='object')\n14\nIndex(['SI01', 'SI02', 'SI03'], dtype='object', name=0) Index(['2012TotalPlacements', '2012PlacementWithin36mos',\n '2012%PlacementsWithin36mos', '2012FosterCareLength(losgr-<6mo.)',\n '2012FosterCareLength(6mo-<1yr)', '2012FosterCareLength(1yr-<1.5yrs)',\n '2012FosterCareLength(1.5yrs-<2yrs)',\n '2012FosterCareLength(2yrs-<2.5yrs)',\n '2012FosterCareLength(2.5yrs-<3yrs)',\n '2012FosterCareLength(3yrs-<3.5yrs)',\n '2012FosterCareLength(3.5yrs-<4yrs)',\n '2012FosterCareLength(4yrs-<4.5yrs)',\n '2012FosterCareLength(4.5yrs-<5yrs)', '2012TotalReunifications'],\n dtype='object')\n14\n" ] ], [ [ "Seems we have repeats in Manhattan", "_____no_output_____" ] ], [ [ "badMN = deepcopy(bad_year[0])\nbadMN", "_____no_output_____" ] ], [ [ "Ah, must have been a ds split across two pages", "_____no_output_____" ] ], [ [ "FC = badMN.columns[:3]\nCWtot = badMN.columns[-1]", "_____no_output_____" ], [ "fc_df = badMN[FC]\ncwtot_df = badMN[CWtot]\nbadMN.drop(columns=FC, inplace=True)\nbadMN.drop(columns=CWtot, inplace=True)\nbadMN", "_____no_output_____" ], [ "badMN_bot = badMN.loc[badMN.index[-4:]].dropna(axis=1)\nbadMN_top = badMN.loc[badMN.index[:-4]].dropna(axis=1)\ngoodMN = pd.concat([badMN_top, badMN_bot], join='outer', sort=True)\ngoodMN", "_____no_output_____" ], [ "goodMN_full = pd.concat([fc_df, goodMN, cwtot_df], axis=1, join='outer', sort=True)\nbad_year[0] = goodMN_full\nfor df in bad_year:\n print(df.index, df.columns)\n print(len(df.columns))", "Index(['MN01', 'MN02', 'MN03', 'MN04', 'MN05', 'MN06', 'MN07', 'MN08', 'MN09',\n 'MN10', 'MN11', 'MN12'],\n dtype='object') Index(['2012TotalPlacements', '2012PlacementWithin36mos',\n '2012%PlacementsWithin36mos', '2012FosterCareLength(1.5yrs-<2yrs)',\n '2012FosterCareLength(1yr-<1.5yrs)',\n '2012FosterCareLength(2.5yrs-<3yrs)',\n '2012FosterCareLength(2yrs-<2.5yrs)',\n '2012FosterCareLength(3.5yrs-<4yrs)',\n '2012FosterCareLength(3yrs-<3.5yrs)',\n '2012FosterCareLength(4.5yrs-<5yrs)',\n '2012FosterCareLength(4yrs-<4.5yrs)', '2012FosterCareLength(6mo-<1yr)',\n '2012FosterCareLength(losgr-<6mo.)', '2012TotalReunifications'],\n dtype='object')\n14\nIndex(['BK01', 'BK02', 'BK03', 'BK04', 'BK05', 'BK06', 'BK07', 'BK08', 'BK09',\n 'BK10', 'BK11', 'BK12', 'BK13', 'BK14', 'BK15', 'BK16', 'BK17', 'BK18'],\n dtype='object', name=0) Index(['2012TotalPlacements', '2012PlacementWithin36mos',\n '2012%PlacementsWithin36mos', '2012FosterCareLength(losgr-<6mo.)',\n '2012FosterCareLength(6mo-<1yr)', '2012FosterCareLength(1yr-<1.5yrs)',\n '2012FosterCareLength(1.5yrs-<2yrs)',\n '2012FosterCareLength(2yrs-<2.5yrs)',\n '2012FosterCareLength(2.5yrs-<3yrs)',\n '2012FosterCareLength(3yrs-<3.5yrs)',\n '2012FosterCareLength(3.5yrs-<4yrs)',\n '2012FosterCareLength(4yrs-<4.5yrs)',\n '2012FosterCareLength(4.5yrs-<5yrs)', '2012TotalReunifications'],\n dtype='object')\n14\nIndex(['BX01', 'BX02', 'BX03', 'BX04', 'BX05', 'BX06', 'BX07', 'BX08', 'BX09',\n 'BX10', 'BX11', 'BX12'],\n dtype='object', name=0) Index(['2012TotalPlacements', '2012PlacementWithin36mos',\n '2012%PlacementsWithin36mos', '2012FosterCareLength(losgr-<6mo.)',\n '2012FosterCareLength(6mo-<1yr)', '2012FosterCareLength(1yr-<1.5yrs)',\n '2012FosterCareLength(1.5yrs-<2yrs)',\n '2012FosterCareLength(2yrs-<2.5yrs)',\n '2012FosterCareLength(2.5yrs-<3yrs)',\n '2012FosterCareLength(3yrs-<3.5yrs)',\n '2012FosterCareLength(3.5yrs-<4yrs)',\n '2012FosterCareLength(4yrs-<4.5yrs)',\n '2012FosterCareLength(4.5yrs-<5yrs)', '2012TotalReunifications'],\n dtype='object')\n14\nIndex(['QN01', 'QN02', 'QN03', 'QN04', 'QN05', 'QN06', 'QN07', 'QN08', 'QN09',\n 'QN10', 'QN11', 'QN12', 'QN13', 'QN14'],\n dtype='object', name=0) Index(['2012TotalPlacements', '2012PlacementWithin36mos',\n '2012%PlacementsWithin36mos', '2012FosterCareLength(losgr-<6mo.)',\n '2012FosterCareLength(6mo-<1yr)', '2012FosterCareLength(1yr-<1.5yrs)',\n '2012FosterCareLength(1.5yrs-<2yrs)',\n '2012FosterCareLength(2yrs-<2.5yrs)',\n '2012FosterCareLength(2.5yrs-<3yrs)',\n '2012FosterCareLength(3yrs-<3.5yrs)',\n '2012FosterCareLength(3.5yrs-<4yrs)',\n '2012FosterCareLength(4yrs-<4.5yrs)',\n '2012FosterCareLength(4.5yrs-<5yrs)', '2012TotalReunifications'],\n dtype='object')\n14\nIndex(['SI01', 'SI02', 'SI03'], dtype='object', name=0) Index(['2012TotalPlacements', '2012PlacementWithin36mos',\n '2012%PlacementsWithin36mos', '2012FosterCareLength(losgr-<6mo.)',\n '2012FosterCareLength(6mo-<1yr)', '2012FosterCareLength(1yr-<1.5yrs)',\n '2012FosterCareLength(1.5yrs-<2yrs)',\n '2012FosterCareLength(2yrs-<2.5yrs)',\n '2012FosterCareLength(2.5yrs-<3yrs)',\n '2012FosterCareLength(3yrs-<3.5yrs)',\n '2012FosterCareLength(3.5yrs-<4yrs)',\n '2012FosterCareLength(4yrs-<4.5yrs)',\n '2012FosterCareLength(4.5yrs-<5yrs)', '2012TotalReunifications'],\n dtype='object')\n14\n" ], [ "ChildWelfare2012 = pd.concat(bad_year, join='outer', sort=True)\nCWminus2012 = pd.read_csv('data/ChildWelfare.csv', index_col=0)\nfull_df = pd.concat([CWminus2012, ChildWelfare2012],\n axis=1, join='outer', sort=True)\nfull_df.drop(index=['BK 11'], inplace=True)\nfull_df.to_csv('data/ChildWelfare.csv', index=True)\nfull_df", "_____no_output_____" ] ], [ [ "# Second Collection Round", "_____no_output_____" ] ], [ [ "directory = 'data/NYCDataSourcesRound2'\nsavedir = 'data/raw_csvs/'\nallfiles_2 = os.listdir(directory)\n# pdffiles = [filename for filename in allfiles if filename.endswith('.pdf')]\ncsvfiles = [filename for filename in allfiles_2 if filename.endswith('.csv')]\nexcelfiles = [filename for filename in allfiles_2 if filename.endswith('.xls') or filename.endswith('.xlsx')]\n\nprint('CSV Files:')\nprint(csvfiles)\nprint('\\nExcel Files:')\nprint(excelfiles)", "CSV Files:\n['communitydistrict-studentsperformingatgradelevelinmath4thgrade.csv', 'communitydistrict-studentsperformingatgradelevelinenglishlanguagearts4thgrade.csv', 'nysd.csv', 'ALL_VARIABLES_D2G1.csv', '2005_-_2011_Graduation_Outcomes_-_School_Level_-_SWD.csv', '2005_-_2011_Graduation_Outcomes_-_School_Level_-_-_Gender.csv', '2005_-_2011_Graduation_Outcomes_-_School_Level_-_-_Ethnicity.csv', 'sub-borougharea-disconnectedyouth.csv', '2001-2013_Graduation_Outcome_School_Level_-_ALL_ELL_SWD_ETHNICITY_GENDER_EVER_ELL_TRANSFER_SCHOOLS.csv', '2017_-_2018_Graduation_Outcomes_School.csv', '2005-2015_Graduation_Rates_Public_School_-_APM.csv', '2005-2010_Graduation_Outcomes_-_School_Level.csv', '2009_-_2010_Graduation_Outcomes_-_Regents-based_Math-_ELA_APM_-_School_Level.csv', '2005_-_2011_Graduation_Outcomes_-_School_Level_-_Classes_of_-_Total_Cohort.csv', 'METADATA_DATA2GO1.csv', '2005_-_2011_Graduation_Outcomes_-_School_Level-_ELL.csv']\n\nExcel Files:\n['Data2go.nyc.2nd.Edition.All.Variables.xlsx', 'On-Time_HS_Grad.xlsx', 'FC_subsidized_housing_database_2018-06-27.xlsx', 'Data2Go.Full.Dataset 2018.xlsx', '2013-dcy-msa-pumas.xls', 'elsec17t.xls', 'MappingAmerica_Demographics.xlsx', 'nta-metadata (1).xlsx', 'DATA2GOHEALTH.NYC 1st edition.xlsx', 'variable-list-labs.xls', 'elsec17_sumtables.xls']\n" ], [ "fourthgrade_stats = csvfiles[0:2]\ndfs = []\n\nfor file in fourthgrade_stats:\n path = f'{directory}/{file}'\n df = pd.read_csv(os.path.join(directory, file), index_col=2)\n pre = df.iloc[0,0]\n df.drop(columns=df.columns[:2], inplace=True)\n df.columns = [pre+col for col in df.columns]\n dfs.append(df)\n\ndf = pd.concat(dfs, axis=1, sort=True)\ndf.to_csv(savedir+'proficiency_4thgrade')", "_____no_output_____" ], [ "excelfiles", "_____no_output_____" ], [ "df = pd.read_excel(os.path.join(directory, excelfiles[3]),\n header=None, skiprows=4, nrows=1, squeeze=True)\ntypes = df.values[0]\nprint(set(types))\n\ninclude = []\nfor count in range(len(types)):\n if types[count] == 'Community District' or types[count] == 'PUMA':\n include.append(count)\n\ninclude.insert(0,0)", "{nan, 'Borough', 'NYC', 'PUMA', 'Community District', 'Tract', 'UNIT OF GEOGRAPHY'}\n" ], [ "df = pd.read_excel(os.path.join(directory, excelfiles[3]), usecols=include, header=None,\n skiprows=[0,1,2,3,4,5,7,8,9,11,12,13,14,15,16,17,18,19], nrows=116)", "_____no_output_____" ], [ "def get_col_names_year(df, col_names=['GEO LABEL']):\n for col in range(1, len(df.columns)):\n name = ' '.join([df.iloc[0, col], str(df.iloc[1, col])])\n col_names.append(name)\n \n df.columns = col_names\n df.drop(index=[0,1], inplace=True)\n", "_____no_output_____" ], [ "get_col_names_year(df)\n\ncomm_dist = [('Community District' in label) for label in df['GEO LABEL']]\nCD = [('CD' in label) for label in df['GEO LABEL']]\n\ndf1 = df[comm_dist]\ndf2 = df[CD]\n\ndfs = [df1, df2]\n\nboroughs_['Richmond'] = boroughs_['Staten Island']\nboroughs_['Staten'] = boroughs_['Staten Island']\n\ndef get_CD_nums(label, boroughs=boroughs_):\n parts = label.split()\n borough_code = boroughs[parts[0]][2]\n nums = [int(part) for part in parts if part.isnumeric()]\n if len(nums) == 1:\n new_label = str(nums[0] + borough_code)\n else:\n new_label = ' '.join([str(num + borough_code) for num in nums])\n \n return new_label\n\ndef set_df_index(df):\n df.dropna(axis=1, how='all', inplace=True)\n df['GEO LABEL'] = df['GEO LABEL'].apply(get_CD_nums)\n df['Community District'] = df['GEO LABEL'].values\n df.set_index('GEO LABEL', inplace=True)\n\nfor df in dfs:\n set_df_index(df)\n\ndf = pd.concat(dfs, axis=1, join='outer', sort=True)\n\ndf.to_csv(savedir+'d2g1.csv')", "_____no_output_____" ], [ "def dict_or_int(value, initialized=False):\n if not initialized:\n if isinstance(value, int):\n output = list(range(value))\n else:\n output = {}\n for sheet, num in value.items():\n output[sheet] = list(range(num))\n return output\n else:\n if isinstance(value, int):\n if isinstance(initialized, list):\n initialized.remove(value)\n else:\n for sheet in initialized.keys():\n initialized[sheet].remove(value)\n else:\n if isinstance(initialized, list):\n output = {}\n for sheet, num in value.items():\n initial = deepcopy(initialized)\n initial.remove(num)\n output[sheet] = initial\n return output\n else:\n for sheet in initialized.keys():\n initialized[sheet].remove(value[sheet])\n return initialized\n\ndef read_d2g_new(filepath, name_row, year_row, startrow, geolabel_col, startcol):\n skiprows = dict_or_int(startrow)\n skiprows = dict_or_int(name_row, initialized=skiprows)\n skiprows = dict_or_int(year_row, initialized=skiprows)\n \n dropcols = dict_or_int(startcol)\n dropcols = dict_or_int(geolabel_col, initialized=dropcols)\n\n dfs = {}\n \n try:\n for sheet, rows in skiprows.items():\n df = pd.read_excel(filepath, sheet_name=sheet, header=None, skiprows=rows)\n dfs[sheet] = df\n except:\n for sheet in ['CD', 'Puma']:\n df = pd.read_excel(filepath, sheet_name=sheet, header=None, skiprows=skiprows)\n dfs[sheet] = df\n\n try:\n for sheet, cols in dropcols.items():\n dfs[sheet].drop(columns=cols, inplace=True)\n except:\n for df in dfs.values():\n df.drop(columns=dropcols, inplace=True)\n \n for df in dfs.values():\n get_col_names_year(df, col_names=['GEO LABEL'])\n set_df_index(df)\n \n df = pd.concat(dfs.values(), axis=1, join='outer', sort=True)\n return df", "_____no_output_____" ], [ "file = os.path.join(directory, excelfiles[0])\n\ndf = read_d2g_new(file, 8, 13, 17, 1, {'CD': 6, 'Puma':5})\n\ndf.to_csv(savedir +'d2g2.csv')", "_____no_output_____" ], [ "file = os.path.join(directory, excelfiles[8])\n\ndf = read_d2g_new(file, {'CD': 6, 'Puma': 7}, {'CD': 10, 'Puma': 11},\n {'CD': 14, 'Puma':15}, 2, 7)\n\ndf.to_csv(savedir + 'd2ghealth.csv')", "_____no_output_____" ], [ "csvfiles", "_____no_output_____" ], [ "df = pd.read_csv(os.path.join(directory, csvfiles[10]))\ndf", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
4a0da17b8d6a952d749f0b777f30266ca15f06e0
61,310
ipynb
Jupyter Notebook
Introduction to Portfolio Construction and Analysis with Python/W1/.ipynb_checkpoints/Drawdown-checkpoint.ipynb
Alashmony/InvestmentManagementML
c4721f77f1523b06edf012d9139b08a2dba39e59
[ "Unlicense" ]
null
null
null
Introduction to Portfolio Construction and Analysis with Python/W1/.ipynb_checkpoints/Drawdown-checkpoint.ipynb
Alashmony/InvestmentManagementML
c4721f77f1523b06edf012d9139b08a2dba39e59
[ "Unlicense" ]
null
null
null
Introduction to Portfolio Construction and Analysis with Python/W1/.ipynb_checkpoints/Drawdown-checkpoint.ipynb
Alashmony/InvestmentManagementML
c4721f77f1523b06edf012d9139b08a2dba39e59
[ "Unlicense" ]
1
2022-02-16T01:33:59.000Z
2022-02-16T01:33:59.000Z
81.637816
20,664
0.738493
[ [ [ "import pandas as pd\nimport numpy as np\nimport matplotlib as plt\n%matplotlib inline\n\nreturns = pd.read_csv(\"data/Portfolios_Formed_on_ME_monthly_EW.csv\", index_col=0 , na_values=-99.99, parse_dates= True)\nreturns.head()", "_____no_output_____" ], [ "returns.index = pd.to_datetime(returns.index, format=\"%Y%m\")\nreturns.index = returns.index.to_period('M')\nreturns.index", "_____no_output_____" ], [ "returns = returns/100\nreturns.head()", "_____no_output_____" ], [ "def drawdown(ret_ser: pd.Series):\n \"\"\"\n Lets Calculate it:\n 1. Compute wealth index\n 2. Compute previous peaks\n 3. Compute Drawdown - which is the wealth value as a percentage of the previous peak\n \"\"\"\n wealth_index = 1000*(1+ret_ser).cumprod()\n prev_peak = wealth_index.cummax()\n draw_down = (wealth_index-prev_peak)/prev_peak\n return pd.DataFrame({\n \"Wealth Index\": wealth_index,\n \"Previous Peak\": prev_peak,\n \"Drawdown\" : draw_down \n })", "_____no_output_____" ], [ "df = drawdown(returns[\"Lo 10\"])\ndf.head()", "_____no_output_____" ], [ "df[[\"Wealth Index\",\"Previous Peak\"]].plot()", "_____no_output_____" ], [ "df", "_____no_output_____" ], [ "df[\"1970\":][[\"Wealth Index\",\"Previous Peak\"]].plot()", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code" ] ]
4a0dafeb997b3d54d335f78c34c5b0ae306dcddb
107,781
ipynb
Jupyter Notebook
docs/source/examples/ERDDAP_Example.ipynb
glos/ioos_qc
17e69ad582275be7ad0f5a2af40c11d810b344e8
[ "Apache-2.0" ]
31
2019-10-09T15:08:38.000Z
2022-01-21T23:45:22.000Z
docs/source/examples/ERDDAP_Example.ipynb
glos/ioos_qc
17e69ad582275be7ad0f5a2af40c11d810b344e8
[ "Apache-2.0" ]
49
2019-10-09T18:58:29.000Z
2022-02-08T22:52:34.000Z
docs/source/examples/ERDDAP_Example.ipynb
glos/ioos_qc
17e69ad582275be7ad0f5a2af40c11d810b344e8
[ "Apache-2.0" ]
13
2019-10-08T19:47:34.000Z
2022-03-19T18:42:25.000Z
109.422335
56,106
0.623904
[ [ [ "# Setup directories\nfrom pathlib import Path\nbasedir = Path().absolute()\nlibdir = basedir.parent.parent.parent\n\n# Other imports\nimport pandas as pd\nimport numpy as np\nfrom datetime import datetime\n\nfrom ioos_qc.plotting import bokeh_plot_collected_results\n\nfrom bokeh import plotting\nfrom bokeh.io import output_notebook", "_____no_output_____" ], [ "# Install QC library\n#!pip install git+git://github.com/ioos/ioos_qc.git\n\n# # Alternative installation (install specific branch):\n# !pip uninstall -y ioos_qc\n# !pip install git+git://github.com/ioos/ioos_qc.git@new_configs\n\n# # Alternative installation (run with local updates):\n# !pip uninstall -y ioos_qc\n# import sys\n# sys.path.append(str(libdir))", "_____no_output_____" ] ], [ [ "## Configuration", "_____no_output_____" ] ], [ [ "erddap_server = 'https://ferret.pmel.noaa.gov/pmel/erddap'\ndataset_id = 'sd1055'", "_____no_output_____" ] ], [ [ "## Get data from ERDDAP as an xarray object", "_____no_output_____" ] ], [ [ "from erddapy import ERDDAP\ne = ERDDAP(\n server=erddap_server,\n protocol='tabledap',\n)\ne.response = 'csv'\ne.dataset_id = dataset_id", "_____no_output_____" ], [ "ds = e.to_xarray()\nds", "_____no_output_____" ] ], [ [ "## Generate a QC configuration for each variable", "_____no_output_____" ] ], [ [ "# Dataset level metadata to drive climatology extraction\nmin_t = str(ds.time.min().dt.floor(\"D\").dt.strftime(\"%Y-%m-%d\").data)\nmax_t = str(ds.time.max().dt.ceil(\"D\").dt.strftime(\"%Y-%m-%d\").data)\nmin_x = float(ds.longitude.min().data)\nmin_y = float(ds.latitude.min().data)\nmax_x = float(ds.longitude.max().data)\nmax_y = float(ds.latitude.max().data)\nbbox = [min_x, min_y, max_x, max_y]", "_____no_output_____" ], [ "time", "CPU times: user 2 µs, sys: 1 µs, total: 3 µs\nWall time: 3.81 µs\n" ], [ "# Configure how each variable's config will be generated\ndefault_config = {\n \"bbox\": bbox,\n \"start_time\": min_t,\n \"end_time\": max_t, \n \"tests\": {\n \"spike_test\": {\n \"suspect_threshold\": \"1\",\n \"fail_threshold\": \"2\"\n },\n \"gross_range_test\": {\n \"suspect_min\": \"min - std * 2\",\n \"suspect_max\": \"max + std / 2\",\n \"fail_min\": \"mean / std\",\n \"fail_max\": \"mean * std\"\n }\n }\n}\n\n# For any variable name or standard_name you can define a custom config\ncustom_config = {\n 'air_temperature': {\n \"variable\": \"air\"\n },\n 'air_pressure': {\n \"variable\": \"pres\"\n },\n 'relative_humidity': {\n \"variable\": \"rhum\"\n },\n 'sea_water_temperature': {\n \"variable\": \"temperature\"\n },\n 'sea_water_practical_salinity': {\n \"variable\": \"salinity\"\n },\n 'eastward_wind': {\n \"variable\": \"uwnd\"\n },\n 'northward_wind': {\n \"variable\": \"vwnd\"\n }\n}", "_____no_output_____" ], [ "# Generate climatology configs\nfrom ioos_qc.config_creator import CreatorConfig, QcConfigCreator, QcVariableConfig, QC_CONFIG_CREATOR_SCHEMA\n\ncreator_config = {\n \"datasets\": [\n {\n \"name\": \"ocean_atlas\",\n \"file_path\": \"../../../resources/ocean_atlas.nc\",\n \"variables\": {\n \"o2\": \"o_an\",\n \"salinity\": \"s_an\",\n \"temperature\": \"t_an\"\n },\n \"3d\": \"depth\"\n },\n {\n \"name\": \"narr\",\n \"file_path\": \"../../../resources/narr.nc\",\n \"variables\": {\n \"air\": \"air\",\n \"pres\": \"slp\",\n \"rhum\": \"rhum\",\n \"uwnd\": \"uwnd\",\n \"vwnd\": \"vwnd\"\n }\n }\n ]\n}\ncc = CreatorConfig(creator_config)\nqccc = QcConfigCreator(cc)", "_____no_output_____" ], [ "# Break down variable by standard name\ndef not_stddev(v):\n return v and not v.endswith(' SD')\n\n#air_temp_vars = ds.filter_by_attrs(long_name=not_stddev, standard_name='air_temperature')\n#pressure_vars = ds.filter_by_attrs(long_name=not_stddev, standard_name='air_pressure')\n# humidity_vars = ds.filter_by_attrs(long_name=not_stddev, standard_name='relative_humidity')\n# water_temp_vars = ds.filter_by_attrs(long_name=not_stddev, standard_name='sea_water_temperature')\n# salinity_vars = ds.filter_by_attrs(long_name=not_stddev, standard_name='sea_water_practical_salinity')\n# uwind_vars = ds.filter_by_attrs(long_name=not_stddev, standard_name='eastward_wind')\n# vwind_vars = ds.filter_by_attrs(long_name=not_stddev, standard_name='northward_wind')\n# all_vars = [air_temp_vars, pressure_vars, humidity_vars, water_temp_vars, salinity_vars, uwind_vars, vwind_vars]\n# all_vars\n\nair_temp = ['air_temperature']\npressure = ['air_pressure']\nhumidity = ['relative_humidity']\nwater_temp = ['sea_water_temperature']\nsalt = ['sea_water_practical_salinity']\nu = ['eastward_wind']\nv = ['northward_wind']\n\nrun_tests = air_temp + pressure + humidity + water_temp + salt + u + v\nfinal_config = {}\n\nfor v in ds:\n da = ds[v]\n\n # Don't run tests for unknown variables\n if 'standard_name' not in da.attrs or da.attrs['standard_name'] not in run_tests:\n continue\n \n # The standard names are identical for the mean and the stddev\n # so ignore the stddev version of the variable\n if v.endswith('_STDDEV'):\n continue\n \n config = default_config.copy()\n \n min_t = str(da.time.min().dt.floor(\"D\").dt.strftime(\"%Y-%m-%d\").data)\n max_t = str(da.time.max().dt.ceil(\"D\").dt.strftime(\"%Y-%m-%d\").data)\n min_x = float(da.longitude.min().data)\n min_y = float(da.latitude.min().data)\n max_x = float(da.longitude.max().data)\n max_y = float(da.latitude.max().data)\n bbox = [min_x, min_y, max_x, max_y]\n\n config[\"bbox\"] = bbox\n config[\"start_time\"] = min_t\n config[\"end_time\"] = max_t\n \n # Allow custom overrides on a variable name basis\n if v in custom_config:\n config.update(custom_config[v])\n \n # Allow custom overrides on a standard_name name basis\n if da.attrs['standard_name'] in custom_config:\n config.update(custom_config[da.attrs['standard_name']])\n \n # Generate the ioos_qc Config object\n qc_var = QcVariableConfig(config)\n qc_config = qccc.create_config(qc_var)\n \n # Strip off the variable that create_config added\n qc_config = list(qc_config.values())[0]\n \n # Add it to the final config\n final_config[v] = qc_config", "_____no_output_____" ], [ "final_config", "_____no_output_____" ], [ "from ioos_qc.config import Config\nfrom ioos_qc.streams import XarrayStream\nfrom ioos_qc.stores import NetcdfStore\nfrom ioos_qc.results import collect_results\n\nc = Config(final_config)\nxs = XarrayStream(ds, time='time', lat='latitude', lon='longitude')\nqc_results = xs.run(c)\nlist_results = collect_results(qc_results, how='list')\nlist_results", "Could not run \"qartod.gross_range_test: Suspect Span(minv=-5.5300699248268215, maxv=0.25323436074757943) must fall within the Fail Span(minv=-1.5473811397940986, maxv=-1.168704748875281)\nCould not run \"qartod.gross_range_test: Suspect Span(minv=-4.139668258934844, maxv=0.9204235357318391) must fall within the Fail Span(minv=-0.09592285696581983, maxv=-0.05400437780570839)\nCould not run \"qartod.gross_range_test: Suspect Span(minv=-13.512635229998683, maxv=7.08925221886197) must fall within the Fail Span(minv=0.2729885537903321, maxv=2.9035131901931153)\nCould not run \"qartod.gross_range_test: Suspect Span(minv=-3.240692452818513, maxv=9.711827661747101) must fall within the Fail Span(minv=2.232390583284701, maxv=6.764526997704617)\nCould not run \"qartod.gross_range_test: Suspect Span(minv=-3.240692452818513, maxv=9.711827661747101) must fall within the Fail Span(minv=2.232390583284701, maxv=6.764526997704617)\n" ], [ "# output_notebook()\n# plot = bokeh_plot_collected_results(list_results)\n# plotting.show(plot)", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ] ]
4a0db0031eabcec6edb21e63efbfb323e9de6722
374,658
ipynb
Jupyter Notebook
notebooks/01-Fourier-Series.ipynb
bradshawben/signal-processing
f7d57d46c153f55dddc491e620f3b06502ad0079
[ "MIT" ]
null
null
null
notebooks/01-Fourier-Series.ipynb
bradshawben/signal-processing
f7d57d46c153f55dddc491e620f3b06502ad0079
[ "MIT" ]
null
null
null
notebooks/01-Fourier-Series.ipynb
bradshawben/signal-processing
f7d57d46c153f55dddc491e620f3b06502ad0079
[ "MIT" ]
null
null
null
753.839034
106,820
0.95261
[ [ [ "# Overview\n\nThis notebook implements fourier series simualtions.", "_____no_output_____" ], [ "# Dependencies", "_____no_output_____" ] ], [ [ "import numpy as np\nimport scipy.signal as signal\nimport matplotlib.pyplot as plt", "_____no_output_____" ] ], [ [ "# 1.3: Periodicity: Definitions, Examples, and Things to Come", "_____no_output_____" ], [ "A function $f(t)$ is said to be period of period $t$ if there exists a number $T > 0$ such that $\\forall t$ $f(t + T) = f(t)$.", "_____no_output_____" ] ], [ [ "# Example: The basic trigonometric functions are periodic.\n\ndef period_one_sine(x):\n return np.sin(2*np.pi*x)\n\narange = np.arange(0, 5, 0.01)\nsin_out = period_one_sine(arange)\n\nplt.figsize=(20, 4)\nplt.plot(arange, sin_out)\nplt.axhline(y=0, linestyle='--', color='black')\nfor i in range(0, 6):\n plt.axvline(x=i, linestyle='--', color='black')", "_____no_output_____" ] ], [ [ "Note that the sine function above has period one. For a general sinosoid of the form $f(t) = sin(\\omega t + \\phi)$ the period is given by $\\frac{\\omega}{2\\pi}$. Note $\\phi$ is a phase shift.", "_____no_output_____" ], [ "## Combining sinosoids\n\nNote that summing sinosoids leads to a periodic function with a period that is the maximum period of all of the sinosoids being summed.", "_____no_output_____" ] ], [ [ "def sinosoid(x):\n return np.sin(2*np.pi*x) + np.cos(4*2*np.pi*x)\n\nsin_out = sinosoid(arange)\n\nplt.figsize=(20, 4)\nplt.plot(arange, sin_out)\nplt.axhline(y=0, linestyle='--', color='black')\nfor i in range(0, 6):\n plt.axvline(x=i, linestyle='--', color='black')", "_____no_output_____" ] ], [ [ "Note that that combination of sinosoids can be arbitrarily complex and the above statement still holds.", "_____no_output_____" ], [ "## Aperiodic sinosoids\n\nSinusoids are only periodic if the ratio of the periods being combined is a raional number.", "_____no_output_____" ] ], [ [ "def sinosoid(x):\n return np.sin(2*np.pi*x) + np.sin(np.sqrt(2)*2*np.pi*x)\n\nsin_out = sinosoid(arange)\n\nplt.figsize=(20, 4)\nplt.plot(arange, sin_out)\nplt.axhline(y=0, linestyle='--', color='black')", "_____no_output_____" ] ], [ [ "# Audio\n\nWe can \"hear\" the audio interpretation of sinosoids, since fundamentally sound is simply waves passing through air.", "_____no_output_____" ] ], [ [ "from IPython.display import Audio", "_____no_output_____" ], [ "sr = 22050 # sample rate", "_____no_output_____" ], [ "concert_a = lambda x: np.cos(2*np.pi*440*x)", "_____no_output_____" ], [ "sin_out = concert_a(np.arange(0, 4, 0.0001))", "_____no_output_____" ], [ "len(sin_out)", "_____no_output_____" ], [ "Audio(sin_out, rate=sr)", "_____no_output_____" ] ], [ [ "# Fourier coefficients\n\nLet's use the theory of fourier series to approximate a few periodic functions. We'll start with the switch function.", "_____no_output_____" ] ], [ [ "from scipy.integrate import quad\nfrom numba import vectorize, float64\nfrom numpy import pi", "_____no_output_____" ], [ "def fourier_series(period, N):\n \"\"\"Calculate the Fourier series coefficients up to the Nth harmonic\"\"\"\n result = []\n T = len(period)\n t = np.arange(T)\n for n in range(N+1):\n an = 2/T*(period * np.cos(2*np.pi*n*t/T)).sum()\n bn = 2/T*(period * np.sin(2*np.pi*n*t/T)).sum()\n result.append((an, bn))\n return np.array(result)", "_____no_output_____" ], [ "Fs = 10000\nfunc1 = lambda t: (abs((t%1)-0.25) < 0.25).astype(float) - (abs((t%1)-0.75) < 0.25).astype(float)\nfunc2 = lambda t: t % 1\nfunc3 = lambda t: (abs((t%1)-0.5) < 0.25).astype(float) + 8*(abs((t%1)-0.5)) * (abs((t%1)-0.5)<0.25)\nfunc4 = lambda t: ((t%1)-0.5)**2\nt = np.arange(-1.5, 2, 1/Fs)\n\nplt.figure(figsize=(20, 8))\nplt.subplot(221); plt.plot(t, func1(t))\nplt.subplot(222); plt.plot(t, func2(t))\nplt.subplot(223); plt.plot(t, func3(t))\nplt.subplot(224); plt.plot(t, func4(t))", "_____no_output_____" ], [ "plt.figure(figsize=(20, 9))\nt_period = np.arange(0, 1, 1/Fs)\n\nF1 = fourier_series(func1(t_period), 20)\nplt.subplot(421); plt.stem(F1[:,0])\nplt.subplot(422); plt.stem(F1[:,1])\n\nF2 = fourier_series(func2(t_period), 20)\nplt.subplot(423); plt.stem(F2[:,0])\nplt.subplot(424); plt.stem(F2[:,1])\n\nF3 = fourier_series(func3(t_period), 20)\nplt.subplot(425); plt.stem(F3[:,0])\nplt.subplot(426); plt.stem(F3[:,1])\n\nF4 = fourier_series(func4(t_period), 20)\nplt.subplot(427); plt.stem(F4[:,0])\nplt.subplot(428); plt.stem(F4[:,1])", "_____no_output_____" ], [ "def reconstruct(P, anbn):\n result = 0\n t = np.arange(P)\n for n, (a, b) in enumerate(anbn):\n if n == 0:\n a = a/2\n result = result + a*np.cos(2*np.pi*n*t/P) + b * np.sin(2*np.pi*n*t/P)\n return result", "_____no_output_____" ], [ "plt.figure(figsize=(20, 8))\n\nF = fourier_series(func1(t_period), 100)\nplt.plot(t_period, func1(t_period), label='Original', lw=2)\nplt.plot(t_period, reconstruct(len(t_period), F[:20,:]), label='Reconstructed with 20 Harmonics');\nplt.plot(t_period, reconstruct(len(t_period), F[:100,:]), label='Reconstructed with 100 Harmonics');", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code" ] ]
4a0de8a56e124a522d257215230fe724e5f8e331
71,079
ipynb
Jupyter Notebook
PyBer_ride_data.ipynb
GirijaJoshi/PyBer_Analysis
faaea2be8baae82ba8ca84314b51954b14784c8d
[ "MIT" ]
1
2020-10-20T15:15:37.000Z
2020-10-20T15:15:37.000Z
PyBer_ride_data.ipynb
GirijaJoshi/PyBer_Analysis
faaea2be8baae82ba8ca84314b51954b14784c8d
[ "MIT" ]
null
null
null
PyBer_ride_data.ipynb
GirijaJoshi/PyBer_Analysis
faaea2be8baae82ba8ca84314b51954b14784c8d
[ "MIT" ]
null
null
null
205.430636
21,512
0.901054
[ [ [ "%matplotlib inline", "_____no_output_____" ], [ "# Import dependencies.\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\nimport pandas as pd", "_____no_output_____" ], [ "# Load in csv\nfile_name = os.path.join(\".\", \"Resources\", \"PyBer_ride_data.csv\")\npyber_ride_df = pd.read_csv(file_name)\npyber_ride_df", "_____no_output_____" ], [ "pyber_ride_df.plot(x=\"Month\", y=\"Avg. Fare ($USD)\")", "_____no_output_____" ], [ "# Set x-axis and tick locations.\nx_axis = np.arange(len(pyber_ride_df))\nprint(x_axis)\ntick_locations = [value for value in x_axis]\nprint(tick_locations)\npyber_ride_df.plot(x=\"Month\", y=\"Avg. Fare ($USD)\")\nplt.xticks(tick_locations,pyber_ride_df[\"Month\"] )\nplt.show()", "[ 0 1 2 3 4 5 6 7 8 9 10 11]\n[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]\n" ], [ "pyber_ride_df.plot(x=\"Month\", y=\"Avg. Fare ($USD)\", kind=\"bar\")\n# plt.xticks(tick_locations,pyber_ride_df[\"Month\"])\nplt.show()", "_____no_output_____" ], [ "# Add Error\nimport statistics\n# Get the standard deviation of the values in the y-axis.\nstdev = statistics.stdev(pyber_ride_df[\"Avg. Fare ($USD)\"])\nstdev", "_____no_output_____" ], [ "# Change the color of the bars to sky blue.Add Cap size. \n# Rotate the labels on the x-axis to horizontal. Set the y-axis increment to every $5.\npyber_ride_df.plot(x=\"Month\", y=\"Avg. Fare ($USD)\", kind=\"bar\", \n yerr=stdev, capsize=3, color=\"skyblue\", )\nprint(pyber_ride_df[\"Avg. Fare ($USD)\"].max())\nprint(pyber_ride_df[\"Avg. Fare ($USD)\"].min())\ny_ticks = np.arange(0, pyber_ride_df[\"Avg. Fare ($USD)\"].max() + 10, step=5.0)\nprint(y_ticks)\nplt.yticks(y_ticks)\nplt.xticks(rotation=0)", "43.82\n10.02\n[ 0. 5. 10. 15. 20. 25. 30. 35. 40. 45. 50.]\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code" ] ]
4a0df276b2d2a13a281fe3fa16482f4381ad4241
6,566
ipynb
Jupyter Notebook
books/io-file.ipynb
khanhicetea/learn-python-intermediate
9bcfcb7f10497ae33e54da195dfdc369f59b4dac
[ "CC-BY-3.0" ]
null
null
null
books/io-file.ipynb
khanhicetea/learn-python-intermediate
9bcfcb7f10497ae33e54da195dfdc369f59b4dac
[ "CC-BY-3.0" ]
null
null
null
books/io-file.ipynb
khanhicetea/learn-python-intermediate
9bcfcb7f10497ae33e54da195dfdc369f59b4dac
[ "CC-BY-3.0" ]
null
null
null
24.777358
151
0.511118
[ [ [ "# INPUT / OUTPUT", "_____no_output_____" ], [ "## open file handle function\n\n`open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)`\n\n- file : filename (or file path)\n- mode :\n - r : read mode (default)\n - w : write mode, truncating the file first\n - x : open for exclusive creation, failing if the file already exists\n - a : open for writing, appending to the end of the file if it exists\n - b : binary mode\n - t : text mode (default)\n - \\+ : open for updating (reading and writing)\n \n - So mode default is 'rt'\n", "_____no_output_____" ] ], [ [ "# read text mode\n\nf1 = open('../README.md', 'rt', encoding='utf-8')\nfirst_line = f1.readline() ## Read 1 line, stop at \\n char\nprint(first_line)\nf1.close() # ensure to close file", "## Learn Python Intermediate\n\n" ], [ "# write mode\n\nimport random\nimport os\n\ndef check_file_exised(filename):\n if os.path.isfile(filename):\n f_stat = os.stat(filename)\n print(f'{filename} is existed with {f_stat.st_size} bytes')\n else:\n print(f'{filename} is not existed')\n\nrandom_file3 = f'/tmp/python-write-{random.randint(100, 999)}'\ncheck_file_exised(random_file3)\n\nf3 = open(random_file3, 'w')\nw1 = f3.write(\"Hello world\")\nw2 = f3.write(\"\\nTiếng Việt\")\nprint(w1, w2) # w1, w2 is number of charaters (text mode) or bytes (binary mode) written to file\nf3.close() # ensure to close file\n\ncheck_file_exised(random_file3) # You can see more 4 bytes because 2 unicode chars with (3 bytes / char)", "/tmp/python-write-738 is not existed\n11 11\n/tmp/python-write-738 is existed with 26 bytes\n" ], [ "# read binary mode\n\ndef read_line_by_line_binary(filename):\n f2 = open(filename, 'rb')\n # read line by line\n for line in f2:\n print(line)\n f2.close() # ensure to close file\n\nread_line_by_line_binary(random_file3)", "b'Hello world\\n'\nb'Ti\\xe1\\xba\\xbfng Vi\\xe1\\xbb\\x87t'\n" ], [ "# read with update\n\nf4 = open(random_file3, 'rt+')\n\nfirst_line = f4.readline()\nprint(first_line)\nf4.write(\"\\nNew line\")\nf4.close()\n\nread_line_by_line_binary(random_file3) # so write on r+ will append on end of file", "Hello world\n\nb'Hello world\\n'\nb'Ti\\xe1\\xba\\xbfng Vi\\xe1\\xbb\\x87t\\n'\nb'New line'\n" ], [ "# seek\nf5 = open(random_file3, 'a+')\nprint(f5.tell()) # tell : current position\nf5.seek(6)\nprint(f5.tell()) # tell : current position\nread1 = f5.read(5)\nprint(f5.tell()) # tell : current position, so read change position too\nprint(read1)\n# write on current pos\nf5.write(\" ! Python !\")\nprint(f5.tell()) # tell : current position\nf5.close()\n\nread_line_by_line_binary(random_file3)\n# so in UNIX, you can not write in middle of file (imagine file is array of bytes, insert some bytes in middle you have to shift all right bytes)", "35\n6\n11\nworld\n46\nb'Hello world\\n'\nb'Ti\\xe1\\xba\\xbfng Vi\\xe1\\xbb\\x87t\\n'\nb'New line ! Python !'\n" ], [ "# append mode\n\nf6 = open(random_file3, 'a')\nf6.write(\"\\nHehehehe\")\nf6.close()\n\nread_line_by_line_binary(random_file3)", "b'Hello world\\n'\nb'Ti\\xe1\\xba\\xbfng Vi\\xe1\\xbb\\x87t\\n'\nb'New line ! Python !\\n'\nb'Hehehehe'\n" ], [ "# with (context manager)\n\n# it auto close file (on finish or on exception => safe way)\nwith open(random_file3, 'rt') as f7:\n for line in f7:\n print(line, end='') # file already have \\n char", "Hello world\nTiếng Việt\nNew line ! Python !\nHehehehe" ] ] ]
[ "markdown", "code" ]
[ [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ] ]
4a0df3d096c91a0f6850a6ee4c66aa903c1a9a7e
4,889
ipynb
Jupyter Notebook
BALLCOL_Submission1.ipynb
ThisIsAndrewLi/Codechef
56631e2618c0009e4c4621262e9fdc7b4f02adc7
[ "MIT" ]
null
null
null
BALLCOL_Submission1.ipynb
ThisIsAndrewLi/Codechef
56631e2618c0009e4c4621262e9fdc7b4f02adc7
[ "MIT" ]
null
null
null
BALLCOL_Submission1.ipynb
ThisIsAndrewLi/Codechef
56631e2618c0009e4c4621262e9fdc7b4f02adc7
[ "MIT" ]
null
null
null
23.618357
91
0.424218
[ [ [ "#define number of red balls (n) and blue balls (m)\n(n,m) = map(int, input().split(' '))", "2 2\n" ], [ "#start count total at zero\ntotal = 0", "_____no_output_____" ], [ "#positions of red balls at time t = 0\nxposition = []\nxvelocity = []\nxmaxposition = 0\ni = 0\nwhile i < n:\n [x,u] = map(int, input().split(' '))\n xposition.append([x,0])\n xvelocity.append(u)\n if x > xmaxposition:\n xmaxposition = x\n i += 1", "1 1\n4 3\n" ], [ "#print(xposition, xvelocity, xmaxposition)", "[[1, 0], [4, 0]] [1, 3] 4\n" ], [ "#positions of blue balls at time t = 0\nypostion = []\nyvelocity = []\nymaxposition = 0\ni = 0\nwhile i < m:\n [y,v] = map(int, input().split(' '))\n yposition.append([0,y])\n yvelocity.append(v)\n if y > ymaxposition:\n ymaxposition = y\n i += 1", "1 1\n3 4\n" ], [ "#print(yposition, yvelocity, ymaxposition)", "[[0, 1], [0, 3]] [1, 4] 3\n" ], [ "while xposition and yposition:\n #update all ball positions at time t\n i = 0\n for i in range(len(xposition)):\n xposition[i][1] = xposition[i][1] + xvelocity[i]\n\n i = 0\n for i in range(len(yposition)):\n yposition[i][0] = yposition[i][0] + yvelocity[i]\n\n a = 0\n while a < len(xposition):\n collisonflag = False\n #check if x-axis ball has left collision area\n if xposition[a][1] > ymaxposition:\n #remove x-axis balls\n del xposition[a]\n del xvelocity[a]\n #check for collisions\n else:\n b = 0\n while b < len(yposition):\n #check if y-axis ball has left collision area\n if yposition[b][0] > xmaxposition:\n #remove y-axis balls\n del yposition[b]\n del yvelocity[b]\n #case when collision has occurred\n elif xposition[a] == yposition[b]:\n collisonflag = True\n total = total + 1\n #remove x-axis and y-axis balls that collided\n del xposition[a]\n del xvelocity[a]\n del yposition[b]\n del yvelocity[b] \n #otherwise increment and check for collision with next y-axis ball\n else:\n b = b + 1\n #increment only if x-axis ball was not removed\n if not collisonflag:\n a = a + 1 \n\n #print(total)\n #print(xposition, xvelocity, xmaxposition)\n #print(yposition, yvelocity, ymaxposition)", "2\n[] [] 4\n[] [] 3\n" ], [ "print(total)", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code" ] ]
4a0df5941e2a936fcf21f0d8f1f56eb1ce2d7179
9,491
ipynb
Jupyter Notebook
Data Science and Machine Learning/Machine-Learning-In-Python-THOROUGH/EXAMPLES/DIFFERENT/PANDAS_DATA_SERIES_20200904_TEMPLATE.ipynb
okara83/Becoming-a-Data-Scientist
f09a15f7f239b96b77a2f080c403b2f3e95c9650
[ "MIT" ]
null
null
null
Data Science and Machine Learning/Machine-Learning-In-Python-THOROUGH/EXAMPLES/DIFFERENT/PANDAS_DATA_SERIES_20200904_TEMPLATE.ipynb
okara83/Becoming-a-Data-Scientist
f09a15f7f239b96b77a2f080c403b2f3e95c9650
[ "MIT" ]
null
null
null
Data Science and Machine Learning/Machine-Learning-In-Python-THOROUGH/EXAMPLES/DIFFERENT/PANDAS_DATA_SERIES_20200904_TEMPLATE.ipynb
okara83/Becoming-a-Data-Scientist
f09a15f7f239b96b77a2f080c403b2f3e95c9650
[ "MIT" ]
2
2022-02-09T15:41:33.000Z
2022-02-11T07:47:40.000Z
16.709507
103
0.465494
[ [ [ "# PANDAS DATA SERIES\n\n### https://www.w3resource.com/python-exercises/pandas/index-data-series.php\n", "_____no_output_____" ] ], [ [ "import numpy as np\nimport pandas as pd", "_____no_output_____" ] ], [ [ "### 2. Write a Pandas program to convert a Pandas module Series to Python list and it's type.", "_____no_output_____" ] ], [ [ "ds2 = pd.series(range(1,11))", "_____no_output_____" ], [ "ds2 = pd.Series(range(1,11))", "_____no_output_____" ] ], [ [ "\n_________________________\nPandas Series and type", "_____no_output_____" ] ], [ [ "ds2", "_____no_output_____" ], [ "type(ds2)", "_____no_output_____" ] ], [ [ " \n ____________________________________\n Convert Pandas Series to Python list\n", "_____no_output_____" ] ], [ [ "ds2.tolist()", "_____no_output_____" ], [ "type(ds2.tolist())", "_____no_output_____" ] ], [ [ "# ", "_____no_output_____" ], [ "### 3. Write a Python program to add, subtract, multiple and divide two Pandas Series. \n ", "_____no_output_____" ], [ "===============================================", "_____no_output_____" ] ], [ [ "a = list(range(2,11,2))\na", "_____no_output_____" ], [ "b = list(range(1,10,2))\nb", "_____no_output_____" ] ], [ [ "===============================================", "_____no_output_____" ] ], [ [ "c = a + b\nc", "_____no_output_____" ], [ "d = a - b\nd", "_____no_output_____" ], [ "e = a * b\ne", "_____no_output_____" ], [ "f = a / b\nf", "_____no_output_____" ] ], [ [ "===============================================", "_____no_output_____" ] ], [ [ "ds3a = pd.Series(a)\nds3a", "_____no_output_____" ], [ "ds3b = pd.Series(b)\nds3b", "_____no_output_____" ] ], [ [ "_________________\nAdd two Series:", "_____no_output_____" ] ], [ [ "ds3_sum = ds3a + ds3b\nds3_sum", "_____no_output_____" ] ], [ [ "____________________\nSubtract two Series:", "_____no_output_____" ] ], [ [ "ds3_sub = ds3a - ds3b\nds3_sub", "_____no_output_____" ] ], [ [ "_____________________\nMultiply two Series:", "_____no_output_____" ] ], [ [ "ds3_mul = ds3a * ds3b\nds3_mul", "_____no_output_____" ] ], [ [ "__________________________\nDivide Series1 by Series2", "_____no_output_____" ] ], [ [ "ds3_div = ds3a / ds3b\nds3_div", "_____no_output_____" ], [ "round(ds3_div,2)", "_____no_output_____" ] ], [ [ "### 5. Write a Pandas program to convert a dictionary to a Pandas series.\n### Sample dictionary: d5 = {'a': 100, 'b': 200, 'c':300, 'd':400, 'e':800}", "_____no_output_____" ] ], [ [ "\nd5 = {'a': 100, 'b': 200, 'c':300, 'd':400, 'e':800}\n", "_____no_output_____" ], [ "Original dictionary:", "_____no_output_____" ], [ "d5", "_____no_output_____" ], [ "Converted series:", "_____no_output_____" ], [ "ds5 = pd.Series(d5)\nds5", "_____no_output_____" ], [ "type(d5)", "_____no_output_____" ], [ "type(ds5)", "_____no_output_____" ] ], [ [ "### 6. Write a Pandas program to convert a NumPy array to a Pandas series.", "_____no_output_____" ], [ "Python list:", "_____no_output_____" ] ], [ [ "lst = list(range(10,51,10))\nlst", "_____no_output_____" ] ], [ [ "NumPy array:", "_____no_output_____" ] ], [ [ "np_ar = np.array(lst)\nnp_ar", "_____no_output_____" ] ], [ [ "Converted Pandas series:", "_____no_output_____" ] ], [ [ "ds6 = pd.Series(np_ar)\nds6", "_____no_output_____" ], [ "type(lst)", "_____no_output_____" ], [ "type(ds6)", "_____no_output_____" ] ], [ [ "### 13. Write a Pandas program to create a subset of a given series based on value and condition.", "_____no_output_____" ], [ "Original Data Series:", "_____no_output_____" ] ], [ [ "ds13 = pd.series(range(0,11))\nds13", "_____no_output_____" ], [ "ds13 = pd.Series(range(0,11))\nds13", "_____no_output_____" ] ], [ [ "\\nSubset of the above Data Series:", "_____no_output_____" ] ], [ [ "n=6\nnew_ds13 = ds13[ds13 < 6]\nnew_ds13", "_____no_output_____" ], [ "type(new_ds13)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ] ]
4a0e003010e491434d2931c7c6f7f2ee3bca6094
329,199
ipynb
Jupyter Notebook
1. Foundations of NLP.ipynb
netangel/AdvancedNLP
85b3983db4844c9484625cbfb73d0803fa7a1264
[ "MIT" ]
null
null
null
1. Foundations of NLP.ipynb
netangel/AdvancedNLP
85b3983db4844c9484625cbfb73d0803fa7a1264
[ "MIT" ]
null
null
null
1. Foundations of NLP.ipynb
netangel/AdvancedNLP
85b3983db4844c9484625cbfb73d0803fa7a1264
[ "MIT" ]
null
null
null
121.925556
255,212
0.818587
[ [ [ "<div style=\"width: 100%; overflow: hidden;\">\n <div style=\"width: 150px; float: left;\"> <img src=\"data/D4Sci_logo_ball.png\" alt=\"Data For Science, Inc\" align=\"left\" border=\"0\"> </div>\n <div style=\"float: left; margin-left: 10px;\"> <h1>NLP with Deep Learning for Everyone</h1>\n<h1>Foundations of NLP</h1>\n <p>Bruno Gonçalves<br/>\n <a href=\"http://www.data4sci.com/\">www.data4sci.com</a><br/>\n @bgoncalves, @data4sci</p></div>\n</div>", "_____no_output_____" ] ], [ [ "import warnings\nwarnings.filterwarnings('ignore')\n\nimport os\nimport gzip\nfrom collections import Counter\nfrom pprint import pprint\n\nimport pandas as pd\nimport numpy as np\n\nimport matplotlib\nimport matplotlib.pyplot as plt \n\nimport string\nimport nltk\nfrom nltk.corpus import stopwords \nfrom nltk.text import TextCollection\nfrom nltk.collocations import BigramCollocationFinder\nfrom nltk.metrics.association import BigramAssocMeasures\n\nimport sklearn\nfrom sklearn.manifold import TSNE\n\nfrom tqdm import tqdm\ntqdm.pandas()\n\nimport watermark\n\n%load_ext watermark\n%matplotlib inline", "_____no_output_____" ] ], [ [ "We start by print out the versions of the libraries we're using for future reference", "_____no_output_____" ] ], [ [ "%watermark -n -v -m -g -iv", "Python implementation: CPython\nPython version : 3.8.5\nIPython version : 7.19.0\n\nCompiler : Clang 10.0.0 \nOS : Darwin\nRelease : 20.5.0\nMachine : x86_64\nProcessor : i386\nCPU cores : 16\nArchitecture: 64bit\n\nGit hash: 39ce5cf3bd8432047933c28fa699f7e39cb38900\n\nwatermark : 2.1.0\npandas : 1.1.3\nnumpy : 1.19.2\nnltk : 3.5\nsklearn : 0.24.1\nmatplotlib: 3.3.2\njson : 2.0.9\n\n" ] ], [ [ "Load default figure style", "_____no_output_____" ] ], [ [ "plt.style.use('./d4sci.mplstyle')\ncolors = plt.rcParams['axes.prop_cycle'].by_key()['color']", "_____no_output_____" ] ], [ [ "# One-Hot Encoding", "_____no_output_____" ] ], [ [ "text = \"\"\"Mary had a little lamb, little lamb,\n little lamb. 'Mary' had a little lamb\n whose fleece was white as snow.\n And everywhere that Mary went\n Mary went, MARY went. Everywhere\n that mary went,\n The lamb was sure to go\"\"\"", "_____no_output_____" ] ], [ [ "The first step is to tokenize the text. NLTK provides us with a convenient tokenizer function we can use. It is also smart enough to be able to handle different languages", "_____no_output_____" ] ], [ [ "tokens = nltk.word_tokenize(text, 'english')", "_____no_output_____" ], [ "pprint(tokens)", "['Mary',\n 'had',\n 'a',\n 'little',\n 'lamb',\n ',',\n 'little',\n 'lamb',\n ',',\n 'little',\n 'lamb',\n '.',\n \"'Mary\",\n \"'\",\n 'had',\n 'a',\n 'little',\n 'lamb',\n 'whose',\n 'fleece',\n 'was',\n 'white',\n 'as',\n 'snow',\n '.',\n 'And',\n 'everywhere',\n 'that',\n 'Mary',\n 'went',\n 'Mary',\n 'went',\n ',',\n 'MARY',\n 'went',\n '.',\n 'Everywhere',\n 'that',\n 'mary',\n 'went',\n ',',\n 'The',\n 'lamb',\n 'was',\n 'sure',\n 'to',\n 'go']\n" ] ], [ [ "You'll note that NLTK includes apostrophes at the beginning of words and returns all punctuation markings.", "_____no_output_____" ] ], [ [ "print(tokens[5])\nprint(tokens[12])\nprint(tokens[13])", ",\n'Mary\n'\n" ] ], [ [ "We wrap it into a utility function to handle these", "_____no_output_____" ] ], [ [ "def tokenize(text, preserve_case=True):\n punctuation = set(string.punctuation)\n text_words = []\n \n for word in nltk.word_tokenize(text):\n # Remove any punctuation characters present in the beginning of the word\n while len(word) > 0 and word[0] in punctuation:\n word = word[1:]\n\n # Remove any punctuation characters present in the end of the word\n while len(word) > 0 and word[-1] in punctuation:\n word = word[:-1]\n \n if len(word) > 0:\n if preserve_case:\n text_words.append(word)\n else:\n text_words.append(word.lower())\n \n return text_words", "_____no_output_____" ], [ "text_words = tokenize(text, False)", "_____no_output_____" ], [ "text_words", "_____no_output_____" ] ], [ [ "We can get a quick one-hot encoded version using pandas:", "_____no_output_____" ] ], [ [ "one_hot = pd.get_dummies(text_words)", "_____no_output_____" ] ], [ [ "Which provides us with a DataFrame where each column corresponds to an individual unique word and each row to a word in our text.", "_____no_output_____" ] ], [ [ "temp = one_hot.astype('str')\ntemp[temp=='0'] = \"\"\ntemp = pd.DataFrame(temp)\ntemp", "_____no_output_____" ] ], [ [ "From here can easily generate a mapping between the words and their numerical id", "_____no_output_____" ] ], [ [ "word_dict = dict(zip(one_hot.columns, np.arange(one_hot.shape[1])))\nword_dict", "_____no_output_____" ] ], [ [ "Allowing us to easily transform from words to ids and back", "_____no_output_____" ], [ "# Bag of Words", "_____no_output_____" ], [ "From the one-hot encoded representation we can easily obtain the bag of words version of our document", "_____no_output_____" ] ], [ [ "pd.DataFrame(one_hot.sum(), columns=['Count'])", "_____no_output_____" ] ], [ [ "A more general representation would be to use a dictionary mapping each word to the number of times it occurs. This has the added advantage of being a dense representation that doesn't waste any space", "_____no_output_____" ], [ "# Stemming", "_____no_output_____" ] ], [ [ "words = ['playing', 'loved', 'ran', 'river', 'friendships', 'misunderstanding', 'trouble', 'troubling']\n\nstemmers = { \n 'LancasterStemmer' : nltk.stem.LancasterStemmer(),\n 'PorterStemmer' : nltk.stem.PorterStemmer(),\n 'RegexpStemmer' : nltk.stem.RegexpStemmer('ing$|s$|e$|able$'),\n 'SnowballStemmer' : nltk.stem.SnowballStemmer('english')\n}", "_____no_output_____" ], [ "matrix = []\n\nfor word in words:\n row = []\n for stemmer in stemmers:\n stem = stemmers[stemmer]\n row.append(stem.stem(word))\n \n matrix.append(row)\n\ncomparison = pd.DataFrame(matrix, index=words, columns=stemmers.keys())", "_____no_output_____" ], [ "comparison", "_____no_output_____" ] ], [ [ "# Lemmatization", "_____no_output_____" ] ], [ [ "wordnet = nltk.stem.WordNetLemmatizer()\n\nresults_n = [wordnet.lemmatize(word, 'n') for word in words]\nresults_v = [wordnet.lemmatize(word, 'v') for word in words]", "_____no_output_____" ], [ "comparison['WordNetLemmatizer Noun'] = results_n\ncomparison['WordNetLemmatizer Verb'] = results_v", "_____no_output_____" ], [ "comparison", "_____no_output_____" ] ], [ [ "# Stopwords", "_____no_output_____" ], [ "NLTK provides stopwords for 23 different languages", "_____no_output_____" ] ], [ [ "os.listdir('/Users/bgoncalves/nltk_data/corpora/stopwords/')", "_____no_output_____" ] ], [ [ "And we can easily use them to filter out meaningless words", "_____no_output_____" ] ], [ [ "stop_words = set(stopwords.words('english')) \n \ntokens = tokenize(text) \n \nfiltered_sentence = [word if word.lower() not in stop_words else \"\" for word in tokens] \n \npd.DataFrame((zip(tokens, filtered_sentence)), columns=['Original', 'Filtered']).set_index('Original')", "_____no_output_____" ] ], [ [ "# N-Grams", "_____no_output_____" ] ], [ [ "def get_ngrams(text, length):\n from nltk.util import ngrams\n \n n_grams = ngrams(tokenize(text), length)\n return [ ' '.join(grams) for grams in n_grams]", "_____no_output_____" ], [ "get_ngrams(text.lower(), 2)", "_____no_output_____" ] ], [ [ "# Collocations", "_____no_output_____" ] ], [ [ "bigrams = BigramCollocationFinder.from_words(tokenize(text, False))\nscored = bigrams.score_ngrams(BigramAssocMeasures.likelihood_ratio)", "_____no_output_____" ], [ "scored", "_____no_output_____" ] ], [ [ "# TF/IDF", "_____no_output_____" ], [ "NLTK has the TextCollection object that allows us to easily compute tf-idf scores from a given corpus. We generate a small corpus by splitting our text by sentence", "_____no_output_____" ] ], [ [ "corpus = text.split('.')", "_____no_output_____" ] ], [ [ "We have 4 documents in our corpus", "_____no_output_____" ] ], [ [ "len(corpus)", "_____no_output_____" ] ], [ [ "NLTK expects the corpus to be tokenized so we do that now", "_____no_output_____" ] ], [ [ "corpus = [tokenize(doc, preserve_case=False) for doc in corpus]", "_____no_output_____" ], [ "corpus", "_____no_output_____" ] ], [ [ "We initialize the TextCollection object with our corpus", "_____no_output_____" ] ], [ [ "nlp = TextCollection(corpus)", "_____no_output_____" ] ], [ [ "This object provides us with a great deal of functionality, like total frequency counts", "_____no_output_____" ] ], [ [ "nlp.plot()", "_____no_output_____" ] ], [ [ "Individual tf/idf scores, etc", "_____no_output_____" ] ], [ [ "nlp.tf_idf('Mary', corpus[3])", "_____no_output_____" ] ], [ [ "To get the full TF/IDF scores for our corpus, we do", "_____no_output_____" ] ], [ [ "TFIDF = []\n\nfor doc in corpus:\n current = {}\n for token in doc:\n current[token] = nlp.tf_idf(token, doc)\n \n TFIDF.append(current)", "_____no_output_____" ], [ "TFIDF", "_____no_output_____" ] ], [ [ "<div style=\"width: 100%; overflow: hidden;\">\n <img src=\"data/D4Sci_logo_full.png\" alt=\"Data For Science, Inc\" align=\"center\" border=\"0\" width=300px> \n</div>", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ] ]
4a0e05cf213a3e4823702f836188ba922246a88f
60,334
ipynb
Jupyter Notebook
doc/examples/early_stopping.ipynb
Gabriel-p/pyABC
a1c963203c9f9e3fa40793ccf214753fb689d27f
[ "BSD-3-Clause" ]
144
2017-10-23T11:20:09.000Z
2022-03-31T08:55:51.000Z
doc/examples/early_stopping.ipynb
Gabriel-p/pyABC
a1c963203c9f9e3fa40793ccf214753fb689d27f
[ "BSD-3-Clause" ]
494
2018-02-14T09:49:26.000Z
2022-03-29T12:09:39.000Z
doc/examples/early_stopping.ipynb
Gabriel-p/pyABC
a1c963203c9f9e3fa40793ccf214753fb689d27f
[ "BSD-3-Clause" ]
45
2018-08-27T18:01:46.000Z
2022-03-30T14:05:37.000Z
110.704587
25,536
0.86651
[ [ [ "Early stopping of model simulations\n===================", "_____no_output_____" ] ], [ [ "This notebook can be downloaded here:\n:download:`Early Stopping <early_stopping.ipynb>`.", "_____no_output_____" ] ], [ [ "For certain distance functions and certain models it is possible to calculate the\ndistance on-the-fly while the model is running. This is e.g. possible if the distance is calculated as a cumulative sum and the model is a stochastic process. For example, Markov Jump Processes belong to this class. However, we want to keep things simple here and only demonstrate how to use the pyABC interface in such cases. So don't expect a sophisticated (or even useful) model implementation here.\n\nIn this example we'll use in particular the following classes for integrated simulation and accepting/rejecting a parameter:", "_____no_output_____" ] ], [ [ "* :class:`IntegratedModel <pyabc.model.IntegratedModel>`\n* :class:`ModelResult <pyabc.model.ModelResult>`", "_____no_output_____" ] ], [ [ "Let's start with the necessary imports:", "_____no_output_____" ] ], [ [ "# install if not done yet\n!pip install pyabc --quiet", "_____no_output_____" ], [ "%matplotlib inline\n\nimport pyabc\nfrom pyabc import (ABCSMC,\n RV, Distribution,\n IntegratedModel, ModelResult,\n MedianEpsilon,\n LocalTransition,\n NoDistance)\nfrom pyabc.sampler import SingleCoreSampler\nimport matplotlib.pyplot as plt\nimport os\nimport tempfile\nimport pandas as pd\nimport numpy as np\n\npyabc.settings.set_figure_params('pyabc') # for beautified plots\n\ndb_path = (\"sqlite:///\" +\n os.path.join(tempfile.gettempdir(), \"test.db\"))", "_____no_output_____" ] ], [ [ "We define here a (very) simple stochastic process, purely for demonstrative reasons.\nFirst, we fix the number of steps *n_steps* to 30.", "_____no_output_____" ] ], [ [ "n_steps = 30", "_____no_output_____" ] ], [ [ "We then define our process as follows:\n\n$$\n x(t+1) = x(t) + s \\xi,\n$$\n\nin which $\\xi \\sim U(0, 1)$ denotes a uniformly in $[0, 1]$ distributed\nrandom variable, and $s$ is the step size, $s = $ step_size.\n\nThe function `simulate` implements this stochastic process:", "_____no_output_____" ] ], [ [ "def simulate(step_size):\n trajectory = np.zeros(n_steps)\n for t in range(1, n_steps):\n xi = np.random.uniform()\n trajectory[t] = trajectory[t-1] + xi * step_size\n return trajectory", "_____no_output_____" ] ], [ [ "We take as distance function between two such generated trajectories\nthe sum of the absolute values of the pointwise differences.", "_____no_output_____" ] ], [ [ "def distance(trajectory_1, trajectory_2):\n return np.absolute(trajectory_1 - trajectory_2).sum()", "_____no_output_____" ] ], [ [ "Let's run the simulation and plot the trajectories to get a better\nidea of the so generated data.\nWe set the ground truth step size *gt_step_size* to ", "_____no_output_____" ] ], [ [ "gt_step_size = 5", "_____no_output_____" ] ], [ [ "This will be used to generate the data which will be subject to inference later on.", "_____no_output_____" ] ], [ [ "gt_trajectory = simulate(gt_step_size)\ntrajectoy_2 = simulate(2)\n\ndist_1_2 = distance(gt_trajectory, trajectoy_2)\n\nplt.plot(gt_trajectory,\n label=\"Step size = {} (Ground Truth)\".format(gt_step_size))\nplt.plot(trajectoy_2,\n label=\"Step size = 2\")\nplt.legend();\nplt.title(\"Distance={:.2f}\".format(dist_1_2));", "_____no_output_____" ] ], [ [ "As you might have noted already we could calculate the distance on the fly.\nAfter each step in the stochastic process, we could increment the cumulative sum.\nThis will supposedly save time in the ABC-SMC run later on.", "_____no_output_____" ] ], [ [ "To implement this in pyABC we use the :class:`IntegratedModel <pyabc.model.IntegratedModel>`.", "_____no_output_____" ] ], [ [ "Let's start with the code first and explain it afterwards.", "_____no_output_____" ] ], [ [ "class MyStochasticProcess(IntegratedModel):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.n_early_stopped = 0\n \n def integrated_simulate(self, pars, eps):\n cumsum = 0\n trajectory = np.zeros(n_steps)\n for t in range(1, n_steps):\n xi = np.random.uniform()\n next_val = trajectory[t-1] + xi * pars[\"step_size\"]\n cumsum += abs(next_val - gt_trajectory[t])\n trajectory[t] = next_val\n if cumsum > eps:\n self.n_early_stopped += 1\n return ModelResult(accepted=False)\n \n return ModelResult(accepted=True,\n distance=cumsum,\n sum_stat={\"trajectory\": trajectory})", "_____no_output_____" ] ], [ [ "Our `MyStochasticProcess` class is a subclass of `IntegratedModel <pyabc.model.IntegratedModel>`.\n\nThe `__init__` method is not really necessary. Here, we just want to keep\ntrack of how often early stopping has actually happened.\n\nMore interesting is the `integrated_simulate` method. This is where the real thing\nhappens.\nAs already said, we calculate the cumulative sum on the fly.\nIn each simulation step, we update the cumulative sum.\nNote that *gt_trajectory* is actually a global variable here.\nIf *cumsum > eps* at some step of the simulation, we return immediately,\nindicating that the parameter was not accepted\nby returning `ModelResult(accepted=False)`.\nIf the *cumsum* never passed *eps*, the parameter got accepted. In this case\nwe return an accepted result together with the calculated distance and the trajectory.\nNote that, while it is mandatory to return the distance, returning the trajectory is optional. If it is returned, it is stored in the database.\n\nWe define a uniform prior over the interval $[0, 10]$ over the step size", "_____no_output_____" ] ], [ [ "prior = Distribution(step_size=RV(\"uniform\", 0 , 10))", "_____no_output_____" ] ], [ [ "and create and instance of our integrated model MyStochasticProcess", "_____no_output_____" ] ], [ [ "model = MyStochasticProcess()", "_____no_output_____" ] ], [ [ "We then configure the ABC-SMC run.\nAs the distance function is calculated within `MyStochasticProcess`, we just pass\n`None` to the `distance_function` parameter. \nAs sampler, we use the `SingleCoreSampler` here. We do so to correctly keep track of `MyStochasticProcess.n_early_stopped`. Otherwise, the counter gets incremented in subprocesses and we don't see anything here.\nOf course, you could also use the `MyStochasticProcess` model in a multi-core or\ndistributed setting.\n\nImportantly, we pre-specify the initial acceptance threshold to a given value, here to 300. Otherwise, pyABC will try to automatically determine it by drawing samples from the prior and evaluating the distance function.\nHowever, we do not have a distance function here, so this approach would break down.", "_____no_output_____" ] ], [ [ "abc = ABCSMC(models=model,\n parameter_priors=prior,\n distance_function=NoDistance(),\n sampler=SingleCoreSampler(),\n population_size=30,\n transitions=LocalTransition(k_fraction=.2),\n eps=MedianEpsilon(300, median_multiplier=0.7))", "_____no_output_____" ] ], [ [ "We then indicate that we want to start a new ABC-SMC run:", "_____no_output_____" ] ], [ [ "abc.new(db_path)", "INFO:History:Start <ABCSMC id=1, start_time=2021-02-21 17:22:41.018237>\n" ] ], [ [ "We do not need to pass any data here. However, we could still pass additionally\na dictionary `{\"trajectory\": gt_trajectory}` only for storage purposes\nto the `new` method. The data will however be ignored during the ABC-SMC run.\n\nThen, let's start the sampling", "_____no_output_____" ] ], [ [ "h = abc.run(minimum_epsilon=40, max_nr_populations=3)", "INFO:ABC:t: 0, eps: 300.\nINFO:ABC:Acceptance rate: 30 / 111 = 2.7027e-01, ESS=3.0000e+01.\nINFO:ABC:t: 1, eps: 140.6687680285705.\nINFO:ABC:Acceptance rate: 30 / 140 = 2.1429e-01, ESS=2.1150e+01.\nINFO:ABC:t: 2, eps: 72.25140375797258.\nINFO:ABC:Acceptance rate: 30 / 433 = 6.9284e-02, ESS=1.8744e+01.\nINFO:pyabc.util:Stopping: maximum number of generations.\nINFO:History:Done <ABCSMC id=1, duration=0:00:01.067589, end_time=2021-02-21 17:22:42.085826>\n" ] ], [ [ "and check how often the early stopping was used:", "_____no_output_____" ] ], [ [ "model.n_early_stopped", "_____no_output_____" ] ], [ [ "Quite a lot actually.", "_____no_output_____" ], [ "Lastly we estimate KDEs of the different populations to inspect our results\nand plot everything (the vertical dashed line is the ground truth step size).", "_____no_output_____" ] ], [ [ "from pyabc.visualization import plot_kde_1d\nfig, ax = plt.subplots()\n\nfor t in range(h.max_t+1):\n particles = h.get_distribution(m=0, t=t)\n plot_kde_1d(*particles, \"step_size\",\n label=\"t={}\".format(t), ax=ax,\n xmin=0, xmax=10, numx=300)\nax.axvline(gt_step_size, color=\"k\", linestyle=\"dashed\"); ", "_____no_output_____" ] ], [ [ "That's it. You should be able to see how the distribution\ncontracts around the true parameter.", "_____no_output_____" ] ] ]
[ "markdown", "raw", "markdown", "raw", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "raw", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "raw" ], [ "markdown" ], [ "raw" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "raw" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ] ]
4a0e079b672925695c2cf24deca525c215d63621
182,977
ipynb
Jupyter Notebook
notebooks/youtube_data_analysis-need_key.ipynb
alvations/datadoubleconfirm
79c977f89e9fff7d4c3bfef17d84d39388a298b6
[ "MIT" ]
39
2018-09-06T03:40:40.000Z
2022-03-30T00:37:17.000Z
notebooks/youtube_data_analysis-need_key.ipynb
alvations/datadoubleconfirm
79c977f89e9fff7d4c3bfef17d84d39388a298b6
[ "MIT" ]
3
2019-05-02T05:17:58.000Z
2020-12-15T14:44:59.000Z
notebooks/youtube_data_analysis-need_key.ipynb
alvations/datadoubleconfirm
79c977f89e9fff7d4c3bfef17d84d39388a298b6
[ "MIT" ]
43
2018-11-15T07:05:54.000Z
2022-03-30T00:42:06.000Z
68.891943
36,460
0.626489
[ [ [ "### This notebook covers how to get statistics on videos returned for a list of search terms on YouTube with the use of YouTube Data API v3. ", "_____no_output_____" ], [ "First go to [Google Developer](http://console.developers.google.com/) and enable YouTube Data API v3 by clicking on the button \"+ ENABLE APIS AND SERVICES\" and searching for YouTube Data API v3. Next, get your unique developer key from the Credentials setting. Then run the following in command line to install the necessary client: `pip install --upgrade google-api-python-client`\n\nThere are only two things which you need to modify in this notebook. 1) Paste the developer key in the code below. 2) Change the search terms in the keywords list to what you want. ", "_____no_output_____" ], [ "<img src=\"https://static.wixstatic.com/media/1ea3da_6e02db1850d845ec9e4325ee8c56eb12~mv2.png/v1/fill/w_1035,h_338,al_c,q_80,usm_0.66_1.00_0.01/1ea3da_6e02db1850d845ec9e4325ee8c56eb12~mv2.webp\">", "_____no_output_____" ] ], [ [ "from apiclient.discovery import build\nfrom apiclient.errors import HttpError\nfrom oauth2client.tools import argparser\nimport pandas as pd\nimport numpy as np\nimport pprint \nimport matplotlib.pyplot as plt\n\nDEVELOPER_KEY = \"\" #paste key here in between \"\"\nYOUTUBE_API_SERVICE_NAME = \"youtube\"\nYOUTUBE_API_VERSION = \"v3\"\n", "_____no_output_____" ], [ "#input list of search terms of interest \nkeywords = [\"bts\",\"blackpink\",\"twice\",\"one direction\"]", "_____no_output_____" ], [ "youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,developerKey=DEVELOPER_KEY)\n\nmax_results=50\norder=\"relevance\"\ntoken=None\nlocation=None\nlocation_radius=None\n\ntitle = []\nchannelId = []\nchannelTitle = []\ncategoryId = []\nvideoId = []\npubDate = [] \nviewCount = []\nlikeCount = []\ndislikeCount = []\ncommentCount = []\nfavoriteCount = []\ncategory = []\ntags = []\nvideos = []\nkeyword = []\n\nfor q in keywords:\n search_response = youtube.search().list(\n q=q,\n type=\"video\",\n pageToken=token,\n order = order,\n part=\"id,snippet\", \n maxResults=max_results,\n location=location,\n locationRadius=location_radius).execute()\n\n\n for search_result in search_response.get(\"items\", []):\n\n keyword.append(q)\n\n if search_result[\"id\"][\"kind\"] == \"youtube#video\":\n\n title.append(search_result['snippet']['title']) \n\n videoId.append(search_result['id']['videoId'])\n\n response = youtube.videos().list(\n part='statistics, snippet',\n id=search_result['id']['videoId']).execute()\n\n channelId.append(response['items'][0]['snippet']['channelId'])\n channelTitle.append(response['items'][0]['snippet']['channelTitle'])\n pubDate.append(response['items'][0]['snippet']['publishedAt'])\n categoryId.append(response['items'][0]['snippet']['categoryId'])\n favoriteCount.append(response['items'][0]['statistics']['favoriteCount'])\n viewCount.append(response['items'][0]['statistics']['viewCount'])\n try:\n likeCount.append(response['items'][0]['statistics']['likeCount'])\n except:\n likeCount.append(\"NaN\")\n\n try:\n dislikeCount.append(response['items'][0]['statistics']['dislikeCount']) \n except:\n dislikeCount.append(\"NaN\")\n\n if 'commentCount' in response['items'][0]['statistics'].keys():\n commentCount.append(response['items'][0]['statistics']['commentCount'])\n else:\n commentCount.append(0)\n\n if 'tags' in response['items'][0]['snippet'].keys():\n tags.append(response['items'][0]['snippet']['tags'])\n else:\n tags.append(\"No Tags\") \n", "_____no_output_____" ], [ "youtube_dict = {'pubDate': pubDate,'tags': tags,'channelId': channelId,'channelTitle': channelTitle,'categoryId':categoryId,'title':title,'videoId':videoId,'viewCount':viewCount,'likeCount':likeCount,'dislikeCount':dislikeCount,'favoriteCount':favoriteCount, 'commentCount':commentCount, 'keyword':keyword}\ndf = pd.DataFrame(youtube_dict)\ndf.head()", "_____no_output_____" ], [ "df.shape", "_____no_output_____" ], [ "df['pubDate'] = pd.to_datetime(df.pubDate)\ndf['publishedDate'] = df['pubDate'].dt.strftime('%d/%m/%Y')", "_____no_output_____" ], [ "#rearranging order of columns\ndf1 = df[['keyword','publishedDate','title','viewCount','channelTitle','commentCount','likeCount','dislikeCount','tags','favoriteCount','videoId','channelId','categoryId']]\ndf1.columns = ['keyword','publishedDate','Title','viewCount','channelTitle','commentCount','likeCount','dislikeCount','tags','favoriteCount','videoId','channelId','categoryId']\ndf1.head()", "_____no_output_____" ], [ "df1.to_csv(\"youtube_bands4.csv\") #download to local drive as a csv file", "_____no_output_____" ], [ "data = pd.read_csv(\"youtube_bands4.csv\")", "_____no_output_____" ], [ "data.dtypes", "_____no_output_____" ], [ "list(data)", "_____no_output_____" ], [ "data = data.drop('Unnamed: 0',1)", "_____no_output_____" ], [ "list(data)", "_____no_output_____" ], [ "data[data.isna().any(axis=1)] #see how many rows has missing data", "_____no_output_____" ], [ "numeric_dtype = ['viewCount','commentCount','likeCount','dislikeCount','favoriteCount']\nfor i in numeric_dtype:\n data[i] = data[i]/1000000 #converting to millions\ndata", "_____no_output_____" ], [ "#sorting the data by likeCount in descending order\ndata.sort_values(\"likeCount\", axis = 0, ascending = False, \n inplace = True, na_position ='last')", "_____no_output_____" ], [ "focus1 = data.head(10) #select top 10 results by likeCount", "_____no_output_____" ], [ "focus1", "_____no_output_____" ], [ "focus1.shape #check number of rows and columns", "_____no_output_____" ], [ "fig, ax = plt.subplots()\nax.barh(range(focus1.shape[0]),focus1['likeCount'])\nax.set_yticks(range(focus1.shape[0]))\nax.set_yticklabels(focus1['Title'])\nax.invert_yaxis() # labels read top-to-bottom\nax.set_xlabel('likeCount in Millions')\n\nplt.show()\n", "_____no_output_____" ], [ "#sorting the data by viewCount in descending order\ndata.sort_values(\"viewCount\", axis = 0, ascending = False, \n inplace = True, na_position ='last')", "_____no_output_____" ], [ "focus1 = data.head(10) #select top 10 results by viewCount", "_____no_output_____" ], [ "fig, ax = plt.subplots()\nax.barh(range(focus1.shape[0]),focus1['viewCount'])\nax.set_yticks(range(focus1.shape[0]))\nax.set_yticklabels(focus1['Title'])\nax.invert_yaxis() # labels read top-to-bottom\nax.set_xlabel('viewCount in Millions')\nplt.show()", "_____no_output_____" ] ], [ [ "#### References:\nhttps://medium.com/greyatom/youtube-data-in-python-6147160c5833 \nhttps://medium.com/@RareLoot/extract-youtube-video-statistics-based-on-a-search-query-308afd786bfe \nhttps://developers.google.com/youtube/v3/getting-started", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown" ]
[ [ "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ] ]
4a0e1e2ad4d109380d502ac6bb25583784d128c3
47,396
ipynb
Jupyter Notebook
read_images.ipynb
mengmeng4263/age_gender_estimation
5bbd640397ebaa673ed2fa6872a9836f6ed9d13b
[ "MIT" ]
564
2017-12-02T17:57:37.000Z
2022-03-31T08:43:59.000Z
read_images.ipynb
praveenkumarchandaliya/Age-Gender-Estimate-TF
9a2d2b18813d2ce0ed5e84d03a668891cdfdc64e
[ "MIT" ]
43
2017-12-02T17:57:28.000Z
2021-08-13T10:44:48.000Z
read_images.ipynb
praveenkumarchandaliya/Age-Gender-Estimate-TF
9a2d2b18813d2ce0ed5e84d03a668891cdfdc64e
[ "MIT" ]
188
2017-12-06T03:00:30.000Z
2022-02-18T12:08:14.000Z
128.793478
35,842
0.853405
[ [ [ "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport argparse\nimport os.path\nimport sys\nimport time\n\nimport tensorflow as tf\n", "_____no_output_____" ], [ "TRAIN_FILE = 'train.tfrecords'", "_____no_output_____" ], [ "def read_and_decode(filename_queue):\n reader = tf.TFRecordReader()\n _, serialized_example = reader.read(filename_queue)\n features = tf.parse_single_example(\n serialized_example,\n # Defaults are not specified since both keys are required.\n features={\n 'image_raw': tf.FixedLenFeature([],tf.string),\n 'age': tf.FixedLenFeature([], tf.int64),\n 'gender':tf.FixedLenFeature([], tf.int64)\n })\n\n # Convert from a scalar string tensor (whose single string has\n # length mnist.IMAGE_PIXELS) to a uint8 tensor with shape\n # [mnist.IMAGE_PIXELS].\n image = tf.image.decode_jpeg(features['image_raw'], channels=3)\n image = tf.image.resize_images(image,[128,128])\n #image = tf.cast(image,tf.uint8)\n # image.set_shape([mnist.IMAGE_PIXELS])\n\n # OPTIONAL: Could reshape into a 28x28 image and apply distortions\n # here. Since we are not applying any distortions in this\n # example, and the next step expects the image to be flattened\n # into a vector, we don't bother.\n\n # Convert from [0, 255] -> [-0.5, 0.5] floats.\n #image = tf.cast(image, tf.float32) * (1. / 255) - 0.5\n\n # Convert label from a scalar uint8 tensor to an int32 scalar.\n age = features['age']#tf.cast(features['age'], tf.int32)\n gender = tf.cast(features['gender'], tf.int32)\n\n return image, age, gender\n", "_____no_output_____" ], [ "def inputs(train, batch_size, num_epochs):\n \"\"\"Reads input data num_epochs times.\n Args:\n train: Selects between the training (True) and validation (False) data.\n batch_size: Number of examples per returned batch.\n num_epochs: Number of times to read the input data, or 0/None to\n train forever.\n Returns:\n A tuple (images, labels), where:\n * images is a float tensor with shape [batch_size, mnist.IMAGE_PIXELS]\n in the range [-0.5, 0.5].\n * labels is an int32 tensor with shape [batch_size] with the true label,\n a number in the range [0, mnist.NUM_CLASSES).\n Note that an tf.train.QueueRunner is added to the graph, which\n must be run using e.g. tf.train.start_queue_runners().\n \"\"\"\n if not num_epochs: num_epochs = None\n # filename = os.path.join(FLAGS.train_dir,\n # TRAIN_FILE if train else VALIDATION_FILE)\n\n with tf.name_scope('input'):\n filename_queue = tf.train.string_input_producer(\n [TRAIN_FILE], num_epochs=num_epochs)\n\n # Even when reading in multiple threads, share the filename\n # queue.\n image, age, gender = read_and_decode(filename_queue)\n\n # Shuffle the examples and collect them into batch_size batches.\n # (Internally uses a RandomShuffleQueue.)\n # We run this in two threads to avoid being a bottleneck.\n images, sparse_labels = tf.train.shuffle_batch(\n [image, age], batch_size=batch_size, num_threads=2,\n capacity=1000 + 3 * batch_size,\n # Ensures a minimum amount of shuffling of examples.\n min_after_dequeue=1000)\n\n return images, sparse_labels", "_____no_output_____" ], [ "def run_training():\n \"\"\"Train MNIST for a number of steps.\"\"\"\n\n # Tell TensorFlow that the model will be built into the default Graph.\n with tf.Graph().as_default():\n # Input images and labels.\n images, labels = inputs(train=True, batch_size=16,\n num_epochs=1)\n\n # Build a Graph that computes predictions from the inference model.\n #logits = mnist.inference(images,\n # FLAGS.hidden1,\n # FLAGS.hidden2)\n\n # Add to the Graph the loss calculation.\n #loss = mnist.loss(logits, labels)\n\n # Add to the Graph operations that train the model.\n #train_op = mnist.training(loss, FLAGS.learning_rate)\n\n # The op for initializing the variables.\n init_op = tf.group(tf.global_variables_initializer(),\n tf.local_variables_initializer())\n\n # Create a session for running operations in the Graph.\n sess = tf.Session()\n\n # Initialize the variables (the trained variables and the\n # epoch counter).\n sess.run(init_op)\n\n # Start input enqueue threads.\n coord = tf.train.Coordinator()\n threads = tf.train.start_queue_runners(sess=sess, coord=coord)\n\n try:\n step = 0\n while not coord.should_stop():\n start_time = time.time()\n\n # Run one step of the model. The return values are\n # the activations from the `train_op` (which is\n # discarded) and the `loss` op. To inspect the values\n # of your ops or variables, you may include them in\n # the list passed to sess.run() and the value tensors\n # will be returned in the tuple from the call.\n #_, loss_value = sess.run([train_op, loss])\n images_val = sess.run([images])\n print(images_val.shape)\n duration = time.time() - start_time\n\n # Print an overview fairly often.\n #if step % 100 == 0:\n # print('Step %d: loss = %.2f (%.3f sec)' % (step, loss_value,\n # duration))\n step += 1\n except tf.errors.OutOfRangeError:\n print('Done training for %d epochs, %d steps.' % (1, step))\n finally:\n # When done, ask the threads to stop.\n coord.request_stop()\n\n # Wait for threads to finish.\n coord.join(threads)\n sess.close()", "_____no_output_____" ], [ " images, labels = inputs(train=True, batch_size=16,\n num_epochs=1)\n\n # Build a Graph that computes predictions from the inference model.\n #logits = mnist.inference(images,\n # FLAGS.hidden1,\n # FLAGS.hidden2)\n\n # Add to the Graph the loss calculation.\n #loss = mnist.loss(logits, labels)\n\n # Add to the Graph operations that train the model.\n #train_op = mnist.training(loss, FLAGS.learning_rate)\n\n # The op for initializing the variables.\n init_op = tf.group(tf.global_variables_initializer(),\n tf.local_variables_initializer())\n\n # Create a session for running operations in the Graph.\n sess = tf.Session()\n\n # Initialize the variables (the trained variables and the\n # epoch counter).\n sess.run(init_op)\n\n # Start input enqueue threads.\n coord = tf.train.Coordinator()\n threads = tf.train.start_queue_runners(sess=sess, coord=coord)", "_____no_output_____" ], [ "images_val,age_val = sess.run([images,labels])", "_____no_output_____" ], [ "images_val[0].shape", "_____no_output_____" ], [ "import matplotlib.pyplot as plt", "_____no_output_____" ], [ "plt.imshow(images_val[6]/255.0)", "_____no_output_____" ], [ "plt.show()", "_____no_output_____" ], [ "sess.close()", "INFO:tensorflow:Error reported to Coordinator: <class 'tensorflow.python.framework.errors_impl.CancelledError'>, Enqueue operation was cancelled\n\t [[Node: input/shuffle_batch/random_shuffle_queue_enqueue = QueueEnqueueV2[Tcomponents=[DT_UINT8, DT_INT32], timeout_ms=-1, _device=\"/job:localhost/replica:0/task:0/device:CPU:0\"](input/shuffle_batch/random_shuffle_queue, input/Cast/_15, input/Cast_1/_17)]]\n" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
4a0e2ae66dd05a4cc4531ee059892904a9987814
156,112
ipynb
Jupyter Notebook
intro-to-pytorch/Part 5 - Inference and Validation (Exercises).ipynb
ChadMcintire/Udacity_Deep_learning
217fd51a2df637967a8f271c76e880ae64182fd8
[ "MIT" ]
null
null
null
intro-to-pytorch/Part 5 - Inference and Validation (Exercises).ipynb
ChadMcintire/Udacity_Deep_learning
217fd51a2df637967a8f271c76e880ae64182fd8
[ "MIT" ]
null
null
null
intro-to-pytorch/Part 5 - Inference and Validation (Exercises).ipynb
ChadMcintire/Udacity_Deep_learning
217fd51a2df637967a8f271c76e880ae64182fd8
[ "MIT" ]
null
null
null
221.121813
51,640
0.889496
[ [ [ "# Inference and Validation\n\nNow that you have a trained network, you can use it for making predictions. This is typically called **inference**, a term borrowed from statistics. However, neural networks have a tendency to perform *too well* on the training data and aren't able to generalize to data that hasn't been seen before. This is called **overfitting** and it impairs inference performance. To test for overfitting while training, we measure the performance on data not in the training set called the **validation** set. We avoid overfitting through regularization such as dropout while monitoring the validation performance during training. In this notebook, I'll show you how to do this in PyTorch. \n\nAs usual, let's start by loading the dataset through torchvision. You'll learn more about torchvision and loading data in a later part. This time we'll be taking advantage of the test set which you can get by setting `train=False` here:\n\n```python\ntestset = datasets.FashionMNIST('~/.pytorch/F_MNIST_data/', download=True, train=False, transform=transform)\n```\n\nThe test set contains images just like the training set. Typically you'll see 10-20% of the original dataset held out for testing and validation with the rest being used for training.", "_____no_output_____" ] ], [ [ "import torch\nfrom torchvision import datasets, transforms\n\n# Define a transform to normalize the data\ntransform = transforms.Compose([transforms.ToTensor(),\n transforms.Normalize((0.5,), (0.5,))])\n# Download and load the training data\ntrainset = datasets.FashionMNIST('~/.pytorch/F_MNIST_data/', download=True, train=True, transform=transform)\ntrainloader = torch.utils.data.DataLoader(trainset, batch_size=64, shuffle=True)\n\n# Download and load the test data\ntestset = datasets.FashionMNIST('~/.pytorch/F_MNIST_data/', download=True, train=False, transform=transform)\ntestloader = torch.utils.data.DataLoader(testset, batch_size=64, shuffle=True)", "_____no_output_____" ] ], [ [ "Here I'll create a model like normal, using the same one from my solution for part 4.", "_____no_output_____" ] ], [ [ "from torch import nn, optim\nimport torch.nn.functional as F\n\nclass Classifier(nn.Module):\n def __init__(self):\n super().__init__()\n self.fc1 = nn.Linear(784, 256)\n self.fc2 = nn.Linear(256, 128)\n self.fc3 = nn.Linear(128, 64)\n self.fc4 = nn.Linear(64, 10)\n \n def forward(self, x):\n # make sure input tensor is flattened\n x = x.view(x.shape[0], -1)\n \n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n x = F.relu(self.fc3(x))\n x = F.log_softmax(self.fc4(x), dim=1)\n \n return x", "_____no_output_____" ] ], [ [ "The goal of validation is to measure the model's performance on data that isn't part of the training set. Performance here is up to the developer to define though. Typically this is just accuracy, the percentage of classes the network predicted correctly. Other options are [precision and recall](https://en.wikipedia.org/wiki/Precision_and_recall#Definition_(classification_context)) and top-5 error rate. We'll focus on accuracy here. First I'll do a forward pass with one batch from the test set.", "_____no_output_____" ] ], [ [ "model = Classifier()\n\nimages, labels = next(iter(testloader))\n# Get the class probabilities\nps = torch.exp(model(images))\n# Make sure the shape is appropriate, we should get 10 class probabilities for 64 examples\nprint(ps.shape)", "torch.Size([64, 10])\n" ] ], [ [ "With the probabilities, we can get the most likely class using the `ps.topk` method. This returns the $k$ highest values. Since we just want the most likely class, we can use `ps.topk(1)`. This returns a tuple of the top-$k$ values and the top-$k$ indices. If the highest value is the fifth element, we'll get back 4 as the index.", "_____no_output_____" ] ], [ [ "top_p, top_class = ps.topk(1, dim=1)\n# Look at the most likely classes for the first 10 examples\nprint(top_class[:10,:])", "tensor([[8],\n [8],\n [8],\n [8],\n [8],\n [8],\n [8],\n [8],\n [8],\n [8]])\n" ] ], [ [ "Now we can check if the predicted classes match the labels. This is simple to do by equating `top_class` and `labels`, but we have to be careful of the shapes. Here `top_class` is a 2D tensor with shape `(64, 1)` while `labels` is 1D with shape `(64)`. To get the equality to work out the way we want, `top_class` and `labels` must have the same shape.\n\nIf we do\n\n```python\nequals = top_class == labels\n```\n\n`equals` will have shape `(64, 64)`, try it yourself. What it's doing is comparing the one element in each row of `top_class` with each element in `labels` which returns 64 True/False boolean values for each row.", "_____no_output_____" ] ], [ [ "equals = top_class == labels.view(*top_class.shape)\nequals.shape", "_____no_output_____" ] ], [ [ "Now we need to calculate the percentage of correct predictions. `equals` has binary values, either 0 or 1. This means that if we just sum up all the values and divide by the number of values, we get the percentage of correct predictions. This is the same operation as taking the mean, so we can get the accuracy with a call to `torch.mean`. If only it was that simple. If you try `torch.mean(equals)`, you'll get an error\n\n```\nRuntimeError: mean is not implemented for type torch.ByteTensor\n```\n\nThis happens because `equals` has type `torch.ByteTensor` but `torch.mean` isn't implemented for tensors with that type. So we'll need to convert `equals` to a float tensor. Note that when we take `torch.mean` it returns a scalar tensor, to get the actual value as a float we'll need to do `accuracy.item()`.", "_____no_output_____" ] ], [ [ "accuracy = torch.mean(equals.type(torch.FloatTensor))\nprint(f'Accuracy: {accuracy.item()*100}%')", "Accuracy: 10.9375%\n" ] ], [ [ "The network is untrained so it's making random guesses and we should see an accuracy around 10%. Now let's train our network and include our validation pass so we can measure how well the network is performing on the test set. Since we're not updating our parameters in the validation pass, we can speed up our code by turning off gradients using `torch.no_grad()`:\n\n```python\n# turn off gradients\nwith torch.no_grad():\n # validation pass here\n for images, labels in testloader:\n ...\n```\n\n>**Exercise:** Implement the validation loop below and print out the total accuracy after the loop. You can largely copy and paste the code from above, but I suggest typing it in because writing it out yourself is essential for building the skill. In general you'll always learn more by typing it rather than copy-pasting. You should be able to get an accuracy above 80%.", "_____no_output_____" ] ], [ [ "model = Classifier()\ncriterion = nn.NLLLoss()\noptimizer = optim.Adam(model.parameters(), lr=0.003)\n\nepochs = 30\nsteps = 0\n\ntrain_losses, test_losses = [], []\nfor e in range(epochs):\n running_loss = 0\n for images, labels in trainloader:\n \n optimizer.zero_grad()\n \n log_ps = model(images)\n loss = criterion(log_ps, labels)\n loss.backward()\n optimizer.step()\n \n running_loss += loss.item()\n \n else:\n test_loss = 0\n accuracy = 0\n ## TODO: Implement the validation pass and print out the validation accuracy\n with torch.no_grad():\n # validation pass here\n for images, labels in testloader:\n #capture the loss\n log_ps = model(images)\n test_loss += criterion(log_ps, labels) \n \n ps = torch.exp(log_ps)\n top_p, top_class = ps.topk(1, dim=1)\n equals = top_class == labels.view(*top_class.shape)\n accuracy += torch.mean(equals.type(torch.FloatTensor))\n \n \n train_losses.append(running_loss/len(trainloader))\n test_losses.append(test_loss/len(testloader))\n\n \n print(\"Epoch: {}/{}.. \".format(e+1, epochs),\n \"Training Loss: {:.3f}.. \".format(running_loss/len(trainloader)),\n \"Test Loss: {:.3f}.. \".format(test_loss/len(testloader)),\n \"Test Accuracy: {:.3f}\".format(accuracy/len(testloader)))", "Epoch: 1/30.. Training Loss: 0.513.. Test Loss: 0.469.. Test Accuracy: 0.838\nEpoch: 2/30.. Training Loss: 0.394.. Test Loss: 0.391.. Test Accuracy: 0.857\nEpoch: 3/30.. Training Loss: 0.354.. Test Loss: 0.422.. Test Accuracy: 0.855\nEpoch: 4/30.. Training Loss: 0.329.. Test Loss: 0.382.. Test Accuracy: 0.868\nEpoch: 5/30.. Training Loss: 0.314.. Test Loss: 0.380.. Test Accuracy: 0.866\nEpoch: 6/30.. Training Loss: 0.299.. Test Loss: 0.373.. Test Accuracy: 0.867\nEpoch: 7/30.. Training Loss: 0.291.. Test Loss: 0.367.. Test Accuracy: 0.874\nEpoch: 8/30.. Training Loss: 0.281.. Test Loss: 0.380.. Test Accuracy: 0.865\nEpoch: 9/30.. Training Loss: 0.276.. Test Loss: 0.384.. Test Accuracy: 0.867\nEpoch: 10/30.. Training Loss: 0.263.. Test Loss: 0.388.. Test Accuracy: 0.864\nEpoch: 11/30.. Training Loss: 0.257.. Test Loss: 0.370.. Test Accuracy: 0.871\nEpoch: 12/30.. Training Loss: 0.252.. Test Loss: 0.370.. Test Accuracy: 0.877\nEpoch: 13/30.. Training Loss: 0.246.. Test Loss: 0.363.. Test Accuracy: 0.881\nEpoch: 14/30.. Training Loss: 0.240.. Test Loss: 0.387.. Test Accuracy: 0.877\nEpoch: 15/30.. Training Loss: 0.240.. Test Loss: 0.410.. Test Accuracy: 0.879\nEpoch: 16/30.. Training Loss: 0.235.. Test Loss: 0.384.. Test Accuracy: 0.877\nEpoch: 17/30.. Training Loss: 0.227.. Test Loss: 0.388.. Test Accuracy: 0.877\nEpoch: 18/30.. Training Loss: 0.222.. Test Loss: 0.393.. Test Accuracy: 0.881\nEpoch: 19/30.. Training Loss: 0.221.. Test Loss: 0.393.. Test Accuracy: 0.882\nEpoch: 20/30.. Training Loss: 0.215.. Test Loss: 0.393.. Test Accuracy: 0.882\nEpoch: 21/30.. Training Loss: 0.214.. Test Loss: 0.396.. Test Accuracy: 0.881\nEpoch: 22/30.. Training Loss: 0.210.. Test Loss: 0.421.. Test Accuracy: 0.882\nEpoch: 23/30.. Training Loss: 0.206.. Test Loss: 0.448.. Test Accuracy: 0.876\nEpoch: 24/30.. Training Loss: 0.207.. Test Loss: 0.456.. Test Accuracy: 0.877\nEpoch: 25/30.. Training Loss: 0.203.. Test Loss: 0.435.. Test Accuracy: 0.880\nEpoch: 26/30.. Training Loss: 0.198.. Test Loss: 0.394.. Test Accuracy: 0.883\nEpoch: 27/30.. Training Loss: 0.191.. Test Loss: 0.437.. Test Accuracy: 0.880\nEpoch: 28/30.. Training Loss: 0.194.. Test Loss: 0.423.. Test Accuracy: 0.882\nEpoch: 29/30.. Training Loss: 0.191.. Test Loss: 0.413.. Test Accuracy: 0.882\nEpoch: 30/30.. Training Loss: 0.183.. Test Loss: 0.441.. Test Accuracy: 0.884\n" ], [ "%matplotlib inline\n%config InlineBackend.figure_format = 'retina'\n\nimport matplotlib.pyplot as plt", "_____no_output_____" ], [ "#plot validation vs training loss\nplt.plot(train_losses, label='Training loss')\nplt.plot(test_losses, label='Validation loss')\nplt.legend(frameon=False)", "_____no_output_____" ] ], [ [ "## Overfitting\n\nIf we look at the training and validation losses as we train the network, we can see a phenomenon known as overfitting.\n\n<img src='assets/overfitting.png' width=450px>\n\nThe network learns the training set better and better, resulting in lower training losses. However, it starts having problems generalizing to data outside the training set leading to the validation loss increasing. The ultimate goal of any deep learning model is to make predictions on new data, so we should strive to get the lowest validation loss possible. One option is to use the version of the model with the lowest validation loss, here the one around 8-10 training epochs. This strategy is called *early-stopping*. In practice, you'd save the model frequently as you're training then later choose the model with the lowest validation loss.\n\nThe most common method to reduce overfitting (outside of early-stopping) is *dropout*, where we randomly drop input units. This forces the network to share information between weights, increasing it's ability to generalize to new data. Adding dropout in PyTorch is straightforward using the [`nn.Dropout`](https://pytorch.org/docs/stable/nn.html#torch.nn.Dropout) module.\n\n```python\nclass Classifier(nn.Module):\n def __init__(self):\n super().__init__()\n self.fc1 = nn.Linear(784, 256)\n self.fc2 = nn.Linear(256, 128)\n self.fc3 = nn.Linear(128, 64)\n self.fc4 = nn.Linear(64, 10)\n \n # Dropout module with 0.2 drop probability\n self.dropout = nn.Dropout(p=0.2)\n \n def forward(self, x):\n # make sure input tensor is flattened\n x = x.view(x.shape[0], -1)\n \n # Now with dropout\n x = self.dropout(F.relu(self.fc1(x)))\n x = self.dropout(F.relu(self.fc2(x)))\n x = self.dropout(F.relu(self.fc3(x)))\n \n # output so no dropout here\n x = F.log_softmax(self.fc4(x), dim=1)\n \n return x\n```\n\nDuring training we want to use dropout to prevent overfitting, but during inference we want to use the entire network. So, we need to turn off dropout during validation, testing, and whenever we're using the network to make predictions. To do this, you use `model.eval()`. This sets the model to evaluation mode where the dropout probability is 0. You can turn dropout back on by setting the model to train mode with `model.train()`. In general, the pattern for the validation loop will look like this, where you turn off gradients, set the model to evaluation mode, calculate the validation loss and metric, then set the model back to train mode.\n\n```python\n# turn off gradients\nwith torch.no_grad():\n \n # set model to evaluation mode\n model.eval()\n \n # validation pass here\n for images, labels in testloader:\n ...\n\n# set model back to train mode\nmodel.train()\n```", "_____no_output_____" ], [ "> **Exercise:** Add dropout to your model and train it on Fashion-MNIST again. See if you can get a lower validation loss or higher accuracy.", "_____no_output_____" ] ], [ [ "## TODO: Define your model with dropout added\nclass Classifier(nn.Module):\n def __init__(self):\n super().__init__()\n self.fc1 = nn.Linear(784, 256)\n self.fc2 = nn.Linear(256, 128)\n self.fc3 = nn.Linear(128, 64)\n self.fc4 = nn.Linear(64, 10)\n \n #Dropout module with 0.2 drop probability\n self.dropout = nn.Dropout(p=0.2)\n \n def forward(self, x):\n x = x.view(x.shape[0], -1)\n \n # Now with dropout\n x = self.dropout(F.relu(self.fc1(x)))\n x = self.dropout(F.relu(self.fc2(x)))\n x = self.dropout(F.relu(self.fc3(x)))\n \n #output so no dropout\n x = F.log_softmax(self.fc4(x), dim=1)\n \n return x", "_____no_output_____" ], [ "#training setup\nmodel = Classifier()\ncriterion = nn.NLLLoss()\noptimizer = optim.Adam(model.parameters(), lr=0.0003)\n\nepochs = 30\nsteps = 0\n\ntraining_losses, test_losses = [], []", "_____no_output_____" ], [ "## TODO: Train your model with dropout, and monitor the training progress with the validation loss and accuracy\nfor e in range(epochs):\n running_loss = 0\n for images, labels in trainloader:\n #reset the gradient so it doesn't accumulate\n optimizer.zero_grad()\n \n log_ps = model(images)\n loss = criterion(log_ps, labels)\n loss.backward()\n optimizer.step()\n \n running_loss += loss.item()\n else:\n test_loss = 0\n accuracy = 0\n \n # Turn off gradients, for validation, saves memory and computations\n with torch.no_grad():\n #turn off gradient computation for validation\n model.eval()\n for images, labels in testloader:\n log_ps = model(images)\n test_loss += criterion(log_ps, labels)\n \n ps = torch.exp(log_ps)\n top_p, top_class = ps.topk(1, dim=1)\n equals = top_class == labels.view(*top_class.shape)\n accuracy += torch.mean(equals.type(torch.FloatTensor))\n \n model.train()\n \n train_losses.append(running_loss/len(trainloader))\n test_losses.append(test_loss/len(testloader))\n\n print(\"Epoch: {}/{}.. \".format(e+1, epochs),\n \"Training Loss: {:.3f}.. \".format(train_losses[-1]),\n \"Test Loss: {:.3f}.. \".format(test_losses[-1]),\n \"Test Accuracy: {:.3f}\".format(accuracy/len(testloader)))\n \n ", "Epoch: 1/30.. Training Loss: 0.183.. Test Loss: 0.463.. Test Accuracy: 0.880\nEpoch: 2/30.. Training Loss: 0.183.. Test Loss: 0.475.. Test Accuracy: 0.888\nEpoch: 3/30.. Training Loss: 0.178.. Test Loss: 0.439.. Test Accuracy: 0.889\nEpoch: 4/30.. Training Loss: 0.178.. Test Loss: 0.449.. Test Accuracy: 0.886\nEpoch: 5/30.. Training Loss: 0.176.. Test Loss: 0.519.. Test Accuracy: 0.872\nEpoch: 6/30.. Training Loss: 0.177.. Test Loss: 0.430.. Test Accuracy: 0.880\nEpoch: 7/30.. Training Loss: 0.167.. Test Loss: 0.487.. Test Accuracy: 0.882\nEpoch: 8/30.. Training Loss: 0.167.. Test Loss: 0.478.. Test Accuracy: 0.889\nEpoch: 9/30.. Training Loss: 0.163.. Test Loss: 0.495.. Test Accuracy: 0.880\nEpoch: 10/30.. Training Loss: 0.165.. Test Loss: 0.471.. Test Accuracy: 0.887\nEpoch: 11/30.. Training Loss: 0.159.. Test Loss: 0.480.. Test Accuracy: 0.885\nEpoch: 12/30.. Training Loss: 0.157.. Test Loss: 0.478.. Test Accuracy: 0.886\nEpoch: 13/30.. Training Loss: 0.162.. Test Loss: 0.525.. Test Accuracy: 0.887\nEpoch: 14/30.. Training Loss: 0.165.. Test Loss: 0.535.. Test Accuracy: 0.886\nEpoch: 15/30.. Training Loss: 0.156.. Test Loss: 0.521.. Test Accuracy: 0.882\nEpoch: 16/30.. Training Loss: 0.158.. Test Loss: 0.510.. Test Accuracy: 0.882\nEpoch: 17/30.. Training Loss: 0.148.. Test Loss: 0.521.. Test Accuracy: 0.886\nEpoch: 18/30.. Training Loss: 0.157.. Test Loss: 0.493.. Test Accuracy: 0.888\nEpoch: 19/30.. Training Loss: 0.149.. Test Loss: 0.554.. Test Accuracy: 0.881\nEpoch: 20/30.. Training Loss: 0.150.. Test Loss: 0.518.. Test Accuracy: 0.884\nEpoch: 21/30.. Training Loss: 0.141.. Test Loss: 0.525.. Test Accuracy: 0.881\nEpoch: 22/30.. Training Loss: 0.147.. Test Loss: 0.551.. Test Accuracy: 0.886\nEpoch: 23/30.. Training Loss: 0.158.. Test Loss: 0.594.. Test Accuracy: 0.880\nEpoch: 24/30.. Training Loss: 0.145.. Test Loss: 0.532.. Test Accuracy: 0.890\nEpoch: 25/30.. Training Loss: 0.145.. Test Loss: 0.571.. Test Accuracy: 0.880\nEpoch: 26/30.. Training Loss: 0.138.. Test Loss: 0.603.. Test Accuracy: 0.885\nEpoch: 27/30.. Training Loss: 0.142.. Test Loss: 0.579.. Test Accuracy: 0.882\nEpoch: 28/30.. Training Loss: 0.131.. Test Loss: 0.611.. Test Accuracy: 0.882\nEpoch: 29/30.. Training Loss: 0.144.. Test Loss: 0.585.. Test Accuracy: 0.885\nEpoch: 30/30.. Training Loss: 0.131.. Test Loss: 0.618.. Test Accuracy: 0.882\n" ], [ "%matplotlib inline\n%config InlineBackend.figure_format = 'retina'\n\nimport matplotlib.pyplot as plt", "_____no_output_____" ], [ "plt.plot(train_losses, label='Training loss')\nplt.plot(test_losses, label='Validation loss')\nplt.legend(frameon=False)", "_____no_output_____" ] ], [ [ "## Inference\n\nNow that the model is trained, we can use it for inference. We've done this before, but now we need to remember to set the model in inference mode with `model.eval()`. You'll also want to turn off autograd with the `torch.no_grad()` context.", "_____no_output_____" ] ], [ [ "# Import helper module (should be in the repo)\nimport helper\n\n# Test out your network!\n\nmodel.eval()\n\ndataiter = iter(testloader)\nimages, labels = dataiter.next()\nimg = images[0]\n# Convert 2D image to 1D vector\nimg = img.view(1, 784)\n\n# Calculate the class probabilities (softmax) for img\nwith torch.no_grad():\n output = model.forward(img)\n\nps = torch.exp(output)\n\n# Plot the image and probabilities\nhelper.view_classify(img.view(1, 28, 28), ps, version='Fashion')", "_____no_output_____" ] ], [ [ "## Next Up!\n\nIn the next part, I'll show you how to save your trained models. In general, you won't want to train a model everytime you need it. Instead, you'll train once, save it, then load the model when you want to train more or use if for inference.", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
4a0e3108919caa1ff0f6345d33238b7c82b6b09a
1,856
ipynb
Jupyter Notebook
01/day-1.ipynb
jdhalimi/aoc-2018
aeea38420dccb8bdef314daf84e7ac259fa757a6
[ "Unlicense" ]
null
null
null
01/day-1.ipynb
jdhalimi/aoc-2018
aeea38420dccb8bdef314daf84e7ac259fa757a6
[ "Unlicense" ]
null
null
null
01/day-1.ipynb
jdhalimi/aoc-2018
aeea38420dccb8bdef314daf84e7ac259fa757a6
[ "Unlicense" ]
null
null
null
16.720721
39
0.420797
[ [ [ "# Avent Of Code 2018 - DAY 1", "_____no_output_____" ], [ "Jean-David HALIMI, 2018", "_____no_output_____" ], [ "## part 1", "_____no_output_____" ] ], [ [ "l = []\nwith open('input-1.txt') as f:\n for x in f:\n l.append(int(x))\n\nprint (sum(l))\n ", "538\n" ] ], [ [ "## part 2", "_____no_output_____" ] ], [ [ "def search_seen(l):\n s = 0\n seen = {s}\n while True:\n for x in l:\n s += x\n if s in seen:\n return s\n seen.add(s)\n\nprint(search_seen(l))", "77271\n" ] ] ]
[ "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ] ]
4a0e319ba23624b01c77e3dde153046015922bdd
5,094
ipynb
Jupyter Notebook
notebook/_fit.ipynb
alex-wenzel/ccal
74dfc604d93e6ce9e12f34a828b601618df51faa
[ "MIT" ]
null
null
null
notebook/_fit.ipynb
alex-wenzel/ccal
74dfc604d93e6ce9e12f34a828b601618df51faa
[ "MIT" ]
null
null
null
notebook/_fit.ipynb
alex-wenzel/ccal
74dfc604d93e6ce9e12f34a828b601618df51faa
[ "MIT" ]
null
null
null
24.608696
92
0.401649
[ [ [ "import plotly", "_____no_output_____" ], [ "plotly.offline.init_notebook_mode(connected=True)", "_____no_output_____" ], [ "from scipy.optimize import minimize", "_____no_output_____" ], [ "def objective_function_test(parameters):\n\n a, b = parameters\n\n return float(a + b)\n\n\nminimize(objective_function_test, (8, 8), bounds=((0, None), (0, None)))", "_____no_output_____" ], [ "import numpy as np", "_____no_output_____" ], [ "import ccal", "_____no_output_____" ], [ "np.random.seed(seed=ccal.RANDOM_SEED)", "_____no_output_____" ], [ "from statsmodels.sandbox.distributions.extras import ACSkewT_gen", "_____no_output_____" ], [ "def objective_function(parameters, y_pdf, model, x):\n\n degree_of_freedom, shape, location, scale = parameters\n\n return (\n (y_pdf - model.pdf(x, degree_of_freedom, shape, loc=location, scale=scale))\n ** 2\n ** 0.5\n ).sum()", "_____no_output_____" ], [ "location = 0\n\nscale = 1\n\ny = np.random.normal(loc=location, scale=scale, size=128)\n\nover = (y.max() - y.min()) * 0\n\nx = np.linspace(y.min() - over, y.max() + over, num=y.size)\n\nmodel = ACSkewT_gen()\n\nfit_result = model.fit(y, loc=location, scale=scale)\n\ny_fit_pdf = model.pdf(\n x, fit_result[0], fit_result[1], loc=fit_result[2], scale=fit_result[3]\n)\n\nfor method in (\n \"Nelder-Mead\",\n \"Powell\",\n \"CG\",\n # \"BFGS\",\n # \"Newton-CG\",\n # \"L-BFGS-B\",\n # \"TNC\",\n # \"COBYLA\",\n # \"SLSQP\",\n # \"trust-constr\",\n # \"dogleg\",\n # \"trust-ncg\",\n # \"trust-exact\",\n # \"trust-krylov\",\n):\n\n print(method)\n\n minimize_result = minimize(\n objective_function,\n (1, 0, location, scale),\n args=(y, model, x),\n method=method,\n bounds=((0, None), (0, 24), (-8, 8), (0, None)),\n )\n\n ccal.plot_and_save(\n {\n \"layout\": {},\n \"data\": [\n {\n \"type\": \"histogram\",\n \"name\": \"Y Distribution\",\n \"histnorm\": \"probability density\",\n \"x\": y,\n },\n {\n \"type\": \"scatter\",\n \"name\": \"Y PDF (parameters from fit)\",\n \"x\": x,\n \"y\": y_fit_pdf,\n },\n {\n \"type\": \"scatter\",\n \"name\": \"Y PDF (parameters from minimize)\",\n \"x\": x,\n \"y\": model.pdf(\n x,\n np.e ** minimize_result.x[0],\n minimize_result.x[1],\n loc=minimize_result.x[2],\n scale=minimize_result.x[3],\n ),\n },\n ],\n },\n None,\n )", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
4a0e344196ba3ca424be88ece5d01c55902e9232
65,406
ipynb
Jupyter Notebook
Sentiment_Analysis_TA_session_Dec_11.ipynb
bakkiaraj/AIML_CEP_2021
1483885152c9e196726668adb1a363814c05ec1d
[ "CC0-1.0" ]
null
null
null
Sentiment_Analysis_TA_session_Dec_11.ipynb
bakkiaraj/AIML_CEP_2021
1483885152c9e196726668adb1a363814c05ec1d
[ "CC0-1.0" ]
null
null
null
Sentiment_Analysis_TA_session_Dec_11.ipynb
bakkiaraj/AIML_CEP_2021
1483885152c9e196726668adb1a363814c05ec1d
[ "CC0-1.0" ]
null
null
null
49.852134
7,474
0.600404
[ [ [ "<a href=\"https://colab.research.google.com/github/bakkiaraj/AIML_CEP_2021/blob/main/Sentiment_Analysis_TA_session_Dec_11.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>", "_____no_output_____" ], [ "We will work with the IMDB dataset, which contains movie reviews from IMDB. Each review is labeled as 1 (for positive) or 0 (for negative) from the rating provided by users together with their reviews.\\\nThis dataset is available [here](https://www.kaggle.com/columbine/imdb-dataset-sentiment-analysis-in-csv-format/download).\n", "_____no_output_____" ], [ "Code referred from [here](https://www.kaggle.com/arunmohan003/sentiment-analysis-using-lstm-pytorch/notebook)", "_____no_output_____" ], [ "#Importing Libraries and Data", "_____no_output_____" ] ], [ [ "import numpy as np \nimport pandas as pd \nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim.lr_scheduler as lr_scheduler\nfrom torch.utils.data import TensorDataset, DataLoader\n\nimport nltk\nnltk.download('stopwords')\nfrom nltk.corpus import stopwords \n\nfrom collections import Counter\nimport string\nimport re\nimport seaborn as sns\nfrom tqdm import tqdm\nimport matplotlib.pyplot as plt", "[nltk_data] Downloading package stopwords to /root/nltk_data...\n[nltk_data] Package stopwords is already up-to-date!\n" ], [ "SEED = 1234\nnp.random.seed(SEED)\ntorch.manual_seed(SEED)\ntorch.cuda.manual_seed(SEED)", "_____no_output_____" ], [ "## upload data files to this colab notebook and read them using the respective paths\n\ndf_train = pd.read_csv('/content/Train.csv')\ndf_val = pd.read_csv('/content/Valid.csv')\ndf_test = pd.read_csv('/content/Test.csv')\ndf_train.head()", "_____no_output_____" ], [ "x_train, y_train = df_train['text'].values, df_train['label'].values\nx_val, y_val = df_val['text'].values, df_val['label'].values\nx_test, y_test = df_test['text'].values, df_test['label'].values\nprint(f'shape of train data is {x_train.shape}')\nprint(f'shape of val data is {x_val.shape}')\nprint(f'shape of test data is {x_test.shape}')", "shape of train data is (40000,)\nshape of val data is (5000,)\nshape of test data is (5000,)\n" ], [ "#plot of positive and negative class count in training set\ndd = pd.Series(y_train).value_counts()\nsns.barplot(x=np.array(['negative','positive']),y=dd.values)\nplt.show()", "_____no_output_____" ] ], [ [ "#Pre-Processing Data", "_____no_output_____" ] ], [ [ "def preprocess_string(s):\n \"\"\" preprocessing string to remove special characters, white spaces and digits \"\"\"\n s = re.sub(r\"[^\\w\\s]\", '', s) # Remove all non-word characters (everything except numbers and letters)\n s = re.sub(r\"\\s+\", '', s) # Replace all runs of whitespaces with no space\n s = re.sub(r\"\\d\", '', s) # replace digits with no space\n return s\n\ndef create_corpus(x_train):\n \"\"\" creates dictionary of 1000 most frequent words in the training set and assigns token number to the words, returns dictionay (named corpus)\"\"\"\n word_list = []\n stop_words = set(stopwords.words('english')) \n for sent in x_train:\n for word in sent.lower().split():\n word = preprocess_string(word)\n if word not in stop_words and word != '':\n word_list.append(word)\n\n word_count = Counter(word_list)\n # sorting on the basis of most common words\n top_words = sorted(word_count, key=word_count.get, reverse=True)[:1000]\n # creating a dict\n corpus = {w:i+1 for i,w in enumerate(top_words)}\n return corpus\n\ndef preprocess(x, y, corpus):\n \"\"\" encodes reviews according to created corpus dictionary\"\"\"\n x_new = []\n for sent in x:\n x_new.append([corpus[preprocess_string(word)] for word in sent.lower().split() if preprocess_string(word) in corpus.keys()])\n\n return np.array(x_new), np.array(y)", "_____no_output_____" ], [ "corpus = create_corpus(x_train)\nprint(f'Length of vocabulary is {len(corpus)}')\nx_train, y_train = preprocess(x_train, y_train, corpus)\nx_val, y_val = preprocess(x_val, y_val, corpus)\nx_test, y_test = preprocess(x_test, y_test, corpus)", "Length of vocabulary is 1000\n" ], [ "#analysis of word count in reviews \nrev_len = [len(i) for i in x_train]\npd.Series(rev_len).hist()\nplt.show()\npd.Series(rev_len).describe()", "_____no_output_____" ] ], [ [ "From the above data, it can be seen that maximum length of review is 653 and 75% of the reviews have length less than 85. Furthermore length of reviews greater than 300 is not significant (from the graph) so will take maximum length of reviews to be 300.", "_____no_output_____" ] ], [ [ "def padding_(sentences, seq_len):\n \"\"\" to tackle variable length of sequences: this function prepads reviews with 0 for reviews whose length is less than seq_len, and truncates reviews with length greater than\n seq_len by removing words after seq_len in review\"\"\"\n\n features = np.zeros((len(sentences), seq_len),dtype=int)\n for ii, review in enumerate(sentences):\n diff = seq_len - len(review)\n\n if diff > 0:\n features[ii,diff:] = np.array(review)\n\n else:\n features[ii] = np.array(review[:seq_len])\n\n return features", "_____no_output_____" ], [ "# maximum review length (300)\nx_train_pad = padding_(x_train,300)\nx_val_pad = padding_(x_val,300)\nx_test_pad = padding_(x_test, 300)", "_____no_output_____" ], [ "is_cuda = torch.cuda.is_available()\n\n# use GPU if available\nif is_cuda:\n device = torch.device(\"cuda\")\n print(\"GPU is available\")\nelse:\n device = torch.device(\"cpu\")\n print(\"GPU not available, CPU used\")", "GPU is available\n" ], [ "# create Tensor datasets\ntrain_data = TensorDataset(torch.from_numpy(x_train_pad), torch.from_numpy(y_train))\nvalid_data = TensorDataset(torch.from_numpy(x_test_pad), torch.from_numpy(y_test))\n\nbatch_size = 50\n\n# dataloaders\ntrain_loader = DataLoader(train_data, shuffle=True, batch_size=batch_size)\nvalid_loader = DataLoader(valid_data, shuffle=True, batch_size=batch_size)", "_____no_output_____" ], [ "# one batch of training data\ndataiter = iter(train_loader)\nsample_x, sample_y = dataiter.next()\n\nprint('Sample input size: ', sample_x.size()) \nprint('Sample input: \\n', sample_x)\nprint('Sample output: \\n', sample_y)", "Sample input size: torch.Size([50, 300])\nSample input: \n tensor([[ 0, 0, 0, ..., 572, 1, 1],\n [ 0, 0, 0, ..., 38, 457, 87],\n [ 0, 0, 0, ..., 168, 841, 253],\n ...,\n [ 0, 0, 0, ..., 171, 5, 225],\n [ 0, 0, 0, ..., 9, 446, 2],\n [ 0, 0, 0, ..., 917, 179, 95]])\nSample output: \n tensor([1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0,\n 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0,\n 0, 1])\n" ] ], [ [ "<img src=\"https://lh3.googleusercontent.com/proxy/JeOqyqJyqifJLvX8Wet6hHNIOZ_wui2xfIkYJsK6fuE13cNJlZxxqe6vZcEe__kIagkOFolHZtyZ150yayUHpBkekTAwdMUg1MNrmVFbd1eumvusUs1zLALKLB5AA3fK\" alt=\"RNN LSTM GRU\" width=\"700\" height=\"250\">\n\nImage Credit- [Article](http://dprogrammer.org/rnn-lstm-gru)", "_____no_output_____" ], [ "#RNN", "_____no_output_____" ] ], [ [ "class RNN(nn.Module):\n def __init__(self,no_layers,vocab_size,hidden_dim,embedding_dim,output_dim):\n super(RNN,self).__init__()\n\n self.output_dim = output_dim\n self.hidden_dim = hidden_dim\n\n self.no_layers = no_layers\n self.vocab_size = vocab_size\n\n self.embedding = nn.Embedding(vocab_size, embedding_dim)\n\n self.rnn = nn.RNN(input_size=embedding_dim,hidden_size=self.hidden_dim,\n num_layers=no_layers, batch_first=True)\n \n self.dropout = nn.Dropout(0.3)\n self.fc = nn.Linear(self.hidden_dim, output_dim)\n self.sig = nn.Sigmoid()\n \n def forward(self,x,hidden):\n batch_size = x.size(0)\n embeds = self.embedding(x) \n rnn_out, hidden = self.rnn(embeds, hidden)\n rnn_out = rnn_out.contiguous().view(-1, self.hidden_dim)\n out = self.dropout(rnn_out)\n out = self.fc(out)\n sig_out = self.sig(out)\n sig_out = sig_out.view(batch_size, -1)\n sig_out = sig_out[:, -1] \n return sig_out, hidden\n \n def init_hidden(self, batch_size):\n ''' Initializes hidden state '''\n h0 = torch.zeros((self.no_layers,batch_size,self.hidden_dim)).to(device)\n return h0", "_____no_output_____" ], [ "no_layers = 2\nvocab_size = len(corpus) + 1 #extra 1 for padding\nembedding_dim = 64\noutput_dim = 1\nhidden_dim = 256", "_____no_output_____" ], [ "model = RNN(no_layers,vocab_size,hidden_dim,embedding_dim,output_dim)\nmodel.to(device)\nprint(model)", "RNN(\n (embedding): Embedding(1001, 64)\n (rnn): RNN(64, 256, num_layers=2, batch_first=True)\n (dropout): Dropout(p=0.3, inplace=False)\n (fc): Linear(in_features=256, out_features=1, bias=True)\n (sig): Sigmoid()\n)\n" ], [ "lr=0.001 #learning rate\ncriterion = nn.BCELoss() #Binary Cross Entropy loss\noptimizer = torch.optim.Adam(model.parameters(), lr=lr) \n\ndef acc(pred,label):\n \"\"\" function to calculate accuracy \"\"\"\n pred = torch.round(pred.squeeze())\n return torch.sum(pred == label.squeeze()).item()", "_____no_output_____" ], [ "patience_early_stopping = 3 #training will stop if model performance does not improve for these many consecutive epochs\ncnt = 0 #counter for checking patience level\nprev_epoch_acc = 0.0 #initializing prev test accuracy for early stopping condition\nscheduler = lr_scheduler.ReduceLROnPlateau(optimizer, mode = 'max', factor = 0.2, patience = 1) \n\nepochs = 10\n\nfor epoch in range(epochs):\n train_acc = 0.0\n model.train()\n \n for inputs, labels in train_loader: #training in batches\n \n inputs, labels = inputs.to(device), labels.to(device) \n h = model.init_hidden(batch_size) \n model.zero_grad()\n output,h = model(inputs,h)\n \n loss = criterion(output.squeeze(), labels.float())\n loss.backward()\n \n accuracy = acc(output,labels)\n train_acc += accuracy\n \n optimizer.step()\n \n \n val_acc = 0.0\n model.eval()\n \n for inputs, labels in valid_loader:\n inputs, labels = inputs.to(device), labels.to(device)\n val_h = model.init_hidden(batch_size)\n output, val_h = model(inputs, val_h)\n accuracy = acc(output,labels)\n val_acc += accuracy\n \n epoch_train_acc = train_acc/len(train_loader.dataset)\n epoch_val_acc = val_acc/len(valid_loader.dataset)\n scheduler.step(epoch_val_acc)\n\n if epoch_val_acc > prev_epoch_acc: #check if val accuracy for current epoch has improved compared to previous epoch\n cnt = 0 #f accuracy improves reset counter to 0\n else: #otherwise increment current counter\n cnt += 1\n prev_epoch_acc = epoch_val_acc\n\n print(f'Epoch {epoch+1}') \n print(f'train_accuracy : {epoch_train_acc*100} val_accuracy : {epoch_val_acc*100}')\n\n if cnt == patience_early_stopping:\n print(f\"early stopping as test accuracy did not improve for {patience_early_stopping} consecutive epochs\")\n break", "Epoch 1\ntrain_accuracy : 52.980000000000004 val_accuracy : 50.160000000000004\nEpoch 2\ntrain_accuracy : 53.63250000000001 val_accuracy : 50.18\nEpoch 3\ntrain_accuracy : 62.480000000000004 val_accuracy : 75.12\nEpoch 4\ntrain_accuracy : 70.565 val_accuracy : 75.14\nEpoch 5\ntrain_accuracy : 71.33500000000001 val_accuracy : 65.52\nEpoch 6\ntrain_accuracy : 73.4475 val_accuracy : 69.26\nEpoch 7\ntrain_accuracy : 76.96 val_accuracy : 78.58000000000001\nEpoch 8\ntrain_accuracy : 74.6225 val_accuracy : 78.16\nEpoch 9\ntrain_accuracy : 76.14999999999999 val_accuracy : 66.22\nEpoch 10\ntrain_accuracy : 67.0575 val_accuracy : 70.94\n" ], [ "def predict_text(text):\n word_seq = np.array([corpus[preprocess_string(word)] for word in text.split() \n if preprocess_string(word) in corpus.keys()])\n word_seq = np.expand_dims(word_seq,axis=0)\n pad = torch.from_numpy(padding_(word_seq,300))\n input = pad.to(device)\n batch_size = 1\n h = model.init_hidden(batch_size)\n #h = tuple([each.data for each in h])\n output, h = model(input, h)\n return(output.item())", "_____no_output_____" ], [ "index = 30\nprint(df_test['text'][index])\nprint('='*70)\nprint(f'Actual sentiment is : {df_test[\"label\"][index]}')\nprint('='*70)\nprob = predict_text(df_test['text'][index])\nstatus = \"positive\" if prob > 0.5 else \"negative\"\nprob = (1 - prob) if status == \"negative\" else prob\nprint(f'Predicted sentiment is {status} with a probability of {prob}')", "This movie is good for entertainment purposes, but it is not historically reliable. If you are looking for a movie and thinking to yourself `Oh I want to learn more about Custer's life and his last stand', do not rent `They Died with Their Boots On'. But, if you would like to watch a movie for the enjoyment of an older western film, with a little bit of romance and just for a good story, this is a fun movie to watch.<br /><br />The story starts out with Custer's (Errol Flynn) first day at West Point. Everyone loves his charming personality which allows him to get away with most everything. The movie follows his career from West Point and his many battles, including his battle in the Civil War. The movie ends with his last stand at Little Big Horn. In between the battle scenes, he finds love and marriage with Libby (Olivia De Havilland).<br /><br />Errol Flynn portrays the arrogant, but suave George Armstrong Custer well. Olivia De Havilland plays the cute, sweet Libby very well, especially in the flirting scene that Custer and Libby first meet. Their chemistry on screen made you believe in their romance. The acting in general was impressive, especially the comedic role ( although stereotypical) of Callie played by Hattie McDaniel. Her character will definitely make you laugh.<br /><br />The heroic war music brought out the excitement of the battle scenes. The beautiful costumes set the tone of the era. The script, at times, was corny, although the movie was still enjoyable to watch. The director's portrayal of Custer was as a hero and history shows this is debatable. Some will watch this movie and see Custer as a hero. Others will watch this movie and learn hate him.<br /><br />I give it a thumbs up for this 1942 western film.\n======================================================================\nActual sentiment is : 1\n======================================================================\nPredicted sentiment is negative with a probability of 0.5339558720588684\n" ] ], [ [ "#GRU", "_____no_output_____" ] ], [ [ "class GRU(nn.Module):\n def __init__(self,no_layers,vocab_size,hidden_dim,embedding_dim):\n super(GRU,self).__init__()\n\n self.output_dim = output_dim\n self.hidden_dim = hidden_dim\n self.no_layers = no_layers\n self.vocab_size = vocab_size\n self.embedding = nn.Embedding(vocab_size, embedding_dim)\n self.gru = nn.GRU(input_size=embedding_dim,hidden_size=self.hidden_dim,\n num_layers=no_layers, batch_first=True)\n self.dropout = nn.Dropout(0.3)\n self.fc = nn.Linear(self.hidden_dim, output_dim)\n self.sig = nn.Sigmoid()\n \n def forward(self,x,hidden):\n batch_size = x.size(0)\n embeds = self.embedding(x) \n gru_out, hidden = self.gru(embeds, hidden)\n gru_out = gru_out.contiguous().view(-1, self.hidden_dim) \n\n out = self.dropout(gru_out)\n out = self.fc(out)\n sig_out = self.sig(out)\n sig_out = sig_out.view(batch_size, -1)\n sig_out = sig_out[:, -1] \n return sig_out, hidden\n \n \n \n def init_hidden(self, batch_size):\n ''' Initializes hidden state '''\n h0 = torch.zeros((self.no_layers,batch_size,self.hidden_dim)).to(device)\n return h0", "_____no_output_____" ], [ "no_layers = 2\nvocab_size = len(corpus) + 1 #extra 1 for padding\nembedding_dim = 64\noutput_dim = 1\nhidden_dim = 256\nmodel = GRU(no_layers,vocab_size,hidden_dim,embedding_dim)\n\n#moving to gpu\nmodel.to(device)\n\nprint(model)", "GRU(\n (embedding): Embedding(1001, 64)\n (gru): GRU(64, 256, num_layers=2, batch_first=True)\n (dropout): Dropout(p=0.3, inplace=False)\n (fc): Linear(in_features=256, out_features=1, bias=True)\n (sig): Sigmoid()\n)\n" ], [ "# loss and optimization functions\nlr=0.001\n\ncriterion = nn.BCELoss()\n\noptimizer = torch.optim.Adam(model.parameters(), lr=lr)\n\n# function to calculate accuracy\ndef acc(pred,label):\n pred = torch.round(pred.squeeze())\n return torch.sum(pred == label.squeeze()).item()", "_____no_output_____" ], [ "patience_early_stopping = 3 #training will stop if model performance does not improve for these many consecutive epochs\ncnt = 0 #counter for checking patience level\nprev_epoch_acc = 0.0 #initializing prev test accuracy for early stopping condition\nscheduler = lr_scheduler.ReduceLROnPlateau(optimizer, mode = 'max', factor = 0.2, patience = 1) \n\nepochs = 10\n\nfor epoch in range(epochs):\n train_acc = 0.0\n model.train()\n \n for inputs, labels in train_loader:\n \n inputs, labels = inputs.to(device), labels.to(device) \n h = model.init_hidden(batch_size)\n model.zero_grad()\n output,h = model(inputs,h)\n \n loss = criterion(output.squeeze(), labels.float())\n loss.backward()\n \n accuracy = acc(output,labels)\n train_acc += accuracy\n \n optimizer.step()\n \n \n val_acc = 0.0\n model.eval()\n \n for inputs, labels in valid_loader:\n inputs, labels = inputs.to(device), labels.to(device)\n val_h = model.init_hidden(batch_size)\n output, val_h = model(inputs, val_h)\n accuracy = acc(output,labels)\n val_acc += accuracy\n \n epoch_train_acc = train_acc/len(train_loader.dataset)\n epoch_val_acc = val_acc/len(valid_loader.dataset)\n scheduler.step(epoch_val_acc)\n\n if epoch_val_acc > prev_epoch_acc: #check if val accuracy for current epoch has improved compared to previous epoch\n cnt = 0 #f accuracy improves reset counter to 0\n else: #otherwise increment current counter\n cnt += 1\n prev_epoch_acc = epoch_val_acc\n\n print(f'Epoch {epoch+1}') \n print(f'train_accuracy : {epoch_train_acc*100} val_accuracy : {epoch_val_acc*100}')\n\n if cnt == patience_early_stopping:\n print(f\"early stopping as test accuracy did not improve for {patience_early_stopping} consecutive epochs\")\n break\n", "Epoch 1\ntrain_accuracy : 77.125 val_accuracy : 83.08\nEpoch 2\ntrain_accuracy : 85.845 val_accuracy : 85.32\nEpoch 3\ntrain_accuracy : 87.9075 val_accuracy : 85.66\nEpoch 4\ntrain_accuracy : 89.92750000000001 val_accuracy : 85.64\nEpoch 5\ntrain_accuracy : 93.13 val_accuracy : 84.89999999999999\nEpoch 6\ntrain_accuracy : 98.02499999999999 val_accuracy : 84.78\nearly stopping as test accuracy did not improve for 3 consecutive epochs\n" ], [ "index = 30\nprint(df_test['text'][index])\nprint('='*70)\nprint(f'Actual sentiment is : {df_test[\"label\"][index]}')\nprint('='*70)\nprob = predict_text(df_test['text'][index])\nstatus = \"positive\" if prob > 0.5 else \"negative\"\nprob = (1 - prob) if status == \"negative\" else prob\nprint(f'Predicted sentiment is {status} with a probability of {prob}')", "This movie is good for entertainment purposes, but it is not historically reliable. If you are looking for a movie and thinking to yourself `Oh I want to learn more about Custer's life and his last stand', do not rent `They Died with Their Boots On'. But, if you would like to watch a movie for the enjoyment of an older western film, with a little bit of romance and just for a good story, this is a fun movie to watch.<br /><br />The story starts out with Custer's (Errol Flynn) first day at West Point. Everyone loves his charming personality which allows him to get away with most everything. The movie follows his career from West Point and his many battles, including his battle in the Civil War. The movie ends with his last stand at Little Big Horn. In between the battle scenes, he finds love and marriage with Libby (Olivia De Havilland).<br /><br />Errol Flynn portrays the arrogant, but suave George Armstrong Custer well. Olivia De Havilland plays the cute, sweet Libby very well, especially in the flirting scene that Custer and Libby first meet. Their chemistry on screen made you believe in their romance. The acting in general was impressive, especially the comedic role ( although stereotypical) of Callie played by Hattie McDaniel. Her character will definitely make you laugh.<br /><br />The heroic war music brought out the excitement of the battle scenes. The beautiful costumes set the tone of the era. The script, at times, was corny, although the movie was still enjoyable to watch. The director's portrayal of Custer was as a hero and history shows this is debatable. Some will watch this movie and see Custer as a hero. Others will watch this movie and learn hate him.<br /><br />I give it a thumbs up for this 1942 western film.\n======================================================================\nActual sentiment is : 1\n======================================================================\nPredicted sentiment is positive with a probability of 0.9998726844787598\n" ] ], [ [ "#LSTM", "_____no_output_____" ] ], [ [ "class LSTM(nn.Module):\n def __init__(self,no_layers,vocab_size,hidden_dim,embedding_dim):\n super(LSTM,self).__init__()\n\n self.output_dim = output_dim\n self.hidden_dim = hidden_dim\n\n self.no_layers = no_layers\n self.vocab_size = vocab_size\n \n self.embedding = nn.Embedding(vocab_size, embedding_dim) #embedding layer\n \n self.lstm = nn.LSTM(input_size=embedding_dim,hidden_size=self.hidden_dim,\n num_layers=no_layers, batch_first=True) #lstm layer\n \n self.dropout = nn.Dropout(0.3) # dropout layer\n self.fc = nn.Linear(self.hidden_dim, output_dim) #fully connected layer\n self.sig = nn.Sigmoid() #sigmoid activation \n \n def forward(self,x,hidden):\n batch_size = x.size(0)\n embeds = self.embedding(x) \n lstm_out, hidden = self.lstm(embeds, hidden) \n lstm_out = lstm_out.contiguous().view(-1, self.hidden_dim) \n out = self.dropout(lstm_out)\n out = self.fc(out)\n sig_out = self.sig(out)\n sig_out = sig_out.view(batch_size, -1)\n sig_out = sig_out[:, -1] \n return sig_out, hidden\n \n \n \n def init_hidden(self, batch_size):\n ''' Initializes hidden state and cell state for LSTM '''\n h0 = torch.zeros((self.no_layers,batch_size,self.hidden_dim)).to(device)\n c0 = torch.zeros((self.no_layers,batch_size,self.hidden_dim)).to(device)\n hidden = (h0,c0)\n return hidden", "_____no_output_____" ], [ "no_layers = 2\nvocab_size = len(corpus) + 1 #extra 1 for padding\nembedding_dim = 64\noutput_dim = 1\nhidden_dim = 256", "_____no_output_____" ], [ "model = LSTM(no_layers,vocab_size,hidden_dim,embedding_dim)\nmodel.to(device)\nprint(model)", "LSTM(\n (embedding): Embedding(1001, 64)\n (lstm): LSTM(64, 256, num_layers=2, batch_first=True)\n (dropout): Dropout(p=0.3, inplace=False)\n (fc): Linear(in_features=256, out_features=1, bias=True)\n (sig): Sigmoid()\n)\n" ], [ "# loss and optimization functions\nlr=0.001\n\ncriterion = nn.BCELoss()\n\noptimizer = torch.optim.Adam(model.parameters(), lr=lr)\n\n# function to calculate accuracy\ndef acc(pred,label):\n pred = torch.round(pred.squeeze())\n return torch.sum(pred == label.squeeze()).item()", "_____no_output_____" ], [ "patience_early_stopping = 3 #training will stop if model performance does not improve for these many consecutive epochs\ncnt = 0 #counter for checking patience level\nprev_epoch_acc = 0.0 #initializing prev test accuracy for early stopping condition\nscheduler = lr_scheduler.ReduceLROnPlateau(optimizer, mode = 'max', factor = 0.2, patience = 1) \n\nepochs = 10\n\nfor epoch in range(epochs):\n train_acc = 0.0\n model.train()\n for inputs, labels in train_loader:\n inputs, labels = inputs.to(device), labels.to(device) \n h = model.init_hidden(batch_size)\n model.zero_grad()\n output,h = model(inputs,h)\n loss = criterion(output.squeeze(), labels.float())\n loss.backward()\n accuracy = acc(output,labels)\n train_acc += accuracy\n optimizer.step()\n \n val_acc = 0.0\n model.eval()\n for inputs, labels in valid_loader:\n val_h = model.init_hidden(batch_size)\n inputs, labels = inputs.to(device), labels.to(device)\n output, val_h = model(inputs, val_h)\n accuracy = acc(output,labels)\n val_acc += accuracy\n \n epoch_train_acc = train_acc/len(train_loader.dataset)\n epoch_val_acc = val_acc/len(valid_loader.dataset)\n scheduler.step(epoch_val_acc)\n\n if epoch_val_acc > prev_epoch_acc: #check if val accuracy for current epoch has improved compared to previous epoch\n cnt = 0 #f accuracy improves reset counter to 0\n else: #otherwise increment current counter\n cnt += 1\n prev_epoch_acc = epoch_val_acc\n\n print(f'Epoch {epoch+1}') \n print(f'train_accuracy : {epoch_train_acc*100} val_accuracy : {epoch_val_acc*100}')\n if cnt == patience_early_stopping:\n print(f\"early stopping as test accuracy did not improve for {patience_early_stopping} consecutive epochs\")\n break", "Epoch 1\ntrain_accuracy : 74.3825 val_accuracy : 80.17999999999999\nEpoch 2\ntrain_accuracy : 83.9875 val_accuracy : 85.68\nEpoch 3\ntrain_accuracy : 86.575 val_accuracy : 85.9\nEpoch 4\ntrain_accuracy : 87.9575 val_accuracy : 85.46000000000001\nEpoch 5\ntrain_accuracy : 89.64750000000001 val_accuracy : 86.26\nEpoch 6\ntrain_accuracy : 91.8325 val_accuracy : 84.36\nEpoch 7\ntrain_accuracy : 94.6375 val_accuracy : 85.16\nEpoch 8\ntrain_accuracy : 98.3175 val_accuracy : 85.14\nEpoch 9\ntrain_accuracy : 99.4225 val_accuracy : 85.16\nEpoch 10\ntrain_accuracy : 99.815 val_accuracy : 85.0\n" ], [ "index = 30\nprint(df_test['text'][index])\nprint('='*70)\nprint(f'Actual sentiment is : {df_test[\"label\"][index]}')\nprint('='*70)\nprob = predict_text(df_test['text'][index])\nstatus = \"positive\" if prob > 0.5 else \"negative\"\nprob = (1 - prob) if status == \"negative\" else prob\nprint(f'Predicted sentiment is {status} with a probability of {prob}')", "This movie is good for entertainment purposes, but it is not historically reliable. If you are looking for a movie and thinking to yourself `Oh I want to learn more about Custer's life and his last stand', do not rent `They Died with Their Boots On'. But, if you would like to watch a movie for the enjoyment of an older western film, with a little bit of romance and just for a good story, this is a fun movie to watch.<br /><br />The story starts out with Custer's (Errol Flynn) first day at West Point. Everyone loves his charming personality which allows him to get away with most everything. The movie follows his career from West Point and his many battles, including his battle in the Civil War. The movie ends with his last stand at Little Big Horn. In between the battle scenes, he finds love and marriage with Libby (Olivia De Havilland).<br /><br />Errol Flynn portrays the arrogant, but suave George Armstrong Custer well. Olivia De Havilland plays the cute, sweet Libby very well, especially in the flirting scene that Custer and Libby first meet. Their chemistry on screen made you believe in their romance. The acting in general was impressive, especially the comedic role ( although stereotypical) of Callie played by Hattie McDaniel. Her character will definitely make you laugh.<br /><br />The heroic war music brought out the excitement of the battle scenes. The beautiful costumes set the tone of the era. The script, at times, was corny, although the movie was still enjoyable to watch. The director's portrayal of Custer was as a hero and history shows this is debatable. Some will watch this movie and see Custer as a hero. Others will watch this movie and learn hate him.<br /><br />I give it a thumbs up for this 1942 western film.\n======================================================================\nActual sentiment is : 1\n======================================================================\nPredicted sentiment is positive with a probability of 0.9999948740005493\n" ], [ "", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown", "markdown", "markdown", "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown", "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ] ]
4a0e3c8d78a0692608996e72616813b4c56be4d5
6,951
ipynb
Jupyter Notebook
Module 3/Part 5/Model Load and save.ipynb
AshishJangra27/Autonomous-Cars
20bf546e448a83263fa29a0aa322c69100d251d3
[ "Apache-2.0" ]
3
2021-09-11T15:44:35.000Z
2022-01-27T14:29:34.000Z
Module 3/Part 5/Model Load and save.ipynb
AshishJangra27/Autonomous-Cars
20bf546e448a83263fa29a0aa322c69100d251d3
[ "Apache-2.0" ]
null
null
null
Module 3/Part 5/Model Load and save.ipynb
AshishJangra27/Autonomous-Cars
20bf546e448a83263fa29a0aa322c69100d251d3
[ "Apache-2.0" ]
2
2021-05-15T10:03:46.000Z
2021-08-02T12:57:27.000Z
70.212121
5,076
0.827075
[ [ [ "import cv2 as cv\nimport numpy as np\n\nimport matplotlib.pyplot as plt\n\nfrom keras.models import load_model", "_____no_output_____" ], [ "model = load_model('CNN_7Epoch.h5')", "_____no_output_____" ], [ "img = cv.imread('Test/seven.png')\ngray = cv.cvtColor(img , cv.COLOR_BGR2GRAY)\n\ngray = gray/255.\ngray = 1. - gray \n\ngray = cv.resize( gray , (28,28))\n\nplt.imshow(gray)\nplt.show()\n\ngray = np.reshape(gray, (1,28,28,1))\n\nprint (\"This image is of a:\",np.argmax(model.predict(gray)))\nresult = model.predict(gray)", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code" ] ]
4a0e40340927224e49b4900193696994bf63be1a
3,653
ipynb
Jupyter Notebook
tests/nb_builds/nb_water/BA.00-References.ipynb
rmsrosa/nbjoint
7019ff336e4a7bb1f6ed20da5fd12b9f702c424a
[ "MIT" ]
null
null
null
tests/nb_builds/nb_water/BA.00-References.ipynb
rmsrosa/nbjoint
7019ff336e4a7bb1f6ed20da5fd12b9f702c424a
[ "MIT" ]
null
null
null
tests/nb_builds/nb_water/BA.00-References.ipynb
rmsrosa/nbjoint
7019ff336e4a7bb1f6ed20da5fd12b9f702c424a
[ "MIT" ]
null
null
null
35.125
1,117
0.614563
[ [ [ "<!--HEADER-->\n[*NBJoint test on a collection of notebooks about some thermodynamic properperties of water*](https://github.com/rmsrosa/nbjoint)", "_____no_output_____" ], [ "<!--BADGES-->\n<a href=\"https://colab.research.google.com/github/rmsrosa/nbjoint/blob/master/tests/nb_builds/nb_water/BA.00-References.ipynb\" target=\"_blank\"><img align=\"left\" src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open in Google Colab\" title=\"Open in Google Colab\"></a><a href=\"https://mybinder.org/v2/gh/rmsrosa/nbjoint/master?filepath=tests/nb_builds/nb_water/BA.00-References.ipynb\" target=\"_blank\"><img align=\"left\" src=\"https://mybinder.org/badge.svg\" alt=\"Open in binder\" title=\"Open in binder\"></a><a href=\"https://nbviewer.jupyter.org/github/rmsrosa/nbjoint/blob/master/tests/nb_builds/nb_water/BA.00-References.ipynb\" target=\"_blank\"><img align=\"left\" src=\"https://img.shields.io/badge/view%20in-nbviewer-orange\" alt=\"View in NBViewer\" title=\"View in NBViewer\"></a><a href=\"https://nbviewer.jupyter.org/github/rmsrosa/nbjoint/blob/master/tests/nb_builds/nb_water_slides/BA.00-References.slides.html\" target=\"_blank\"><img align=\"left\" src=\"https://img.shields.io/badge/view-slides-darkgreen\" alt=\"View Slides\" title=\"View Slides\"></a>&nbsp;", "_____no_output_____" ], [ "<!--NAVIGATOR-->\n[<- Choosing the Best Fit with AIC](05.00-Best_AIC_Fitting.ipynb) | [Water Contents](00.00-Water_Contents.ipynb) | [References](BA.00-References.ipynb) \n\n---\n", "_____no_output_____" ], [ "# References", "_____no_output_____" ], [ "- G. K. Batchelor (2000); \"An Introduction to Fluid Dynamics\"; Cambridge University Press, UK.\n- E. A. Bender (2000), \"An Introduction to Mathematical Modeling\"; (Dover Books on Computer Science) Dover Publications; 1st edition.\n- K. P. Burnham, D. R. Anderson (2002), \"Model Selection and Multimodel Inference: A practical information-theoretic approach\"; Springer-Verlag; 2nd edition.\n- G. H. Golub and C. F. Van Loan (1996), \"Matrix Computations\", Johns Hopkins University Press, 3rd edition.\n- L. N. Trefethen and D. Bau III (1997); \"Numerical Linear Algebra\"; SIAM: Society for Industrial and Applied Mathematics; 1st edition.", "_____no_output_____" ], [ "<!--NAVIGATOR-->\n\n---\n[<- Choosing the Best Fit with AIC](05.00-Best_AIC_Fitting.ipynb) | [Water Contents](00.00-Water_Contents.ipynb) | [References](BA.00-References.ipynb) ", "_____no_output_____" ] ] ]
[ "markdown" ]
[ [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ] ]
4a0e628cb1bdddc448f707e460d2c6159789e03a
2,060
ipynb
Jupyter Notebook
assignments/assignment1.ipynb
cspui/cv
cc882cb31517c7e2c6436d0fbb837d0b43abcc95
[ "MIT" ]
null
null
null
assignments/assignment1.ipynb
cspui/cv
cc882cb31517c7e2c6436d0fbb837d0b43abcc95
[ "MIT" ]
null
null
null
assignments/assignment1.ipynb
cspui/cv
cc882cb31517c7e2c6436d0fbb837d0b43abcc95
[ "MIT" ]
null
null
null
21.458333
174
0.479126
[ [ [ "comp_name = \"Perantis\"\nname = input(\"Name: \")\nic = input(\"ic: \")\naddress = input(\"Address: \")\n\nprint(f\"Name: {name} \\nIc: {ic} \\nAddress: {address} \\n \\nHi, \\nI am submitting an application letter for a job to {comp_name}. \\n \\nBest regards, \\n{name}.\")", "Name: a \nIc: 1 \nAddress: 1,3 \n \nHi, \nI am submitting an application letter for a job to Perantis. \n \nBest regards, \na.\n" ], [ "import math\ndef quadratic(a,b,c):\n\n x1 = (-b + math.sqrt(b**2 - (4*a*c))) / (2*a)\n x2 = (-b - math.sqrt(b**2 - (4*a*c))) / (2*a)\n print(x1, x2)\n return x1, x2\n\n\na, b, c = 2,8,1\nquadratic(a,b,c)", "-0.12917130661302934 -3.8708286933869704\n" ] ] ]
[ "code" ]
[ [ "code", "code" ] ]
4a0e76b455f827474e32b7d1f56903b82bc86455
123,810
ipynb
Jupyter Notebook
.ipynb_checkpoints/Local Analysis-checkpoint.ipynb
jamesjisu/Medical-AI
28e52a1ef8c8d74001a098d68643cf1107d24795
[ "MIT" ]
null
null
null
.ipynb_checkpoints/Local Analysis-checkpoint.ipynb
jamesjisu/Medical-AI
28e52a1ef8c8d74001a098d68643cf1107d24795
[ "MIT" ]
null
null
null
.ipynb_checkpoints/Local Analysis-checkpoint.ipynb
jamesjisu/Medical-AI
28e52a1ef8c8d74001a098d68643cf1107d24795
[ "MIT" ]
null
null
null
39.964493
10,212
0.346798
[ [ [ "import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as mdates\nfrom datetime import datetime\n\npd.set_option('display.max_columns', None)\npd.set_option('display.max_rows', 10)", "_____no_output_____" ], [ "df = pd.read_csv('data/final_cohort.csv')", "_____no_output_____" ], [ "df.head()", "_____no_output_____" ] ], [ [ "## Make Timeline in Python", "_____no_output_____" ] ], [ [ "names = df['knumber']\ndates = df['Date']", "_____no_output_____" ], [ "dates", "_____no_output_____" ], [ "min(dates)", "_____no_output_____" ], [ "max(dates)", "_____no_output_____" ], [ "dates = [datetime.strptime(x, \"%m/%d/%Y\") for x in dates]", "_____no_output_____" ], [ "levels = np.tile([-5, 5, -3, 3, -1, 1],\n int(np.ceil(len(dates)/6)))[:len(dates)]\n\nfig, ax = plt.subplots(figsize=(8.8, 4), constrained_layout=True)\nax.set(title=\"Test Timeline\")\n\nax.vlines(dates, 0, levels, color=\"tab:red\") # The vertical stems.\nax.plot(dates, np.zeros_like(dates), \"-o\",\n color=\"k\", markerfacecolor=\"w\") # Baseline and markers on it.\n\n# annotate lines\n# for d, l, r in zip(dates, levels, names):\n# ax.annotate(r, xy=(d, l),\n# xytext=(-3, np.sign(l)*3), textcoords=\"offset points\",\n# horizontalalignment=\"right\",\n# verticalalignment=\"bottom\" if l > 0 else \"top\")\n\n# format xaxis with 4 month intervals\nax.xaxis.set_major_locator(mdates.MonthLocator(interval=24))\nax.xaxis.set_major_formatter(mdates.DateFormatter(\"%b %Y\"))\nplt.setp(ax.get_xticklabels(), rotation=30, ha=\"right\")\n\n# remove y axis and spines\nax.yaxis.set_visible(False)\n#ax.spines[[\"left\", \"top\", \"right\"]].set_visible(False)\n\nax.margins(y=0.1)\nplt.show()", "_____no_output_____" ], [ "df['month_year'] = df['Date'].apply(lambda x: x.split('/')[0] + '/15/' + x.split('/')[2])", "_____no_output_____" ], [ "df['quarter_year'] = df['month_year'].apply(quarter_parse)", "_____no_output_____" ], [ "def quarter_parse(x):\n if x.split('/')[0] in ['01', '02', '03']:\n return '02/15/' + x.split('/')[1]\n if x.split('/')[0] in ['04', '05', '06']:\n return '5/15/' + x.split('/')[1]\n if x.split('/')[0] in ['07', '08', '09']:\n return '8/15/' + x.split('/')[1]\n if x.split('/')[0] in ['10', '11', '12']:\n return '11/15/' + x.split('/')[1]\n ", "_____no_output_____" ], [ "def specialty_sort(x):\n if x == 'Radiology': \n return 0\n elif x == 'Cardiovascular':\n return 1\n else:\n return 2\ndef path_sort(x):\n if x == '510K': \n return 0\n elif x == 'DEN':\n return 1\n else:\n return 2", "_____no_output_____" ], [ "df['specialty_sort'] = df['Specialty'].apply(specialty_sort)\ndf['path_sort'] = df['Specialty'].apply(path_sort)", "_____no_output_____" ], [ "master_df = pd.DataFrame(columns = df.columns)\nfor qrt_yr in set(df['quarter_year'].values):\n tempdf = df[df['quarter_year'] == qrt_yr]\n tempdf = tempdf.sort_values(by = 'specialty_sort').sort_values(by='path_sort')\n tempdf['height'] = range(len(tempdf))\n master_df = master_df.append(tempdf)\nmaster_df[['quarter_year', 'Name', 'Specialty', 'path', 'height']].to_csv('data/timeline_quarter_data.csv')", "_____no_output_____" ], [ "master_df = pd.DataFrame(columns = df.columns)\nfor qrt_yr in set(df['month_year'].values):\n tempdf = df[df['month_year'] == qrt_yr]\n tempdf = tempdf.sort_values(by = 'specialty_sort').sort_values(by='path_sort')\n tempdf['height'] = range(len(tempdf))\n master_df = master_df.append(tempdf)\nmaster_df[['month_year', 'Name', 'Specialty', 'path', 'height']].to_csv('data/timeline_month_data.csv')", "_____no_output_____" ], [ "tempdf", "_____no_output_____" ], [ "master_df", "_____no_output_____" ], [ "\\", "_____no_output_____" ], [ "vdf = df[['quarter_year', 'Specialty']].value_counts()", "_____no_output_____" ], [ "vdf.unstack('Specialty')", "_____no_output_____" ], [ "vdf.unstack('Specialty').fillna(0).to_csv('data/timeline_bar_data.csv')", "_____no_output_____" ], [ "vdf", "_____no_output_____" ], [ "df[['Date', 'Name', 'Specialty', 'path']].to_csv('data/timeline_data.csv')", "_____no_output_____" ], [ "df['path'].value_counts()", "_____no_output_____" ] ], [ [ "## State Map", "_____no_output_____" ] ], [ [ "df['STATE'].value_counts()", "_____no_output_____" ], [ "state_dict = df['STATE'].value_counts().to_dict()", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code" ]
[ [ "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ] ]
4a0e88b592549a4e3e980e01d04b2d407eabcb29
75,908
ipynb
Jupyter Notebook
NeuralNetworks/Perceptrons/DNNClassifier.ipynb
Harsh188/100_Days_of_ML
7f793813cc340ea6aeb4b028cb9be303afe25e36
[ "MIT" ]
4
2021-05-25T21:59:54.000Z
2022-01-08T03:16:24.000Z
NeuralNetworks/Perceptrons/DNNClassifier.ipynb
Harsh188/100_Days_of_ML
7f793813cc340ea6aeb4b028cb9be303afe25e36
[ "MIT" ]
null
null
null
NeuralNetworks/Perceptrons/DNNClassifier.ipynb
Harsh188/100_Days_of_ML
7f793813cc340ea6aeb4b028cb9be303afe25e36
[ "MIT" ]
1
2021-03-07T07:11:31.000Z
2021-03-07T07:11:31.000Z
218.126437
57,296
0.906545
[ [ [ "### What is a dense neural network?\nA dense layer is a fully connected layer where all the neurons in a layer are connected to the ones in the next layer.\n\n", "_____no_output_____" ], [ "## Imports", "_____no_output_____" ] ], [ [ "import numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\nfrom sklearn import preprocessing, svm\nfrom sklearn.model_selection import train_test_split\nimport tensorflow as tf\nfrom tensorflow import keras", "_____no_output_____" ] ], [ [ "## Data Set", "_____no_output_____" ] ], [ [ "fashion_mnist = keras.datasets.fashion_mnist\n\n(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()", "Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/train-labels-idx1-ubyte.gz\n32768/29515 [=================================] - 0s 2us/step\nDownloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/train-images-idx3-ubyte.gz\n26427392/26421880 [==============================] - 3s 0us/step\nDownloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/t10k-labels-idx1-ubyte.gz\n8192/5148 [===============================================] - 0s 0us/step\nDownloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/t10k-images-idx3-ubyte.gz\n4423680/4422102 [==============================] - 1s 0us/step\n" ], [ "class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',\n 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']", "_____no_output_____" ], [ "print(\"Train images shape:\",train_images.shape)\nprint(\"Train labels length:\",len(train_labels))\ntrain_labels", "Train images shape: (60000, 28, 28)\nTrain labels length: 60000\n" ], [ "print(\"Test images shape:\",test_images.shape)\nprint(\"Test labels length:\",len(test_labels))\n", "Test images shape: (10000, 28, 28)\nTest labels length: 10000\n" ] ], [ [ "## Preprocessing", "_____no_output_____" ] ], [ [ "plt.figure()\nplt.imshow(train_images[0])\nplt.colorbar()\nplt.grid(False)\nplt.show()", "_____no_output_____" ], [ "train_images = train_images / 255.0\n\ntest_images = test_images / 255.0", "_____no_output_____" ], [ "plt.figure(figsize=(10,10))\nfor i in range(25):\n plt.subplot(5,5,i+1)\n plt.xticks([])\n plt.yticks([])\n plt.grid(False)\n plt.imshow(train_images[i], cmap=plt.cm.binary)\n plt.xlabel(class_names[train_labels[i]])\nplt.show()", "_____no_output_____" ] ], [ [ "## Model", "_____no_output_____" ] ], [ [ "model = tf.keras.models.Sequential([\n tf.keras.layers.Flatten(input_shape=(28,28)),\n tf.keras.layers.Dense(128, activation='relu'),\n tf.keras.layers.Dense(10)\n])", "_____no_output_____" ], [ "model.compile(optimizer='adam',\n loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n metrics=['accuracy'])", "_____no_output_____" ] ], [ [ "## Training", "_____no_output_____" ] ], [ [ "model.fit(train_images, train_labels, epochs=10)", "Epoch 1/10\n1875/1875 [==============================] - 2s 879us/step - loss: 0.4996 - accuracy: 0.8250\nEpoch 2/10\n1875/1875 [==============================] - 2s 914us/step - loss: 0.3701 - accuracy: 0.8670\nEpoch 3/10\n1875/1875 [==============================] - 2s 940us/step - loss: 0.3322 - accuracy: 0.87960s\nEpoch 4/10\n1875/1875 [==============================] - 2s 909us/step - loss: 0.3105 - accuracy: 0.8855\nEpoch 5/10\n1875/1875 [==============================] - 2s 882us/step - loss: 0.2940 - accuracy: 0.8918\nEpoch 6/10\n1875/1875 [==============================] - 2s 884us/step - loss: 0.2792 - accuracy: 0.8958\nEpoch 7/10\n1875/1875 [==============================] - 2s 886us/step - loss: 0.2676 - accuracy: 0.9010\nEpoch 8/10\n1875/1875 [==============================] - 2s 944us/step - loss: 0.2550 - accuracy: 0.9042\nEpoch 9/10\n1875/1875 [==============================] - 2s 895us/step - loss: 0.2485 - accuracy: 0.9082\nEpoch 10/10\n1875/1875 [==============================] - 2s 863us/step - loss: 0.2406 - accuracy: 0.9097\n" ] ], [ [ "## Accuracy", "_____no_output_____" ] ], [ [ "test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)\n\nprint('\\nTest accuracy:', test_acc)", "313/313 - 0s - loss: 0.3438 - accuracy: 0.8782\n\nTest accuracy: 0.8781999945640564\n" ] ], [ [ "Credits: [Basic classification: Classify images of clothing](https://www.tensorflow.org/tutorials/keras/classification)", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ] ]
4a0e8e2062bb0bcd51bbeed3760fbce5c0e7e9f8
76,377
ipynb
Jupyter Notebook
notebooks/data_collection_vanko.ipynb
datascisteven/Twitter-Sentiment-Analysis
2e9fd11fb75e76597bb3cc41d0239f929aea710d
[ "MIT" ]
null
null
null
notebooks/data_collection_vanko.ipynb
datascisteven/Twitter-Sentiment-Analysis
2e9fd11fb75e76597bb3cc41d0239f929aea710d
[ "MIT" ]
null
null
null
notebooks/data_collection_vanko.ipynb
datascisteven/Twitter-Sentiment-Analysis
2e9fd11fb75e76597bb3cc41d0239f929aea710d
[ "MIT" ]
2
2021-05-18T08:19:34.000Z
2021-08-07T21:11:27.000Z
91.142005
29,232
0.803488
[ [ [ "import numpy as np\nimport pandas as pd\nimport json\nimport requests\nimport matplotlib.pyplot as plt\nplt.style.use('ggplot')\nimport seaborn as sns", "_____no_output_____" ] ], [ [ "## Loading Labeled Dataset with hate tweets IDs", "_____no_output_____" ] ], [ [ "df = pd.read_csv('../data/hate_add.csv')\ndf = df[(df['racism']=='racism') | (df['racism']=='sexism')]", "_____no_output_____" ], [ "df.head()", "_____no_output_____" ], [ "df.info()", "<class 'pandas.core.frame.DataFrame'>\nInt64Index: 5347 entries, 0 to 5346\nData columns (total 2 columns):\n # Column Non-Null Count Dtype \n--- ------ -------------- ----- \n 0 572342978255048705 5347 non-null int64 \n 1 racism 5347 non-null object\ndtypes: int64(1), object(1)\nmemory usage: 125.3+ KB\n" ], [ "df.racism.value_counts()", "_____no_output_____" ], [ "df.columns = ['id','label']", "_____no_output_____" ], [ "def group_list(l,size = 100):\n \"\"\"\n Generate batches of 100 ids in each\n Returns list of strings with , seperated ids\n \"\"\"\n n_l =[]\n idx = 0\n while idx < len(l): \n n_l.append(\n ','.join([str(i) for i in l[idx:idx+size]])\n )\n idx += size\n return n_l", "_____no_output_____" ], [ "import config\n\ndef tweets_request(tweets_ids):\n \n \"\"\"\n Make a requests to Tweeter API\n \"\"\"\n \n df_lst = []\n \n for batch in tweets_ids:\n url = \"https://api.twitter.com/2/tweets?ids={}&tweet.fields=created_at&expansions=author_id&user.fields=created_at\".format(batch)\n payload={}\n headers = {'Authorization': 'Bearer ' + config.bearer_token,\n 'Cookie': 'personalization_id=\"v1_hzpv7qXpjB6CteyAHDWYQQ==\"; guest_id=v1%3A161498381400435837'}\n r = requests.request(\"GET\", url, headers=headers, data=payload)\n data = r.json()\n if 'data' in data.keys():\n df_lst.append(pd.DataFrame(data['data']))\n \n return pd.concat(df_lst)", "_____no_output_____" ] ], [ [ "## Getting actual tweets text with API requests", "_____no_output_____" ] ], [ [ "racism_sex_hate_id = group_list(list(df2.id))", "_____no_output_____" ], [ "# df_rac_sex_hate = tweets_request(racism_sex_hate_id)", "_____no_output_____" ], [ "df_rac_sex_hate", "_____no_output_____" ], [ "df_rac_sex_hate = pd.read_csv('../data/df_ras_sex_hate.csv')", "_____no_output_____" ], [ "df_rac_sex_hate = df_rac_sex_hate.drop(columns=['Unnamed: 0', 'id', 'author_id', 'created_at'])", "_____no_output_____" ], [ "df_rac_sex_hate['class'] = 1", "_____no_output_____" ], [ "df_rac_sex_hate.head()", "_____no_output_____" ], [ "df_rac_sex_hate.shape", "_____no_output_____" ] ], [ [ "## Loading Labeled Dataset with tweets", "_____no_output_____" ] ], [ [ "df_l = pd.read_csv(\"../data/labeled_data.csv\")\ndf_l.head()", "_____no_output_____" ], [ "print(df_l['class'].value_counts(normalize=True))\n\n# Class Imbalance \n\nfig, ax = plt.subplots(figsize=(10,6))\nax = sns.countplot(df_l['class'], palette='Set2')\n\nax.set_title('Amount of Tweets Per Label',fontsize = 20)\nax.set_xlabel('Type of Tweet',fontsize = 15)\nax.set_ylabel('Count',fontsize = 15)\nax.set_xticklabels(['Hate_speech','Offensive_language', 'Neither'],fontsize = 13)\n\ntotal = float(len(df_l)) # one person per row \nfor p in ax.patches:\n height = p.get_height()\n ax.text(p.get_x()+p.get_width()/2.,\n height + 3,\n '{:1.2f}'.format(height/total * 100) + '%',\n ha=\"center\") ", "1 0.774321\n2 0.167978\n0 0.057701\nName: class, dtype: float64\n" ], [ "# class 0 - hate tweets\n# class 1 - offensive_language tweets\n# class 2 - neither tweets", "_____no_output_____" ], [ "df_l['class'].value_counts()", "_____no_output_____" ], [ "# considering only class 0 (hate tweets) and class 2 (neither tweets) as binary classification problem\n# updating neither tweets as not hate speech", "_____no_output_____" ], [ "df_l = df_l.drop(columns=['Unnamed: 0', 'count', 'hate_speech', 'offensive_language', 'neither'])", "_____no_output_____" ], [ "df_l = df_l[(df_l['class']==0) | (df_l['class']==2)]", "_____no_output_____" ], [ "df_l['class'] = df_l['class'].map(lambda x : 0 if x == 2 else 1)", "_____no_output_____" ], [ "df_l.rename(columns={'tweet':'text'}, inplace= True)", "_____no_output_____" ] ], [ [ "## Lets combine 2 Data Frames with Labeled Classes of hate speach and not hate speach", "_____no_output_____" ] ], [ [ "df_combined = pd.concat([df_rac_sex_hate,df_l])", "_____no_output_____" ], [ "print(df_combined['class'].value_counts(normalize=True))\n\n# Class Imbalance \n\nfig, ax = plt.subplots(figsize=(10,6))\nax = sns.countplot(df_combined['class'], palette='Set2')\n\nax.set_title('Amount of Tweets Per Label',fontsize = 20)\nax.set_xlabel('Type of Tweet',fontsize = 15)\nax.set_ylabel('Count',fontsize = 15)\nax.set_xticklabels(['Not Hate Speech','Hate Speech'],fontsize = 13)\n\ntotal = float(len(df_combined)) # one person per row \nfor p in ax.patches:\n height = p.get_height()\n ax.text(p.get_x()+p.get_width()/2.,\n height + 3,\n '{:1.2f}'.format(height/total * 100) + '%',\n ha=\"center\") ", "1 0.50066\n0 0.49934\nName: class, dtype: float64\n" ] ], [ [ "### Saving combined Data to CSV file ", "_____no_output_____" ] ], [ [ "df_combined.to_csv('../data/balanced_data_combined.csv')", "_____no_output_____" ] ] ]
[ "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code", "code", "code", "code", "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ] ]
4a0e9a70ea403c29fcec719d62dd0d3213c50fca
17,643
ipynb
Jupyter Notebook
pretrained-model/pegasus/pegasus-select-sentence.ipynb
AetherPrior/malaya
45d37b171dff9e92c5d30bd7260b282cd0912a7d
[ "MIT" ]
88
2021-01-06T10:01:31.000Z
2022-03-30T17:34:09.000Z
pretrained-model/pegasus/pegasus-select-sentence.ipynb
AetherPrior/malaya
45d37b171dff9e92c5d30bd7260b282cd0912a7d
[ "MIT" ]
43
2021-01-14T02:44:41.000Z
2022-03-31T19:47:42.000Z
pretrained-model/pegasus/pegasus-select-sentence.ipynb
AetherPrior/malaya
45d37b171dff9e92c5d30bd7260b282cd0912a7d
[ "MIT" ]
38
2021-01-06T07:15:03.000Z
2022-03-19T05:07:50.000Z
33.039326
155
0.478943
[ [ [ "import os\n\nos.environ['CUDA_VISIBLE_DEVICES'] = ''", "_____no_output_____" ], [ "import numpy as np\nfrom numpy.random import default_rng\nimport random\nimport collections\nimport re\nimport tensorflow as tf\nfrom tqdm import tqdm", "_____no_output_____" ], [ "max_seq_length_encoder = 512\nmax_seq_length_decoder = 128\nmasked_lm_prob = 0.2\nmax_predictions_per_seq = int(masked_lm_prob * max_seq_length_encoder)\ndo_whole_word_mask = True\nEOS_ID = 1", "_____no_output_____" ], [ "MaskedLmInstance = collections.namedtuple(\n 'MaskedLmInstance', ['index', 'label']\n)\n\n\nclass TrainingInstance(object):\n \"\"\"A single training instance (sentence pair).\"\"\"\n\n def __init__(self, tokens, tokens_y, masked_lm_positions, masked_lm_labels):\n self.tokens = tokens\n self.tokens_y = tokens_y\n self.masked_lm_positions = masked_lm_positions\n self.masked_lm_labels = masked_lm_labels", "_____no_output_____" ], [ "def sliding(strings, n = 5):\n results = []\n for i in range(len(strings) - n):\n results.append(strings[i : i + n])\n return results\n\n\ndef _get_ngrams(n, text):\n ngram_set = set()\n text_length = len(text)\n max_index_ngram_start = text_length - n\n for i in range(max_index_ngram_start + 1):\n ngram_set.add(tuple(text[i : i + n]))\n return ngram_set\n\n\ndef _get_word_ngrams(n, sentences):\n assert len(sentences) > 0\n assert n > 0\n\n words = sum(sentences, [])\n return _get_ngrams(n, words)\n\n\ndef cal_rouge(evaluated_ngrams, reference_ngrams):\n reference_count = len(reference_ngrams)\n evaluated_count = len(evaluated_ngrams)\n\n overlapping_ngrams = evaluated_ngrams.intersection(reference_ngrams)\n overlapping_count = len(overlapping_ngrams)\n\n if evaluated_count == 0:\n precision = 0.0\n else:\n precision = overlapping_count / evaluated_count\n\n if reference_count == 0:\n recall = 0.0\n else:\n recall = overlapping_count / reference_count\n\n f1_score = 2.0 * ((precision * recall) / (precision + recall + 1e-8))\n return {'f': f1_score, 'p': precision, 'r': recall}\n\n\ndef _rouge_clean(s):\n return re.sub(r'[^a-zA-Z0-9 ]', '', s)\n\n\ndef get_rouges(strings, n = 1):\n rouges = []\n for i in range(len(strings)):\n abstract = strings[i]\n doc_sent_list = [strings[k] for k in range(len(strings)) if k != i]\n sents = _rouge_clean(' '.join(doc_sent_list)).split()\n abstract = _rouge_clean(abstract).split()\n evaluated_1grams = _get_word_ngrams(n, [sents])\n reference_1grams = _get_word_ngrams(n, [abstract])\n rouges.append(cal_rouge(evaluated_1grams, reference_1grams)['f'])\n return rouges\n\n\n# Principal Select top-m scored sentences according to importance.\n# As a proxy for importance we compute ROUGE1-F1 (Lin, 2004) between the sentence and the rest of the document\ndef get_rouge(strings, top_k = 1, minlen = 4):\n rouges = get_rouges(strings)\n s = np.argsort(rouges)[::-1]\n s = [i for i in s if len(strings[i].split()) >= minlen]\n return s[:top_k]\n\n\n# Random Uniformly select m sentences at random.\ndef get_random(strings, top_k = 1):\n return rng.choice(len(strings), size = top_k, replace = False)\n\n\n# Lead Select the first m sentences.\ndef get_lead(strings, top_k = 1):\n return [i for i in range(top_k)]\n\n\ndef combine(l):\n r = []\n for s in l:\n if s[-1] != '.':\n if s in ['[MASK]', '[MASK2]']:\n e = ' .'\n else:\n e = '.'\n s = s + e\n r.append(s)\n return ' '.join(r)\n\n\ndef is_number_regex(s):\n if re.match('^\\d+?\\.\\d+?$', s) is None:\n return s.isdigit()\n return True\n\n\ndef reject(token):\n t = token.replace('##', '')\n if is_number_regex(t):\n return True\n if t.startswith('RM'):\n return True\n if token in '!{<>}:;.,\"\\'':\n return True\n return False\n\n\ndef create_masked_lm_predictions(\n tokens,\n vocab_words,\n rng,\n):\n \"\"\"Creates the predictions for the masked LM objective.\"\"\"\n\n cand_indexes = []\n for (i, token) in enumerate(tokens):\n if token == '[CLS]' or token == '[SEP]' or token == '[MASK2]':\n continue\n if reject(token):\n continue\n if (\n do_whole_word_mask\n and len(cand_indexes) >= 1\n and token.startswith('##')\n ):\n cand_indexes[-1].append(i)\n else:\n cand_indexes.append([i])\n\n rng.shuffle(cand_indexes)\n\n output_tokens = list(tokens)\n\n num_to_predict = min(\n max_predictions_per_seq,\n max(1, int(round(len(tokens) * masked_lm_prob))),\n )\n\n masked_lms = []\n covered_indexes = set()\n for index_set in cand_indexes:\n if len(masked_lms) >= num_to_predict:\n break\n if len(masked_lms) + len(index_set) > num_to_predict:\n continue\n is_any_index_covered = False\n for index in index_set:\n if index in covered_indexes:\n is_any_index_covered = True\n break\n if is_any_index_covered:\n continue\n for index in index_set:\n covered_indexes.add(index)\n\n masked_token = None\n # 80% of the time, replace with [MASK]\n if rng.random() < 0.8:\n masked_token = '[MASK]'\n else:\n # 10% of the time, keep original\n if rng.random() < 0.5:\n masked_token = tokens[index]\n # 10% of the time, replace with random word\n else:\n masked_token = vocab_words[\n np.random.randint(0, len(vocab_words) - 1)\n ]\n\n output_tokens[index] = masked_token\n\n masked_lms.append(\n MaskedLmInstance(index = index, label = tokens[index])\n )\n assert len(masked_lms) <= num_to_predict\n masked_lms = sorted(masked_lms, key = lambda x: x.index)\n\n masked_lm_positions = []\n masked_lm_labels = []\n for p in masked_lms:\n masked_lm_positions.append(p.index)\n masked_lm_labels.append(p.label)\n\n return (output_tokens, masked_lm_positions, masked_lm_labels)\n\n\ndef get_feature(x, y, tokenizer, vocab_words, rng, dedup_factor = 5, **kwargs):\n tokens = tokenizer.tokenize(x)\n if len(tokens) > (max_seq_length_encoder - 2):\n tokens = tokens[:max_seq_length_encoder - 2]\n \n if '[MASK2]' not in tokens:\n return []\n\n tokens = ['[CLS]'] + tokens + ['[SEP]']\n \n tokens_y = tokenizer.tokenize(y)\n if len(tokens_y) > (max_seq_length_decoder - 1):\n tokens_y = tokens_y[:max_seq_length_decoder - 1]\n \n tokens_y = tokenizer.convert_tokens_to_ids(tokens_y)\n tokens_y = tokens_y + [EOS_ID]\n results = []\n for i in range(dedup_factor):\n output_tokens, masked_lm_positions, masked_lm_labels = create_masked_lm_predictions(\n tokens, vocab_words, rng, **kwargs\n )\n output_tokens = tokenizer.convert_tokens_to_ids(output_tokens)\n masked_lm_labels = tokenizer.convert_tokens_to_ids(masked_lm_labels)\n t = TrainingInstance(\n output_tokens, tokens_y, masked_lm_positions, masked_lm_labels\n )\n results.append(t)\n return results\n\n\ndef group_doc(data):\n results, result = [], []\n for i in data:\n if not len(i) and len(result):\n results.append(result)\n result = []\n else:\n result.append(i)\n\n if len(result):\n results.append(result)\n return results\n\n\ndef create_int_feature(values):\n feature = tf.train.Feature(\n int64_list = tf.train.Int64List(value = list(values))\n )\n return feature\n\n\ndef create_float_feature(values):\n feature = tf.train.Feature(\n float_list = tf.train.FloatList(value = list(values))\n )\n return feature\n\n\ndef write_instance_to_example_file(\n instances,\n output_file\n):\n writer = tf.python_io.TFRecordWriter(output_file)\n for (inst_index, instance) in enumerate(instances):\n input_ids = list(instance.tokens)\n target_ids = list(instance.tokens_y)\n while len(input_ids) < max_seq_length_encoder:\n input_ids.append(0)\n target_ids.append(0)\n masked_lm_positions = list(instance.masked_lm_positions)\n masked_lm_ids = list(instance.masked_lm_labels)\n masked_lm_weights = [1.0] * len(masked_lm_ids)\n while len(masked_lm_positions) < max_predictions_per_seq:\n masked_lm_positions.append(0)\n masked_lm_ids.append(0)\n masked_lm_weights.append(0.0)\n\n features = collections.OrderedDict()\n features['input_ids'] = create_int_feature(input_ids)\n features['targets_ids'] = create_int_feature(target_ids)\n features['masked_lm_positions'] = create_int_feature(\n masked_lm_positions\n )\n features['masked_lm_ids'] = create_int_feature(masked_lm_ids)\n features['masked_lm_weights'] = create_float_feature(masked_lm_weights)\n tf_example = tf.train.Example(\n features = tf.train.Features(feature = features)\n )\n writer.write(tf_example.SerializeToString())\n\n tf.logging.info('Wrote %d total instances', inst_index)\n\n\ndef process_documents(\n file,\n output_file,\n tokenizer,\n min_slide = 5,\n max_slide = 13,\n dedup_mask = 2,\n):\n with open(file) as fopen:\n data = fopen.read().split('\\n')\n rng = default_rng()\n vocab_words = list(tokenizer.vocab.keys())\n grouped = group_doc(data)\n results = []\n for s in range(min_slide, max_slide, 1):\n for r in tqdm(grouped):\n slided = sliding(r, s)\n X, Y = [], []\n for i in range(len(slided)):\n try:\n strings = slided[i]\n rouge_ = get_rouge(strings)\n y = strings[rouge_[0]]\n strings[rouge_[0]] = '[MASK2]'\n x = combine(strings)\n result = get_feature(\n x,\n y,\n tokenizer,\n vocab_words,\n rng,\n dedup_factor = dedup_mask,\n )\n results.extend(result)\n except:\n pass\n\n write_instance_to_example_file(results, output_file)", "_____no_output_____" ], [ "import tokenization\n\ntokenizer = tokenization.FullTokenizer(vocab_file = 'pegasus.wordpiece', do_lower_case=False)", "WARNING:tensorflow:From /home/husein/pure-text/tokenization.py:135: The name tf.gfile.GFile is deprecated. Please use tf.io.gfile.GFile instead.\n\n" ], [ "file = 'dumping-cleaned-news.txt'\noutput_file = 'news.tfrecord'\nmin_slide = 5\nmax_slide = 13\ndedup_mask = 5", "_____no_output_____" ], [ "with open(file) as fopen:\n data = fopen.read().split('\\n')\nrng = default_rng()\nvocab_words = list(tokenizer.vocab.keys())\ngrouped = group_doc(data)", "_____no_output_____" ], [ "results = []\nfor s in range(min_slide, max_slide, 1):\n for r in tqdm(grouped[:100]):\n slided = sliding(r, s)\n X, Y = [], []\n for i in range(len(slided)):\n try:\n strings = slided[i]\n rouge_ = get_rouge(strings)\n y = strings[rouge_[0]]\n strings[rouge_[0]] = '[MASK2]'\n x = combine(strings)\n result = get_feature(\n x,\n y,\n tokenizer,\n vocab_words,\n rng,\n dedup_factor = dedup_mask,\n )\n results.extend(result)\n except:\n pass", "100%|██████████| 100/100 [00:06<00:00, 15.92it/s]\n100%|██████████| 100/100 [00:07<00:00, 13.48it/s]\n100%|██████████| 100/100 [00:07<00:00, 13.44it/s]\n100%|██████████| 100/100 [00:07<00:00, 12.69it/s]\n100%|██████████| 100/100 [00:07<00:00, 12.66it/s]\n100%|██████████| 100/100 [00:08<00:00, 12.23it/s]\n100%|██████████| 100/100 [00:07<00:00, 13.17it/s]\n100%|██████████| 100/100 [00:07<00:00, 13.59it/s]\n" ], [ "write_instance_to_example_file(results, output_file)", "INFO:tensorflow:Wrote 34829 total instances\n" ], [ "!rm {output_file}", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
4a0ea8fd821eee07c33a41794256ca8aed9d6712
41,859
ipynb
Jupyter Notebook
11_DeepLearningAI/01_NeuralNetworksandDeepLearning/01_Week2_PythonBasicsWithNumpyv3.ipynb
KartikKannapur/Data_Structures_and_Algorithms_Python
66e3c8112826aeffb78bd74d02be1a8d1e478de8
[ "MIT" ]
1
2017-06-11T04:57:07.000Z
2017-06-11T04:57:07.000Z
11_DeepLearningAI/01_NeuralNetworksandDeepLearning/01_Week2_PythonBasicsWithNumpyv3.ipynb
KartikKannapur/Data_Structures_and_Algorithms_Python
66e3c8112826aeffb78bd74d02be1a8d1e478de8
[ "MIT" ]
null
null
null
11_DeepLearningAI/01_NeuralNetworksandDeepLearning/01_Week2_PythonBasicsWithNumpyv3.ipynb
KartikKannapur/Data_Structures_and_Algorithms_Python
66e3c8112826aeffb78bd74d02be1a8d1e478de8
[ "MIT" ]
null
null
null
34.65149
960
0.510906
[ [ [ "# Python Basics with Numpy (optional assignment)\n\nWelcome to your first assignment. This exercise gives you a brief introduction to Python. Even if you've used Python before, this will help familiarize you with functions we'll need. \n\n**Instructions:**\n- You will be using Python 3.\n- Avoid using for-loops and while-loops, unless you are explicitly told to do so.\n- Do not modify the (# GRADED FUNCTION [function name]) comment in some cells. Your work would not be graded if you change this. Each cell containing that comment should only contain one function.\n- After coding your function, run the cell right below it to check if your result is correct.\n\n**After this assignment you will:**\n- Be able to use iPython Notebooks\n- Be able to use numpy functions and numpy matrix/vector operations\n- Understand the concept of \"broadcasting\"\n- Be able to vectorize code\n\nLet's get started!", "_____no_output_____" ], [ "## About iPython Notebooks ##\n\niPython Notebooks are interactive coding environments embedded in a webpage. You will be using iPython notebooks in this class. You only need to write code between the ### START CODE HERE ### and ### END CODE HERE ### comments. After writing your code, you can run the cell by either pressing \"SHIFT\"+\"ENTER\" or by clicking on \"Run Cell\" (denoted by a play symbol) in the upper bar of the notebook. \n\nWe will often specify \"(≈ X lines of code)\" in the comments to tell you about how much code you need to write. It is just a rough estimate, so don't feel bad if your code is longer or shorter.\n\n**Exercise**: Set test to `\"Hello World\"` in the cell below to print \"Hello World\" and run the two cells below.", "_____no_output_____" ] ], [ [ "### START CODE HERE ### (≈ 1 line of code)\ntest = \"Hello World\"\n### END CODE HERE ###", "_____no_output_____" ], [ "print (\"test: \" + test)", "test: Hello World\n" ] ], [ [ "**Expected output**:\ntest: Hello World", "_____no_output_____" ], [ "<font color='blue'>\n**What you need to remember**:\n- Run your cells using SHIFT+ENTER (or \"Run cell\")\n- Write code in the designated areas using Python 3 only\n- Do not modify the code outside of the designated areas", "_____no_output_____" ], [ "## 1 - Building basic functions with numpy ##\n\nNumpy is the main package for scientific computing in Python. It is maintained by a large community (www.numpy.org). In this exercise you will learn several key numpy functions such as np.exp, np.log, and np.reshape. You will need to know how to use these functions for future assignments.\n\n### 1.1 - sigmoid function, np.exp() ###\n\nBefore using np.exp(), you will use math.exp() to implement the sigmoid function. You will then see why np.exp() is preferable to math.exp().\n\n**Exercise**: Build a function that returns the sigmoid of a real number x. Use math.exp(x) for the exponential function.\n\n**Reminder**:\n$sigmoid(x) = \\frac{1}{1+e^{-x}}$ is sometimes also known as the logistic function. It is a non-linear function used not only in Machine Learning (Logistic Regression), but also in Deep Learning.\n\n<img src=\"images/Sigmoid.png\" style=\"width:500px;height:228px;\">\n\nTo refer to a function belonging to a specific package you could call it using package_name.function(). Run the code below to see an example with math.exp().", "_____no_output_____" ] ], [ [ "# GRADED FUNCTION: basic_sigmoid\n\nimport math\n\ndef basic_sigmoid(x):\n \"\"\"\n Compute sigmoid of x.\n\n Arguments:\n x -- A scalar\n\n Return:\n s -- sigmoid(x)\n \"\"\"\n \n ### START CODE HERE ### (≈ 1 line of code)\n s = 1/(1+math.exp(-1*x))\n ### END CODE HERE ###\n \n return s", "_____no_output_____" ], [ "basic_sigmoid(3)", "_____no_output_____" ] ], [ [ "**Expected Output**: \n<table style = \"width:40%\">\n <tr>\n <td>** basic_sigmoid(3) **</td> \n <td>0.9525741268224334 </td> \n </tr>\n\n</table>", "_____no_output_____" ], [ "Actually, we rarely use the \"math\" library in deep learning because the inputs of the functions are real numbers. In deep learning we mostly use matrices and vectors. This is why numpy is more useful. ", "_____no_output_____" ] ], [ [ "### One reason why we use \"numpy\" instead of \"math\" in Deep Learning ###\nx = [1, 2, 3]\nbasic_sigmoid(x) # you will see this give an error when you run it, because x is a vector.", "_____no_output_____" ] ], [ [ "In fact, if $ x = (x_1, x_2, ..., x_n)$ is a row vector then $np.exp(x)$ will apply the exponential function to every element of x. The output will thus be: $np.exp(x) = (e^{x_1}, e^{x_2}, ..., e^{x_n})$", "_____no_output_____" ] ], [ [ "import numpy as np\n\n# example of np.exp\nx = np.array([1, 2, 3])\nprint(np.exp(x)) # result is (exp(1), exp(2), exp(3))", "[ 2.71828183 7.3890561 20.08553692]\n" ] ], [ [ "Furthermore, if x is a vector, then a Python operation such as $s = x + 3$ or $s = \\frac{1}{x}$ will output s as a vector of the same size as x.", "_____no_output_____" ] ], [ [ "# example of vector operation\nx = np.array([1, 2, 3])\nprint (x + 3)", "[4 5 6]\n" ] ], [ [ "Any time you need more info on a numpy function, we encourage you to look at [the official documentation](https://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.exp.html). \n\nYou can also create a new cell in the notebook and write `np.exp?` (for example) to get quick access to the documentation.\n\n**Exercise**: Implement the sigmoid function using numpy. \n\n**Instructions**: x could now be either a real number, a vector, or a matrix. The data structures we use in numpy to represent these shapes (vectors, matrices...) are called numpy arrays. You don't need to know more for now.\n$$ \\text{For } x \\in \\mathbb{R}^n \\text{, } sigmoid(x) = sigmoid\\begin{pmatrix}\n x_1 \\\\\n x_2 \\\\\n ... \\\\\n x_n \\\\\n\\end{pmatrix} = \\begin{pmatrix}\n \\frac{1}{1+e^{-x_1}} \\\\\n \\frac{1}{1+e^{-x_2}} \\\\\n ... \\\\\n \\frac{1}{1+e^{-x_n}} \\\\\n\\end{pmatrix}\\tag{1} $$", "_____no_output_____" ] ], [ [ "# GRADED FUNCTION: sigmoid\n\nimport numpy as np # this means you can access numpy functions by writing np.function() instead of numpy.function()\n\ndef sigmoid(x):\n \"\"\"\n Compute the sigmoid of x\n\n Arguments:\n x -- A scalar or numpy array of any size\n\n Return:\n s -- sigmoid(x)\n \"\"\"\n \n ### START CODE HERE ### (≈ 1 line of code)\n s = 1/(1+np.exp(-1*x))\n ### END CODE HERE ###\n \n return s", "_____no_output_____" ], [ "x = np.array([1, 2, 3])\nsigmoid(x)", "_____no_output_____" ] ], [ [ "**Expected Output**: \n<table>\n <tr> \n <td> **sigmoid([1,2,3])**</td> \n <td> array([ 0.73105858, 0.88079708, 0.95257413]) </td> \n </tr>\n</table> \n", "_____no_output_____" ], [ "### 1.2 - Sigmoid gradient\n\nAs you've seen in lecture, you will need to compute gradients to optimize loss functions using backpropagation. Let's code your first gradient function.\n\n**Exercise**: Implement the function sigmoid_grad() to compute the gradient of the sigmoid function with respect to its input x. The formula is: $$sigmoid\\_derivative(x) = \\sigma'(x) = \\sigma(x) (1 - \\sigma(x))\\tag{2}$$\nYou often code this function in two steps:\n1. Set s to be the sigmoid of x. You might find your sigmoid(x) function useful.\n2. Compute $\\sigma'(x) = s(1-s)$", "_____no_output_____" ] ], [ [ "# GRADED FUNCTION: sigmoid_derivative\n\ndef sigmoid_derivative(x):\n \"\"\"\n Compute the gradient (also called the slope or derivative) of the sigmoid function with respect to its input x.\n You can store the output of the sigmoid function into variables and then use it to calculate the gradient.\n \n Arguments:\n x -- A scalar or numpy array\n\n Return:\n ds -- Your computed gradient.\n \"\"\"\n \n ### START CODE HERE ### (≈ 2 lines of code)\n s = sigmoid(x)\n ds = s*(1-s)\n ### END CODE HERE ###\n \n return ds", "_____no_output_____" ], [ "x = np.array([1, 2, 3])\nprint (\"sigmoid_derivative(x) = \" + str(sigmoid_derivative(x)))", "sigmoid_derivative(x) = [ 0.19661193 0.10499359 0.04517666]\n" ] ], [ [ "**Expected Output**: \n\n\n<table>\n <tr> \n <td> **sigmoid_derivative([1,2,3])**</td> \n <td> [ 0.19661193 0.10499359 0.04517666] </td> \n </tr>\n</table> \n\n", "_____no_output_____" ], [ "### 1.3 - Reshaping arrays ###\n\nTwo common numpy functions used in deep learning are [np.shape](https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.shape.html) and [np.reshape()](https://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html). \n- X.shape is used to get the shape (dimension) of a matrix/vector X. \n- X.reshape(...) is used to reshape X into some other dimension. \n\nFor example, in computer science, an image is represented by a 3D array of shape $(length, height, depth = 3)$. However, when you read an image as the input of an algorithm you convert it to a vector of shape $(length*height*3, 1)$. In other words, you \"unroll\", or reshape, the 3D array into a 1D vector.\n\n<img src=\"images/image2vector_kiank.png\" style=\"width:500px;height:300;\">\n\n**Exercise**: Implement `image2vector()` that takes an input of shape (length, height, 3) and returns a vector of shape (length\\*height\\*3, 1). For example, if you would like to reshape an array v of shape (a, b, c) into a vector of shape (a*b,c) you would do:\n``` python\nv = v.reshape((v.shape[0]*v.shape[1], v.shape[2])) # v.shape[0] = a ; v.shape[1] = b ; v.shape[2] = c\n```\n- Please don't hardcode the dimensions of image as a constant. Instead look up the quantities you need with `image.shape[0]`, etc. ", "_____no_output_____" ] ], [ [ "# GRADED FUNCTION: image2vector\ndef image2vector(image):\n \"\"\"\n Argument:\n image -- a numpy array of shape (length, height, depth)\n \n Returns:\n v -- a vector of shape (length*height*depth, 1)\n \"\"\"\n \n ### START CODE HERE ### (≈ 1 line of code)\n v = image.reshape((image.shape[0]*image.shape[2]*3), 1)\n ### END CODE HERE ###\n \n return v", "_____no_output_____" ], [ "# This is a 3 by 3 by 2 array, typically images will be (num_px_x, num_px_y,3) where 3 represents the RGB values\nimage = np.array([[[ 0.67826139, 0.29380381],\n [ 0.90714982, 0.52835647],\n [ 0.4215251 , 0.45017551]],\n\n [[ 0.92814219, 0.96677647],\n [ 0.85304703, 0.52351845],\n [ 0.19981397, 0.27417313]],\n\n [[ 0.60659855, 0.00533165],\n [ 0.10820313, 0.49978937],\n [ 0.34144279, 0.94630077]]])\n\nprint (\"image2vector(image) = \" + str(image2vector(image)))", "image2vector(image) = [[ 0.67826139]\n [ 0.29380381]\n [ 0.90714982]\n [ 0.52835647]\n [ 0.4215251 ]\n [ 0.45017551]\n [ 0.92814219]\n [ 0.96677647]\n [ 0.85304703]\n [ 0.52351845]\n [ 0.19981397]\n [ 0.27417313]\n [ 0.60659855]\n [ 0.00533165]\n [ 0.10820313]\n [ 0.49978937]\n [ 0.34144279]\n [ 0.94630077]]\n" ] ], [ [ "**Expected Output**: \n\n\n<table style=\"width:100%\">\n <tr> \n <td> **image2vector(image)** </td> \n <td> [[ 0.67826139]\n [ 0.29380381]\n [ 0.90714982]\n [ 0.52835647]\n [ 0.4215251 ]\n [ 0.45017551]\n [ 0.92814219]\n [ 0.96677647]\n [ 0.85304703]\n [ 0.52351845]\n [ 0.19981397]\n [ 0.27417313]\n [ 0.60659855]\n [ 0.00533165]\n [ 0.10820313]\n [ 0.49978937]\n [ 0.34144279]\n [ 0.94630077]]</td> \n </tr>\n \n \n</table>", "_____no_output_____" ], [ "### 1.4 - Normalizing rows\n\nAnother common technique we use in Machine Learning and Deep Learning is to normalize our data. It often leads to a better performance because gradient descent converges faster after normalization. Here, by normalization we mean changing x to $ \\frac{x}{\\| x\\|} $ (dividing each row vector of x by its norm).\n\nFor example, if $$x = \n\\begin{bmatrix}\n 0 & 3 & 4 \\\\\n 2 & 6 & 4 \\\\\n\\end{bmatrix}\\tag{3}$$ then $$\\| x\\| = np.linalg.norm(x, axis = 1, keepdims = True) = \\begin{bmatrix}\n 5 \\\\\n \\sqrt{56} \\\\\n\\end{bmatrix}\\tag{4} $$and $$ x\\_normalized = \\frac{x}{\\| x\\|} = \\begin{bmatrix}\n 0 & \\frac{3}{5} & \\frac{4}{5} \\\\\n \\frac{2}{\\sqrt{56}} & \\frac{6}{\\sqrt{56}} & \\frac{4}{\\sqrt{56}} \\\\\n\\end{bmatrix}\\tag{5}$$ Note that you can divide matrices of different sizes and it works fine: this is called broadcasting and you're going to learn about it in part 5.\n\n\n**Exercise**: Implement normalizeRows() to normalize the rows of a matrix. After applying this function to an input matrix x, each row of x should be a vector of unit length (meaning length 1).", "_____no_output_____" ] ], [ [ "# GRADED FUNCTION: normalizeRows\n\ndef normalizeRows(x):\n \"\"\"\n Implement a function that normalizes each row of the matrix x (to have unit length).\n \n Argument:\n x -- A numpy matrix of shape (n, m)\n \n Returns:\n x -- The normalized (by row) numpy matrix. You are allowed to modify x.\n \"\"\"\n \n ### START CODE HERE ### (≈ 2 lines of code)\n # Compute x_norm as the norm 2 of x. Use np.linalg.norm(..., ord = 2, axis = ..., keepdims = True)\n x_norm = np.linalg.norm(x, axis=1, keepdims = True)\n \n # Divide x by its norm.\n x = x/x_norm\n ### END CODE HERE ###\n\n return x", "_____no_output_____" ], [ "x = np.array([\n [0, 3, 4],\n [1, 6, 4]])\nprint(\"normalizeRows(x) = \" + str(normalizeRows(x)))", "normalizeRows(x) = [[ 0. 0.6 0.8 ]\n [ 0.13736056 0.82416338 0.54944226]]\n" ] ], [ [ "**Expected Output**: \n\n<table style=\"width:60%\">\n\n <tr> \n <td> **normalizeRows(x)** </td> \n <td> [[ 0. 0.6 0.8 ]\n [ 0.13736056 0.82416338 0.54944226]]</td> \n </tr>\n \n \n</table>", "_____no_output_____" ], [ "**Note**:\nIn normalizeRows(), you can try to print the shapes of x_norm and x, and then rerun the assessment. You'll find out that they have different shapes. This is normal given that x_norm takes the norm of each row of x. So x_norm has the same number of rows but only 1 column. So how did it work when you divided x by x_norm? This is called broadcasting and we'll talk about it now! ", "_____no_output_____" ], [ "### 1.5 - Broadcasting and the softmax function ####\nA very important concept to understand in numpy is \"broadcasting\". It is very useful for performing mathematical operations between arrays of different shapes. For the full details on broadcasting, you can read the official [broadcasting documentation](http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html).", "_____no_output_____" ], [ "**Exercise**: Implement a softmax function using numpy. You can think of softmax as a normalizing function used when your algorithm needs to classify two or more classes. You will learn more about softmax in the second course of this specialization.\n\n**Instructions**:\n- $ \\text{for } x \\in \\mathbb{R}^{1\\times n} \\text{, } softmax(x) = softmax(\\begin{bmatrix}\n x_1 &&\n x_2 &&\n ... &&\n x_n \n\\end{bmatrix}) = \\begin{bmatrix}\n \\frac{e^{x_1}}{\\sum_{j}e^{x_j}} &&\n \\frac{e^{x_2}}{\\sum_{j}e^{x_j}} &&\n ... &&\n \\frac{e^{x_n}}{\\sum_{j}e^{x_j}} \n\\end{bmatrix} $ \n\n- $\\text{for a matrix } x \\in \\mathbb{R}^{m \\times n} \\text{, $x_{ij}$ maps to the element in the $i^{th}$ row and $j^{th}$ column of $x$, thus we have: }$ $$softmax(x) = softmax\\begin{bmatrix}\n x_{11} & x_{12} & x_{13} & \\dots & x_{1n} \\\\\n x_{21} & x_{22} & x_{23} & \\dots & x_{2n} \\\\\n \\vdots & \\vdots & \\vdots & \\ddots & \\vdots \\\\\n x_{m1} & x_{m2} & x_{m3} & \\dots & x_{mn}\n\\end{bmatrix} = \\begin{bmatrix}\n \\frac{e^{x_{11}}}{\\sum_{j}e^{x_{1j}}} & \\frac{e^{x_{12}}}{\\sum_{j}e^{x_{1j}}} & \\frac{e^{x_{13}}}{\\sum_{j}e^{x_{1j}}} & \\dots & \\frac{e^{x_{1n}}}{\\sum_{j}e^{x_{1j}}} \\\\\n \\frac{e^{x_{21}}}{\\sum_{j}e^{x_{2j}}} & \\frac{e^{x_{22}}}{\\sum_{j}e^{x_{2j}}} & \\frac{e^{x_{23}}}{\\sum_{j}e^{x_{2j}}} & \\dots & \\frac{e^{x_{2n}}}{\\sum_{j}e^{x_{2j}}} \\\\\n \\vdots & \\vdots & \\vdots & \\ddots & \\vdots \\\\\n \\frac{e^{x_{m1}}}{\\sum_{j}e^{x_{mj}}} & \\frac{e^{x_{m2}}}{\\sum_{j}e^{x_{mj}}} & \\frac{e^{x_{m3}}}{\\sum_{j}e^{x_{mj}}} & \\dots & \\frac{e^{x_{mn}}}{\\sum_{j}e^{x_{mj}}}\n\\end{bmatrix} = \\begin{pmatrix}\n softmax\\text{(first row of x)} \\\\\n softmax\\text{(second row of x)} \\\\\n ... \\\\\n softmax\\text{(last row of x)} \\\\\n\\end{pmatrix} $$", "_____no_output_____" ] ], [ [ "# GRADED FUNCTION: softmax\n\ndef softmax(x):\n \"\"\"Calculates the softmax for each row of the input x.\n\n Your code should work for a row vector and also for matrices of shape (n, m).\n\n Argument:\n x -- A numpy matrix of shape (n,m)\n\n Returns:\n s -- A numpy matrix equal to the softmax of x, of shape (n,m)\n \"\"\"\n \n ### START CODE HERE ### (≈ 3 lines of code)\n # Apply exp() element-wise to x. Use np.exp(...).\n x_exp = np.exp(x)\n\n # Create a vector x_sum that sums each row of x_exp. Use np.sum(..., axis = 1, keepdims = True).\n x_sum = np.sum(x_exp, axis = 1, keepdims = True)\n \n # Compute softmax(x) by dividing x_exp by x_sum. It should automatically use numpy broadcasting.\n s = x_exp/x_sum\n\n ### END CODE HERE ###\n \n return s", "_____no_output_____" ], [ "x = np.array([\n [9, 2, 5, 0, 0],\n [7, 5, 0, 0 ,0]])\nprint(\"softmax(x) = \" + str(softmax(x)))", "softmax(x) = [[ 9.80897665e-01 8.94462891e-04 1.79657674e-02 1.21052389e-04\n 1.21052389e-04]\n [ 8.78679856e-01 1.18916387e-01 8.01252314e-04 8.01252314e-04\n 8.01252314e-04]]\n" ] ], [ [ "**Expected Output**:\n\n<table style=\"width:60%\">\n\n <tr> \n <td> **softmax(x)** </td> \n <td> [[ 9.80897665e-01 8.94462891e-04 1.79657674e-02 1.21052389e-04\n 1.21052389e-04]\n [ 8.78679856e-01 1.18916387e-01 8.01252314e-04 8.01252314e-04\n 8.01252314e-04]]</td> \n </tr>\n</table>\n", "_____no_output_____" ], [ "**Note**:\n- If you print the shapes of x_exp, x_sum and s above and rerun the assessment cell, you will see that x_sum is of shape (2,1) while x_exp and s are of shape (2,5). **x_exp/x_sum** works due to python broadcasting.\n\nCongratulations! You now have a pretty good understanding of python numpy and have implemented a few useful functions that you will be using in deep learning.", "_____no_output_____" ], [ "<font color='blue'>\n**What you need to remember:**\n- np.exp(x) works for any np.array x and applies the exponential function to every coordinate\n- the sigmoid function and its gradient\n- image2vector is commonly used in deep learning\n- np.reshape is widely used. In the future, you'll see that keeping your matrix/vector dimensions straight will go toward eliminating a lot of bugs. \n- numpy has efficient built-in functions\n- broadcasting is extremely useful", "_____no_output_____" ], [ "## 2) Vectorization", "_____no_output_____" ], [ "\nIn deep learning, you deal with very large datasets. Hence, a non-computationally-optimal function can become a huge bottleneck in your algorithm and can result in a model that takes ages to run. To make sure that your code is computationally efficient, you will use vectorization. For example, try to tell the difference between the following implementations of the dot/outer/elementwise product.", "_____no_output_____" ] ], [ [ "import time\n\nx1 = [9, 2, 5, 0, 0, 7, 5, 0, 0, 0, 9, 2, 5, 0, 0]\nx2 = [9, 2, 2, 9, 0, 9, 2, 5, 0, 0, 9, 2, 5, 0, 0]\n\n### CLASSIC DOT PRODUCT OF VECTORS IMPLEMENTATION ###\ntic = time.process_time()\ndot = 0\nfor i in range(len(x1)):\n dot+= x1[i]*x2[i]\ntoc = time.process_time()\nprint (\"dot = \" + str(dot) + \"\\n ----- Computation time = \" + str(1000*(toc - tic)) + \"ms\")\n\n### CLASSIC OUTER PRODUCT IMPLEMENTATION ###\ntic = time.process_time()\nouter = np.zeros((len(x1),len(x2))) # we create a len(x1)*len(x2) matrix with only zeros\nfor i in range(len(x1)):\n for j in range(len(x2)):\n outer[i,j] = x1[i]*x2[j]\ntoc = time.process_time()\nprint (\"outer = \" + str(outer) + \"\\n ----- Computation time = \" + str(1000*(toc - tic)) + \"ms\")\n\n### CLASSIC ELEMENTWISE IMPLEMENTATION ###\ntic = time.process_time()\nmul = np.zeros(len(x1))\nfor i in range(len(x1)):\n mul[i] = x1[i]*x2[i]\ntoc = time.process_time()\nprint (\"elementwise multiplication = \" + str(mul) + \"\\n ----- Computation time = \" + str(1000*(toc - tic)) + \"ms\")\n\n### CLASSIC GENERAL DOT PRODUCT IMPLEMENTATION ###\nW = np.random.rand(3,len(x1)) # Random 3*len(x1) numpy array\ntic = time.process_time()\ngdot = np.zeros(W.shape[0])\nfor i in range(W.shape[0]):\n for j in range(len(x1)):\n gdot[i] += W[i,j]*x1[j]\ntoc = time.process_time()\nprint (\"gdot = \" + str(gdot) + \"\\n ----- Computation time = \" + str(1000*(toc - tic)) + \"ms\")", "dot = 278\n ----- Computation time = 0.17164100000011118ms\nouter = [[ 81. 18. 18. 81. 0. 81. 18. 45. 0. 0. 81. 18. 45. 0.\n 0.]\n [ 18. 4. 4. 18. 0. 18. 4. 10. 0. 0. 18. 4. 10. 0.\n 0.]\n [ 45. 10. 10. 45. 0. 45. 10. 25. 0. 0. 45. 10. 25. 0.\n 0.]\n [ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0.]\n [ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0.]\n [ 63. 14. 14. 63. 0. 63. 14. 35. 0. 0. 63. 14. 35. 0.\n 0.]\n [ 45. 10. 10. 45. 0. 45. 10. 25. 0. 0. 45. 10. 25. 0.\n 0.]\n [ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0.]\n [ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0.]\n [ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0.]\n [ 81. 18. 18. 81. 0. 81. 18. 45. 0. 0. 81. 18. 45. 0.\n 0.]\n [ 18. 4. 4. 18. 0. 18. 4. 10. 0. 0. 18. 4. 10. 0.\n 0.]\n [ 45. 10. 10. 45. 0. 45. 10. 25. 0. 0. 45. 10. 25. 0.\n 0.]\n [ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0.]\n [ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.\n 0.]]\n ----- Computation time = 0.3644930000001878ms\nelementwise multiplication = [ 81. 4. 10. 0. 0. 63. 10. 0. 0. 0. 81. 4. 25. 0. 0.]\n ----- Computation time = 0.18332000000009785ms\ngdot = [ 26.78929192 18.98909621 16.49198788]\n ----- Computation time = 0.25575599999982934ms\n" ], [ "x1 = [9, 2, 5, 0, 0, 7, 5, 0, 0, 0, 9, 2, 5, 0, 0]\nx2 = [9, 2, 2, 9, 0, 9, 2, 5, 0, 0, 9, 2, 5, 0, 0]\n\n### VECTORIZED DOT PRODUCT OF VECTORS ###\ntic = time.process_time()\ndot = np.dot(x1,x2)\ntoc = time.process_time()\nprint (\"dot = \" + str(dot) + \"\\n ----- Computation time = \" + str(1000*(toc - tic)) + \"ms\")\n\n### VECTORIZED OUTER PRODUCT ###\ntic = time.process_time()\nouter = np.outer(x1,x2)\ntoc = time.process_time()\nprint (\"outer = \" + str(outer) + \"\\n ----- Computation time = \" + str(1000*(toc - tic)) + \"ms\")\n\n### VECTORIZED ELEMENTWISE MULTIPLICATION ###\ntic = time.process_time()\nmul = np.multiply(x1,x2)\ntoc = time.process_time()\nprint (\"elementwise multiplication = \" + str(mul) + \"\\n ----- Computation time = \" + str(1000*(toc - tic)) + \"ms\")\n\n### VECTORIZED GENERAL DOT PRODUCT ###\ntic = time.process_time()\ndot = np.dot(W,x1)\ntoc = time.process_time()\nprint (\"gdot = \" + str(dot) + \"\\n ----- Computation time = \" + str(1000*(toc - tic)) + \"ms\")", "dot = 278\n ----- Computation time = 0.19262100000005944ms\nouter = [[81 18 18 81 0 81 18 45 0 0 81 18 45 0 0]\n [18 4 4 18 0 18 4 10 0 0 18 4 10 0 0]\n [45 10 10 45 0 45 10 25 0 0 45 10 25 0 0]\n [ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n [ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n [63 14 14 63 0 63 14 35 0 0 63 14 35 0 0]\n [45 10 10 45 0 45 10 25 0 0 45 10 25 0 0]\n [ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n [ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n [ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n [81 18 18 81 0 81 18 45 0 0 81 18 45 0 0]\n [18 4 4 18 0 18 4 10 0 0 18 4 10 0 0]\n [45 10 10 45 0 45 10 25 0 0 45 10 25 0 0]\n [ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n [ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]]\n ----- Computation time = 0.14469999999988659ms\nelementwise multiplication = [81 4 10 0 0 63 10 0 0 0 81 4 25 0 0]\n ----- Computation time = 0.12715100000004753ms\ngdot = [ 26.78929192 18.98909621 16.49198788]\n ----- Computation time = 0.2968430000001021ms\n" ] ], [ [ "As you may have noticed, the vectorized implementation is much cleaner and more efficient. For bigger vectors/matrices, the differences in running time become even bigger. \n\n**Note** that `np.dot()` performs a matrix-matrix or matrix-vector multiplication. This is different from `np.multiply()` and the `*` operator (which is equivalent to `.*` in Matlab/Octave), which performs an element-wise multiplication.", "_____no_output_____" ], [ "### 2.1 Implement the L1 and L2 loss functions\n\n**Exercise**: Implement the numpy vectorized version of the L1 loss. You may find the function abs(x) (absolute value of x) useful.\n\n**Reminder**:\n- The loss is used to evaluate the performance of your model. The bigger your loss is, the more different your predictions ($ \\hat{y} $) are from the true values ($y$). In deep learning, you use optimization algorithms like Gradient Descent to train your model and to minimize the cost.\n- L1 loss is defined as:\n$$\\begin{align*} & L_1(\\hat{y}, y) = \\sum_{i=0}^m|y^{(i)} - \\hat{y}^{(i)}| \\end{align*}\\tag{6}$$", "_____no_output_____" ] ], [ [ "# GRADED FUNCTION: L1\n\ndef L1(yhat, y):\n \"\"\"\n Arguments:\n yhat -- vector of size m (predicted labels)\n y -- vector of size m (true labels)\n \n Returns:\n loss -- the value of the L1 loss function defined above\n \"\"\"\n \n ### START CODE HERE ### (≈ 1 line of code)\n loss = np.sum(abs(yhat - y),axis = 0, keepdims = True)\n ### END CODE HERE ###\n \n return loss", "_____no_output_____" ], [ "yhat = np.array([.9, 0.2, 0.1, .4, .9])\ny = np.array([1, 0, 0, 1, 1])\nprint(\"L1 = \" + str(L1(yhat,y)))", "L1 = [ 1.1]\n" ] ], [ [ "**Expected Output**:\n\n<table style=\"width:20%\">\n\n <tr> \n <td> **L1** </td> \n <td> 1.1 </td> \n </tr>\n</table>\n", "_____no_output_____" ], [ "**Exercise**: Implement the numpy vectorized version of the L2 loss. There are several way of implementing the L2 loss but you may find the function np.dot() useful. As a reminder, if $x = [x_1, x_2, ..., x_n]$, then `np.dot(x,x)` = $\\sum_{j=0}^n x_j^{2}$. \n\n- L2 loss is defined as $$\\begin{align*} & L_2(\\hat{y},y) = \\sum_{i=0}^m(y^{(i)} - \\hat{y}^{(i)})^2 \\end{align*}\\tag{7}$$", "_____no_output_____" ] ], [ [ "# GRADED FUNCTION: L2\n\ndef L2(yhat, y):\n \"\"\"\n Arguments:\n yhat -- vector of size m (predicted labels)\n y -- vector of size m (true labels)\n \n Returns:\n loss -- the value of the L2 loss function defined above\n \"\"\"\n \n ### START CODE HERE ### (≈ 1 line of code)\n loss = np.sum(abs(yhat - y)**2,axis = 0, keepdims = True)\n ### END CODE HERE ###\n \n return loss", "_____no_output_____" ], [ "yhat = np.array([.9, 0.2, 0.1, .4, .9])\ny = np.array([1, 0, 0, 1, 1])\nprint(\"L2 = \" + str(L2(yhat,y)))", "L2 = [ 0.43]\n" ] ], [ [ "**Expected Output**: \n<table style=\"width:20%\">\n <tr> \n <td> **L2** </td> \n <td> 0.43 </td> \n </tr>\n</table>", "_____no_output_____" ], [ "Congratulations on completing this assignment. We hope that this little warm-up exercise helps you in the future assignments, which will be more exciting and interesting!", "_____no_output_____" ], [ "<font color='blue'>\n**What to remember:**\n- Vectorization is very important in deep learning. It provides computational efficiency and clarity.\n- You have reviewed the L1 and L2 loss.\n- You are familiar with many numpy functions such as np.sum, np.dot, np.multiply, np.maximum, etc...", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown" ]
[ [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown" ], [ "code", "code" ], [ "markdown", "markdown", "markdown" ] ]
4a0eac1743ef2ffc9601febe96a09c81f29c5dca
224,142
ipynb
Jupyter Notebook
experiments/cnn_3/oracle.run1-oracle.run2/trials/7/trial.ipynb
stevester94/csc500-notebooks
4c1b04c537fe233a75bed82913d9d84985a89177
[ "MIT" ]
null
null
null
experiments/cnn_3/oracle.run1-oracle.run2/trials/7/trial.ipynb
stevester94/csc500-notebooks
4c1b04c537fe233a75bed82913d9d84985a89177
[ "MIT" ]
null
null
null
experiments/cnn_3/oracle.run1-oracle.run2/trials/7/trial.ipynb
stevester94/csc500-notebooks
4c1b04c537fe233a75bed82913d9d84985a89177
[ "MIT" ]
null
null
null
123.698675
73,448
0.812489
[ [ [ "import os, json, sys, time, random\nimport numpy as np\nimport torch\nfrom easydict import EasyDict\nfrom math import floor\nfrom easydict import EasyDict\n\nfrom steves_utils.vanilla_train_eval_test_jig import Vanilla_Train_Eval_Test_Jig\n\nfrom steves_utils.torch_utils import get_dataset_metrics, independent_accuracy_assesment\nfrom steves_models.configurable_vanilla import Configurable_Vanilla\nfrom steves_utils.torch_sequential_builder import build_sequential\nfrom steves_utils.lazy_map import Lazy_Map\nfrom steves_utils.sequence_aggregator import Sequence_Aggregator\n\nfrom steves_utils.stratified_dataset.traditional_accessor import Traditional_Accessor_Factory\n\nfrom steves_utils.cnn_do_report import (\n get_loss_curve,\n get_results_table,\n get_parameters_table,\n get_domain_accuracies,\n)\n\nfrom steves_utils.torch_utils import (\n confusion_by_domain_over_dataloader,\n independent_accuracy_assesment\n)\n\nfrom steves_utils.utils_v2 import (\n per_domain_accuracy_from_confusion,\n get_datasets_base_path\n)\n\n# from steves_utils.ptn_do_report import TBD", "_____no_output_____" ], [ "required_parameters = {\n \"experiment_name\",\n \"lr\",\n \"device\",\n \"dataset_seed\",\n \"seed\",\n \"labels\",\n \"domains_target\",\n \"domains_source\",\n \"num_examples_per_domain_per_label_source\",\n \"num_examples_per_domain_per_label_target\",\n \"batch_size\",\n \"n_epoch\",\n \"patience\",\n \"criteria_for_best\",\n \"normalize_source\",\n \"normalize_target\",\n \"x_net\",\n \"NUM_LOGS_PER_EPOCH\",\n \"BEST_MODEL_PATH\",\n \"pickle_name_source\",\n \"pickle_name_target\",\n \"torch_default_dtype\",\n}", "_____no_output_____" ], [ "from steves_utils.ORACLE.utils_v2 import (\n ALL_SERIAL_NUMBERS,\n ALL_DISTANCES_FEET_NARROWED,\n)\n\nstandalone_parameters = {}\nstandalone_parameters[\"experiment_name\"] = \"MANUAL CORES CNN\"\nstandalone_parameters[\"lr\"] = 0.0001\nstandalone_parameters[\"device\"] = \"cuda\"\n\nstandalone_parameters[\"dataset_seed\"] = 1337\nstandalone_parameters[\"seed\"] = 1337\nstandalone_parameters[\"labels\"] = ALL_SERIAL_NUMBERS\n\nstandalone_parameters[\"domains_source\"] = [8,32,50]\nstandalone_parameters[\"domains_target\"] = [14,20,26,38,44,]\n\nstandalone_parameters[\"num_examples_per_domain_per_label_source\"]=-1\nstandalone_parameters[\"num_examples_per_domain_per_label_target\"]=-1\n\nstandalone_parameters[\"pickle_name_source\"] = \"oracle.Run1_framed_2000Examples_stratified_ds.2022A.pkl\"\nstandalone_parameters[\"pickle_name_target\"] = \"oracle.Run2_framed_2000Examples_stratified_ds.2022A.pkl\"\n\nstandalone_parameters[\"torch_default_dtype\"] = \"torch.float32\" \n\nstandalone_parameters[\"batch_size\"]=128\n\nstandalone_parameters[\"n_epoch\"] = 3\n\nstandalone_parameters[\"patience\"] = 10\n\nstandalone_parameters[\"criteria_for_best\"] = \"target_accuracy\"\nstandalone_parameters[\"normalize_source\"] = False\nstandalone_parameters[\"normalize_target\"] = False\n\nstandalone_parameters[\"x_net\"] = [\n {\"class\": \"nnReshape\", \"kargs\": {\"shape\":[-1, 1, 2, 256]}},\n {\"class\": \"Conv2d\", \"kargs\": { \"in_channels\":1, \"out_channels\":256, \"kernel_size\":(1,7), \"bias\":False, \"padding\":(0,3), },},\n {\"class\": \"ReLU\", \"kargs\": {\"inplace\": True}},\n {\"class\": \"BatchNorm2d\", \"kargs\": {\"num_features\":256}},\n\n {\"class\": \"Conv2d\", \"kargs\": { \"in_channels\":256, \"out_channels\":80, \"kernel_size\":(2,7), \"bias\":True, \"padding\":(0,3), },},\n {\"class\": \"ReLU\", \"kargs\": {\"inplace\": True}},\n {\"class\": \"BatchNorm2d\", \"kargs\": {\"num_features\":80}},\n {\"class\": \"Flatten\", \"kargs\": {}},\n\n {\"class\": \"Linear\", \"kargs\": {\"in_features\": 80*256, \"out_features\": 256}}, # 80 units per IQ pair\n {\"class\": \"ReLU\", \"kargs\": {\"inplace\": True}},\n {\"class\": \"BatchNorm1d\", \"kargs\": {\"num_features\":256}},\n\n {\"class\": \"Linear\", \"kargs\": {\"in_features\": 256, \"out_features\": len(standalone_parameters[\"labels\"])}},\n]\n\nstandalone_parameters[\"NUM_LOGS_PER_EPOCH\"] = 10\nstandalone_parameters[\"BEST_MODEL_PATH\"] = \"./best_model.pth\"", "_____no_output_____" ], [ "# Parameters\nparameters = {\n \"experiment_name\": \"cnn_3:oracle.run1-oracle.run2\",\n \"domains_source\": [8, 32, 50, 14, 20, 26, 38, 44],\n \"domains_target\": [8, 32, 50, 14, 20, 26, 38, 44],\n \"labels\": [\n \"3123D52\",\n \"3123D65\",\n \"3123D79\",\n \"3123D80\",\n \"3123D54\",\n \"3123D70\",\n \"3123D7B\",\n \"3123D89\",\n \"3123D58\",\n \"3123D76\",\n \"3123D7D\",\n \"3123EFE\",\n \"3123D64\",\n \"3123D78\",\n \"3123D7E\",\n \"3124E4A\",\n ],\n \"pickle_name_source\": \"oracle.Run1_10kExamples_stratified_ds.2022A.pkl\",\n \"pickle_name_target\": \"oracle.Run2_10kExamples_stratified_ds.2022A.pkl\",\n \"device\": \"cuda\",\n \"lr\": 0.0001,\n \"batch_size\": 128,\n \"normalize_source\": False,\n \"normalize_target\": False,\n \"num_examples_per_domain_per_label_source\": -1,\n \"num_examples_per_domain_per_label_target\": -1,\n \"torch_default_dtype\": \"torch.float32\",\n \"n_epoch\": 50,\n \"patience\": 3,\n \"criteria_for_best\": \"target_accuracy\",\n \"x_net\": [\n {\"class\": \"nnReshape\", \"kargs\": {\"shape\": [-1, 1, 2, 256]}},\n {\n \"class\": \"Conv2d\",\n \"kargs\": {\n \"in_channels\": 1,\n \"out_channels\": 256,\n \"kernel_size\": [1, 7],\n \"bias\": False,\n \"padding\": [0, 3],\n },\n },\n {\"class\": \"ReLU\", \"kargs\": {\"inplace\": True}},\n {\"class\": \"BatchNorm2d\", \"kargs\": {\"num_features\": 256}},\n {\n \"class\": \"Conv2d\",\n \"kargs\": {\n \"in_channels\": 256,\n \"out_channels\": 80,\n \"kernel_size\": [2, 7],\n \"bias\": True,\n \"padding\": [0, 3],\n },\n },\n {\"class\": \"ReLU\", \"kargs\": {\"inplace\": True}},\n {\"class\": \"BatchNorm2d\", \"kargs\": {\"num_features\": 80}},\n {\"class\": \"Flatten\", \"kargs\": {}},\n {\"class\": \"Linear\", \"kargs\": {\"in_features\": 20480, \"out_features\": 256}},\n {\"class\": \"ReLU\", \"kargs\": {\"inplace\": True}},\n {\"class\": \"BatchNorm1d\", \"kargs\": {\"num_features\": 256}},\n {\"class\": \"Linear\", \"kargs\": {\"in_features\": 256, \"out_features\": 16}},\n ],\n \"NUM_LOGS_PER_EPOCH\": 10,\n \"BEST_MODEL_PATH\": \"./best_model.pth\",\n \"dataset_seed\": 500,\n \"seed\": 500,\n}\n", "_____no_output_____" ], [ "# Set this to True if you want to run this template directly\nSTANDALONE = False\nif STANDALONE:\n print(\"parameters not injected, running with standalone_parameters\")\n parameters = standalone_parameters\n\nif not 'parameters' in locals() and not 'parameters' in globals():\n raise Exception(\"Parameter injection failed\")\n\n#Use an easy dict for all the parameters\np = EasyDict(parameters)\n\nsupplied_keys = set(p.keys())\n\nif supplied_keys != required_parameters:\n print(\"Parameters are incorrect\")\n if len(supplied_keys - required_parameters)>0: print(\"Shouldn't have:\", str(supplied_keys - required_parameters))\n if len(required_parameters - supplied_keys)>0: print(\"Need to have:\", str(required_parameters - supplied_keys))\n raise RuntimeError(\"Parameters are incorrect\")\n\n", "_____no_output_____" ], [ "###################################\n# Set the RNGs and make it all deterministic\n###################################\nnp.random.seed(p.seed)\nrandom.seed(p.seed)\ntorch.manual_seed(p.seed)\n\ntorch.use_deterministic_algorithms(True) ", "_____no_output_____" ], [ "torch.set_default_dtype(eval(p.torch_default_dtype))", "_____no_output_____" ], [ "###################################\n# Build the network(s)\n# Note: It's critical to do this AFTER setting the RNG\n###################################\nx_net = build_sequential(p.x_net)", "_____no_output_____" ], [ "start_time_secs = time.time()", "_____no_output_____" ], [ "def wrap_in_dataloader(p, ds):\n return torch.utils.data.DataLoader(\n ds,\n batch_size=p.batch_size,\n shuffle=True,\n num_workers=1,\n persistent_workers=True,\n prefetch_factor=50,\n pin_memory=True\n )\n\ntaf_source = Traditional_Accessor_Factory(\n labels=p.labels,\n domains=p.domains_source,\n num_examples_per_domain_per_label=p.num_examples_per_domain_per_label_source,\n pickle_path=os.path.join(get_datasets_base_path(), p.pickle_name_source),\n seed=p.dataset_seed\n)\ntrain_original_source, val_original_source, test_original_source = \\\n taf_source.get_train(), taf_source.get_val(), taf_source.get_test()\n\n\ntaf_target = Traditional_Accessor_Factory(\n labels=p.labels,\n domains=p.domains_target,\n num_examples_per_domain_per_label=p.num_examples_per_domain_per_label_source,\n pickle_path=os.path.join(get_datasets_base_path(), p.pickle_name_target),\n seed=p.dataset_seed\n)\ntrain_original_target, val_original_target, test_original_target = \\\n taf_target.get_train(), taf_target.get_val(), taf_target.get_test()\n\n\n# For CNN We only use X and Y. And we only train on the source.\n# Properly form the data using a transform lambda and Lazy_Map. Finally wrap them in a dataloader\n\ntransform_lambda = lambda ex: ex[:2] # Strip the tuple to just (x,y)\n\n\ntrain_processed_source = wrap_in_dataloader(\n p,\n Lazy_Map(train_original_source, transform_lambda)\n)\nval_processed_source = wrap_in_dataloader(\n p,\n Lazy_Map(val_original_source, transform_lambda)\n)\ntest_processed_source = wrap_in_dataloader(\n p,\n Lazy_Map(test_original_source, transform_lambda)\n)\n\ntrain_processed_target = wrap_in_dataloader(\n p,\n Lazy_Map(train_original_target, transform_lambda)\n)\nval_processed_target = wrap_in_dataloader(\n p,\n Lazy_Map(val_original_target, transform_lambda)\n)\ntest_processed_target = wrap_in_dataloader(\n p,\n Lazy_Map(test_original_target, transform_lambda)\n)\n\n\n\ndatasets = EasyDict({\n \"source\": {\n \"original\": {\"train\":train_original_source, \"val\":val_original_source, \"test\":test_original_source},\n \"processed\": {\"train\":train_processed_source, \"val\":val_processed_source, \"test\":test_processed_source}\n },\n \"target\": {\n \"original\": {\"train\":train_original_target, \"val\":val_original_target, \"test\":test_original_target},\n \"processed\": {\"train\":train_processed_target, \"val\":val_processed_target, \"test\":test_processed_target}\n },\n})", "_____no_output_____" ], [ "ep = next(iter(test_processed_target))\nep[0].dtype", "_____no_output_____" ], [ "model = Configurable_Vanilla(\n x_net=x_net,\n label_loss_object=torch.nn.NLLLoss(),\n learning_rate=p.lr\n)", "_____no_output_____" ], [ "jig = Vanilla_Train_Eval_Test_Jig(\n model=model,\n path_to_best_model=p.BEST_MODEL_PATH,\n device=p.device,\n label_loss_object=torch.nn.NLLLoss(),\n)\n\njig.train(\n train_iterable=datasets.source.processed.train,\n source_val_iterable=datasets.source.processed.val,\n target_val_iterable=datasets.target.processed.val,\n patience=p.patience,\n num_epochs=p.n_epoch,\n num_logs_per_epoch=p.NUM_LOGS_PER_EPOCH,\n criteria_for_best=p.criteria_for_best\n)", "epoch: 1, [batch: 1 / 7000], examples_per_second: 382.5972, train_label_loss: 2.7911, \n" ], [ "total_experiment_time_secs = time.time() - start_time_secs", "_____no_output_____" ], [ "source_test_label_accuracy, source_test_label_loss = jig.test(datasets.source.processed.test)\ntarget_test_label_accuracy, target_test_label_loss = jig.test(datasets.target.processed.test)\n\nsource_val_label_accuracy, source_val_label_loss = jig.test(datasets.source.processed.val)\ntarget_val_label_accuracy, target_val_label_loss = jig.test(datasets.target.processed.val)\n\nhistory = jig.get_history()\n\ntotal_epochs_trained = len(history[\"epoch_indices\"])\n\nval_dl = wrap_in_dataloader(p, Sequence_Aggregator((datasets.source.original.val, datasets.target.original.val)))\n\nconfusion = confusion_by_domain_over_dataloader(model, p.device, val_dl, forward_uses_domain=False)\nper_domain_accuracy = per_domain_accuracy_from_confusion(confusion)\n\n# Add a key to per_domain_accuracy for if it was a source domain\nfor domain, accuracy in per_domain_accuracy.items():\n per_domain_accuracy[domain] = {\n \"accuracy\": accuracy,\n \"source?\": domain in p.domains_source\n }\n\n# Do an independent accuracy assesment JUST TO BE SURE!\n# _source_test_label_accuracy = independent_accuracy_assesment(model, datasets.source.processed.test, p.device)\n# _target_test_label_accuracy = independent_accuracy_assesment(model, datasets.target.processed.test, p.device)\n# _source_val_label_accuracy = independent_accuracy_assesment(model, datasets.source.processed.val, p.device)\n# _target_val_label_accuracy = independent_accuracy_assesment(model, datasets.target.processed.val, p.device)\n\n# assert(_source_test_label_accuracy == source_test_label_accuracy)\n# assert(_target_test_label_accuracy == target_test_label_accuracy)\n# assert(_source_val_label_accuracy == source_val_label_accuracy)\n# assert(_target_val_label_accuracy == target_val_label_accuracy)\n\n###################################\n# Write out the results\n###################################\n\nexperiment = {\n \"experiment_name\": p.experiment_name,\n \"parameters\": p,\n \"results\": {\n \"source_test_label_accuracy\": source_test_label_accuracy,\n \"source_test_label_loss\": source_test_label_loss,\n \"target_test_label_accuracy\": target_test_label_accuracy,\n \"target_test_label_loss\": target_test_label_loss,\n \"source_val_label_accuracy\": source_val_label_accuracy,\n \"source_val_label_loss\": source_val_label_loss,\n \"target_val_label_accuracy\": target_val_label_accuracy,\n \"target_val_label_loss\": target_val_label_loss,\n \"total_epochs_trained\": total_epochs_trained,\n \"total_experiment_time_secs\": total_experiment_time_secs,\n \"confusion\": confusion,\n \"per_domain_accuracy\": per_domain_accuracy,\n },\n \"history\": history,\n \"dataset_metrics\": get_dataset_metrics(datasets, \"cnn\"),\n}", "_____no_output_____" ], [ "get_loss_curve(experiment)", "_____no_output_____" ], [ "get_results_table(experiment)", "_____no_output_____" ], [ "get_domain_accuracies(experiment)", "_____no_output_____" ], [ "print(\"Source Test Label Accuracy:\", experiment[\"results\"][\"source_test_label_accuracy\"], \"Target Test Label Accuracy:\", experiment[\"results\"][\"target_test_label_accuracy\"])\nprint(\"Source Val Label Accuracy:\", experiment[\"results\"][\"source_val_label_accuracy\"], \"Target Val Label Accuracy:\", experiment[\"results\"][\"target_val_label_accuracy\"])", "Source Test Label Accuracy: 0.7659322916666667 Target Test Label Accuracy: 0.5967916666666667\nSource Val Label Accuracy: 0.7659947916666666 Target Val Label Accuracy: 0.5966197916666667\n" ], [ "json.dumps(experiment)", "_____no_output_____" ] ] ]
[ "code" ]
[ [ "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code", "code" ] ]
4a0eace00d639e17b346160e340903ba5261de42
1,693
ipynb
Jupyter Notebook
index.ipynb
velaia/nbdev-start
f498a109b427790b979902d6d5905fcde87953eb
[ "Apache-2.0" ]
null
null
null
index.ipynb
velaia/nbdev-start
f498a109b427790b979902d6d5905fcde87953eb
[ "Apache-2.0" ]
1
2022-02-26T06:49:15.000Z
2022-02-26T06:49:15.000Z
index.ipynb
velaia/nbdev-start
f498a109b427790b979902d6d5905fcde87953eb
[ "Apache-2.0" ]
null
null
null
15.971698
81
0.480213
[ [ [ "#hide\nfrom nbdev_start.core import *", "_____no_output_____" ], [ "project_name = \"nbdev_start\"", "_____no_output_____" ] ], [ [ "# nbvdev_start Project\n\n> Helps me get started with nbdev.", "_____no_output_____" ], [ "This file will become your README and also the index of your documentation.", "_____no_output_____" ], [ "## Install", "_____no_output_____" ], [ "`pip install nbdev_start`", "_____no_output_____" ], [ "## How to use", "_____no_output_____" ], [ "Fill me in please! Don't forget code examples:", "_____no_output_____" ] ], [ [ "say_hello('Youna')", "_____no_output_____" ], [ "\n", "_____no_output_____" ] ] ]
[ "code", "markdown", "code" ]
[ [ "code", "code" ], [ "markdown", "markdown", "markdown", "markdown", "markdown", "markdown" ], [ "code", "code" ] ]
4a0eb0255df14f1abcfed086b331cb9193072436
19,647
ipynb
Jupyter Notebook
intro-to-pytorch/Part 6 - Saving and Loading Models.ipynb
ArtaFarahmand/deep-learning-v2-pytorch-master
4602e0862fbe47e615814cf6f595dfea27b5b2e2
[ "MIT" ]
null
null
null
intro-to-pytorch/Part 6 - Saving and Loading Models.ipynb
ArtaFarahmand/deep-learning-v2-pytorch-master
4602e0862fbe47e615814cf6f595dfea27b5b2e2
[ "MIT" ]
null
null
null
intro-to-pytorch/Part 6 - Saving and Loading Models.ipynb
ArtaFarahmand/deep-learning-v2-pytorch-master
4602e0862fbe47e615814cf6f595dfea27b5b2e2
[ "MIT" ]
null
null
null
49.240602
5,596
0.682954
[ [ [ "# Saving and Loading Models\n\nIn this notebook, I'll show you how to save and load models with PyTorch. This is important because you'll often want to load previously trained models to use in making predictions or to continue training on new data.", "_____no_output_____" ] ], [ [ "%matplotlib inline\n%config InlineBackend.figure_format = 'retina'\n\nimport matplotlib.pyplot as plt\n\nimport torch\nfrom torch import nn\nfrom torch import optim\nimport torch.nn.functional as F\nfrom torchvision import datasets, transforms\n\nimport helper\nimport fc_model", "_____no_output_____" ], [ "# Define a transform to normalize the data\ntransform = transforms.Compose([transforms.ToTensor(),\n transforms.Normalize((0.5,), (0.5,))])\n# Download and load the training data\ntrainset = datasets.FashionMNIST('~/.pytorch/F_MNIST_data/', download=True, train=True, transform=transform)\ntrainloader = torch.utils.data.DataLoader(trainset, batch_size=64, shuffle=True)\n\n# Download and load the test data\ntestset = datasets.FashionMNIST('~/.pytorch/F_MNIST_data/', download=True, train=False, transform=transform)\ntestloader = torch.utils.data.DataLoader(testset, batch_size=64, shuffle=True)", "_____no_output_____" ] ], [ [ "Here we can see one of the images.", "_____no_output_____" ] ], [ [ "image, label = next(iter(trainloader))\nhelper.imshow(image[0,:]);", "_____no_output_____" ] ], [ [ "# Train a network\n\nTo make things more concise here, I moved the model architecture and training code from the last part to a file called `fc_model`. Importing this, we can easily create a fully-connected network with `fc_model.Network`, and train the network using `fc_model.train`. I'll use this model (once it's trained) to demonstrate how we can save and load models.", "_____no_output_____" ] ], [ [ "# Create the network, define the criterion and optimizer\n\nmodel = fc_model.Network(784, 10, [512, 256, 128])\ncriterion = nn.NLLLoss()\noptimizer = optim.Adam(model.parameters(), lr=0.001)", "_____no_output_____" ], [ "fc_model.train(model, trainloader, testloader, criterion, optimizer, epochs=2)", "Epoch: 1/2.. Training Loss: 1.697.. Test Loss: 0.987.. Test Accuracy: 0.637\nEpoch: 1/2.. Training Loss: 1.006.. Test Loss: 0.740.. Test Accuracy: 0.728\nEpoch: 1/2.. Training Loss: 0.815.. Test Loss: 0.701.. Test Accuracy: 0.737\nEpoch: 1/2.. Training Loss: 0.805.. Test Loss: 0.630.. Test Accuracy: 0.764\nEpoch: 1/2.. Training Loss: 0.744.. Test Loss: 0.599.. Test Accuracy: 0.769\nEpoch: 1/2.. Training Loss: 0.713.. Test Loss: 0.606.. Test Accuracy: 0.773\nEpoch: 1/2.. Training Loss: 0.654.. Test Loss: 0.569.. Test Accuracy: 0.787\nEpoch: 1/2.. Training Loss: 0.710.. Test Loss: 0.545.. Test Accuracy: 0.797\nEpoch: 1/2.. Training Loss: 0.678.. Test Loss: 0.531.. Test Accuracy: 0.804\nEpoch: 1/2.. Training Loss: 0.615.. Test Loss: 0.555.. Test Accuracy: 0.796\nEpoch: 1/2.. Training Loss: 0.600.. Test Loss: 0.531.. Test Accuracy: 0.809\nEpoch: 1/2.. Training Loss: 0.612.. Test Loss: 0.527.. Test Accuracy: 0.805\nEpoch: 1/2.. Training Loss: 0.593.. Test Loss: 0.527.. Test Accuracy: 0.804\nEpoch: 1/2.. Training Loss: 0.609.. Test Loss: 0.494.. Test Accuracy: 0.814\nEpoch: 1/2.. Training Loss: 0.563.. Test Loss: 0.497.. Test Accuracy: 0.818\nEpoch: 1/2.. Training Loss: 0.563.. Test Loss: 0.515.. Test Accuracy: 0.813\nEpoch: 1/2.. Training Loss: 0.620.. Test Loss: 0.516.. Test Accuracy: 0.810\nEpoch: 1/2.. Training Loss: 0.567.. Test Loss: 0.482.. Test Accuracy: 0.824\nEpoch: 1/2.. Training Loss: 0.569.. Test Loss: 0.476.. Test Accuracy: 0.829\nEpoch: 1/2.. Training Loss: 0.594.. Test Loss: 0.477.. Test Accuracy: 0.824\nEpoch: 1/2.. Training Loss: 0.602.. Test Loss: 0.494.. Test Accuracy: 0.819\nEpoch: 1/2.. Training Loss: 0.568.. Test Loss: 0.473.. Test Accuracy: 0.831\nEpoch: 1/2.. Training Loss: 0.582.. Test Loss: 0.461.. Test Accuracy: 0.828\nEpoch: 2/2.. Training Loss: 0.541.. Test Loss: 0.469.. Test Accuracy: 0.830\nEpoch: 2/2.. Training Loss: 0.538.. Test Loss: 0.462.. Test Accuracy: 0.832\nEpoch: 2/2.. Training Loss: 0.526.. Test Loss: 0.480.. Test Accuracy: 0.826\nEpoch: 2/2.. Training Loss: 0.546.. Test Loss: 0.463.. Test Accuracy: 0.833\nEpoch: 2/2.. Training Loss: 0.545.. Test Loss: 0.485.. Test Accuracy: 0.822\nEpoch: 2/2.. Training Loss: 0.534.. Test Loss: 0.465.. Test Accuracy: 0.835\nEpoch: 2/2.. Training Loss: 0.557.. Test Loss: 0.470.. Test Accuracy: 0.826\nEpoch: 2/2.. Training Loss: 0.551.. Test Loss: 0.464.. Test Accuracy: 0.830\nEpoch: 2/2.. Training Loss: 0.508.. Test Loss: 0.462.. Test Accuracy: 0.834\nEpoch: 2/2.. Training Loss: 0.516.. Test Loss: 0.484.. Test Accuracy: 0.829\nEpoch: 2/2.. Training Loss: 0.520.. Test Loss: 0.463.. Test Accuracy: 0.834\nEpoch: 2/2.. Training Loss: 0.504.. Test Loss: 0.439.. Test Accuracy: 0.840\nEpoch: 2/2.. Training Loss: 0.483.. Test Loss: 0.466.. Test Accuracy: 0.834\nEpoch: 2/2.. Training Loss: 0.506.. Test Loss: 0.462.. Test Accuracy: 0.836\nEpoch: 2/2.. Training Loss: 0.515.. Test Loss: 0.437.. Test Accuracy: 0.842\nEpoch: 2/2.. Training Loss: 0.521.. Test Loss: 0.449.. Test Accuracy: 0.836\nEpoch: 2/2.. Training Loss: 0.486.. Test Loss: 0.436.. Test Accuracy: 0.844\nEpoch: 2/2.. Training Loss: 0.511.. Test Loss: 0.456.. Test Accuracy: 0.827\nEpoch: 2/2.. Training Loss: 0.560.. Test Loss: 0.443.. Test Accuracy: 0.838\nEpoch: 2/2.. Training Loss: 0.502.. Test Loss: 0.462.. Test Accuracy: 0.834\nEpoch: 2/2.. Training Loss: 0.545.. Test Loss: 0.443.. Test Accuracy: 0.839\nEpoch: 2/2.. Training Loss: 0.504.. Test Loss: 0.442.. Test Accuracy: 0.840\nEpoch: 2/2.. Training Loss: 0.512.. Test Loss: 0.434.. Test Accuracy: 0.845\n" ] ], [ [ "## Saving and loading networks\n\nAs you can imagine, it's impractical to train a network every time you need to use it. Instead, we can save trained networks then load them later to train more or use them for predictions.\n\nThe parameters for PyTorch networks are stored in a model's `state_dict`. We can see the state dict contains the weight and bias matrices for each of our layers.", "_____no_output_____" ] ], [ [ "print(\"Our model: \\n\\n\", model, '\\n')\nprint(\"The state dict keys: \\n\\n\", model.state_dict().keys())", "Our model: \n\n Network(\n (hidden_layers): ModuleList(\n (0): Linear(in_features=784, out_features=512, bias=True)\n (1): Linear(in_features=512, out_features=256, bias=True)\n (2): Linear(in_features=256, out_features=128, bias=True)\n )\n (output): Linear(in_features=128, out_features=10, bias=True)\n (dropout): Dropout(p=0.5, inplace=False)\n) \n\nThe state dict keys: \n\n odict_keys(['hidden_layers.0.weight', 'hidden_layers.0.bias', 'hidden_layers.1.weight', 'hidden_layers.1.bias', 'hidden_layers.2.weight', 'hidden_layers.2.bias', 'output.weight', 'output.bias'])\n" ] ], [ [ "The simplest thing to do is simply save the state dict with `torch.save`. For example, we can save it to a file `'checkpoint.pth'`.", "_____no_output_____" ] ], [ [ "torch.save(model.state_dict(), 'checkpoint.pth')", "_____no_output_____" ] ], [ [ "Then we can load the state dict with `torch.load`.", "_____no_output_____" ] ], [ [ "state_dict = torch.load('checkpoint.pth')\nprint(state_dict.keys())", "odict_keys(['hidden_layers.0.weight', 'hidden_layers.0.bias', 'hidden_layers.1.weight', 'hidden_layers.1.bias', 'hidden_layers.2.weight', 'hidden_layers.2.bias', 'output.weight', 'output.bias'])\n" ] ], [ [ "And to load the state dict in to the network, you do `model.load_state_dict(state_dict)`.", "_____no_output_____" ] ], [ [ "model.load_state_dict(state_dict)", "_____no_output_____" ] ], [ [ "Seems pretty straightforward, but as usual it's a bit more complicated. Loading the state dict works only if the model architecture is exactly the same as the checkpoint architecture. If I create a model with a different architecture, this fails.", "_____no_output_____" ] ], [ [ "# Try this\nmodel = fc_model.Network(784, 10, [400, 200, 100])\n# This will throw an error because the tensor sizes are wrong!\nmodel.load_state_dict(state_dict)", "_____no_output_____" ] ], [ [ "This means we need to rebuild the model exactly as it was when trained. Information about the model architecture needs to be saved in the checkpoint, along with the state dict. To do this, you build a dictionary with all the information you need to compeletely rebuild the model.", "_____no_output_____" ] ], [ [ "checkpoint = {'input_size': 784,\n 'output_size': 10,\n 'hidden_layers': [each.out_features for each in model.hidden_layers],\n 'state_dict': model.state_dict()}\n\ntorch.save(checkpoint, 'checkpoint.pth')", "_____no_output_____" ] ], [ [ "Now the checkpoint has all the necessary information to rebuild the trained model. You can easily make that a function if you want. Similarly, we can write a function to load checkpoints. ", "_____no_output_____" ] ], [ [ "def load_checkpoint(filepath):\n checkpoint = torch.load(filepath)\n model = fc_model.Network(checkpoint['input_size'],\n checkpoint['output_size'],\n checkpoint['hidden_layers'])\n model.load_state_dict(checkpoint['state_dict'])\n \n return model", "_____no_output_____" ], [ "model = load_checkpoint('checkpoint.pth')\nprint(model)", "Network(\n (hidden_layers): ModuleList(\n (0): Linear(in_features=784, out_features=400, bias=True)\n (1): Linear(in_features=400, out_features=200, bias=True)\n (2): Linear(in_features=200, out_features=100, bias=True)\n )\n (output): Linear(in_features=100, out_features=10, bias=True)\n (dropout): Dropout(p=0.5, inplace=False)\n)\n" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ] ]
4a0ec0df83901f0d29b3ecc53e3d5a5eb907153d
765,130
ipynb
Jupyter Notebook
explore-data.ipynb
bominzhang/QPCsupercurrent
2c566d64b67558f2ed7b522932b193d4b86aae0c
[ "BSD-3-Clause" ]
1
2020-05-24T00:55:29.000Z
2020-05-24T00:55:29.000Z
explore-data.ipynb
bominzhang/QPCsupercurrent
2c566d64b67558f2ed7b522932b193d4b86aae0c
[ "BSD-3-Clause" ]
null
null
null
explore-data.ipynb
bominzhang/QPCsupercurrent
2c566d64b67558f2ed7b522932b193d4b86aae0c
[ "BSD-3-Clause" ]
2
2020-05-21T19:29:13.000Z
2021-12-30T18:34:48.000Z
112.884332
184,328
0.714621
[ [ [ "# Explore the generated data\nHere we explore the data that is generated with the [generate-data.ipynb](generate-data.ipynb) notebook.\nYou can either run the simulations or download the data set. See [README.md](README.md) for the download link and instructions.\n\n### Joining the seperate data files of one simulation together, example:\n```python\n# for example if the generated files have the following names:\n# 'tmp/1d_alpha_vs_B_x_000.hdf',\n# 'tmp/1d_alpha_vs_B_x_001.hdf', \n# 'tmp/1d_alpha_vs_B_x_002.hdf', ...\n# The following line with join the files and save it as 'data/new_name.hdf'.\ndf = common.combine_dfs('tmp/1d_alpha_vs_B_x_*.hdf', 'data/new_name.hdf')\n```", "_____no_output_____" ] ], [ [ "import holoviews as hv\nimport numpy as np\nimport pandas as pd\nimport common\nhv.notebook_extension()\n\ndef add_energy_gs(df):\n hbar = df.hbar.unique()[0]\n eV = df.eV.unique()[0]\n flux_quantum_over_2pi = hbar / (2 * eV) / (eV * 1e6)\n df['E'] = df['currents'].apply(np.cumsum)\n df['E'] *= flux_quantum_over_2pi\n df['phase_gs_arg'] = df['E'].apply(np.argmin)\n df['phase_gs'] = [row['phases'][row['phase_gs_arg']] for i, row in df.iterrows()]\n\n # Move the phase_gs from -π to +π if they are within the tolerance\n tol = np.diff(df['phases'].iloc[0]).max()\n df['phase_gs'] = [-row['phase_gs'] if row['phase_gs'] < -(np.pi - tol) else row['phase_gs'] \n for i, row in df.iterrows()]\n return df", "_____no_output_____" ] ], [ [ "# Data like Figure 4 but with all combinations", "_____no_output_____" ] ], [ [ "%%opts Curve (color='k') Scatter (s=200)\n\ndef plot(orbital, g, alpha, mu, disorder, salt, B_x):\n gr = gb.get_group((orbital, g, alpha, mu, disorder, salt))\n gr = gr.set_index('B_x', drop=False)\n x = gr.loc[B_x]\n current = hv.Curve((gr.B_x, gr.current_c), kdims=['B_x'], vdims=['I_c'])[0:, 0:]\n phase_gs = hv.Curve((gr.B_x, gr.phase_gs), kdims=['B_x'], vdims=['theta_gs'])[:, -3.2:3.2]\n cpr = hv.Curve((x.phases, x.currents), kdims=['phi'], vdims=['I'])\n energy = hv.Curve((x.phases, x.E), kdims=['phi'], vdims=['I'])\n E_min = hv.Scatter((x.phase_gs, x.E[x.phase_gs_arg]), kdims=['phi'], vdims=['E'])\n VLine = hv.VLine(B_x)\n return (current * VLine + phase_gs * VLine + cpr + energy * E_min).cols(2)\n\nkdims = [hv.Dimension('orbital', values=df.orbital.unique()), \n hv.Dimension('g', values=df.g.unique()), \n hv.Dimension('alpha', values=df.alpha.unique()), \n hv.Dimension('mu', values=df.mu.unique()), \n hv.Dimension('disorder', values=df.disorder.unique()), \n hv.Dimension('salt', values=df.salt.unique()), \n hv.Dimension('B_x', values=df.B_x.unique())]", "_____no_output_____" ], [ "df = pd.read_hdf('data/I_c(B_x)_mu10,20meV_disorder0,75meV_T0.1K_all_combinations_of_effects.hdf')\ndf = add_energy_gs(df)\nparams = ['orbital', 'g', 'alpha', 'mu', 'disorder', 'salt']\ngb = df.groupby(params)\nhv.DynamicMap(plot, kdims=kdims)", "_____no_output_____" ] ], [ [ "First mode, no disorder, T=50mK, with orbital and SOI", "_____no_output_____" ] ], [ [ "df = pd.read_hdf('data/I_c(B_x)_mu10_disorder0_T0.05K_orbital.hdf')\ndf = add_energy_gs(df)\nparams = ['orbital', 'g', 'alpha', 'mu', 'disorder', 'salt']\ngb = df.groupby(params)\nhv.DynamicMap(plot, kdims=kdims)", "_____no_output_____" ] ], [ [ "First mode, no disorder, T=50mK, without orbital and SOI, Zeeman only", "_____no_output_____" ] ], [ [ "df = pd.read_hdf('data/I_c(B_x)_mu10_disorder0_T0.05K.hdf')\ndf = add_energy_gs(df)\nparams = ['orbital', 'g', 'alpha', 'mu', 'disorder', 'salt']\ngb = df.groupby(params)\nhv.DynamicMap(plot, kdims=kdims)", "_____no_output_____" ], [ "%%opts Curve (color='k') Scatter (s=200)\n\ndef plot(orbital, g, alpha, mu, disorder, salt, B_x):\n gr = gb.get_group((orbital, g, alpha, mu, disorder, salt))\n gr = gr.set_index('B_x', drop=False)\n x = gr.loc[B_x]\n current = hv.Curve((gr.B_x, gr.current_c), kdims=['B_x'], vdims=['I_c'])[0:, 0:]\n phase_gs = hv.Curve((gr.B_x, gr.phase_gs), kdims=['B_x'], vdims=['theta_gs'])[:, -3.2:3.2]\n cpr = hv.Curve((x.phases, x.currents), kdims=['phi'], vdims=['I'])\n energy = hv.Curve((x.phases, x.E), kdims=['phi'], vdims=['I'])\n IB = hv.Curve((gr.mu, gr.current_c), kdims=['potential'], vdims=['I_c'])\n E_min = hv.Scatter((x.phase_gs, x.E[x.phase_gs_arg]), kdims=['phi'], vdims=['E'])\n VLine = hv.VLine(B_x)\n return (current * VLine + phase_gs * VLine + cpr + energy * E_min).cols(2)\n\nkdims = [hv.Dimension('orbital', values=df.orbital.unique()), \n hv.Dimension('g', values=df.g.unique()), \n hv.Dimension('alpha', values=df.alpha.unique()), \n hv.Dimension('mu', values=df.mu.unique()), \n hv.Dimension('disorder', values=df.disorder.unique()), \n hv.Dimension('salt', values=df.salt.unique()), \n hv.Dimension('B_x', values=df.B_x.unique())]", "_____no_output_____" ] ], [ [ "First mode, no disorder, T=50mK, with orbital but no spin-orbital", "_____no_output_____" ] ], [ [ "df = pd.read_hdf('data/I_c(B_x)_mu10_disorder0_T0.05K_onlyorbital.hdf')\ndf = add_energy_gs(df)\nparams = ['orbital', 'g', 'alpha', 'mu', 'disorder', 'salt']\ngb = df.groupby(params)\nhv.DynamicMap(plot, kdims=kdims)", "_____no_output_____" ], [ "df = pd.read_hdf('data/I_c(B_x)_mu5,10,20meV_disorder0,75meV_T0.05K_orbital_SOI_Zeeman.hdf')\ndf = add_energy_gs(df)\nparams = ['orbital', 'g', 'alpha', 'mu', 'disorder', 'salt']\ngb = df.groupby(params)\nhv.DynamicMap(plot, kdims=kdims)", "_____no_output_____" ] ], [ [ "# Different $T$, with or without leads, different lenghts of the system", "_____no_output_____" ] ], [ [ "df2 = pd.read_hdf('data/I_c(B_x)_no_disorder_combinations_of_effects_and_geometries.hdf')\ndf2 = add_energy_gs(df2)\nparams = ['T', 'L', 'orbital', 'g', 'alpha', 'mu', 'with_leads']\ngb = df2.groupby(params)", "_____no_output_____" ], [ "%%opts Curve (color='k') Scatter (s=200)\n\ndef plot(T, L, orbital, g, alpha, mu, with_leads, B_x):\n gr = gb.get_group((T, L, orbital, g, alpha, mu, with_leads))\n gr = gr.set_index('B_x', drop=False)\n x = gr.loc[B_x]\n current = hv.Curve((gr.B_x, gr.current_c), kdims=['B_x'], vdims=['I_c'])[:, 0:]\n phase_gs = hv.Curve((gr.B_x, gr.phase_gs), kdims=['B_x'], vdims=['theta_gs'])[:, -3.2:3.2]\n cpr = hv.Curve((x.phases, x.currents), kdims=['phi'], vdims=['I'])\n energy = hv.Curve((x.phases, x.E), kdims=['phi'], vdims=['E'])\n E_min = hv.Scatter((x.phase_gs, x.E[x.phase_gs_arg]), kdims=['phi'], vdims=['E'])\n VLine = hv.VLine(B_x)\n return (current * VLine + phase_gs * VLine + cpr + energy * E_min).cols(2)\n\nkdims = [hv.Dimension('T', values=df2['T'].unique()), \n hv.Dimension('L', values=df2.L.unique()), \n hv.Dimension('orbital', values=df2.orbital.unique()), \n hv.Dimension('g', values=df2.g.unique()), \n hv.Dimension('alpha', values=df2.alpha.unique()), \n hv.Dimension('mu', values=df2.mu.unique()), \n hv.Dimension('with_leads', values=df2.with_leads.unique()),\n hv.Dimension('B_x', values=df2.B_x.unique())]\n\ndm = hv.DynamicMap(plot, kdims=kdims)\ndm", "_____no_output_____" ], [ "ds = hv.Dataset(df2)\nds.to.curve(['B_x'], ['current_c'], groupby=params, dynamic=True).overlay('L').select(B=(0, 0.5))", "_____no_output_____" ], [ "params = ['T', 'B_x', 'orbital', 'g', 'alpha', 'mu', 'with_leads']\ncurve = ds.to.curve(['L'], ['current_c'], groupby=params, dynamic=True)\ncurve.redim(current_c=dict(range=(0, None)))", "_____no_output_____" ] ], [ [ "# Rotation of field", "_____no_output_____" ] ], [ [ "%%opts Path [aspect='square']\ndf = pd.read_hdf('data/I_c(B_x)_mu20meV_rotation_of_field_in_xy_plane.hdf')\ndf = add_energy_gs(df)\ndf2 = common.drop_constant_columns(df)\nds = hv.Dataset(df2)\ncurrent = ds.to.curve(kdims='B', vdims='current_c', groupby=['theta', 'disorder']).redim(current_c=dict(range=(0, None)))\nphase = ds.to.curve(kdims='B', vdims='phase_gs', groupby=['theta', 'disorder'])\ncurrent + phase", "_____no_output_____" ] ] ]
[ "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code", "markdown", "code" ]
[ [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code" ], [ "markdown" ], [ "code", "code", "code", "code" ], [ "markdown" ], [ "code" ] ]