Doing things from scratch is great for learning, but I think it's worth showcasing how same can be done via numpy, which would be better choice for real world applications:
importnumpyasnp# Vector in numpy
height_weight_age=np.asarray([70,170,40])grades=np.asarray([85,80,75,62])# Vector addition / subtraction
print(np.asarray([1,2,3])+np.asarray([4,5,6]))# => array([5, 7, 9])
print(np.asarray([5,7,9])-np.asarray([4,5,6]))# => array([5, 7, 9])
# Componentwise sum
# Without `axis=0`, it would sum all matrix components
print(np.asarray([[1,2],[3,4],[5,6],[7,8]]).sum(axis=0))# => array([16, 20])
# Multiplying vector with a number
print(2*np.asarray([2,4,6]))# => array([4, 8, 12])
# Componentwise mean
print(np.asarray([[1,2],[3,4],[5,6]]).mean(axis=0))# => array([3., 4.])
# Dot product
print(np.asarray([1,2,3]).dot(np.asarray([4,5,6])))# => 32
# Sum of squares
# Equivalent to dot with self
print(np.asarray([1,2,3]).dot(np.asarray([1,2,3])))# => 14
# Magnitude
print(np.linalg.norm(np.asarray([3,4])))# => 5.0
# Squared difference
defsquared_difference(v,w):return(v-w).dot(v-w)# Euclidean distance
defdistance(v,w):returnnp.linalg.norm(v-w)
Even if some of the cases might look more confusing, greatest advantage of numpy is that it's optimized for maniuplating with large, multidimensional data arrays, which is perfect for data analytics use.
Doing things from scratch is great for learning, but I think it's worth showcasing how same can be done via numpy, which would be better choice for real world applications:
Even if some of the cases might look more confusing, greatest advantage of numpy is that it's optimized for maniuplating with large, multidimensional data arrays, which is perfect for data analytics use.
Absolutely agree. Thank you for sharing this!