# Custom Vector and Matrix classes in python for machine learning

I am creating a machine learning tool set from scratch in python. I have never done something of this kind and I don't usually use python but I thought it would be good to expand my horizons. I am really looking for aspects of the code that would really hinder performance and things to consider since this will be used for a neural network implementation.

class vector:
def __init__(self, size):
self.elems = [0] * size
self.size = size
def __repr__(self):
return repr(self.elems)
def __mul__(self, other):
if(self.size != other.size):
raise ArithmeticError("vectors of two different lengths")
a = 0
for i in range(self.size):
a += self.elems[i] * other.elems[i]
return a
def set(self, array):
for i in range(self.size):
self.elems[i] = array[i]
self.mag =  sum([i**2 for i in self.elems])**.5
def normalize(self):
a =  vector(self.size)
a.set([i/self.mag for i in self.elems])
return(a)

class matrix:
def __init__(self, r, c):
self.coloums = [vector(c) for i in range(r)]
self.r = r
self.c = c
def __repr__(self):
return repr(self.coloums)
def __mul__(self, other):
if(type(other) != vector):
raise TypeError("matrices can only be multiplied by vectors")
if(self.c != other.size):
raise ArithmeticError("rows and lengths do not match")
a = vector(self.r)
a.set([(other*self.coloums[i]) for i in range(self.r)])
return a
def set(self, multiarray):
for i in range(self.c):
self.coloums[i].set(multiarray[i])


I am aware this has no way of multiply by a scalar but I have no need for that just yet and it would be pretty trivial to implement.

• Is this something you are doing for learning? If not, just use numpy or one of pythons many machine learning frameworks – Oscar Smith Jan 1 '19 at 5:58
• I think he's trying to make his own framework. – austingae Jan 1 '19 at 6:31
• Yes the purpose is to do it on my own @Oscar I could use a library but that defeats the purpose. – robert gibson Jan 1 '19 at 6:38
• (Welcome to Code Review!) (Stick to standards such as The Python Style Guide and Embedded Documentation Conventions.) – greybeard Jan 1 '19 at 8:17