Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import csv
- # Provides only numerical data, without any additional comments which are in the first column in .csv file
- with open('loss.csv', 'rb') as csvfile:
- data = [row[1:] for row in csv.reader(csvfile, delimiter='\t')]
- # This nested horrible construct provides sum of products X*Y, where X is the j-th element of the first row
- # and Y is the j-th element i-th row. Pairs data[0] and data[i] provide data to fit linear equation.
- # len(data) provides number of lines, so len(data)-1 is the number of linear equations to obtain
- sop = [sum(j) for j in [[float(x) * float(y) for x, y in zip(data[0], data[i])] for i in xrange(1, len(data))]]
- # N is the number of X, Y pairs, instead of zero it can be any number from xrange(0, len(data))
- n = len(data[0])
- # Average of X
- x_avg = sum([float(x) for x in data[0]]) / n
- # Average of Y in i-th row
- y_avg = [sum(j) / n for j in [[float(y) for y in data[i]] for i in xrange(1, len(data))]]
- # sos is the sum of X**2
- sos = sum([float(j)**2 for j in data[0]])
- # list of b coeficients of linear equation
- a = [(i - n * x_avg * j) / (sos - n * x_avg**2) for i, j in zip(sop, y_avg)]
- # list of b coeficients of linear equation
- b = [j - i * x_avg for i, j in zip(a, y_avg)]
- # printing results
- print 'Results of regression analysis:'
- x = 1
- for i, j in zip(a, b):
- print 'Equation ' + str(x) + ': y = %.4ex + %.4e' % (i, j)
- x += 1
Advertisement
Add Comment
Please, Sign In to add comment