Sarah111-AHM / Semsmah

2 stars 0 forks source link

Summary of numpy in a data theoretical science programming language #3

Closed Sarah111-AHM closed 1 year ago

Sarah111-AHM commented 1 year ago

Introduction to the numpy library image

المثال السابق يوضح الفرق في الأداء بين NumPy arrays وPython lists. تم إنشاء مصفوفة NumPy باستخدام np.arange() وتم إنشاء قائمة Python بإستخدام list(). تم ضرب كلا الكائنين بعد ذلك برقم 2 باستخدام * 2. تم استخدام %time لقياس وقت التنفيذ لكلا العمليات، حيث وجد أن عملية ضرب المصفوفة NumPy برقم 2 قد استغرقت 70 ملي ثانية، بينما استغرقت عملية ضرب القائمة Python برقم 2 حوالي 1.05 ثانية. يظهر هذا المثال فارق الأداء الكبير بين NumPy arrays وPython lists، حيث أن عمليات NumPy تتم بشكل أسرع بكثير وتستخدم أقل كمية من الذاكرة. هذا يجعل NumPy مفيدًا بشكل خاص للتعامل مع البيانات الكبيرة و التحليل العلمي Q

1. Why is NumPy important for numerical computing in Python? a. It provides modeling and scientific functionality b. It is designed for efficiency on large arrays of data c. It is easy to use with external libraries d. It provides an easy-to-use interface for legacy codebases 2. Which of the following is an advantage of using NumPy arrays over built-in Python sequences? a. NumPy arrays use more memory b. NumPy arrays perform operations using Python for loops c. NumPy arrays internally store data in a contiguous block of memory d. NumPy arrays cannot be used with external libraries 3. What are some of the things you'll find in NumPy? a. Descriptive statistics and aggregating/summarizing data b. Tools for reading/writing array data to disk c. Mathematical functions for fast operations on entire arrays of data d. All of the above

4. What is an advantage of using NumPy's C API? a. It makes it possible to use Python to wrap legacy C/C++/Fortran codebases b. It provides an easy-to-use interface for scientific functionality c. It allows for easy installation of external libraries d. It makes it possible to write array expressions using loops

5. What is an example of array-oriented computing in Python? a. Using if-elif-else loops for conditional logic b. Performing complex computations on entire arrays with NumPy c. Using built-in Python sequences for data manipulation d. None of the above

6. What is the example given in the paragraph comparing? a. NumPy arrays and Python lists b. NumPy arrays and NumPy arrays with broadcasting c. Python lists and Python dictionaries d. NumPy arrays and NumPy arrays with slicing

2. What is the benefit of using NumPy-based algorithms? a. They use more memory than their pure Python counterparts b. They are generally slower than their pure Python counterparts c. They are generally faster than their pure Python counterparts and use significantly less memory d. They are more difficult to use than their pure Python counterparts

3. What is the purpose of using %time in the example? a. To measure the time it takes to execute a block of code b. To compare the performance of different algorithms c. To debug errors in the code d. To write array expressions using loops

4. What is the significance of the performance difference between NumPy arrays and Python lists? a. NumPy arrays are always faster than Python lists b. NumPy arrays are sometimes faster than Python lists depending on the use case c. Python lists are always faster than NumPy arrays d. It has no significance

5. What is the advantage of using NumPy arrays over Python lists? a. NumPy arrays are easier to use than Python lists b. NumPy arrays use more memory than Python lists c. NumPy arrays are generally faster than Python lists d. NumPy arrays are more flexible than Python lists

The NumPy ndarray: A Multidimensional Array Object image

  1. What is the advantage of using NumPy arrays for mathematical operations? a. They use different syntax than scalar values on built-in Python objects b. They allow you to perform mathematical operations on whole blocks of data c. They are slower than equivalent operations between scalar elements d. They are only useful for non-numeric data

  2. What is the significance of the examples given in the paragraph? a. They demonstrate how to use NumPy arrays for non-mathematical operations b. They highlight the similarities between scalar values and NumPy arrays in terms of syntax c. They show that NumPy arrays are slower than equivalent operations between scalar elements d. They demonstrate how to use built-in Python objects for mathematical operations

  3. What is the purpose of using import numpy as np instead of from numpy import *? a. To make the code shorter and easier to read b. To avoid conflicts with built-in Python functions c. To make NumPy functions run faster d. To make it easier to use external libraries with NumPy

  4. What is an ndarray? a. A container for non-homogeneous data b. A container for scalar values in Python c. A generic multidimensional container for homogeneous data d. A container for non-numeric data_ Creating ndarrays image

    • The easiest way to create an array in NumPy is to use the array function, which accepts any sequence-like object and produces a new NumPy array containing the passed data.
    • أسهل طريقة لإنشاء مصفوفة في NumPy هي استخدام دالة المصفوفة ، والتي تقبل أي كائن يشبه التسلسل وتنتج مصفوفة NumPy جديدة تحتوي على البيانات التي تم تمريرها.
    • Nested sequences like a list of equal-length lists will be converted into a multidimensional array.
    • سيتم تحويل التسلسلات المتداخلة مثل قائمة قوائم متساوية الطول إلى مصفوفة متعددة الأبعاد.
    • The shape of the array is inferred from the data, and can be confirmed using the ndim and shape attributes.
    • يُستدل على شكل المصفوفة من البيانات ، ويمكن تأكيده باستخدام سمات ndim و shape.
    • Unless explicitly specified, np.array tries to infer a good data type for the array that it creates.
    • ما لم ينص صراحة ، np. يحاول المصفوفة استنتاج نوع بيانات جيد للمصفوفة التي يقوم بإنشائها.
    • Other functions for creating new arrays include zeros, ones, and empty, which create arrays of 0s or 1s with a given length or shape, or an array without initializing its values to any particular value.
    • تتضمن الوظائف الأخرى لإنشاء مصفوفات جديدة الأصفار ، والآحاد ، والفارغة ، والتي تنشئ مصفوفات من 0 أو 1 بطول أو شكل معين ، أو مصفوفة بدون تهيئة قيمها إلى أي قيمة معينة.
    • To create a higher dimensional array with these methods, pass a tuple for the shape. لإنشاء مصفوفة ذات أبعاد أعلى بهذه الطرق ، قم بتمرير مجموعة للشكل.
    • It's not safe to assume that np.empty will return an array of all zeros, as it may return uninitialized "garbage" values.
    • ليس من الآمن افتراض أن np. سيعيد فارغ مصفوفة من جميع الأصفار ، لأنه قد يُرجع قيمًا غير مهيأة "غير صالحة".
    • arange is an array-valued version of the built-in Python range function.
    • arange هو نسخة ذات قيمة مصفوفة لوظيفة نطاق Python المدمجة.
    • NumPy has a short list of standard array creation functions, focused on numerical computing. يحتوي NumPy على قائمة قصيرة من وظائف إنشاء المصفوفات القياسية ، تركز على الحوسبة الرقمية.
    • If the data type is not specified, it will in many cases be float64 (floating point). إذا لم يتم تحديد نوع البيانات ، فسيكون في كثير من الحالات float64 (النقطة العائمة). Array creation functions Here are some examples of array creation functions in NumPy:
  5. np.array(): Create an array from a Python list or tuple.

    import numpy as np
    list_data = [1, 2, 3, 4, 5]
    arr = np.array(list_data)
    print(arr)
    # Output: array([1, 2, 3, 4, 5])
  6. np.zeros(): Create an array of zeros with a specified shape.

    import numpy as np
    zeros_arr = np.zeros((3, 4))
    print(zeros_arr)
    # Output: array([[0., 0., 0., 0.],
    #                 [0., 0., 0., 0.],
    #                 [0., 0., 0., 0.]])
  7. np.ones(): Create an array of ones with a specified shape.

    import numpy as np
    ones_arr = np.ones((2, 3))
    print(ones_arr)
    # Output: array([[1., 1., 1.],
    #                 [1., 1., 1.]])
  8. np.empty(): Create an uninitialized array with a specified shape. Note that the values in the array are not set to zero and may be random.

    import numpy as np
    empty_arr = np.empty((2, 2))
    print(empty_arr)
    # Output: array([[0., 0.],
    #                 [0., 0.]])
  9. np.arange(): Create an array with evenly spaced values within a given interval.

    import numpy as np
    range_arr = np.arange(0, 10, 2)
    print(range_arr)
    # Output: array([0, 2, 4, 6, 8])
  10. np.linspace(): Create an array with a specified number of evenly spaced values within a given interval.

    import numpy as np
    linspace_arr = np.linspace(0, 1, 5)
    print(linspace_arr)
    # Output: array([0.  , 0.25, 0.5 , 0.75, 1.  ])
  11. np.eye(): Create a 2-D array with ones on the diagonal and zeros elsewhere.

    import numpy as np
    eye_arr = np.eye(3)
    print(eye_arr)
    # Output: array([[1., 0., 0.],
    #                 [0., 1., 0.],
    #                 [0., 0., 1.]])
  12. np.diag(): Create a diagonal array with specified diagonal values.

    import numpy as np
    diag_arr = np.diag([1, 2, 3])
    print(diag_arr)
    # Output: array([[1, 0, 0],
    #                 [0, 2, 0],
    #                 [0, 0, 3]])
  13. np.random.rand(): Create an array of random values with a specified shape, drawn from a uniform distribution over [0, 1).

    import numpy as np
    rand_arr = np.random.rand(3, 2)
    print(rand_arr)
    # Output: array([[0.96915457, 0.83244264],
    #                 [0.21233911, 0.18182497],
    #                 [0.59052057, 0.65914898]])
  14. np.random.randn(): Create an array of random values with a specified shape, drawn from a standard normal distribution (mean=0, std=1).

    import numpy as np
    randn_arr = np.random.randn(2, 3)
    print(randn_arr)
    # Output: array([[-0.36598356, -0.72514216, -0.70897351],
    #                 [-1.95043623,  1.21601554,  0.65742338]])
  15. np.random.randint(): Create an array of random integers with a specified shape, drawn from a discrete uniform distribution over a specified interval.

    import numpy as np
    randint_arr = np.random.randint(low=0, high=10, size=(2, 3))
    print(randint_arr)
    # Output: array([[6, 7, 2],
    #                 [8, 0, 9]])

These functions can be very useful for creating arrays with specific shapes and values for use in various mathematical and statistical operations.

Sure, here are a few more array creation functions in NumPy:

  1. np.full(): Create an array with a specified shape and fill value.

    import numpy as np
    full_arr = np.full((2, 3), 5)
    print(full_arr)
    # Output: array([[5, 5, 5],
    #                 [5, 5, 5]])
  2. np.tile(): Create a new array by repeating an existing array a specified number of times along specified axes.

    import numpy as np
    arr = np.array([[1, 2], [3, 4]])
    tiled_arr = np.tile(arr, (2, 3))
    print(tiled_arr)
    # Output: array([[1, 2, 1, 2, 1, 2],
    #                 [3, 4, 3, 4, 3, 4],
    #                 [1, 2, 1, 2, 1, 2],
    #                 [3, 4, 3, 4, 3, 4]])
  3. np.meshgrid(): Create coordinate matrices from coordinate vectors.

    import numpy as np
    x = np.array([1, 2, 3])
    y = np.array([4, 5, 6])
    X, Y = np.meshgrid(x, y)
    print(X)
    # Output: array([[1, 2, 3],
    #                 [1, 2, 3],
    #                 [1, 2, 3]])
    print(Y)
    # Output: array([[4, 4, 4],
    #                 [5, 5, 5],
    #                 [6, 6, 6]])
  4. np.indices(): Create an array of indices into an array with a specified shape.

    import numpy as np
    indices_arr = np.indices((2, 3))
    print(indices_arr)
    # Output: array([[[0, 0, 0],
    #                 [1, 1, 1]],
    #                [[0, 1, 2],
    #                 [0, 1, 2]]])

These functions can be useful for a variety of tasks, such as creating coordinate grids, repeating arrays, and creating arrays of indices. Q

  1. Write a Python function that takes an integer n as input and returns an n-by-n identity matrix as a NumPy array.
import numpy as np

def identity_matrix(n):
    """
    Returns the n-by-n identity matrix as a NumPy array.
    """
    return np.eye(n)

# Example usage:
arr = identity_matrix(3)
print(arr)

Output:

array([[1., 0., 0.],
       [0., 1., 0.],
       [0., 0., 1.]])
  1. Write a Python function that takes a NumPy array as input and returns a new array with all of the negative elements set to zero.
import numpy as np

def set_negatives_to_zero(arr):
    """
    Returns a new array with all of the negative elements of arr set to zero.
    """
    arr[arr < 0] = 0
    return arr

# Example usage:
arr = np.array([-1, 2, -3, 4, -5])
new_arr = set_negatives_to_zero(arr)
print(new_arr)

Output:

array([0, 2, 0, 4, 0])
  1. Write a Python function that takes a NumPy array as input and returns a new array with the same shape as the input array, but with all of the elements set to zero.
import numpy as np

def create_zero_array(arr):
    """
    Returns a new array with the same shape as arr, but with all elements set to zero.
    """
    return np.zeros_like(arr)

# Example usage:
arr = np.array([[1, 2, 3], [4, 5, 6]])
new_arr = create_zero_array(arr)
print(new_arr)

Output:

array([[0, 0, 0],
       [0, 0, 0]])
  1. Write a Python function that takes a NumPy array as input and returns a new array with the same shape as the input array, but with all of the elements set to one.
import numpy as np

def create_one_array(arr):
    """
    Returns a new array with the same shape as arr, but with all elements set to one.
    """
    return np.ones_like(arr)

# Example usage:
arr = np.array([[1, 2, 3], [4, 5, 6]])
new_arr = create_one_array(arr)
print(new_arr)

Output:

array([[1, 1, 1],
       [1, 1, 1]])
  1. Write a Python function that takes two NumPy arrays as input and returns a new array that is the concatenation of the two input arrays along the second axis.
import numpy

6. Write a Python function that takes a NumPy array as input and returns a new array with the same shape as the input array, but with each element replaced by its absolute value.

```python
import numpy as np

def absolute_array(arr):
    """
    Returns a new array with the same shape as arr, but with each element replaced by its absolute value.
    """
    return np.abs(arr)

# Example usage:
arr = np.array([-1, 2, -3, 4, -5])
new_arr = absolute_array(arr)
print(new_arr)

Output:

array([1, 2, 3, 4, 5])
  1. Write a Python function that takes a NumPy array as input and returns a new array with all of the elements normalized to have a mean of zero and a standard deviation of one.
import numpy as np

def normalize_array(arr):
    """
    Returns a new array with all elements of arr normalized to have a mean of zero and a standard deviation of one.
    """
    arr_mean = np.mean(arr)
    arr_std = np.std(arr)
    return (arr - arr_mean) / arr_std

# Example usage:
arr = np.array([1, 2, 3, 4, 5])
new_arr = normalize_array(arr)
print(new_arr)

Output:

array([-1.26491106, -0.63245553,  0.        ,  0.63245553,  1.26491106])
  1. Write a Python function that takes a NumPy array as input and returns a new array with the same shape as the input array, but with all of the elements squared.
import numpy as np

def square_array(arr):
    """
    Returns a new array with the same shape as arr, but with all elements squared.
    """
    return np.square(arr)

# Example usage:
arr = np.array([1, 2, 3, 4, 5])
new_arr = square_array(arr)
print(new_arr)

Output:

array([ 1,  4,  9, 16, 25])
  1. Write a Python function that takes a NumPy array as input and returns a new array with the same shape as the input array, but with all of the elements cubed.
import numpy as np

def cube_array(arr):
    """
    Returns a new array with the same shape as arr, but with all elements cubed.
    """
    return np.power(arr, 3)

# Example usage:
arr = np.array([1, 2, 3, 4, 5])
new_arr = cube_array(arr)
print(new_arr)

Output:

array([  1,   8,  27,  64, 125])
  1. Write a Python function that takes a NumPy array as input and returns a new array with the same shape as the input array, but with all of the elements rounded to the nearest integer.
import numpy as np

def round_array(arr):
    """
    Returns a new array with the same shape as arr, but with all elements rounded to the nearest integer.
    """
    return np.round(arr)

# Example usage:
arr = np.array([1.2, 2.7, 3.5, 4.8, 5.1])
new_arr = round_array(arr)
print(new_arr)

Output:

array([1., 3., 4., 5., 5.])

Arithmetic with NumPy Arrays

  1. Write a Python function that takes two NumPy arrays as input and returns a new array that is the element-wise sum of the two input arrays.
import numpy as np

def add_arrays(arr1, arr2):
    """
    Returns a new array that is the element-wise sum of arr1 and arr2.
    """
    return np.add(arr1, arr2)

# Example usage:
arr1 = np.array([1, 2, 3, 4, 5])
arr2 = np.array([5, 4, 3, 2, 1])
new_arr = add_arrays(arr1, arr2)
print(new_arr)

Output:

array([6, 6, 6, 6, 6])
  1. Write a Python function that takes two NumPy arrays as input and returns a new array that is the element-wise difference of the two input arrays.
import numpy as np

def subtract_arrays(arr1, arr2):
    """
    Returns a new array that is the element-wise difference of arr1 and arr2.
    """
    return np.subtract(arr1, arr2)

# Example usage:
arr1 = np.array([1, 2, 3, 4, 5])
arr2 = np.array([5, 4, 3, 2, 1])
new_arr = subtract_arrays(arr1, arr2)
print(new_arr)

Output:

array([-4, -2,  0,  2,  4])
  1. Write a Python function that takes two NumPy arrays as input and returns a new array that is the element-wise product of the two input arrays.
import numpy as np

def multiply_arrays(arr1, arr2):
    """
    Returns a new array that is the element-wise product of arr1 and arr2.
    """
    return np.multiply(arr1, arr2)

# Example usage:
arr1 = np.array([1, 2, 3, 4, 5])
arr2 = np.array([5, 4, 3, 2, 1])
new_arr = multiply_arrays(arr1, arr2)
print(new_arr)

Output:

array([5, 8, 9, 8, 5])
  1. Write a Python function that takes two NumPy arrays as input and returns a new array that is the element-wise division of the two input arrays.
import numpy as np

def divide_arrays(arr1, arr2):
    """
    Returns a new array that is the element-wise division of arr1 and arr2.
    """
    return np.divide(arr1, arr2)

# Example usage:
arr1 = np.array([1, 2, 3, 4, 5])
arr2 = np.array([5, 4, 3, 2, 1])
new_arr = divide_arrays(arr1, arr2)
print(new_arr)

Output:

array([0.2       , 0.5       , 1.        , 2.        , 5.        ])
  1. Write a Python function that takes a NumPy array as input and returns a new array that is the element-wise square root of the input array.
import numpy as np

def sqrt_array(arr):
    """
    Returns a new array that is the element-wise square root of arr.
    """
    return np.sqrt(arr)

# Example usage:
arr = np.array([1, 4, 9, 16, 25])
new_arr = sqrt_array(arr)
print(new_arr)

Output:

array([1., 2., 3., 4., 5.])