Guest User

Untitled

a guest
Aug 10th, 2016
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.37 KB | None | 0 0
  1. import csv
  2.  
  3. # Provides only numerical data, without any additional comments which are in the first column in .csv file
  4. with open('loss.csv', 'rb') as csvfile:
  5.     data = [row[1:] for row in csv.reader(csvfile, delimiter='\t')]
  6.  
  7. # This nested horrible construct provides sum of products X*Y, where X is the j-th element of the first row
  8. # and Y is the j-th element i-th row. Pairs data[0] and data[i] provide data to fit linear equation.
  9. # len(data) provides number of lines, so len(data)-1 is the number of linear equations to obtain
  10. 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))]]
  11.  
  12. # N is the number of X, Y pairs, instead of zero it can be any number from xrange(0, len(data))
  13. n = len(data[0])
  14.  
  15. # Average of X
  16. x_avg = sum([float(x) for x in data[0]]) / n
  17.  
  18. # Average of Y in i-th row
  19. y_avg = [sum(j) / n for j in [[float(y) for y in data[i]] for i in xrange(1, len(data))]]
  20.  
  21. # sos is the sum of X**2
  22. sos = sum([float(j)**2 for j in data[0]])
  23.  
  24. # list of b coeficients of linear equation
  25. a = [(i - n * x_avg * j) / (sos - n * x_avg**2) for i, j in zip(sop, y_avg)]
  26.  
  27. # list of b coeficients of linear equation
  28. b = [j - i * x_avg for i, j in zip(a, y_avg)]
  29.  
  30. # printing results
  31. print 'Results of regression analysis:'
  32. x = 1
  33. for i, j in zip(a, b):
  34.     print 'Equation ' + str(x) + ': y = %.4ex + %.4e' % (i, j)
  35.     x += 1
Advertisement
Add Comment
Please, Sign In to add comment