PYTHON NUMPY TUTORIAL CIS 581

Similar documents
Python Numpy (1) Intro to multi-dimensional array & numerical linear algebra. Harry Lee January 29, 2018 CEE 696

NumPy. Daniël de Kok. May 4, 2017

MLCV 182: Practical session 1 Ron Shapira Weber Computer Science, Ben-Gurion University

Chapter 5 : Informatics Practices. Class XII ( As per CBSE Board) Numpy - Array. New Syllabus Visit : python.mykvs.in for regular updates

Numerical Methods. Centre for Mathematical Sciences Lund University. Spring 2015

Python for Scientists

PYTHON FOR MEDICAL PHYSICISTS. Radiation Oncology Medical Physics Cancer Care Services, Royal Brisbane & Women s Hospital

NumPy Primer. An introduction to numeric computing in Python

DSC 201: Data Analysis & Visualization

MS6021 Scientific Computing. TOPICS: Python BASICS, INTRO to PYTHON for Scientific Computing

Introduction to NumPy

Python Crash Course Numpy, Scipy, Matplotlib

HW0 v3. October 2, CSE 252A Computer Vision I Fall Assignment 0

Lists How lists are like strings

Introduction to Machine Learning. Useful tools: Python, NumPy, scikit-learn

Python Tutorial. CS/CME/BioE/Biophys/BMI 279 Oct. 17, 2017 Rishi Bedi

COMP1730/COMP6730 Programming for Scientists. Sequence types, part 2

Programming for Engineers in Python

Short Introduction to Python Machine Learning Course Laboratory

Introduction to Python Part 2

Exercise: Introduction to NumPy arrays

Implement NN using NumPy

ARTIFICIAL INTELLIGENCE AND PYTHON

Handling arrays in Python (numpy)

Introduction to Python (All the Basic Stuff)

The Python interpreter

NumPy quick reference

ENGR 102 Engineering Lab I - Computation

Lab 1 - Basic ipython Tutorial (EE 126 Fall 2014)

Numpy fast array interface

Chapter 2. Python Programming for Physicists. Soon-Hyung Yook. March 31, Soon-Hyung Yook Chapter 2 March 31, / 52

Week Two. Arrays, packages, and writing programs

LECTURE 19. Numerical and Scientific Packages

Lecture 1: Introduction to Python

Numerical Calculations

Intelligente Datenanalyse Intelligent Data Analysis

Introduction to Scientific Computing with Python, part two.

Part VI. Scientific Computing in Python. Alfredo Parra : Scripting with Python Compact Max-PlanckMarch 6-10,

Scientific Computing with Python. Quick Introduction

CSC Advanced Scientific Computing, Fall Numpy

Intro to scientific Python in 45'

Visualize ComplexCities

Introduction to Python Practical 1

Introduction to Python Part 1. Brian Gregor Research Computing Services Information Services & Technology

NumPy and SciPy. Lab Objective: Create and manipulate NumPy arrays and learn features available in NumPy and SciPy.

Session 1: Introduction to Python from the Matlab perspective. October 9th, 2017 Sandra Diaz

7 Control Structures, Logical Statements

Python Review CS224N - 1/19/18. Jay Whang and Zach Maurer Stanford University

Control Structures 1 / 17

Fundamentals: Expressions and Assignment

CPSC 217 Midterm (Python 3 version)

Derek Bridge School of Computer Science and Information Technology University College Cork

Babu Madhav Institute of Information Technology, UTU 2015

Introduction to Scientific Python, CME 193 Jan. 9, web.stanford.edu/~ermartin/teaching/cme193-winter15

Course May 18, Advanced Computational Physics. Course Hartmut Ruhl, LMU, Munich. People involved. SP in Python: 3 basic points

Introduction to Computer Programming CSCI-UA 2. Review Midterm Exam 1

Computational Physics

Introduction to Mathematical and Scientific Programming TUTORIAL WEEK 1 (MATH 1MP3) Winter 2019

Why NumPy / SciPy? NumPy / SciPy / Matplotlib. A Tour of NumPy. Initializing a NumPy array

LECTURE 22. Numerical and Scientific Packages

Comp 150 Exam 2 Overview.

Part 1 (80 points) Multiple Choice Questions (20 questions * 4 points per question = 80 points)

cosmos_python_ Python as calculator May 31, 2018

Chapter 4 : Informatics Practices. Data Handling. Class XI ( As per CBSE Board) Visit : python.mykvs.in for regular updates

Chapter 3 : Computer Science. Class XI ( As per CBSE Board) Data Handling. Visit : python.mykvs.in for regular updates

Ch.1 Introduction. Why Machine Learning (ML)? manual designing of rules requires knowing how humans do it.

The SciPy Stack. Jay Summet

Table of Contents. Preface... xxi

Introduction to Python: The Multi-Purpose Programming Language. Robert M. Porsch June 14, 2017

Python Compact. 1 Python Compact. 2 What do we cover in this introduction lecture? February 7, What is also interesting to know?

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

NumPy. Computational Physics. NumPy

python 01 September 16, 2016

06/11/2014. Subjects. CS Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / ) Beginning with Python

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

Overview of List Syntax

Constraint-based Metabolic Reconstructions & Analysis H. Scott Hinton. Matlab Tutorial. Lesson: Matlab Tutorial

CSE 115. Introduction to Computer Science I

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Python Tutorial for CSE 446

Introduction to Python and NumPy I

Ch.1 Introduction. Why Machine Learning (ML)?

Shell / Python Tutorial. CS279 Autumn 2017 Rishi Bedi

Crash Dive into Python

Python 1: Intro! Max Dougherty Andrew Schmitt

D R S H YA M N C H AW D A

(DRAFT) PYTHON FUNDAMENTALS II: NUMPY & MATPLOTLIB

debugging, hexadecimals, tuples

GE PROBLEM SOVING AND PYTHON PROGRAMMING. Question Bank UNIT 1 - ALGORITHMIC PROBLEM SOLVING

Onion Language Reference Manual. By: Andrew Aday, (aza2112) Amol Kapoor (ajk2227), Jonathan Zhang (jz2814)

DSC 201: Data Analysis & Visualization

Problem Based Learning 2018

CSSE 120 Introduction to Software Development Practice for Test 1 paper-and-pencil part Page 1 of 6

ENGR (Socolofsky) Week 07 Python scripts

SECTION 1: INTRODUCTION. ENGR 112 Introduction to Engineering Computing

Python for Data Analysis. Prof.Sushila Aghav-Palwe Assistant Professor MIT

Certified Data Science with Python Professional VS-1442

An Introduction to MATLAB

Introduction to Programming II W4260. Lecture 2

TMA4320 Tips for Python Coding

Transcription:

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 can be seen in the Variable Explorer. Similar to MATLAB s command window. a = 3 - defines a variable. No need to specify variable type. Documentation. print(type(a)) # Prints "<class 'int'>" print(a + 1) # Addition; prints "4" print(a ** 2) # Exponentiation; prints "9". ** Represents exponentiation, not ^. print(a *= 2) # Prints "6" Comments start with a #. In Spyder, use #%% to define a region (Each IDE/text editor has its own command). Multiline comments are between a pair of """.

BOOLEANS Python implements all the usual operators for Boolean logic, but uses English words rather than symbols (&&,, etc.) t = True f = False print(type(t)) # Prints "<class 'bool'>" print(t and f) # Logical AND; prints "False" print(t or f) # Logical OR; prints "True" print(not t) # Logical NOT; prints "False" print(t!= f) # Logical XOR; prints "True

LISTS Python has many different data structures like lists, dictionaries, sets and tuples. In this tutorial we ll take a look at just lists. Documentation. More on lists. Note: Unlike MATLAB, Python indexing starts at 0. xs = [3, 1, 2] # Create a list print(xs, xs[2]) # Prints "[3, 1, 2] 2 xs[2] = 'foo' print(xs) # Lists can contain elements of different types # Prints "[3, 1, 'foo']" xs.append('bar') # Add a new element to the end of the list print(xs) x = xs.pop() print(x, xs) # Prints "[3, 1, 'foo', 'bar']" # Remove and return the last element of the list # Prints "bar [3, 1, 'foo']"

SLICING IN LISTS Slicing in lists is pretty useful in Python. Here s a brief introduction. We ll mostly focus on slicing using NumPy. nums = list(range(5)) print(nums) # Prints "[0, 1, 2, 3, 4]" # range is a built-in function that creates a list of integers print(nums[2:4]) # Get a slice from index 2 to 4 (exclusive); prints "[2, 3]" print(nums[2:]) # Get a slice from index 2 to the end; prints "[2, 3, 4]" nums[2:4] = [8, 9] # Assign a new sublist to a slice print(nums) # Prints "[0, 1, 8, 9, 4]"

FUNCTIONS, LOOPS AND CONDITIONALS Python functions are defined using the def keyword. Conditional statements documentation, Functions documentation. def sign(x): if x > 0: return 'positive elif x < 0: return 'negative else: return 'zero' for x in [-1, 0, 1]: print(sign(x)) # Prints "negative", "zero", "positive" NOTE: Indentation in Python is used to determine the grouping of statements. e.g.: Loops, If-Else, Functions. Use TABS

VECTORS, ARRAYS USING NUMPY A NumPy array is a grid of values, all of the same type. The shape of an array is a tuple of integers giving the size of the array along each dimension. Array Creation import numpy as np a = np.array([1, 2, 3]) # Create a rank 1 array print(a.shape) print(a[0], a[1], a[2]) # Prints "1 2 3" b = np.array([[1,2,3],[4,5,6]]) print(b.shape) # Prints "(2, 3)" # Prints "(3,). Indicates 3 elements along a dimension. # Create a rank 2 array print(b[0, 0], b[0, 1], b[1, 0]) # Prints "1 2 4"

OTHER METHODS TO CREATE ARRAYS import numpy as np a = np.zeros((2,2)) # Create an array of all zeros b = np.ones((1,2)) # Create an array of all ones c = np.full((2,2), 7) # Create a 2x2 array where all elements are equal to 7. d = np.eye(2) # Create a 2x2 identity matrix e = np.random.random((2,2)) # Create an array filled with random values Documentation.

NUMPY DATATYPES Every NumPy array is a grid of elements of the same type. NumPy provides a large set of numeric datatypes that you can use to construct arrays. NumPy tries to guess a datatype when you create an array, but functions that construct arrays usually also include an optional argument to explicitly specify the datatype. Here is an example: import numpy as np x = np.array([1.0, 2.0]) # Let numpy choose the datatype print(x.dtype) # Prints "float64" x = np.array([1, 2], dtype=np.int64) # Force a particular datatype print(x.dtype) # Prints "int64"

IMPORTANT FUNCTIONS np.sin, np.cos, np.tan, np.radians, np.angles Elementwise np.round, np.ceil, np.floor Elementwise np.cumsum, np.log, np.exp Elementwise np.max, np.min, np.interp Elementwise np.linalg.norm, np.linalg.det, np.trace, np.linalg.inv, np.linalg.pinv np.matlib.repmat, np.lib.pad np.sort, np.argsort, np.count_nonzero np.copyto, np.reshape, np.ravel, np.asarray

NUMPY ARRAY INDEXING Numpy offers several ways to index into arrays. Slicing: Similar to Python lists, numpy arrays can be sliced. Since arrays may be multidimensional, you must specify a slice for each dimension of the array. Boolean array indexing: np.where() returns a Boolean array. CODE. Documentation.

ROW MAJOR AND COLUMN MAJOR By default, NumPy is Row Major. It can, however, be forced to operate in Column Major. CODE.

NUMPY OPERATIONS - MATH Elementwise Sum. Elementwise difference. Elementwise product. Elementwise division. Elementwise square root. Unlike MATLAB, * is an elementwise multiplication, not multiplication. Use np.dot() to multiply matrices or to computer inner product of two vectors. Documentation.

SAVE AND LOAD PKL, NPY, MAT Pickle NumPy MAT Files CODE.

PLOTTING AND DISPLAYING IMAGES 2D Plot with 1 function 2D Plot with multiple functions Subplots Displaying images CODE.

DEBUGGING Breakpoints Pdb Useful for text editors like Sublime, notepad++. CODE. PDB Tutorial.

MORE RESOURCES Parts of this tutorial have been taken from the CS231n Python NumPy Tutorial: http://cs231n.github.io/python-numpy-tutorial/ Learn Python Online: https://www.learnpython.org/ Learn NumPy Online: https://www.tutorialspoint.com/numpy/ (Also Python) Python 2.7 documentation: https://docs.python.org/2/index.html NumPy and SciPy documentation: https://docs.scipy.org/doc/