Introduction : Lesson 7. Matrix Math and NumPy (5)

olxtar·2022년 2월 16일
0
post-thumbnail

NumPy Quiz를 풀어보자!

NumPy Quiz

# Use the numpy library
import numpy as np


def prepare_inputs(inputs):
    # TODO: create a 2-dimensional ndarray from the given 1-dimensional list;
    #       assign it to input_array
    input_array = None
    
    # TODO: find the minimum value in input_array and subtract that
    #       value from all the elements of input_array. Store the
    #       result in inputs_minus_min
    inputs_minus_min = None

    # TODO: find the maximum value in inputs_minus_min and divide
    #       all of the values in inputs_minus_min by the maximum value.
    #       Store the results in inputs_div_max.
    inputs_div_max = None

    # return the three arrays we've created
    return input_array, inputs_minus_min, inputs_div_max
    

def multiply_inputs(m1, m2):
    # TODO: Check the shapes of the matrices m1 and m2. 
    #       m1 and m2 will be ndarray objects.
    #
    #       Return False if the shapes cannot be used for matrix
    #       multiplication. You may not use a transpose
    pass


    # TODO: If you have not returned False, then calculate the matrix product
    #       of m1 and m2 and return it. Do not use a transpose,
    #       but you swap their order if necessary
    pass
    

def find_mean(values):
    # TODO: Return the average of the values in the given Python list
    pass


input_array, inputs_minus_min, inputs_div_max = prepare_inputs([-1,2,7])
print("Input as Array: {}".format(input_array))
print("Input minus min: {}".format(inputs_minus_min))
print("Input  Array: {}".format(inputs_div_max))

print("Multiply 1:\n{}".format(multiply_inputs(np.array([[1,2,3],[4,5,6]]), np.array([[1],[2],[3],[4]]))))
print("Multiply 2:\n{}".format(multiply_inputs(np.array([[1,2,3],[4,5,6]]), np.array([[1],[2],[3]]))))
print("Multiply 3:\n{}".format(multiply_inputs(np.array([[1,2,3],[4,5,6]]), np.array([[1,2]]))))

print("Mean == {}".format(find_mean([1,3,4])))



NumPy Quiz - My Answer

# Use the numpy library
import numpy as np


def prepare_inputs(inputs):
    # TODO: create a 2-dimensional ndarray from the given 1-dimensional list;
    #       assign it to input_array
    input_array = np.array(inputs)[None, :]
    
    
    # TODO: find the minimum value in input_array and subtract that
    #       value from all the elements of input_array. Store the
    #       result in inputs_minus_min
    inputs_minus_min = input_array - np.min( input_array )

    # TODO: find the maximum value in inputs_minus_min and divide
    #       all of the values in inputs_minus_min by the maximum value.
    #       Store the results in inputs_div_max.
    inputs_div_max = inputs_minus_min / (np.max( inputs_minus_min) )

    # return the three arrays we've created
    return input_array, inputs_minus_min, inputs_div_max
    

def multiply_inputs(m1, m2):
    # TODO: Check the shapes of the matrices m1 and m2. 
    #       m1 and m2 will be ndarray objects.
    #
    #       Return False if the shapes cannot be used for matrix
    #       multiplication. You may not use a transpose
    if m1.shape[0] != m2.shape[1] and m1.shape[1] != m2.shape[0]:
        return False


    # TODO: If you have not returned False, then calculate the matrix product
    #       of m1 and m2 and return it. Do not use a transpose,
    #       but you swap their order if necessary
    if m1.shape[0] == m2.shape[1]:
        return np.matmul( m2, m1 )
        
    else:
        return np.matmul( m1, m2 )
    

def find_mean(values):
    # TODO: Return the average of the values in the given Python list
    return np.mean(values)


input_array, inputs_minus_min, inputs_div_max = prepare_inputs([-1,2,7])
print("Input as Array: {}".format(input_array))
print("Input minus min: {}".format(inputs_minus_min))
print("Input  Array: {}".format(inputs_div_max))

print("Multiply 1:\n{}".format(multiply_inputs(np.array([[1,2,3],[4,5,6]]), np.array([[1],[2],[3],[4]]))))
print("Multiply 2:\n{}".format(multiply_inputs(np.array([[1,2,3],[4,5,6]]), np.array([[1],[2],[3]]))))
print("Multiply 3:\n{}".format(multiply_inputs(np.array([[1,2,3],[4,5,6]]), np.array([[1,2]]))))

print("Mean == {}".format(find_mean([1,3,4])))

Comment 1 :
첫번째 TODO 주어진 1차원의 List로 2차원의 ndarray를 만들라해서...
1. List를 ndarray로 변환한다.
2. 2차원으로 reshape한다.
였는데!
주어진 List의 1차원 Length가 몇인지 알 수 없잖아?
그래서 reshape( ?, ? )가 되버림...

그래서 ndarrray로 변환한 놈을
( [None, :] ) 로 1행 n열 형태 변환함

근데 정답보니...

np.array( [ inputs ] )
중괄호 하나 겉에 쳐주면 되네 ^ㅡ^

Comment 2 :
m1,m2의 multiply 문제에서
나는 if문에 or을 사용하려했다.
하지만 and 임
무슨말이냐...
주어진 두 개의 Matrix가 matrix multiplication이 되지 않는다는 것은
m1의 Row수 != m2의 Col수
m1의 Col수 != m2의 Row수

둘다여야 한다는 것임!



NumPy Quiz - Solution

# Use the numpy library
import numpy as np


######################################################
#
#      MESSAGE TO STUDENTS:
#
#  This file contains a solution to the coding quiz. Feel free
#  to look at it when you are stuck, but try to solve the
#   problem on your own first.
#
######################################################


def prepare_inputs(inputs):
    # TODO: create a 2-dimensional ndarray from the given 1-dimensional list;
    #       assign it to input_array
    input_array = np.array([inputs])
    
    # TODO: find the minimum value in input_array and subtract that
    #       value from all the elements of input_array. Store the
    #       result in inputs_minus_min
    # We can use NumPy's min function and element-wise division
    inputs_minus_min = input_array - np.min(input_array)

    # TODO: find the maximum value in inputs_minus_min and divide
    #       all of the values in inputs_minus_min by the maximum value.
    #       Store the results in inputs_div_max.
    # We can use NumPy's max function and element-wise division
    inputs_div_max = inputs_minus_min / np.max(inputs_minus_min)

    return input_array, inputs_minus_min, inputs_div_max
    

def multiply_inputs(m1, m2):
    # Check the shapes of the matrices m1 and m2. 
    # m1 and m2 will be ndarray objects.
    #
    # Return False if the shapes cannot be used for matrix
    # multiplication. You may not use a transpose
    if m1.shape[0] != m2.shape[1] and m1.shape[1] != m2.shape[0]:     
        return False

    # Have not returned False, so calculate the matrix product
    # of m1 and m2 and return it. Do not use a transpose,
    #       but you swap their order if necessary
    if m1.shape[1] == m2.shape[0]:
        return np.matmul(m1, m2)        
    else:
        return np.matmul(m2, m1)        


def find_mean(values):
    # Return the average of the values in the given Python list
    # NumPy has a lot of helpful methods like this.
    return np.mean(values)



NumPy Quiz - Output

Input as Array: [[-1  2  7]]
Input minus min: [[0 3 8]]
Input  Array: [[0.    0.375 1.   ]]
Multiply 1:
False
Multiply 2:
[[14]
 [32]]
Multiply 3:
[[ 9 12 15]]
Mean == 2.6666666666666665

Nice job!  That's right!
profile
예술과 기술

0개의 댓글