drmattmedical

Medical Apps & Things


Attempt P(x) for small x,y datasets

#Python
import numpy
import matplotlib.pylab as plt


#X ARRAY HERE
x = numpy.array([0,1,2,3,4,5,6,7,8,9])

#Y ARRAY HERE
# y = risk of stroke/tia/systemic embolism
y = numpy.array([0.3,0.9,2.9,4.6,6.7,10.0,13.6,15.7,15.2,17.4])
# y = risk of ischaemic stroke
#y = numpy.array([0.2,0.6,2.2,3.2,4.8,7.2,9.7,11.2,10.8,12.2])

degree = 1
modelvalues = numpy.array([0])
test = False

# Polynomial Regression
results = {}

while not test:

coeffs = numpy.polyfit(x, y, degree)

# Polynomial Coefficients
results['polynomial'] = coeffs.tolist()

# r-squared
p = numpy.poly1d(coeffs)
# fit values, and mean
yhat = p(x) # or [p(z) for z in x]
ybar = numpy.sum(y)/len(y) # or sum(y)/len(y)
ssreg = numpy.sum((yhat-ybar)**2) # or sum([ (yihat - ybar)**2 for yihat in yhat])
sstot = numpy.sum((y - ybar)**2) # or sum([ (yi - ybar)**2 for yi in y])
results['r^2'] = ssreg / sstot
derived = numpy.polyval(coeffs, x).tolist()
modelvalues = numpy.around(derived, decimals=1).tolist()
test = numpy.array_equal(y, modelvalues)

degree += 1

print ("COEFFICIENTS (Nth to 0 order):",results)
print("PROVIDED Y-VALUES:", y)
print("DERIVED Y-VALUES:",modelvalues)
plt.plot(x, y, "bo")
plt.plot(x, numpy.polyval(coeffs, x), "r--", lw = 2)
plt.xlabel(degree)


print(test, degree, "COEFFICIENTS")

plt.tight_layout()
plt.show()