BogoToBogo
  • Home
  • About
  • Big Data
  • Machine Learning
  • AngularJS
  • Python
  • C++
  • go
  • DevOps
  • Kubernetes
  • Algorithms
  • More...
    • Qt 5
    • Linux
    • FFmpeg
    • Matlab
    • Django 1.8
    • Ruby On Rails
    • HTML5 & CSS

NumPy array basics B

python_logo




Bookmark and Share





bogotobogo.com site search:

NumPy array

This chapter is the continuation from NumPy Array Basics A. We've been playing with the following NumPy array:

>>> import numpy as np
>>> rArray = np.arange(0,20).reshape((5,4))
>>> rArray
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15],
       [16, 17, 18, 19]]) 

In previous chapter, we've learned slicing NumPy array works just like python list.




Assigning values to a NumPy array

Much like python lists, we can assign values to specific positions:

>>> squareArray = rArray[:3:,:3,]
>>> squareArray
array([[  0,   1,   2],
       [  4,  50,   6],
       [  8,   9, 100]])
>>> squareArray[0,0] *= 10
>>> squareArray[1,1] *= 10
>>> squareArray[2,2] *= 10
>>> squareArray
array([[   0,    1,    2],
       [   4,  500,    6],
       [   8,    9, 1000]])



Assigning values to a slice of NumPy array

We can slice a NumPy array, and assign values to it. The example below, slices the first row and assigns -1 to the elements of the 1st row:

>>> squareArray
array([[   0,    1,    2],
       [   4,  500,    6],
       [   8,    9, 1000]])
>>> squareArray[:1:,] = -1
>>> squareArray
array([[  -1,   -1,   -1],
       [   4,  500,    6],
       [   8,    9, 1000]])


Indexing using an array of indices

We can indexing NumPy array using an array of indices:

>>> import numpy as np
>>> indxArr = np.array([0,1,1,2,3])
>>> indxArr
array([0, 1, 1, 2, 3])
>>> rnd = np.random.random((10,1))
>>> rnd
array([[ 0.20903716],
       [ 0.98787586],
       [ 0.12038364],
       [ 0.54208977],
       [ 0.49319279],
       [ 0.77011847],
       [ 0.57856482],
       [ 0.55202036],
       [ 0.58084383],
       [ 0.45641956]])
>>> rnd[indxArr]
array([[ 0.20903716],
       [ 0.98787586],
       [ 0.98787586],
       [ 0.12038364],
       [ 0.54208977]])

We first defined NumPy index array, indxArr, and then use it to access elements of random NumPy array, rnd. As we can see from the output, we were able to get 0th, 1st, 1st, 2nd, and 3rd elements of the random array.




Array - empty(...)

The np.empty(...) is filled with random/junk values:

>>> import numpy as np
>>> emptyArray = np.empty((2,3))
>>> emptyArray
array([[  0.00000000e+000,   3.39519327e-313,   0.00000000e+000],
       [  4.94065646e-324,   1.83322544e-316,   6.94110822e-310]])

It looks like random, but it's not. So, if we need real random numbers, we should not use this empty(...).




Indexing using a boolean array of indices

We can do indexing NumPy array with boolean array:

>>> squareArray
array([[  -1,   -1,   -1],
       [   4,  500,    6],
       [   8,    9, 1000]])

>>> boolArray
array([[ True, False, False],
       [False,  True, False],
       [False, False,  True]], dtype=bool)
>>> squareArray[boolArray]
array([  -1,  500, 1000])

We set the index array with bool value True only for the diagonal elements, and we were able to get only those items as 1-D array.




Indexing using index row/column arrays
>>> squareArray
array([[  -1,   -1,   -1],
       [   4,  500,    6],
       [   8,    9, 1000]])

>>> indxRow = np.array([False, True, False])
>>> indxCol = np.array([True, False, True])
>>> squareArray[indxRow, indxCol]
array([4, 6])

indxRow wanted only the 2nd row, and indxCol wanted only the 1st and the 3rd, and we got the right one.

We can use a boolean matrix based on some test and use that as an index in order to get the elements of a matrix that pass the test:




Operations on arrays

We can use a boolean matrix based on some test and use that as an index in order to get the elements of a matrix that pass the test:

>>> import numpy as np
>>> myArray = np.arange(0,9).reshape(3,3)
>>> myArray
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])
>>> myAverage = np.average(myArray)
>>> myAverage
4.0
>>> aboveAverage = myArray > myAverage
>>> aboveAverage
array([[False, False, False],
       [False, False,  True],
       [ True,  True,  True]], dtype=bool)
>>> myArray[aboveAverage]
array([5, 6, 7, 8])



Clamping an array

The way of indexing as in the previous section can also be used to assign values to elements of the array. This is particularly useful if we want to filter an array. We can sure that all of its values are above/below a certain threshold:

We'll use std(...) which returns the standard deviation of all the elements in the given array.

>>> import numpy as np
>>> myArray = np.arange(0,9).reshape(3,3)
>>> myArray
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])
...
>>> myArray[aboveAverage]
array([5, 6, 7, 8])

>>> standDeviation = np.std(myArray)
>>> standardDev = np.std(myArray)
>>> standardDev
2.5819888974716112

We'll make a copy of myArray that will be clamped. It will only contain values within one standard deviation of the mean. Values that are too low or to high will be set to the min and max respectively. We set dtype=float because usually myAverage and standardDev are floating point numbers.

>>> clampedMyArray = np.array(myArray.copy(), dtype=float) 
>>> clampedMyArray
array([[ 0.,  1.,  2.],
       [ 3.,  4.,  5.],
       [ 6.,  7.,  8.]])

>>> clampedMyArray[ (myArray-myAverage) > standardDev ] = myAverage+standardDev
>>> clampedMyArray[ (myArray-myAverage) < -standardDev ] = myAverage-standardDev 
>>> clampedMyArray
array([[ 1.4180111,  1.4180111,  2.       ],
       [ 3.       ,  4.       ,  5.       ],
       [ 6.       ,  6.5819889,  6.5819889]])
>>> 



Array multiplication etc.
>>> import numpy as np
>>> myArray = np.arange(1,10).reshape(3,3)
>>> myArray
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])

>>> myArray*10
array([[10, 20, 30],
       [40, 50, 60],
       [70, 80, 90]])

>>> myZeros = myArray * np.zeros((3,3))
>>> myZeros
array([[ 0.,  0.,  0.],
       [ 0.,  0.,  0.],
       [ 0.,  0.,  0.]])

>>> addedOnes = myArray + np.ones((3,3))
>>> addedOnes
array([[  2.,   3.,   4.],
       [  5.,   6.,   7.],
       [  8.,   9.,  10.]])

{dot} is actually matrix multiplication:

>>> A = np.array( [ [1,2],[3,4] ] )
>>> B = np.array( [ [5,6],[7,8] ] )
>>> np.dot(A,B)
array([[19, 22],
       [43, 50]])



Append
>>> a = np.arange(10)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> b = a + 1
>>> b
array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10])
>>> np.append(b, [11,12])
array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12])




where
>>> numpy.where(condition[, x, y])

It return elements, either from x or y, depending on condition.
If only condition is given, return condition.nonzero().

Parameters :

  1. condition : array_like, bool When True, yield x, otherwise yield y.
  2. x, y : array_like, optional Values from which to choose. x and y need to have the same shape as condition.

Returns :

out : ndarray or tuple of ndarrays If both x and y are specified, the output array contains elements of x where condition is True, and elements from y elsewhere. If only condition is given, return the tuple condition.nonzero(), the indices where condition is True.

Only the condition is given, where returns the indices for the elements that satisfying the condition:

>>> x = np.arange(9).reshape(3,3)
>>> x
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])
>>> np.where(x>7)
(array([2]), array([2]))

It returns (2,2) as indices for the element '8'.

>>> np.where(x <= 3)
(array([0, 0, 0, 1]), array([0, 1, 2, 0]))

If several elements meet the condition, it returns indices for all those elements (1st 4 elements are <= 3) as shown in the example above.

Following example shows the case when both x and y are given with the condition. If condition is met, where() returns x-element, otherwise it returns y-element. In the example, it returns x's diagonal elements, and y's elements are returned off-diagonal positions:

>>> np.where([ [True, False, False], [False, True, False], [False, False, True] ],
...          [ [11, 12, 13], [21, 22, 23], [31, 32, 33] ],
...          [ [911, 912, 913], [921, 922, 923], [931, 932, 933] ])
array([[ 11, 912, 913],
       [921,  22, 923],
       [931, 932,  33]])

In the same context, the example below returns diagonal indices (0,0), (1,1), and (2,2):

>>> np.where( [ [1,0,0],[0,1,0],[0,0,1] ])
(array([0, 1, 2]), array([0, 1, 2]))

Let's look at more cases;

>>> x = np.arange(9.).reshape(3, 3)
>>> x
array([[ 0.,  1.,  2.],
       [ 3.,  4.,  5.],
       [ 6.,  7.,  8.]])
>>> np.where( x > 5 )
(array([2, 2, 2]), array([0, 1, 2]))
>>> x[np.where( x > 5 )]
array([ 6.,  7.,  8.])
>>> x[np.where(x<5)]
array([ 0.,  1.,  2.,  3.,  4.])

The following example works as a sort of mask: if any element of x not satisfying x < 5, -1 will replace the element:

>>> np.where(x<5, x, -1)
array([[ 0.,  1.,  2.],
       [ 3.,  4., -1.],
       [-1., -1., -1.]])




Conditional zip and where
>>> x = [1,2,3,4,5]
>>> y = [11,12,13,14,15]
>>> condition = [True,False,True,False,True]
>>> [xv if c else yv for (c,xv,yv) in zip(condition,x,y)]
[1, 12, 3, 14, 5]

The same thing can be done using NumPy's where:

>>> import numpy as np
>>> np.where([1,0,1,0,1], np.arange(1,6), np.arange(11,16))
array([ 1, 12,  3, 14,  5])




astype

The astype cast to a specified type:

>>> x = np.array([1.1, 2.2, 3.3])
>>> x
array([ 1.1,  2.2,  3.3])
>>> x.astype(int)
array([1, 2, 3])

A little bit complex example:

mask2 = np.where((mask==2)|(mask==0),0,1).astype('uint8')

If mask==2 or mask== 1, mask2 get 0, other wise it gets 1 as 'uint8' type.















Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization

YouTubeMy YouTube channel

Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong







Python tutorial



Python Home

Introduction

Running Python Programs (os, sys, import)

Modules and IDLE (Import, Reload, exec)

Object Types - Numbers, Strings, and None

Strings - Escape Sequence, Raw String, and Slicing

Strings - Methods

Formatting Strings - expressions and method calls

Files and os.path

Traversing directories recursively

Subprocess Module

Regular Expressions with Python

Regular Expressions Cheat Sheet

Object Types - Lists

Object Types - Dictionaries and Tuples

Functions def, *args, **kargs

Functions lambda

Built-in Functions

map, filter, and reduce

Decorators

List Comprehension

Sets (union/intersection) and itertools - Jaccard coefficient and shingling to check plagiarism

Hashing (Hash tables and hashlib)

Dictionary Comprehension with zip

The yield keyword

Generator Functions and Expressions

generator.send() method

Iterators

Classes and Instances (__init__, __call__, etc.)

if__name__ == '__main__'

argparse

Exceptions

@static method vs class method

Private attributes and private methods

bits, bytes, bitstring, and constBitStream

json.dump(s) and json.load(s)

Python Object Serialization - pickle and json

Python Object Serialization - yaml and json

Priority queue and heap queue data structure

Graph data structure

Dijkstra's shortest path algorithm

Prim's spanning tree algorithm

Closure

Functional programming in Python

Remote running a local file using ssh

SQLite 3 - A. Connecting to DB, create/drop table, and insert data into a table

SQLite 3 - B. Selecting, updating and deleting data

MongoDB with PyMongo I - Installing MongoDB ...

Python HTTP Web Services - urllib, httplib2

Web scraping with Selenium for checking domain availability

REST API : Http Requests for Humans with Flask

Blog app with Tornado

Multithreading ...

Python Network Programming I - Basic Server / Client : A Basics

Python Network Programming I - Basic Server / Client : B File Transfer

Python Network Programming II - Chat Server / Client

Python Network Programming III - Echo Server using socketserver network framework

Python Network Programming IV - Asynchronous Request Handling : ThreadingMixIn and ForkingMixIn

Python Coding Questions I

Python Coding Questions II

Python Coding Questions III

Python Coding Questions IV

Python Coding Questions V

Python Coding Questions VI

Python Coding Questions VII

Python Coding Questions VIII

Python Coding Questions IX

Python Coding Questions X

Image processing with Python image library Pillow

Python and C++ with SIP

PyDev with Eclipse

Matplotlib

Redis with Python

NumPy array basics A

NumPy Matrix and Linear Algebra

Pandas with NumPy and Matplotlib

Celluar Automata

Batch gradient descent algorithm

Longest Common Substring Algorithm

Python Unit Test - TDD using unittest.TestCase class

Simple tool - Google page ranking by keywords

Google App Hello World

Google App webapp2 and WSGI

Uploading Google App Hello World

Python 2 vs Python 3

virtualenv and virtualenvwrapper

Uploading a big file to AWS S3 using boto module

Scheduled stopping and starting an AWS instance

Cloudera CDH5 - Scheduled stopping and starting services

Removing Cloud Files - Rackspace API with curl and subprocess

Checking if a process is running/hanging and stop/run a scheduled task on Windows

Apache Spark 1.3 with PySpark (Spark Python API) Shell

Apache Spark 1.2 Streaming

bottle 0.12.7 - Fast and simple WSGI-micro framework for small web-applications ...

Flask app with Apache WSGI on Ubuntu14/CentOS7 ...

Selenium WebDriver

Fabric - streamlining the use of SSH for application deployment

Ansible Quick Preview - Setting up web servers with Nginx, configure enviroments, and deploy an App

Neural Networks with backpropagation for XOR using one hidden layer

NLP - NLTK (Natural Language Toolkit) ...

RabbitMQ(Message broker server) and Celery(Task queue) ...

OpenCV3 and Matplotlib ...

Simple tool - Concatenating slides using FFmpeg ...

iPython - Signal Processing with NumPy

iPython and Jupyter - Install Jupyter, iPython Notebook, drawing with Matplotlib, and publishing it to Github

iPython and Jupyter Notebook with Embedded D3.js

Downloading YouTube videos using youtube-dl embedded with Python

Machine Learning : scikit-learn ...

Django 1.6/1.8 Web Framework ...


Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong






OpenCV 3 image and video processing with Python



OpenCV 3 with Python

Image - OpenCV BGR : Matplotlib RGB

Basic image operations - pixel access

iPython - Signal Processing with NumPy

Signal Processing with NumPy I - FFT and DFT for sine, square waves, unitpulse, and random signal

Signal Processing with NumPy II - Image Fourier Transform : FFT & DFT

Inverse Fourier Transform of an Image with low pass filter: cv2.idft()

Image Histogram

Video Capture and Switching colorspaces - RGB / HSV

Adaptive Thresholding - Otsu's clustering-based image thresholding

Edge Detection - Sobel and Laplacian Kernels

Canny Edge Detection

Hough Transform - Circles

Watershed Algorithm : Marker-based Segmentation I

Watershed Algorithm : Marker-based Segmentation II

Image noise reduction : Non-local Means denoising algorithm

Image object detection : Face detection using Haar Cascade Classifiers

Image segmentation - Foreground extraction Grabcut algorithm based on graph cuts

Image Reconstruction - Inpainting (Interpolation) - Fast Marching Methods

Video : Mean shift object tracking

Machine Learning : Clustering - K-Means clustering I

Machine Learning : Clustering - K-Means clustering II

Machine Learning : Classification - k-nearest neighbors (k-NN) algorithm




Machine Learning with scikit-learn



scikit-learn installation

scikit-learn : Features and feature extraction - iris dataset

scikit-learn : Machine Learning Quick Preview

scikit-learn : Data Preprocessing I - Missing / Categorical data

scikit-learn : Data Preprocessing II - Partitioning a dataset / Feature scaling / Feature Selection / Regularization

scikit-learn : Data Preprocessing III - Dimensionality reduction vis Sequential feature selection / Assessing feature importance via random forests

Data Compression via Dimensionality Reduction I - Principal component analysis (PCA)

scikit-learn : Data Compression via Dimensionality Reduction II - Linear Discriminant Analysis (LDA)

scikit-learn : Data Compression via Dimensionality Reduction III - Nonlinear mappings via kernel principal component (KPCA) analysis

scikit-learn : Logistic Regression, Overfitting & regularization

scikit-learn : Supervised Learning & Unsupervised Learning - e.g. Unsupervised PCA dimensionality reduction with iris dataset

scikit-learn : Unsupervised_Learning - KMeans clustering with iris dataset

scikit-learn : Linearly Separable Data - Linear Model & (Gaussian) radial basis function kernel (RBF kernel)

scikit-learn : Decision Tree Learning I - Entropy, Gini, and Information Gain

scikit-learn : Decision Tree Learning II - Constructing the Decision Tree

scikit-learn : Random Decision Forests Classification

scikit-learn : Support Vector Machines (SVM)

scikit-learn : Support Vector Machines (SVM) II

Flask with Embedded Machine Learning I : Serializing with pickle and DB setup

Flask with Embedded Machine Learning II : Basic Flask App

Flask with Embedded Machine Learning III : Embedding Classifier

Flask with Embedded Machine Learning IV : Deploy

Flask with Embedded Machine Learning V : Updating the classifier

scikit-learn : Sample of a spam comment filter using SVM - classifying a good one or a bad one




Machine learning algorithms and concepts

Batch gradient descent algorithm

Single Layer Neural Network - Perceptron model on the Iris dataset using Heaviside step activation function

Batch gradient descent versus stochastic gradient descent

Single Layer Neural Network - Adaptive Linear Neuron using linear (identity) activation function with batch gradient descent method

Single Layer Neural Network : Adaptive Linear Neuron using linear (identity) activation function with stochastic gradient descent (SGD)

Logistic Regression

VC (Vapnik-Chervonenkis) Dimension and Shatter

Bias-variance tradeoff

Maximum Likelihood Estimation (MLE)

Neural Networks with backpropagation for XOR using one hidden layer

minHash

tf-idf weight

Natural Language Processing (NLP): Sentiment Analysis I (IMDb & bag-of-words)

Natural Language Processing (NLP): Sentiment Analysis II (tokenization, stemming, and stop words)

Natural Language Processing (NLP): Sentiment Analysis III (training & cross validation)

Natural Language Processing (NLP): Sentiment Analysis IV (out-of-core)

Locality-Sensitive Hashing (LSH) using Cosine Distance (Cosine Similarity)




Artificial Neural Networks (ANN)

[Note] Sources are available at Github - Jupyter notebook files

1. Introduction

2. Forward Propagation

3. Gradient Descent

4. Backpropagation of Errors

5. Checking gradient

6. Training via BFGS

7. Overfitting & Regularization

8. Deep Learning I : Image Recognition (Image uploading)

9. Deep Learning II : Image Recognition (Image classification)

10 - Deep Learning III : Deep Learning III : Theano, TensorFlow, and Keras









Contact

BogoToBogo
contactus@bogotobogo.com

Follow Bogotobogo

About Us

contactus@bogotobogo.com

YouTubeMy YouTube channel
Pacific Ave, San Francisco, CA 94115

Pacific Ave, San Francisco, CA 94115

Copyright © 2024, bogotobogo
Design: Web Master