CME 193: Introduction to Scientific Python Lecture 5: Object Oriented Programming
|
|
- Sherilyn Briggs
- 6 years ago
- Views:
Transcription
1 CME 193: Introduction to Scientific Python Lecture 5: Object Oriented Programming Nolan Skochdopole stanford.edu/class/cme193 5: Object Oriented Programming 5-1
2 Contents Classes Numpy Exercises 5: Object Oriented Programming 5-2
3 Simplest example # define class: class Leaf: pass # instantiate object leaf = Leaf() print leaf # < main.leaf instance at 0x10049df80> 5: Object Oriented Programming 5-3
4 Initializing an object Define how a class is instantiated by defining the init method. Seasoned programmer: in Python only one constructor method. 5: Object Oriented Programming 5-4
5 Initializing an object The init or constructor method. class Leaf: def init (self, color): self.color = color # (default) public attribute redleaf = Leaf( red ) blueleaf = Leaf( blue ) print redleaf.color # red Note how we access object attributes. We will have more on public/private attributes and encapsulation next time. 5: Object Oriented Programming 5-5
6 Self The self parameter seems strange at first sight. It refers to the the object (instance) itself. Hence self.color = color sets the color of the object self.color equal to the variable color. 5: Object Oriented Programming 5-6
7 Another example Classes have methods (similar to functions) class Stock(): def init (self, name, symbol, prices=[]): self.name = name self.symbol = symbol self.prices = prices def high_price(self): if len(self.prices) == 0: return MISSING PRICES return max(self.prices) apple = Stock( Apple, APPL, [500.43, ]) print apple.high_price() Recall: list.append() or dict.items(). These are simply class methods! 5: Object Oriented Programming 5-7
8 Another example Classes have methods (similar to functions) class Stock(): def init (self, name, symbol, prices=[]): self.name = name self.symbol = symbol self.prices = prices def high_price(self): if len(self.prices) == 0: return MISSING PRICES return max(self.prices) apple = Stock( Apple, APPL, [500.43, ]) print apple.high_price() Recall: list.append() or dict.items(). These are simply class methods! 5: Object Oriented Programming 5-8
9 Class attributes class Leaf: n_leafs = 0 # class attribute: shared def init (self, color): self.color = color # object attribute Leaf.n_leafs += 1 redleaf = Leaf( red ) blueleaf = Leaf( blue ) print redleaf.color # red print Leaf.n_leafs # 2 Class attributes are shared among all objects of that class. 5: Object Oriented Programming 5-9
10 Attributes are by default public! class Leaf: def init (self, color): self.color = color def getcolor(self): return self.color blueleaf = Leaf( blue ) color = blueleaf.getcolor() print color # blue color = red print blueleaf.getcolor() #? blueleaf.color = red print blueleaf.getcolor() #? What do you think is returned by the last two print statements? 5: Object Oriented Programming 5-10
11 Access attributes by returning them with methods What happens with this example? class Student: def init (self, name, classes=[]): self.name = name self.classes = classes def getclasses(self): return self.classes def addclass(self, c): self.classes.append(c) s = Student( Jabrill ) s.addclass( CME 193 ) classes = s.getclasses() print classes # [ CME 193 ] classes[0] = CME 195 print s.getclasses() #? 5: Object Oriented Programming 5-11
12 Access attributes by returning them with methods How would you fix the last example? class Student: def init (self, name, classes=[]): self.name = name self.classes = classes def getclasses(self): return list(self.classes) def addclass(self, c): self.classes.append(c) s = Student( Jabrill ) s.addclass( CME 193 ) classes = s.getclasses() print classes # [ CME 193 ] classes[0] = CME 195 print s.getclasses() #? 5: Object Oriented Programming 5-12
13 Access attributes by returning them with methods How would you fix the last example? class Student: def init (self, name, classes=[]): self.name = name self.classes = classes def getclasses(self): return list(self.classes) def addclass(self, c): self.classes.append(c) s = Student( Jabrill ) s.addclass( CME 193 ) classes = s.getclasses() print classes # [ CME 193 ] classes[0] = CME 195 print s.getclasses() #? 5: Object Oriented Programming 5-13
14 Private attributes Python does have a way to declare attributes as private. class Leaf: def init (self, color): self. color = color def getcolor(self): return self. color blueleaf = Leaf( blue ) color = blueleaf.getcolor() print color # blue color = red print blueleaf.getcolor() #? print blueleaf. color # AttributeError: Leaf instance has # no attribute color 5: Object Oriented Programming 5-14
15 Private attributes However, there is still a way for us to access private attributes outside of the class methods. class Leaf: def init (self, color): self. color = color def getcolor(self): return self. color blueleaf = Leaf( blue ) color = blueleaf.getcolor() print color # blue color = red print blueleaf.getcolor() #? print blueleaf._leaf color #? 5: Object Oriented Programming 5-15
16 Public vs private attributes As we ve seen, no real way to fully protect our class attributes. Bad practice to access object attributes directly. Can use private attributes to make it harder/more work to access. 5: Object Oriented Programming 5-16
17 Operator overloading We can override built in methods to define how our objects behave with Python operators/functions. Some methods to override init (self,...): Constructor repr (self): Represent the object (machine) cmp (self, other): Compare self and other add (self, other): Add self and other Many more! 5: Object Oriented Programming 5-17
18 Example class Student: def init (self, name, classes=[]): self.name = name self.classes = classes def getclasses(self): return self.classes def getname(self): return self.name s = Student( Jabrill, [ CME 193, CME 195 ]) print s # < main.student instance at 0x7f68f0c39d88> print s.getname() # Jabrill print s.getclasses() # [ CME 193, CME 195 ] 5: Object Oriented Programming 5-18
19 Example class Student: def init (self, name, classes=[]): self.name = name self.classes = classes def getclasses(self): return self.classes def getname(self): return self.name def repr (self): string = %s: % self.name string += %s % self.classes return string s = Student( Jabrill, [ CME 193, CME 195 ]) print s # Jabrill: [ CME 193, CME 195 ] 5: Object Oriented Programming 5-19
20 Operator overloading This ability to define how objects behave with basic operators allows us to define interactions between objects. One of the most powerful aspects of object oriented programming. 5: Object Oriented Programming 5-20
21 Example Implementing Rational numbers class Rational: pass 5: Object Oriented Programming 5-21
22 Setup What information should the class hold? Numerator Denominator 5: Object Oriented Programming 5-22
23 Setup What information should the class hold? Numerator Denominator 5: Object Oriented Programming 5-23
24 Init Implement the init method class Rational: def init (self, p, q=1): self.p = p self.q = q 5: Object Oriented Programming 5-24
25 Init Implement the init method class Rational: def init (self, p, q=1): self.p = p self.q = q 5: Object Oriented Programming 5-25
26 Issues Issues? class Rational: def init (self, p, q=1): self.p = p self.q = q Ignore the division by 0 for now, more on that later. 5: Object Oriented Programming 5-26
27 Issues Issues? class Rational: def init (self, p, q=1): self.p = p self.q = q Ignore the division by 0 for now, more on that later. 5: Object Oriented Programming 5-27
28 Greatest common divisor and 1 2 are the same rational. We d like to for the objects to be the same. Let s store our rational numbers in fully reduced form. Implement a gcd(a, b) function that computes the greatest common divisor of a and b. def gcd(a, b): if b == 0: return a else: return gcd(b, a%b) If interested: Verify Euclidean Algorithm 5: Object Oriented Programming 5-28
29 Greatest common divisor class Rational: def init (self, p, q=1): g = gcd(p, q) self.p = p / g self.q = q / g Can put the gcd function in the same file as your class outside of the class definition (easiest to put above class definition) or import file with the function. 5: Object Oriented Programming 5-29
30 Representing your class: Operator overloading Implement repr or str early to print Useful for debugging 5: Object Oriented Programming 5-30
31 Operator overloading: adding two Rationals Add Rationals just like Ints and Doubles? Rational(10,2) + Rational(4,3) To use +, we implement the add method class Rational: #... def add (self, other): p = self.p * other.q + other.p * self.q q = self.q * other.q return Rational(p, q) #... Does this change any of self or other? 5: Object Oriented Programming 5-31
32 Operator overloading: Comparing cmp compares objects If self is smaller than other, return a negative value If self and other are equal, return 0 If self is larger than other, return a positive value You will implement this function and others in the exercise for today. 5: Object Oriented Programming 5-32
33 Class hierarchy through inheritance It can be useful (especially in larger projects) to have a hierarchy of classes. Example Animal Bird Pet Hawk Seagull... Dog Cat : Object Oriented Programming 5-33
34 Inheritance Can have one class inherit attributes from another class. Original class is called base class or parent class. New class is called derived class or child class. Child classes will usually redefine or add new attributes. 5: Object Oriented Programming 5-34
35 Inheritance Suppose we first define an abstract class class Animal: def init (self, n_legs, color): self.n_legs = n_legs self.color = color def make_noise(self): print noise 5: Object Oriented Programming 5-35
36 Inheritance We can define sub classes and inherit from another class. class Dog(Animal): def init (self, color, name): Animal. init (self, 4, color) self.name = name def make_noise(self): print self.name + : + woof bird = Animal(2, white ) bird.make_noise() # noise brutus = Dog( black, Brutus ) brutus.make_noise() # Brutus: woof shelly = Dog( white, Shelly ) shelly.make_noise() # Shelly: woof 5: Object Oriented Programming 5-36
37 Contents Classes Numpy Exercises 5: Object Oriented Programming 5-37
38 Numpy Fundamental package for scientific computing with Python N-dimensional array object Linear algebra, Fourier transform, random number capabilities Building block for other packages (e.g. Scipy) Open source 5: Object Oriented Programming 5-38
39 Numpy Fundamental package for scientific computing with Python N-dimensional array object Linear algebra, Fourier transform, random number capabilities Building block for other packages (e.g. Scipy) Open source 5: Object Oriented Programming 5-39
40 import numpy as np Basics: import numpy as np A = np.array([[1, 2, 3], [4, 5, 6]]) print A # [[1 2 3] # [4 5 6]] Af = np.array([1, 2, 3], float) Slicing as usual. 5: Object Oriented Programming 5-40
41 More basics np.arange(0, 1, 0.2) # array([ 0., 0.2, 0.4, 0.6, 0.8]) np.linspace(0, 2*np.pi, 4) # array([ 0.0, 2.09, 4.18, 6.28]) A = np.zeros((2,3)) # array([[ 0., 0., 0.], # [ 0., 0., 0.]]) # np.ones, np.diag A.shape # (2, 3) 5: Object Oriented Programming 5-41
42 More basics np.random.random((2,3)) # array([[ , , ], # [ , , ]]) a = np.random.normal(loc=1.0, scale=2.0, size=(2,2)) # array([[ , ], # [ , ]]) np.savetxt("a_out.txt", a) # save to file b = np.loadtxt("a_out.txt") # read from file 5: Object Oriented Programming 5-42
43 Arrays are mutable A = np.zeros((2, 2)) # array([[ 0., 0.], # [ 0., 0.]]) C = A C[0, 0] = 1 print A # [[ 1. 0.] # [ 0. 0.]] 5: Object Oriented Programming 5-43
44 Array attributes a = np.arange(10).reshape((2,5)) a.ndim a.shape a.size a.t a.dtype # 2 dimension # (2, 5) shape of array # 10 # of elements # transpose # data type 5: Object Oriented Programming 5-44
45 Basic operations Arithmetic operators: elementwise application a = np.arange(4) # array([0, 1, 2, 3]) b = np.array([2, 3, 2, 4]) a * b # array([ 0, 3, 4, 12]) b - a # array([2, 2, 0, 1]) c = [2, 3, 4, 5] a * c # array([ 0, 3, 8, 15]) Also, we can use += and *=. 5: Object Oriented Programming 5-45
46 Array broadcasting When operating on two arrays, numpy compares shapes. Two dimensions are compatible when 1. They are of equal size 2. One of them is 1 5: Object Oriented Programming 5-46
47 Array broadcasting 5: Object Oriented Programming 5-47
48 Array broadcasting with scalars This also allows us to add a constant to a matrix or multiply a matrix by a constant A = np.ones((3,3)) print 3 * A - 1 # [[ ] # [ ] # [ ]] 5: Object Oriented Programming 5-48
49 Vector operations inner product outer product dot product (matrix multiplication) # note: numpy automatically converts lists u = [1, 2, 3] v = [1, 1, 1] np.inner(u, v) # 6 np.outer(u, v) # array([[1, 1, 1], # [2, 2, 2], # [3, 3, 3]]) np.dot(u, v) # 6 5: Object Oriented Programming 5-49
50 Matrix operations First, define some matrices: A = np.ones((3, 2)) # array([[ 1., 1.], # [ 1., 1.], # [ 1., 1.]]) A.T # array([[ 1., 1., 1.], # [ 1., 1., 1.]]) B = np.ones((2, 3)) # array([[ 1., 1., 1.], # [ 1., 1., 1.]]) 5: Object Oriented Programming 5-50
51 Matrix operations np.dot(a, B) # array([[ 2., 2., 2.], # [ 2., 2., 2.], # [ 2., 2., 2.]]) np.dot(b, A) # array([[ 3., 3.], # [ 3., 3.]]) np.dot(b.t, A.T) # array([[ 2., 2., 2.], # [ 2., 2., 2.], # [ 2., 2., 2.]]) np.dot(a, B.T) # Traceback (most recent call last): # File "<stdin>", line 1, in <module> # ValueError: shapes (3,2) and (3,2) not aligned:... #... 2 (dim 1)!= 3 (dim 0) 5: Object Oriented Programming 5-51
52 Operations along axes a = np.random.random((2,3)) # array([[ , , ], # [ , , ]]) a.sum() # a.sum(axis=0) # column sum # array([ , , ]) a.cumsum() # array([ , , , , # , ]) a.cumsum(axis=1) # cumulative row sum # array([[ , , ], # [ , , ]]) a.min() # a.max(axis=0) # array([ , , ]) 5: Object Oriented Programming 5-52
53 Slicing arrays More advanced slicing a = np.random.random((4,5)) a[2, :] # third row, all columns a[1:3] # 2nd, 3rd row, all columns a[:, 2:4] # all rows, columns 3 and 4 5: Object Oriented Programming 5-53
54 Iterating over arrays Iterating over multidimensional arrays is done with respect to the first axis: for row in A Looping over all elements: for element in A.flat 5: Object Oriented Programming 5-54
55 Reshaping Reshape using reshape. Total size must remain the same. Resize using resize, always works: chopping or appending zeros First dimension has priority, so beware of unexpected results Try it! 5: Object Oriented Programming 5-55
56 Reshaping Reshape using reshape. Total size must remain the same. Resize using resize, always works: chopping or appending zeros First dimension has priority, so beware of unexpected results Try it! 5: Object Oriented Programming 5-56
57 Reshaping Reshape using reshape. Total size must remain the same. Resize using resize, always works: chopping or appending zeros First dimension has priority, so beware of unexpected results Try it! 5: Object Oriented Programming 5-57
58 Matrix operations import numpy.linalg eye(3) trace(a) column_stack((a,b)) row_stack((a,b,a)) Identity matrix Trace Stack column wise Stack row wise 5: Object Oriented Programming 5-58
59 Linear algebra import numpy.linalg qr cholesky inv(a) solve(a,b) Computes the QR decomposition Computes the Cholesky decomposition Inverse Solves Ax = b for A full rank lstsq(a,b) Solves arg min x Ax b 2 eig(a) Eigenvalue decomposition eig(a) Eigenvalue decomposition for symmetric or hermitian eigvals(a) Computes eigenvalues. svd(a, full) Singular value decomposition pinv(a) Computes pseudo-inverse of A 5: Object Oriented Programming 5-59
60 Fourier transform import numpy.fft fft 1-dimensional DFT fft2 2-dimensional DFT fftn N-dimensional DFT ifft 1-dimensional inverse DFT (etc.) rfft Real DFT (1-dim) ifft Imaginary DFT (1-dim) 5: Object Oriented Programming 5-60
61 Random sampling import numpy.random rand(d0,d1,...,dn) randn(d0, d1,...,dn) randint(lo, hi, size) choice(a, size, repl, p) shuffle(a) permutation(a) Random values in a given shape Random standard normal Random integers [lo, hi) Sample from a Permutation (in-place) Permutation (new array) 5: Object Oriented Programming 5-61
62 import numpy.random Distributions in random The list of distributions to sample from is quite long, and includes beta binomial chisquare exponential dirichlet gamma laplace lognormal pareto poisson power 5: Object Oriented Programming 5-62
63 Contents Classes Numpy Exercises 5: Object Oriented Programming 5-63
64 Exercises See course website for exercises for this lecture. 5: Object Oriented Programming 5-64
CME 193: Introduction to Scientific Python Lecture 4: File I/O and Classes
CME 193: Introduction to Scientific Python Lecture 4: File I/O and Classes Sven Schmit stanford.edu/~schmit/cme193 4: File I/O and Classes 4-1 Feedback form Please take a moment to fill out feedback form
More informationCME 193: Introduction to Scientific Python Lecture 5: Numpy, Scipy, Matplotlib
CME 193: Introduction to Scientific Python Lecture 5: Numpy, Scipy, Matplotlib Sven Schmit stanford.edu/~schmit/cme193 5: Numpy, Scipy, Matplotlib 5-1 Contents Second part of course Numpy Scipy Matplotlib
More informationCME 193: Introduction to Scientific Python Lecture 6: Numpy, Scipy, Matplotlib
CME 193: Introduction to Scientific Python Lecture 6: Numpy, Scipy, Matplotlib Nolan Skochdopole stanford.edu/class/cme193 6: Numpy, Scipy, Matplotlib 6-1 Contents Homeworks and Project Numpy Scipy Matplotlib
More informationCME 193: Introduction to Scientific Python Lecture 6: Classes and iterators
CME 193: Introduction to Scientific Python Lecture 6: Classes and iterators Sven Schmit stanford.edu/~schmit/cme193 6: Classes and iterators 6-1 Contents Classes Generators and Iterators Exercises 6: Classes
More informationLecture 07: Python Generators, Iterators, and Decorators
BI296: Linux and Shell Programming Lecture 07: Python Generators, Iterators, and Decorators Maoying,Wu ricket.woo@gmail.com Dept. of Bioinformatics & Biostatistics Shanghai Jiao Tong University Spring,
More informationCME 193: Introduction to Scientific Python Lecture 4: Strings and File I/O
CME 193: Introduction to Scientific Python Lecture 4: Strings and File I/O Nolan Skochdopole stanford.edu/class/cme193 4: Strings and File I/O 4-1 Contents Strings File I/O Classes Exercises 4: Strings
More informationNumPy. Daniël de Kok. May 4, 2017
NumPy Daniël de Kok May 4, 2017 Introduction Today Today s lecture is about the NumPy linear algebra library for Python. Today you will learn: How to create NumPy arrays, which store vectors, matrices,
More informationNumPy is suited to many applications Image processing Signal processing Linear algebra A plethora of others
Introduction to NumPy What is NumPy NumPy is a Python C extension library for array-oriented computing Efficient In-memory Contiguous (or Strided) Homogeneous (but types can be algebraic) NumPy is suited
More informationNumPy Primer. An introduction to numeric computing in Python
NumPy Primer An introduction to numeric computing in Python What is NumPy? Numpy, SciPy and Matplotlib: MATLAB-like functionality for Python Numpy: Typed multi-dimensional arrays Fast numerical computation
More informationScientific Programming. Lecture A08 Numpy
Scientific Programming Lecture A08 Alberto Montresor Università di Trento 2018/10/25 Acknowledgments: Stefano Teso, Documentation http://disi.unitn.it/~teso/courses/sciprog/python_appendices.html https://docs.scipy.org/doc/numpy-1.13.0/reference/
More informationfile:///users/jacobperricone/desktop/stanford/cme193_s18/cme193/lectures/presentations/lecture4.slides.html?print-pdf%20=%20true#/ 1/94
CME 193 Introduction to Scienti c Python Spring 2018 Lecture 4 File I/O and Object Oriented Programming file:///users/jacobperricone/desktop/stanford/cme193_s18/cme193/lectures/presentations/lecture4.slides.html?print-pdf%20=%20true#/
More informationShort Introduction to Python Machine Learning Course Laboratory
Pattern Recognition and Applications Lab Short Introduction to Python Machine Learning Course Laboratory Battista Biggio battista.biggio@diee.unica.it Luca Didaci didaci@diee.unica.it Dept. Of Electrical
More informationLECTURE 22. Numerical and Scientific Packages
LECTURE 22 Numerical and Scientific Packages NUMERIC AND SCIENTIFIC APPLICATIONS As you might expect, there are a number of third-party packages available for numerical and scientific computing that extend
More informationIntroduction to NumPy
Lab 3 Introduction to NumPy Lab Objective: NumPy is a powerful Python package for manipulating data with multi-dimensional vectors. Its versatility and speed makes Python an ideal language for applied
More informationProgramming for Engineers in Python
Programming for Engineers in Python Autumn 2016-17 Lecture 11: NumPy & SciPy Introduction, Plotting and Data Analysis 1 Today s Plan Introduction to NumPy & SciPy Plotting Data Analysis 2 NumPy and SciPy
More informationLECTURE 19. Numerical and Scientific Packages
LECTURE 19 Numerical and Scientific Packages NUMERICAL AND SCIENTIFIC APPLICATIONS As you might expect, there are a number of third-party packages available for numerical and scientific computing that
More informationNumpy fast array interface
NUMPY Numpy fast array interface Standard Python is not well suitable for numerical computations lists are very flexible but also slow to process in numerical computations Numpy adds a new array data type
More informationNumPy and SciPy. Shawn T. Brown Director of Public Health Applications Pittsburgh Supercomputing Center Pittsburgh Supercomputing Center
NumPy and SciPy Shawn T. Brown Director of Public Health Applications Pittsburgh Supercomputing Center 2012 Pittsburgh Supercomputing Center What are NumPy and SciPy NumPy and SciPy are open-source add-on
More informationDerek Bridge School of Computer Science and Information Technology University College Cork
CS4618: rtificial Intelligence I Vectors and Matrices Derek Bridge School of Computer Science and Information Technology University College Cork Initialization In [1]: %load_ext autoreload %autoreload
More informationMLCV 182: Practical session 1 Ron Shapira Weber Computer Science, Ben-Gurion University
MLCV 182: Practical session 1 Ron Shapira Weber Computer Science, Ben-Gurion University Getting Started There are two different versions of Python being supported at the moment, 2.7 and 3.6. For compatibility
More informationNumPy. Arno Proeme, ARCHER CSE Team Attributed to Jussi Enkovaara & Martti Louhivuori, CSC Helsinki
NumPy Arno Proeme, ARCHER CSE Team aproeme@epcc.ed.ac.uk Attributed to Jussi Enkovaara & Martti Louhivuori, CSC Helsinki Reusing this material This work is licensed under a Creative Commons Attribution-
More informationDSC 201: Data Analysis & Visualization
DSC 201: Data Analysis & Visualization Arrays Dr. David Koop Class Example class Rectangle: def init (self, x, y, w, h): self.x = x self.y = y self.w = w self.h = h def set_corner(self, x, y): self.x =
More informationCreating a new data type
Appendix B Creating a new data type Object-oriented programming languages allow programmers to create new data types that behave much like built-in data types. We will explore this capability by building
More informationNumPy. Computational Physics. NumPy
NumPy Computational Physics NumPy Outline Some Leftovers Get people on line! Write a function / Write a script NumPy NumPy Arrays; dexing; Iterating Creating Arrays Basic Operations Copying Linear Algebra
More informationNumerical Calculations
Fundamentals of Programming (Python) Numerical Calculations Sina Sajadmanesh Sharif University of Technology Some slides have been adapted from Scipy Lecture Notes at http://www.scipy-lectures.org/ Outline
More informationComputational Physics
Computational Physics Objects : Lists & Arrays Prof. Paul Eugenio Department of Physics Florida State University Jan 24, 2019 http://hadron.physics.fsu.edu/~eugenio/comphy/ Announcements Read chapter 3
More informationThe SciPy Stack. Jay Summet
The SciPy Stack Jay Summet May 1, 2014 Outline Numpy - Arrays, Linear Algebra, Vector Ops MatPlotLib - Data Plotting SciPy - Optimization, Scientific functions TITLE OF PRESENTATION 2 What is Numpy? 3rd
More informationPhys Techniques of Radio Astronomy Part 1: Python Programming LECTURE 3
Phys 60441 Techniques of Radio Astronomy Part 1: Python Programming LECTURE 3 Tim O Brien Room 3.214 Alan Turing Building tim.obrien@manchester.ac.uk Tuples Lists and strings are examples of sequences.
More informationIntelligente Datenanalyse Intelligent Data Analysis
Universität Potsdam Institut für Informatik Lehrstuhl Maschinelles Lernen Intelligent Data Analysis Tobias Scheffer, Gerrit Gruben, Nuno Marquez Plan for this lecture Introduction to Python Main goal is
More informationCMSC201 Computer Science I for Majors
CMSC201 Computer Science I for Majors Lecture 25 Classes All materials copyright UMBC and Dr. Katherine Gibson unless otherwise noted Run time Last Class We Covered Run time of different algorithms Selection,
More informationNumerical Programming in Python
Numerical Programming in Python p. 1/?? Numerical Programming in Python Part III: Using Python for Numerics Nick Maclaren Computing Service nmm1@cam.ac.uk, ext. 34761 February 2006 Numerical Programming
More informationWhy NumPy / SciPy? NumPy / SciPy / Matplotlib. A Tour of NumPy. Initializing a NumPy array
NumPy / SciPy / Matplotlib NumPy is an extension to Python adding support for arrays and matrices, along with a large library of high-level mathematical functions to operate on them. SciPy is a library
More informationNumPy quick reference
John W. Shipman 2016-05-30 12:28 Abstract A guide to the more common functions of NumPy, a numerical computation module for the Python programming language. This publication is available in Web form1 and
More informationIntroduction to Machine Learning. Useful tools: Python, NumPy, scikit-learn
Introduction to Machine Learning Useful tools: Python, NumPy, scikit-learn Antonio Sutera and Jean-Michel Begon September 29, 2016 2 / 37 How to install Python? Download and use the Anaconda python distribution
More informationPython for Scientists
High level programming language with an emphasis on easy to read and easy to write code Includes an extensive standard library We use version 3 History: Exists since 1991 Python 3: December 2008 General
More informationPYTHON NUMPY TUTORIAL CIS 581
PYTHON NUMPY TUTORIAL CIS 581 VARIABLES AND SPYDER WORKSPACE Spyder is a Python IDE that s a part of the Anaconda distribution. Spyder has a Python console useful to run commands quickly and variables
More informationExercise: Introduction to NumPy arrays
Exercise: Introduction to NumPy arrays Aim: Introduce basic NumPy array creation and indexing Issues covered: Importing NumPy Creating an array from a list Creating arrays of zeros or ones Understanding
More informationIAP Python - Lecture 4
IAP Python - Lecture 4 Andrew Farrell MIT SIPB January 13, 2011 NumPy, SciPy, and matplotlib are a collection of modules that together are trying to create the functionality of MATLAB in Python. Andrew
More informationPython Numpy (1) Intro to multi-dimensional array & numerical linear algebra. Harry Lee January 29, 2018 CEE 696
Python Numpy (1) Intro to multi-dimensional array & numerical linear algebra Harry Lee January 29, 2018 CEE 696 Table of contents 1. Introduction 2. Linear Algebra 1 Introduction From the last lecture
More informationProblem Based Learning 2018
Problem Based Learning 2018 Introduction to Machine Learning with Python L. Richter Department of Computer Science Technische Universität München Monday, Jun 25th L. Richter PBL 18 1 / 21 Overview 1 2
More informationNumPy and SciPy. Lab Objective: Create and manipulate NumPy arrays and learn features available in NumPy and SciPy.
Lab 2 NumPy and SciPy Lab Objective: Create and manipulate NumPy arrays and learn features available in NumPy and SciPy. Introduction NumPy and SciPy 1 are the two Python libraries most used for scientific
More informationINHERITANCE AND INTERFACES 7
INHERITANCE AND INTERFACES 7 COMPUTER SCIENCE 61A October 16, 2014 1 Inheritance Today, we explore another powerful tool that comes with object-oriented programming inheritance. Suppose we want to write
More informationImplement NN using NumPy
Implement NN using NumPy Hantao Zhang Deep Learning with Python Reading: https://www.tutorialspoint.com/numpy/ Recommendation for Using Python Install anaconda on your PC. If you already have installed
More informationPart VI. Scientific Computing in Python. Alfredo Parra : Scripting with Python Compact Max-PlanckMarch 6-10,
Part VI Scientific Computing in Python Compact Course @ Max-PlanckMarch 6-10, 2017 63 Doing maths in Python Standard sequence types (list, tuple,... ) Can be used as arrays Can contain different types
More informationHW0 v3. October 2, CSE 252A Computer Vision I Fall Assignment 0
HW0 v3 October 2, 2018 1 CSE 252A Computer Vision I Fall 2018 - Assignment 0 1.0.1 Instructor: David Kriegman 1.0.2 Assignment Published On: Tuesday, October 2, 2018 1.0.3 Due On: Tuesday, October 9, 2018
More informationIntroduction to Programming Using Java (98-388)
Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;
More informationDSC 201: Data Analysis & Visualization
DSC 201: Data Analysis & Visualization Classes & Arrays Dr. David Koop Sets Sets are like dictionaries but without any values: s = {'MA', 'RI', 'CT', 'NH'}; t = {'MA', 'NY', 'NH'} {} is an empty dictionary,
More informationAn array is a collection of data that holds fixed number of values of same type. It is also known as a set. An array is a data type.
Data Structures Introduction An array is a collection of data that holds fixed number of values of same type. It is also known as a set. An array is a data type. Representation of a large number of homogeneous
More information(DRAFT) PYTHON FUNDAMENTALS II: NUMPY & MATPLOTLIB
(DRAFT) PYTHON FUNDAMENTALS II: NUMPY & MATPLOTLIB TROY P. KLING Contents 1. Importing Libraries 1 2. Introduction to numpy 2 3. Introduction to matplotlib 5 4. Image Processing 8 5. The Mandelbrot Set
More informationAlgorithms and Programming
Algorithms and Programming Lecture 6 Classes, UML, NumPy Camelia Chira Course content Introduction in the software development process Procedural programming Modular programming Abstract data types Software
More informationDSC 201: Data Analysis & Visualization
DSC 201: Data Analysis & Visualization Arrays and Series Dr. David Koop Exception Example def divide(mylist, x,y): newlist = [] try: z = x // y below, mid, above = \ mylist[:z], mylist[z], mylist[z+1:]
More informationSession 04: Introduction to Numpy
Session 04: Introduction to Numpy October 9th, 2017 Wouter Klijn Overview Introduction Hello world Arrays Creating Interacting Copying Differences with Matlab Matrixes vs Array Why Why not Matlib module
More informationPart I. Wei Tianwen. A Brief Introduction to Python. Part I. Wei Tianwen. Basics. Object Oriented Programming
2017 Table of contents 1 2 Integers and floats Integer int and float float are elementary numeric types in. integer >>> a=1 >>> a 1 >>> type (a) Integers and floats Integer int and float
More informationHow to declare an array in C?
Introduction An array is a collection of data that holds fixed number of values of same type. It is also known as a set. An array is a data type. Representation of a large number of homogeneous values.
More informationEffective Programming Practices for Economists. 10. Some scientific tools for Python
Effective Programming Practices for Economists 10. Some scientific tools for Python Hans-Martin von Gaudecker Department of Economics, Universität Bonn A NumPy primer The main NumPy object is the homogeneous
More informationCSC Advanced Scientific Computing, Fall Numpy
CSC 223 - Advanced Scientific Computing, Fall 2017 Numpy Numpy Numpy (Numerical Python) provides an interface, called an array, to operate on dense data buffers. Numpy arrays are at the core of most Python
More informationRobot Vision Systems Lecture 3: Methods for Dense Matrices in OpenCV
Computer Vision Laboratory Robot Vision Systems Lecture 3: Methods for Dense Matrices in OpenCV Michael Felsberg michael.felsberg@liu.se Further Methods Mat::diag(int d=0) (d0 lower half) Mat::convertTo(OutputArray,int
More informationMatrices. A Matrix (This one has 2 Rows and 3 Columns) To add two matrices: add the numbers in the matching positions:
Matrices A Matrix is an array of numbers: We talk about one matrix, or several matrices. There are many things we can do with them... Adding A Matrix (This one has 2 Rows and 3 Columns) To add two matrices:
More informationWhat is MATLAB? What is MATLAB? Programming Environment MATLAB PROGRAMMING. Stands for MATrix LABoratory. A programming environment
What is MATLAB? MATLAB PROGRAMMING Stands for MATrix LABoratory A software built around vectors and matrices A great tool for numerical computation of mathematical problems, such as Calculus Has powerful
More informationFinal exam. Final exam will be 12 problems, drop any 2. Cumulative up to and including week 14 (emphasis on weeks 9-14: classes & pointers)
Review Final exam Final exam will be 12 problems, drop any 2 Cumulative up to and including week 14 (emphasis on weeks 9-14: classes & pointers) 2 hours exam time, so 12 min per problem (midterm 2 had
More informationLecture 15: High Dimensional Data Analysis, Numpy Overview
Lecture 15: High Dimensional Data Analysis, Numpy Overview Chris Tralie, Duke University 3/3/2016 Announcements Mini Assignment 3 Out Tomorrow, due next Friday 3/11 11:55PM Rank Top 3 Final Project Choices
More informationcosmos_python_ Python as calculator May 31, 2018
cosmos_python_2018 May 31, 2018 1 Python as calculator Note: To convert ipynb to pdf file, use command: ipython nbconvert cosmos_python_2015.ipynb --to latex --post pdf In [3]: 1 + 3 Out[3]: 4 In [4]:
More informationCOMP1730/COMP6730 Programming for Scientists. Sequence types, part 2
COMP1730/COMP6730 Programming for Scientists Sequence types, part 2 Lecture outline * Lists * Mutable objects & references Sequence data types (recap) * A sequence contains n 0 values (its length), each
More informationCS129: Introduction to Matlab (Code)
CS129: Introduction to Matlab (Code) intro.m Introduction to Matlab (adapted from http://www.stanford.edu/class/cs223b/matlabintro.html) Stefan Roth , 09/08/2003 Stolen
More information1 2 (3 + x 3) x 2 = 1 3 (3 + x 1 2x 3 ) 1. 3 ( 1 x 2) (3 + x(0) 3 ) = 1 2 (3 + 0) = 3. 2 (3 + x(0) 1 2x (0) ( ) = 1 ( 1 x(0) 2 ) = 1 3 ) = 1 3
6 Iterative Solvers Lab Objective: Many real-world problems of the form Ax = b have tens of thousands of parameters Solving such systems with Gaussian elimination or matrix factorizations could require
More informationExceptions & a Taste of Declarative Programming in SQL
Exceptions & a Taste of Declarative Programming in SQL David E. Culler CS8 Computational Structures in Data Science http://inst.eecs.berkeley.edu/~cs88 Lecture 12 April 18, 2016 Computational Concepts
More informationPython Review CS224N - 1/19/18. Jay Whang and Zach Maurer Stanford University
Python Review CS224N - 1/19/18 Jay Whang and Zach Maurer Stanford University Topics 1. Why Python? 2. Language Basics 3. Introduction to Numpy 4. Practical Python Tips 5. Other Great References Why Python?
More informationLab 4 S Objectives. The string type. Exercise 0
Lab 4 S2 2017 Lab 4 Note: There may be more exercises in this lab than you can finish during the lab time. If you do not have time to finish all exercises (in particular, the programming problems), you
More informationCOMPSCI 105 S Principles of Computer Science. Classes 3
S2 2017 Principles of Computer Science Classes 3 Exercise } Exercise } Create a Student class: } The Student class should have three attributes: id, last_name, and first_name. } Create a constructor to
More informationComputational Physics Adaptive, Multi-Dimensional, & Monte Carlo Integration Feb 21, 2019
Computational Physics Adaptive, Multi-Dimensional, & Monte Carlo Integration Feb 21, 219 http://hadron.physics.fsu.edu/~eugenio/comphy/ eugenio@fsu.edu f(x) trapezoidal rule Series Integration review from
More informationCSI33 Data Structures
Outline Department of Mathematics and Computer Science Bronx Community College September 6, 2017 Outline Outline 1 Chapter 2: Data Abstraction Outline Chapter 2: Data Abstraction 1 Chapter 2: Data Abstraction
More informationLecture 21. Programming with Subclasses
Lecture 21 Programming with Subclasses Announcements for Today Reading Today: See reading online Tuesday: Chapter 7 Prelim, Nov 10 th 7:30-9:00 Material up to Today Review has been posted Recursion + Loops
More informationMathematics. Jaehyun Park. CS 97SI Stanford University. June 29, 2015
Mathematics Jaehyun Park CS 97SI Stanford University June 29, 2015 Outline Algebra Number Theory Combinatorics Geometry Algebra 2 Sum of Powers n k=1 k 3 k 2 = 1 n(n + 1)(2n + 1) 6 = ( k ) 2 = ( 1 2 n(n
More informationLecture 21. Programming with Subclasses
Lecture 21 Programming with Subclasses Announcements for Today Reading Today: See reading online Tuesday: Chapter 7 Prelim, Nov 9 th 7:30-9:00 Material up to Today Review has been posted Recursion + Loops
More informationINTRODUCTION TO DATA SCIENCE
INTRODUCTION TO DATA SCIENCE JOHN P DICKERSON PREM SAGGAR Today! Lecture #3 9/5/2018 CMSC320 Mondays & Wednesdays 2pm 3:15pm ANNOUNCEMENTS Register on Piazza: piazza.com/umd/fall2018/cmsc320 219 have registered
More informationMatrix Multiplication
Matrix Multiplication CPS343 Parallel and High Performance Computing Spring 2018 CPS343 (Parallel and HPC) Matrix Multiplication Spring 2018 1 / 32 Outline 1 Matrix operations Importance Dense and sparse
More informationPython for Finance. Control Flow, data structures and first application (part 2) Andras Niedermayer
Python for Finance Control Flow, data structures and first application (part 2) Andras Niedermayer Outline 1 Control Flow 2 Modules 3 Data types and structures. Working with arrays and matrices. 4 Numpy
More informationChapter 5 : Informatics Practices. Class XII ( As per CBSE Board) Numpy - Array. New Syllabus Visit : python.mykvs.in for regular updates
Chapter 5 : Informatics Practices Class XII ( As per CBSE Board) Numpy - Array New Syllabus 2019-20 NumPy stands for Numerical Python.It is the core library for scientific computing in Python. It consist
More informationSciPy. scipy [www.scipy.org and links on course web page] scipy arrays
SciPy scipy [www.scipy.org and links on course web page] - scipy is a collection of many useful numerical algorithms (numpy is the array core) - Python wrappers around compiled libraries and subroutines
More informationPC-MATLAB PRIMER. This is intended as a guided tour through PCMATLAB. Type as you go and watch what happens.
PC-MATLAB PRIMER This is intended as a guided tour through PCMATLAB. Type as you go and watch what happens. >> 2*3 ans = 6 PCMATLAB uses several lines for the answer, but I ve edited this to save space.
More informationPython An Introduction
Python An Introduction Calle Lejdfors and Lennart Ohlsson calle.lejdfors@cs.lth.se Python An Introduction p. 1 Overview Basic Python Numpy Python An Introduction p. 2 What is Python? Python plays a key
More informationAbsent: Lecture 3 Page 1. def foo(a, b): a = 5 b[0] = 99
1. A function is a procedural abstract (a named body of code to perform some action and return a resulting value). The syntax of a function definition is: def functionname([parameter [, parameter]*]):
More informationIntroduction to Matlab
Introduction to Matlab Andreas C. Kapourani (Credit: Steve Renals & Iain Murray) 9 January 08 Introduction MATLAB is a programming language that grew out of the need to process matrices. It is used extensively
More informationPROGRAMMING IN C AND C++:
PROGRAMMING IN C AND C++: Week 1 1. Introductions 2. Using Dos commands, make a directory: C:\users\YearOfJoining\Sectionx\USERNAME\CS101 3. Getting started with Visual C++. 4. Write a program to print
More information2.1 Indefinite Loops. while <condition>: <body> rabbits = 3 while rabbits > 0: print rabbits rabbits -= 1
2.1 Indefinite Loops The final kind of control flow is Python s indefinite loop, the while loop. It functions much like the for loop in that it repeatedly executes some body of statements. The difference
More information2-9 Operations with Complex Numbers
2-9 Operations with Complex Numbers Warm Up Lesson Presentation Lesson Quiz Algebra 2 Warm Up Express each number in terms of i. 1. 9i 2. Find each complex conjugate. 3. 4. Find each product. 5. 6. Objective
More informationVector: A series of scalars contained in a column or row. Dimensions: How many rows and columns a vector or matrix has.
ASSIGNMENT 0 Introduction to Linear Algebra (Basics of vectors and matrices) Due 3:30 PM, Tuesday, October 10 th. Assignments should be submitted via e-mail to: matlabfun.ucsd@gmail.com You can also submit
More informationCourse Number 432/433 Title Algebra II (A & B) H Grade # of Days 120
Whitman-Hanson Regional High School provides all students with a high- quality education in order to develop reflective, concerned citizens and contributing members of the global community. Course Number
More informationSearch. The Nearest Neighbor Problem
3 Nearest Neighbor Search Lab Objective: The nearest neighbor problem is an optimization problem that arises in applications such as computer vision, pattern recognition, internet marketing, and data compression.
More informationConstraint-based Metabolic Reconstructions & Analysis H. Scott Hinton. Matlab Tutorial. Lesson: Matlab Tutorial
1 Matlab Tutorial 2 Lecture Learning Objectives Each student should be able to: Describe the Matlab desktop Explain the basic use of Matlab variables Explain the basic use of Matlab scripts Explain the
More informationEuclid's Algorithm. MA/CSSE 473 Day 06. Student Questions Odd Pie Fight Euclid's algorithm (if there is time) extended Euclid's algorithm
MA/CSSE 473 Day 06 Euclid's Algorithm MA/CSSE 473 Day 06 Student Questions Odd Pie Fight Euclid's algorithm (if there is time) extended Euclid's algorithm 1 Quick look at review topics in textbook REVIEW
More informationMatrix Multiplication
Matrix Multiplication CPS343 Parallel and High Performance Computing Spring 2013 CPS343 (Parallel and HPC) Matrix Multiplication Spring 2013 1 / 32 Outline 1 Matrix operations Importance Dense and sparse
More informationTheano Tutorials. Ian Goodfellow
Theano Tutorials Ian Goodfellow Outline 1. Basic usage: How to write a theano program 2. Advanced usage: Symbolic manipulations and debugging, etc. 3A. Internals: how to add your own features 3B. Machine
More informationMathematics 308 Geometry. Chapter 9. Drawing three dimensional objects
Mathematics 308 Geometry Chapter 9. Drawing three dimensional objects In this chapter we will see how to draw three dimensional objects with PostScript. The task will be made easier by a package of routines
More informationIntro to scientific Python in 45'
Intro to scientific Python in 45' ... or Python for Matlab Users Getting help at the center Ask your questions on the martinos-python mailing list: martinos-python@nmr.mgh.harvard.edu you can at subscribe:
More informationCourse Learning Outcomes for Unit I. Reading Assignment. Unit Lesson. UNIT I STUDY GUIDE Number Theory and the Real Number System
UNIT I STUDY GUIDE Number Theory and the Real Number System Course Learning Outcomes for Unit I Upon completion of this unit, students should be able to: 2. Relate number theory, integer computation, and
More informationInstantiation of Template class
Class Templates Templates are like advanced macros. They are useful for building new classes that depend on already existing user defined classes or built-in types. Example: stack of int or stack of double
More informationAlgorithmic number theory Cryptographic hardness assumptions. Table of contents
Algorithmic number theory Cryptographic hardness assumptions Foundations of Cryptography Computer Science Department Wellesley College Fall 2016 Table of contents Introduction Primes and Divisibility Modular
More informationOverview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017
Overview of OOP Dr. Zhang COSC 1436 Summer, 2017 7/18/2017 Review Data Structures (list, dictionary, tuples, sets, strings) Lists are enclosed in square brackets: l = [1, 2, "a"] (access by index, is mutable
More informationDesign Patterns: State, Bridge, Visitor
Design Patterns: State, Bridge, Visitor State We ve been talking about bad uses of case statements in programs. What is one example? Another way in which case statements are sometimes used is to implement
More information