Session 4 - Part 2 Flashcards

1
Q

Although we are processed small amounts of data like single numbers or long lists, neuroimagning data however,

A

contains millions of numbers and processing these one ar a time with loops is not going to work

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

For larger scale data analysis (usually with neuroimagning data) we can use pre-existing modules and core tool for this in Python is

A

numpy

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Numpy works with

A

large blocks of numbers called ‘matrices’ (or sometimes ‘arrays’)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Matrices are often rectangular blocks that are

A

stored as rows x columns

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Matrices are often rectangular blocks that are stored as rows x columns.

For instance:

A

3 rows by 2 columns so it would have shape (3, 2).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

The order of the dimensions of matrices is always

A

(rows, columns).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

For most of the time we will be working with 2D matrices, however numpy will cope with any number of dimension from

A

(from 1D up to any number of dimensions).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Matrices are usually two-dimensional whereas arrays can be

A

have any number of dimensions

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

when performing addition, subtraction, multiplication, or division on matrices, they must be of

A

he same size, meaning they must have the same number of rows and columns.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Example of addition of matrices

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Example of subtraction of matrices:

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Example of multiplication and division of matrices - element by element mulplication/division|

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

numpy and scipy are two modules that support for much of the

A

scientific work that you will want to do in Python

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

numpy provides “low-level” routines for manipulating matrices like

A

linear algebra routines (e.g. inverting a matrix), Fourier transforms and random number capabilities (using a range of distributions).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

scipy provides “higher-level” routines for science and engineering and uses numpy as base and then adds

A

additional algorithms for things like image and signal processing.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

matplotlib is a

A

plotting library that lets you produce a range of different graphs

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Numpy uses the numpy.array class to store

A

arrays of numbers

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Numpy arrays can be any

A

number of dimensions and any size

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Python is a 0-indexed language. This means that if we have a2x2 array

A

the two rows are referred to using indices 0 and 1 and the two columns are referred to using indices 0 and 1.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

When indexing into numpy arrays, we use

A

square brackets (similar to lists).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

We can also use a range separated by a colon (:) in array which is exclusive of last number (similar to range function) e.g., - (2)

A

data[0:100, 0:100] This gives us a 100x100 subarray of the data array

data[50:, :] This gives us the 51st row onwards and all of the columns –> In Python, indexing starts from 0, so the 51st row corresponds to index 50. T

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q
A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

Explain the code please - (5)

A

import numpy as np: This line imports the NumPy library and aliases it as np, allowing us to refer to NumPy functions and objects using the shorter name np.

z = np.zeros((2, 3)): This line creates a 2x3 matrix filled with zeros.

The numbers (2, 3) inside the parentheses represent the dimensions of the matrix, with 2 rows and 3 columns.

print(‘Here is an array of zeros’): This line prints a descriptive message to indicate that the following array contains all zeros.

print(z): This line prints the array z containing zeros to the console.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

What is the output of the code?

A

Here is an array of zeros
[[0. 0. 0.]
[0. 0. 0.]]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

What does z[0, 0] = 1.0 do? - (2)

z = np.zeros((2,3)) producign 2x3 matrix of zeros

A

This line sets the element at the first row and first column of the matrix z to 1.0.

In other words, it modifies the top-left element of the matrix.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

What does z[0, :] = 2.0 - (2)

z = np.zeros((2,3)) producign 2x3 matrix of zeros

A

This line sets all elements in the first row (all columns) of the matrix z to 2.0.

It fills the entire first row with the value 2.0.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q
A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

What does z[:, 1] = 3.0- (2)

z = np.zeros((2,3)) producign 2x3 matrix of zeros

A

This line sets all elements in the second column (all rows) of the matrix z to 3.0.

It fills the entire second column with the value 3.0.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

What does z[0, :] = 2.0 - (2)

z = np.zeros((2,3)) producign 2x3 matrix of zeros

A

This line sets all elements in the first row (all columns) of the matrix z to 2.0.

It fills the entire first row with the value 2.0.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

What does z[:, 1] = 3.0- (2)

z = np.zeros((2,3)) producign 2x3 matrix of zeros

A

This line sets all elements in the second column (all rows) of the matrix z to 3.0.

It fills the entire second column with the value 3.0.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

What does single_num = z[0,1] do if we print it out? - (2)

z = np.zeros((2,3)) producing 2x3 matrix of zeros

A

Extracts a single number from the first row and first column of the matrix

The item at z[0,1] is 0.0

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q
A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

What does a_row = z[0,:] do if we print it out? - (3)

z = np.zeros((2,3)) producing 2x3 matrix of zeros

A

In the context of array indexing in NumPy, the comma separates the row index from the column index.

In this expression, z[0, :], 0 indicates the row index (specifically the first row), and : indicates that all columns in that row are selected.

Output:
[0. 0. 0.]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

So with matrices we can set

A

certain elements to be certain values as well as extract single and multiple numbers

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q
A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

What does rArray=np.random.rand(200,200) do?

A

This line initializes a NumPy array named rArray with dimensions 200x200 filled with random numbers generated using np.random.rand().

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
37
Q

What does print(f’Array size={rArray.size}’) display?
if rArray=np.random.rand(200,200)

A

This line prints the total number of elements in the rArray array which is 4000

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
38
Q

What does rint(f’Array shape={rArray.shape}’)display?
if rArray=np.random.rand(200,200) - (2)

A

This line prints the shape of the rArray array, which represents its dimensions as a tuple (rows, columns)

output: Array shape=(200, 200)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
39
Q

What does smallerArray=rArray[0:100,0:100] do

if rArray = np.random.rand(200,200)

A

This line creates a subset of the rArray array, selecting rows from index 0 to 99 and columns from index 0 to 99, effectively creating a smaller 100x100 array from the original 200x200 array.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
40
Q

: How can the size parameter in np.zeros be represented, according to the comment # The size thing here is a tuple - it can also be a list?

A

The size parameter in np.zeros can be represented as either a tuple or a list, allowing flexibility in specifying the dimensions of the array to be created.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
41
Q

Explain the code - (4)

import numpy as np

z = np.zeros((2, 3)) # The size thing here is a tuple - it can also be a list
print(‘Here is an array of zeros’)
print(z) #array of 2x3 zeros

print(‘Now I set the bottom right element (1,2) to 9’)
z[1,2]=9 #Work out how to do this

print(z [1,:])

A

This code snippet begins by importing the NumPy library and aliasing it as np.

It then initializes a 2x3 NumPy array named z filled with zeros.

The line z[1, 2] = 9 modifies the bottom-right element of the array to 9.

Finally, it prints the second row of the array using print(z[1, :]), where z[1, :] selects the entire second row of the array.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
42
Q

What is the output of this code?

import numpy as np

z = np.zeros((2, 3)) # The size thing here is a tuple - it can also be a list
print(‘Here is an array of zeros’)
print(z) #array of 2x3 zeros

print(‘Now I set the bottom right element (1,2) to 9’)
z[1,2]=9 #Work out how to do this

print(z [1,:])

A
43
Q

What does the comment mean: # The size thing here is a tuple - it can also be a list - (4)

A

refers to the argument passed to np.zeros(), which specifies the dimensions of the array.

In Python, dimensions are often represented as tuples, where the first element indicates the number of rows and the second element indicates the number of columns.

However, this argument could also be provided as a list.

44
Q

We can also produce an array filled with ones instead of zeros using

A

np.ones((3,4)

45
Q

Explain what this code does - (3)

A

his code imports the NumPy library with the alias np

a 3x4 matrix filled with ones using the np.ones function and stores it in the variable o.

Finally, it prints the contents of the o matrix to the output console.

46
Q

What is the output of this code?

A
47
Q

If we want to type in some data we can produce an array by hand using np.array function e.g., - (2)

A

Create a 2x4 array of numbers - we do this by converting a list of lists to an array.

a = np.array([[1, 2, 3,8], [4, 5, 6,9]])

48
Q

Explain this code - (3)

A

This code imports the NumPy library as np and creates a 2x4 NumPy array named “a” by converting a list of lists into an array.

The array contains the elements [[1, 2, 3, 8], [4, 5, 6, 9]].

Finally, it prints out the array “a”.

49
Q

What is the output of this code?

A
50
Q

If you entered all integers in your array then

A

it produces an int array

51
Q

There are 3 ways to produce a float array - (3)

A
  1. Force a float array by making at least one number floating point with a decimal point
  2. Force a float array by specifying it to numpy at creation time using dtype
  3. Force a float array by explicitly casting an int array
52
Q

Ways to produce float array

  1. Force a float array by making at least one number floating point with a decimal point
A

a = np.array([[1.0, 2, 3], [4, 5, 6]])
print(a)

Output:
[[1. 2. 3.]
[4. 5. 6.]]

53
Q

Ways to produce float array

  1. # Force a float array by specifying it to numpy at creation time
A

a = np.array([[1, 2, 3], [4, 5, 6]], dtype=float) # <— that dtype thing tells numpy to make it floats
print(a)

output:
[[1. 2. 3.]
[4. 5. 6.]]

54
Q

What does single_num = z[0,1] do if we print it out? - (2)

z = np.zeros((2,3)) producing 2x3 matrix of zeros

A

Extracts a single number from the first row and first column of the matrix

The item at z[0,1] is 0.0

55
Q

Ways to produce float array

  1. Force a float array by explicitly casting an int array
A

a = np.array([[1, 2, 3], [4, 5, 6]]) # Initially it’s an int array…
a = a.astype(float) # … but now we’ve ‘floated’ it!

print(a)

output:
[[1. 2. 3.]
[4. 5. 6.]]

56
Q

explain code - (5)

a = np.array([[1.0, 2, 3], [4, 5, 6]])
print(a)

A

This code creates a NumPy array named a containing two rows and three columns.

It ensures the array contains floating-point numbers by including at least one number with a decimal point (1.0).

By including a floating-point number (1.0) in the array, it forces NumPy to interpret all numbers in the array as floating-point numbers.

Therefore, even though some numbers are entered as integers (2, 3, 4, 5, 6), they will be converted to floats when the array is created.

Finally, it prints the array a.

57
Q

explain this code:

a = np.array([[1, 2, 3], [4, 5, 6]], dtype=float) # <— that dtype thing tells numpy to make it floats
print(a)

A

This code initializes a 2x3 NumPy array with the values [[1, 2, 3], [4, 5, 6]] and forces every integer value to be a float by specifying dtype=float and prints the resulting array.

58
Q

Break down what a = np.array ([[1.0,2,3],[4,5,6]]) mean - (3)

A

So, [[1.0, 2, 3], [4, 5, 6]] creates a 2x3 array - 3 elements in the list so 3 columns and 2 lists meaning 2 rows

The first inner list [1.0, 2, 3] represents the first row of the array. It contains three elements: 1.0, 2, and 3.

The second inner list [4, 5, 6] represents the second row of the array. It also contains three elements: 4, 5, and 6.

59
Q

Explain thsi code - (4)

A

This code initializes a NumPy array a with integer values in a 2x3 format, meaning it has 2 rows and 3 columns.

Then, it uses the astype method to explicitly cast the data type of the array a to float.

This operation overrides the original array a and changes its data type from integer to float.

Finally, it prints the modified array a, now containing floating-point values.

60
Q

You can also replace dtype as float with

A

int e.g., a = np.array([[1, 2, 3.3], [4, 5, 6]], dtype= int)

61
Q

Explain this code - (4)

A

This code initializes a NumPy array a with values in a 2x3 format.

It specifies the data type of the array as int, which forces all elements to be integers, even if they were floats initially.

This is achieved using the dtype=int parameter in the np.array function call.

Finally, it prints the resulting array a.

62
Q

What is output of the code going to be - going to be same even if its 3.6 instead of 3.6

A
63
Q

when specifying the data type as int using dtype=int, any float values are truncated to integers. So, for example, if a value is 3.6, it will be

A

converted to 3.

64
Q

In numpy module, you can also use other data types such as

A

as np.complex for complex numbers, np.bool for arrays of bools and a range of more specialist types if you need to.

65
Q

You can also produce a list then

A

convert to array using np.array

66
Q

Example of converting list to numpy array

A
67
Q

What will be output of the code?

A
68
Q

Explain this code - (4):

A

This code first imports the NumPy library and then defines a list of numbers (my_numbers) containing two sub-lists.

Next, it converts the list my_numbers into a NumPy array using the np.array() function which is stored in variable ‘a’

The resulting array a is a 2D array with the same structure as the original list and a size of 2x3 (2 rows and 3 columns).

Finally, it prints the array a,

69
Q

For many reasons, we often want to make … in arrays

A

ranges of numbers in arrays

70
Q

For many reasons, we often want to make ranges of numbers in arrays.

There are quite a few ways to do this but the two it is important to remember and know about are - (2)

A

np.arange and np.linspace

71
Q

What are the main differences between np.arange and the built-in range function? - (2)

A

The main differences are:
np.arange returns a NumPy array object of dtype int or float depending on what data type is specificed, while range returns a sequence of integers

np.arange can handle floating-point numbers, whereas range only works with integers.

72
Q

Explain this code - (3)

A

In the first example (a = np.arange(3)), it creates an array containing numbers from 0 up to (but not including) 3.

In the second example (b = np.arange(1, 3)), it creates an array containing numbers from 1 up to (but not including) 3.

In the third example (c = np.arange(1, 3, 0.5)), it creates an array containing numbers from 1 up to (but not including) 3, with a step size of 0.5,

73
Q

What would be the output of this code?

A
74
Q

Explain the code snippet (output attached) - (4)

A

This code snippet first imports the matplotlib.pyplot module and the numpy module as plt and np,
respectively.

It then generates an array of ‘x’ values from 1 to 5 with a step size of 1 using np.arange(1, 6, 1).

Next, it calculates ‘y’ values by squaring each ‘x’ value.

Finally, it plots the data with ‘x’ values on the x-axis and ‘y’ values on the y-axis using plt.plot() and displays the plot using plt.show().

75
Q

Normally leaving this line out of plt.show() will still show plot in colab but might be

A

a warning

76
Q

How to produce x range from -5 to 5 inclusive with steps of 1?

A

x = np.arrange(-5,6,1)

77
Q

What is the purpose of np.linspace in Python?

A

np.linspace is used to generate a specified number of evenly spaced numbers between a start and stop value.

78
Q

What are the arguements to the function called np.linspace?

A

(start, stop, count)

79
Q

Get 5 equally spaced numbers between 0.0 and 1.0 inclusive

What does the following code snippet do? - (4)

import numpy as np

a = np.linspace(0.0, 1.0, 5)
print(a)

A

This code uses np.linspace to generate an array a containing 5 equally spaced numbers between 0.0 and 1.0 (inclusive).

The np.linspace function takes three arguments: the start value (0.0), the stop value (1.0), and the number of values to generate (5).

It returns an array with equally spaced numbers, including both the start and stop values.

The resulting array a is then printed.

80
Q

Get 5 equally spaced numbers between 0.0 and 1.0 inclusive

Output of this code

import numpy as np

a = np.linspace(0.0, 1.0, 5)
print(a)

A

[0. 0.25 0.5 0.75 1. ]

81
Q

Modify the code below to plot a nice smooth cubic function (x to the power of 3) between -5 and 5 with exactly 100 steps:

A
82
Q

Explain this code - (4)

A

This code snippet imports the matplotlib.pyplot module and the numpy module as plt and np, respectively.

It then generates an array x containing 100 equally spaced numbers between -5 and 6 using np.linspace(-5, 6, 100).

Next, it calculates ‘y’ values by cubing each ‘x’ value.

Finally, it plots the data with ‘x’ values on the x-axis and ‘y’ values on the y-axis using plt.plot(), adds gridlines to the plot using plt.grid(True), and displays the plot using plt.show().

83
Q

To make graphs smoother then change

A

the steps in np.array/counts in np/linspace

84
Q

The np.linspace produces an array? - (2)

A

produces an array.

It generates evenly spaced numbers over a specified interval and returns them as an array.

85
Q

Numpy can produce

A

random numbers

86
Q

Functions for producing random numbers from numpy come from

A

np.random module

87
Q

Output of 1D array vs 2D array:

A
88
Q

The np.random.rand in np.random module for producing random numbers produces

A

evenly distributed numbers between 0 and 1.

89
Q

The parameter we pass to the np.random.rand function is the - (5)

A

size of the array of random numbers that we require.

This parameter determines the shape of the output array in terms of rows and columns.

For example:

np.random.rand(5) will generate a 1D array with 5 elements.
np.random.rand(3, 4) will generate a 2D array with 3 rows and 4 columns.

90
Q

What does the following code snippet do? - (2)

import numpy as np

r = np.random.rand(2, 2)
print(r)

A

This code snippet uses np.random.rand() to generate a 2D array r with 2 rows and 2 columns, filled with random numbers between 0 and 1.

It then prints the generated array r

91
Q

Explain this code - (4)

A

This code snippet generates a 20x20 array of random numbers between 0 and 1 using np.random.rand().

It then displays the array r as an image using plt.imshow(), with colors representing the values of the numbers (When displaying numerical data as an image, each numerical value in the array is mapped to a color)

Additionally, it adds a color bar to the side of the plot using plt.colorbar(), which helps interpret the colors.

Finally, it displays the plot using plt.show().

92
Q

All of the generated numbers here lie between 0 and 1 (as well as colour bar runs from 0 to1)

A

Each number is equally likely to be chosen - we say that the distribution is ‘uniform’.

93
Q

Another function in numpy to produce random numbers in np.random module is

A

np.random.randn

94
Q

The randn function in Numpypy produces… - (2)

A

The randn function in NumPy generates random numbers drawn from a normal distribution.

The ‘n’ at the end of the function name indicates that it follows a normal distribution.

95
Q

Explain this code snippet - (4)

A

This code snippet generates a 50x50 array of random numbers drawn from a normal distribution using np.random.randn().

It then displays the array rn as an image using plt.imshow(), with colors representing the values of the numbers.

Additionally, it adds a color bar to the side of the plot using plt.colorbar(), which helps interpret the colors.

Finally, it displays the plot using plt.show().

96
Q

We can visualise these two sets of numbers side-by-side using the

A

subplots function of matplotlib

97
Q

Explain this code - (3) - assuming previous code of defining ‘r’ and ‘rn’ and producing their graphs

fig,a = plt.subplots(1,2)

fig,a = plt.subplots(1,2)

a[0].imshow(rn) #This function shows your normal-random array as an image

a[1].imshow(r) #This function shows your uniform-random array as an image

A

fig, a = plt.subplots(1, 2): This line creates a figure with two subplots arranged side by side. The subplots() function returns a figure (fig) and an array of axes (a). In this case, 1 indicates that there is only one row of subplots, and 2 indicates that there are two subplots in total (side by side).

a[0].imshow(rn): This line displays the first subplot (a[0]) and shows the normal-random array rn as an image using the imshow() function. a[0] refers to the first subplot created by plt.subplots(), and imshow() is a function used to display arrays as images.

a[1].imshow(r): This line displays the second subplot (a[1]) and shows the uniform-random array r as an image using the imshow() function. a[1] refers to the second subplot created by plt.subplots().

98
Q

Explain this code - (5)

A

This code snippet assumes that rn and r have been defined previously as arrays representing different types of random numbers.

It creates a figure with two subplots arranged side by side using plt.subplots(1, 2).

In the first subplot (a[0]), it computes and displays a histogram of all numbers in the array rn after flattening it into a 1D list using flatten(). The histogram is computed with 50 bins.

In the second subplot (a[1]), it computes and displays a histogram of all numbers in the array r. Similar to the first subplot, the histogram is computed with 50 bins.

This allows for a visual comparison of the distributions of two arrays, which may represent different types of random numbers.

99
Q

Arithmetic on numpy arrays works in the way you would probably expect. To perform arithmetic on two arrays, they normally need to be

A

the same size

100
Q

How does scalar arithmetic work with numpy arrays?

A

Scalar arithmetic with numpy arrays involves operating on the entire array with a single number, known as a ‘scalar’.

101
Q

Explain this code - (4)

import numpy as np

a=np.array([[1,2],[3,4]])
b=np.array([[5,6],[7,8]])
c=a+b # Adding two arrays which are the same size
d=a*10 # Multiplying a single array by a scalar
print(a)
print(b)
print(c)
print(d)

A

Two arrays ‘a’ and ‘b’ are defined with the same dimensions, both being 2x2 arrays.

The arrays ‘a’ and ‘b’ are added together element-wise, resulting in array ‘c’.

Array ‘a’ is multiplied by scalar 10, resulting in array ‘d’. Since ‘a’ is a 2x2 array, ‘d’ will also be a 2x2 array where each element of ‘a’ is multiplied by 10.

The arrays ‘a’, ‘b’, ‘c’, and ‘d’ are printed to observe the results of the operations.

102
Q

What will be output of the code?

import numpy as np

a=np.array([[1,2],[3,4]])
b=np.array([[5,6],[7,8]])
c=a+b # Adding two arrays which are the same size
d=a*10 # Multiplying a single array by a scalar
print(a)
print(b)
print(c)
print(d)

A
103
Q

What does the following code snippet do? - (3)

a_mean = a.mean()
print(a_mean)

a_sd = a.std()
print(a_sd)

a_var = a.var()
print(a_var)

A

a_mean = a.mean() calculates the mean (average) of the numbers in array ‘a’ and assigns it to the variable ‘a_mean’. The mean is then printed.

a_sd = a.std() computes the sample standard deviation of the numbers in array ‘a’ and assigns it to the variable ‘a_sd’. The standard deviation is then printed.

a_var = a.var() determines the sample variance of the numbers in array ‘a’ and assigns it to the variable ‘a_var’. The variance is then printed.