{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "#
CS568:Deep Learning
Spring 2020
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This is part 2 of Recitation 1 for the course CS-568: Deep Learning. This notebook introduces basic fundamentals of python. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Python \n", "Python is a high-level, open source and interpreted programming language. It is almost like pseudo-code, allows you to express very powerful ideas in few lines of code. Why python?\n", "+ Simple and easy to learn\n", "+ Used to build web applications\n", "+ Used with big data frameworks\n", "+ Extensive support libraries\n", "+ Must-know language for deep learning" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### i) Take input from user" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "name = input(\"What's your name? \")\n", "print('Hi, ', name)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### ii) Data types" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "a = 1 # integer\n", "print(type(a))\n", "print(\"*\"*50)\n", "b = 1.1 # float\n", "print(type(b))\n", "print(\"*\"*50)\n", "c = 1 + 2j # complex number (a + bi)\n", "print(type(c))\n", "print(\"*\"*50)\n", "d = \"hello\" # string\n", "print(type(d))\n", "print(\"*\"*50)\n", "e = True # boolean (True / False)\n", "print(type(e))\n", "print(\"*\"*50)" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "Python is a strongly typed language, variables are bound to specific data types. For example" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "value = 10 + \"10\"" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "number = input(\"Please enter any number between 1 and 10: \")\n", "value = 10 + number\n", "print(value)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "number = input(\"Please enter any number between 1 and 10: \")\n", "value = 10 + int(number)\n", "print(value)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### iii) Type conversion\n", "+ int() to convert a string into an integer.\n", "+ float() to convert a string into a float.\n", "+ bool() to convert a string into a boolean value.\n", "+ To check the type of variable use print(type(number))\n", "\n", "#### iv) Strings" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "course = 'Deep Learning'\n", "print(len(course)) # to get the length of string\n", "print('pak'+'istan') # combine two strings using + operator\n", "print('deep'*10) # repeat string multiple times using * operator\n", "print(course[0:4]) # square brackets used to access the elements of string\n", "print(course.lower()) # lower() method returns the string in lower case\n", "print(course.upper()) # upper() method returns the string in upper case\n", "height = 'tall'\n", "print(height.replace('t','m')) # replace() method used to swap elements of string\n", "splitted = course.split(' ')\n", "print(splitted) # split the string into two sub-strings\n", "check_var = 'Deep' in course # check if the phrase is in the string or not\n", "print(check_var)\n", "check_var = 'deep' not in course\n", "print(check_var)\n", "acc = 90\n", "txt = \"testing accuracy {}%\"\n", "print(txt.format(acc)) # combine text with numbers" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### v) Common operators in python" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "x = 5\n", "y = 2\n", "print(\"x+y = \",x + y) # addition\n", "print(\"x-y = \",x-y) # subtraction\n", "print(\"x*y = \",x * y) # multiplication\n", "print(\"x/y = \",x / y) # division\n", "print(\"x%y = \",x % y) # modulus\n", "print(\"x**y = \",x**y) # power" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### vi) Logical operators to combine conditional statements" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "x = 5\n", "y = 5\n", "print(x > 3 and x < 10)\n", "print(x < 5 or x < 4)\n", "print(not(x > 3 and x < 10))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### vii) Data container: List\n", "Generic container for numeric indexing" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "same_type_list = [1, 3, 4, 89, 23, 43, 90] # lists can be heterogeneous\n", "diff_type_list = [1, 3, \"hello\", 4.9, \"c\"] \n", "print(same_type_list[3])\n", "print(len(same_type_list))\n", "same_type_list[0] = \"I'm new\"\n", "print(same_type_list)\n", "print(same_type_list[8])\n", "print(max(same_type_list))\n", "print(min(same_type_list))\n", "print(sorted(same_type_list))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "courses_list = [] # add items in the list\n", "courses_list.append(\"deep learning\")\n", "courses_list.append(\"data science\")\n", "courses_list.append(\"internet of things\")\n", "print(courses_list, \"Total courses: \"+str(len(courses_list)))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "courses_list.remove(\"data science\") # remove items from the list\n", "print(courses_list, \"Total courses: \"+str(len(courses_list)))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "comb_list = same_type_list + diff_type_list + courses_list # combine three lists\n", "print(comb_list)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "del comb_list" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Slicing lists**" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "some_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n", "print(some_list[5:]) # Get a slice from index 5 to last index\n", "print(some_list[:3]) # Get a slice from start to index 5 to \n", "print(some_list[3:9:2]) # Get a slice from index 3 to 9 with step 2" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**List comprehension**" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "nums = [0, 1, 2, 3, 4]\n", "squares = []\n", "for x in nums:\n", " squares.append(x ** 2)\n", "print(squares)\n", "\n", "## The simple form of above code using list comprehension\n", "nums = [0, 1, 2, 3, 4]\n", "squares = [x ** 2 for x in nums]\n", "print(squares) # Prints [0, 1, 4, 9, 16]\n", "\n", "## List comprehension can also contain conditions\n", "# new_list = [expression for_loop_one_or_more condtions]\n", "res = [num for num in nums if num % 2 == 0 and num>0]\n", "print(res)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### viii) Data container: Tuple\n", "A tuple is a collection which is ordered and unchangeable. Once a tuple is created, you cannot change, add and remove its values." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "same_type_tuple = (1, 10, 7) # tuples can be heterogeneous\n", "diff_type_tuple = (1, 2, \"foo\") \n", "\n", "print(diff_type_tuple[2])\n", "print(same_type_tuple[1])\n", "\n", "same_type_tuple[0] = 3" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### ix) Data container: Dictionaries\n", "A dictionary consists of a collection of key-value pairs. Dictionary elements are accessed via keys." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "students_dict = {\"student1\": \"Ali\", \"student2\": \"Ahmed\", \"student3\": \"Nadia\"}\n", "\n", "print(students_dict[\"student1\"]) # access elements using key values\n", "print(students_dict.get(\"student4\"))\n", "print(students_dict.get(\"student4\", \"student does not exist\")) \n", "print(students_dict)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "students_dict[\"student1\"] = \"Hassan\" # assig new element to student\n", "print(students_dict)\n", "for x, y in students_dict.items(): print(\"key and value:\",x,y)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### x) Data container: Sets\n", "Group of unique elements" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "my_set = {\"obj1\", \"obj2\", \"obj3\"}\n", "print(my_set)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "print(my_set[1])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### xi) Functions\n", "A function is defined using def keyword and ends with :" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def calculate_area(l,w):\n", " area = l*w\n", " return area\n", "area = calculate_area(5,2)\n", "print(\"The area is \",area)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### xii) Classes" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "class Person:\n", " # Constructor\n", " def __init__(self, name): # Create an instance variable\n", " self.name = name\n", " # Instance method \n", " def talk(self):\n", " print(\"Hi, i am \" + self.name)\n", " \n", "p1 = Person(\"Noor\") # Construct an instance of the person class\n", "p1.talk() # Call an instance method" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### xiii) Loops" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "courses = ['deep learning', 'data mining', 'data science']\n", "for course in courses:\n", " print(course)\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "courses = ['deep learning', 'data mining', 'data science']\n", "for idx, course in enumerate(courses):\n", " print('#%d: %s' % (idx + 1, course))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### File formats and loading\n", "\n", "- .txt: plain text file\n", " - .pkl: python objects\n", " - .csv: tabular data - fields separated by commas\n", " - .npz: zipped archive of npy files\n", " - .npy: numpy arrays (saved using numpy library)\n", " \n", "Four different modes to open a file:\n", "+ **r** - Read - Default value. Opens a file for reading, error if the file does not exist\n", "+ **a** - Append - Opens a file for appending, creates the file if it does not exist\n", "+ **w** - Write - Opens a file for writing, creates the file if it does not exist\n", "+ **x** - Create - Creates the specified file, returns an error if the file exists" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# read data from a text file \n", "nfile = open(\"deeplearning_course.txt\", \"r\")\n", "print(nfile.readlines())\n", "nfile.close()\n", "\n", "with open(\"deeplearning_course.txt\", \"r\") as file:\n", " print(file.readlines())" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "import pickle\n", "\n", "mydict = {\"student1\": \"Ali\", \"Student2\": \"Ahmed\", \"Student3\": \"Nida\"}\n", "\n", "pickle.dump(mydict, open(\"store.pkl\", \"wb\"))\n", "\n", "loaded = pickle.load(open(\"store.pkl\", \"rb\"))\n", "print(loaded)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "import csv\n", "\n", "with open (\"course_file.csv\", \"r\") as f:\n", " reader = csv.reader(f, delimiter=\",\") \n", " i = 0 \n", " for row in reader: \n", " if row[1]=='Deep learning':\n", " print(row)\n", " i+=1 " ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.5.3" } }, "nbformat": 4, "nbformat_minor": 2 }