Reader small image

You're reading from  The Python Workshop Second Edition - Second Edition

Product typeBook
Published inNov 2022
Reading LevelN/a
PublisherPackt
ISBN-139781804610619
Edition2nd Edition
Languages
Right arrow
Authors (5):
Corey Wade
Corey Wade
author image
Corey Wade

Corey Wade, M.S. Mathematics, M.F.A. Writing & Consciousness, is the founder and director of Berkeley Coding Academy where he teaches Machine Learning and AI to teens from all over the world. Additionally, Corey chairs the Math Department at Berkeley Independent Study where he has received multiple grants to run after-school coding programs to help bridge the tech skills gap. Additional experiences include teaching Natural Language Processing with Hello World, developing Data Science curricula with Pathstream, and publishing statistics and machine learning models with Towards Data Science, Springboard, and Medium.
Read more about Corey Wade

Mario Corchero Jiménez
Mario Corchero Jiménez
author image
Mario Corchero Jiménez

Mario Corchero Jiménez is a senior software developer at Bloomberg. He leads the Python infrastructure team in London, enabling the company to work effectively in Python and building company-wide libraries and tools. His professional experience is mainly in C++ and Python, and he has contributed some patches to multiple Python open source projects. He is a PSF fellow, having received the Q3 2018 PSF Community Award, is vice president of Python Espaa (the Python Spain association), and has served as Chair of PyLondinium, PyConES17, and PyCon Charlas at PyCon 2018. Mario is passionate about the Python community, open source, and inner source.
Read more about Mario Corchero Jiménez

Andrew Bird
Andrew Bird
author image
Andrew Bird

Andrew Bird is the data and analytics manager of Vesparum Capital. He leads the software and data science teams at Vesparum, overseeing full-stack web development in Django/React. He is an Australian actuary (FIAA, CERA) who has previously worked with Deloitte Consulting in financial services. Andrew also currently works as a full-stack developer for Draftable Pvt. Ltd. He manages the ongoing development of the donation portal for the Effective Altruism Australia website on a voluntary basis. Andrew has also co-written one of our bestselling titles, "The Python Workshop".
Read more about Andrew Bird

Dr. Lau Cher Han
Dr. Lau Cher Han
author image
Dr. Lau Cher Han

Dr Lau Cher Han is a Chief data scientist, and currently the CEO of LEAD, an institution that provides programs on data science, full stack web development, and digital marketing. Well-versed in programming languages: JavaScript, Python, C# and so on he is experienced in web frameworks: MEAN Stack, ASP.NET, Python Django and is multilingual, speaking English, Chinese, Bahasa fluently. His knowledge of Chinese spreads even into its dialects: Hokkien, Teochew, and Cantonese.
Read more about Dr. Lau Cher Han

Graham Lee
Graham Lee
author image
Graham Lee

Graham Lee is an experienced programmer and writer. He has written books including Professional Cocoa Application Security, Test-Driven iOS Development, APPropriate Behaviour and APPosite Concerns. He is a developer who's been programming for long enough to want to start telling other people about the mistakes he's made, in the hope that they'll avoid repeating them. In his case, this means having worked for about 12 years as a professional. His first programming experience can hardly be called professional at all: as it was in BASIC, on a Dragon 32 microcomputer.
Read more about Graham Lee

View More author details
Right arrow

Matrix operations

Let’s learn how to use nested lists to perform basic matrix operations. Although many developers use NumPy to perform matrix operations, it’s very useful to learn how to manipulate matrices using straight Python. First, you will add two matrices in Python. Matrix addition requires both matrices to have the same dimensions; the results will also be of the same dimensions.

In the next exercise, you will perform matrix operations.

Exercise 27 – implementing matrix operations (addition and subtraction)

In this exercise, you will use the matrices in the following figures:

Figure 2.7 – Matrix data for the X matrix

Figure 2.7 – Matrix data for the X matrix

Figure 2.8 – Matrix data for the Y matrix

Figure 2.8 – Matrix data for the Y matrix

Now, let’s add and subtract the X and Y matrices using Python.

The following steps will enable you to complete this exercise:

  1. Open a new Jupyter Notebook.
  2. Create two nested lists, X and Y, to store the values:
    X = [[1,2,3],[4,5,6],[7,8,9]]
    Y = [[10,11,12],[13,14,15],[16,17,18]]
  3. Initialize a 3 x 3 zero matrix called result as a placeholder:
    # Initialize a result placeholder
    result = [[0,0,0],
        [0,0,0],
        [0,0,0]]
  4. Now, implement the algorithm by iterating through the cells and columns of the matrix:
    # iterate through rows
    for i in range(len(X)):
    # iterate through columns
      for j in range(len(X[0])):
        result[i][j] = X[i][j] + Y[i][j]
    print(result)

As you learned in the previous section, first, you iterate the rows in the X matrix, then iterate the columns. You do not have to iterate the Y matrix again because both matrices are of the same dimensions. The result of a particular row (denoted by i) and a particular column (denoted by j) equals the sum of the respective row and column in the X and Y matrices.

The output will be as follows:

[[11, 13, 15], [17, 19, 21], [23, 25, 27]]
  1. You can also perform subtraction using two matrices using the same algorithm with a different operator. The idea behind this is the same as in Step 3, except you are doing subtraction. You can implement the following code to try out matrix subtraction:
    X = [[10,11,12],[13,14,15],[16,17,18]]
    Y = [[1,2,3],[4,5,6],[7,8,9]]
    # Initialize a result placeholder
    result = [[0,0,0],
        [0,0,0],
        [0,0,0]]
    # iterate through rows
    for i in range(len(X)):
    # iterate through columns
      for j in range(len(X[0])):
        result[i][j] = X[i][j] - Y[i][j]
    print(result)

Here is the output:

[[9, 9, 9], [9, 9, 9], [9, 9, 9]]

In this exercise, you were able to perform basic addition and subtraction using two matrices. In the next section, you will perform multiplication on matrices.

Matrix multiplication operations

Let’s use nested lists to perform matrix multiplication for the two matrices shown in Figures 2.9 and 2.10:

Figure 2.9 – The data of the X matrix

Figure 2.9 – The data of the X matrix

Figure 2.10 – The data of the Y matrix

Figure 2.10 – The data of the Y matrix

For matrix multiplication, the number of columns in the first matrix (X) must equal the number of rows in the second matrix (Y). The result will have the same number of rows as the first matrix and the same number of columns as the second matrix. In this case, the resulting matrix will be a 3 x 4 matrix.

Exercise 28 – implementing matrix operations (multiplication)

In this exercise, your end goal will be to multiply two matrices, X and Y, and get an output value. The following steps will enable you to complete this exercise:

  1. Open a new Jupyter notebook.
  2. Create two nested lists, X and Y, to store the value of the X and Y matrices:
    X = [[1, 2], [4, 5], [3, 6]]
    Y = [[1,2,3,4],[5,6,7,8]]
  3. Create a zero-matrix placeholder to store the result:
    result = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
  4. Implement the matrix multiplication algorithm to compute the result:
    # iterating by row of X
    for i in range(len(X)):
      # iterating by column by Y
      for j in range(len(Y[0])):
        # iterating by rows of Y
        for k in range(len(Y)):
          result[i][j] += X[i][k] * Y[k][j]

You may have noticed that this algorithm is slightly different from the one you used in Step 3 of Exercise 27 – implementing matrix operations (addition and subtraction). This is because you need to iterate the rows of the second matrix, Y, as the matrices have different shapes, which is what is mentioned in the preceding code snippet.

  1. Now, print the final result:
    for r in result:
      print(r)

Let’s look at the output:

Figure 2.11 – Output of multiplying the X and Y matrices

Figure 2.11 – Output of multiplying the X and Y matrices

Note

To review the packages that data scientists use to perform matrix calculations, such as NumPy, check out https://docs.scipy.org/doc/numpy/.

In the next section, you will work with and learn about a new data structure: Python dictionaries.

Previous PageNext Page
You have been reading a chapter from
The Python Workshop Second Edition - Second Edition
Published in: Nov 2022Publisher: PacktISBN-13: 9781804610619
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Authors (5)

author image
Corey Wade

Corey Wade, M.S. Mathematics, M.F.A. Writing & Consciousness, is the founder and director of Berkeley Coding Academy where he teaches Machine Learning and AI to teens from all over the world. Additionally, Corey chairs the Math Department at Berkeley Independent Study where he has received multiple grants to run after-school coding programs to help bridge the tech skills gap. Additional experiences include teaching Natural Language Processing with Hello World, developing Data Science curricula with Pathstream, and publishing statistics and machine learning models with Towards Data Science, Springboard, and Medium.
Read more about Corey Wade

author image
Mario Corchero Jiménez

Mario Corchero Jiménez is a senior software developer at Bloomberg. He leads the Python infrastructure team in London, enabling the company to work effectively in Python and building company-wide libraries and tools. His professional experience is mainly in C++ and Python, and he has contributed some patches to multiple Python open source projects. He is a PSF fellow, having received the Q3 2018 PSF Community Award, is vice president of Python Espaa (the Python Spain association), and has served as Chair of PyLondinium, PyConES17, and PyCon Charlas at PyCon 2018. Mario is passionate about the Python community, open source, and inner source.
Read more about Mario Corchero Jiménez

author image
Andrew Bird

Andrew Bird is the data and analytics manager of Vesparum Capital. He leads the software and data science teams at Vesparum, overseeing full-stack web development in Django/React. He is an Australian actuary (FIAA, CERA) who has previously worked with Deloitte Consulting in financial services. Andrew also currently works as a full-stack developer for Draftable Pvt. Ltd. He manages the ongoing development of the donation portal for the Effective Altruism Australia website on a voluntary basis. Andrew has also co-written one of our bestselling titles, "The Python Workshop".
Read more about Andrew Bird

author image
Dr. Lau Cher Han

Dr Lau Cher Han is a Chief data scientist, and currently the CEO of LEAD, an institution that provides programs on data science, full stack web development, and digital marketing. Well-versed in programming languages: JavaScript, Python, C# and so on he is experienced in web frameworks: MEAN Stack, ASP.NET, Python Django and is multilingual, speaking English, Chinese, Bahasa fluently. His knowledge of Chinese spreads even into its dialects: Hokkien, Teochew, and Cantonese.
Read more about Dr. Lau Cher Han

author image
Graham Lee

Graham Lee is an experienced programmer and writer. He has written books including Professional Cocoa Application Security, Test-Driven iOS Development, APPropriate Behaviour and APPosite Concerns. He is a developer who's been programming for long enough to want to start telling other people about the mistakes he's made, in the hope that they'll avoid repeating them. In his case, this means having worked for about 12 years as a professional. His first programming experience can hardly be called professional at all: as it was in BASIC, on a Dragon 32 microcomputer.
Read more about Graham Lee