def fitData(fileName): xVals, yVals = getData(fileName) xVals = numpy.array(xVals) yVals = numpy.array(yVals) xVals = xVals*9.81 #get force numpy.plot(xVals, yVals, 'bo', label = 'Measured points') model = numpy.polyfit(xVals, yVals, 1) xVals = xVals + [2] yVals = yVals + [] estYVals = numpy.polyval(model, xVals) numpy.plot(xVals, estYVals, 'r', label = 'Linear fit, r**2 = ' + str(round(rSquared(yVals, estYVals), 5))) model = numpy.polyfit(xVals, yVals, 2) estYVals = numpy.polyval(model, xVals) numpy.plot(xVals, estYVals, 'g--', label = 'Quadratic fit, r**2 = ' + str(round(rSquared(yVals, estYVals), 5))) numpy.title('A Linear Spring') labelPlot() numpy.legend(loc = 'best')
def fitData1(fileName): xVals, yVals = getData(fileName) xVals = numpy.array(xVals) yVals = numpy.array(yVals) xVals = xVals * 9.81 #get force numpy.plot(xVals, yVals, 'bo', label='Measured points') labelPlot() model = numpy.polyfit(xVals, yVals, 1) estYVals = numpy.polyval(model, xVals) numpy.plot(xVals, estYVals, 'r', label='Linear fit, k = ' + str(round(1 / model[0], 5))) numpy.legend(loc='best')
def fitData(fileName): xVals, yVals = getData(fileName) xVals = numpy.array(xVals) yVals = numpy.array(yVals) xVals = xVals * 9.81 #get force numpy.plot(xVals, yVals, 'bo', label='Measured points') labelPlot() a, b = numpy.polyfit(xVals, yVals, 1) estYVals = a * numpy.array(xVals) + b print('a =', a, 'b =', b) numpy.plot(xVals, estYVals, 'r', label='Linear fit, k = ' + str(round(1 / a, 5))) numpy.legend(loc='best')
def genFits(xVals, yVals, degrees): models = [] for d in degrees: model = numpy.polyfit(xVals, yVals, d) models.append(model) return models
for i in range(len(xVals)): if i in toTrain: trainX.append(xVals[i]) trainY.append(yVals[i]) else: testX.append(xVals[i]) testY.append(yVals[i]) return trainX, trainY, testX, testY numSubsets = 10 dimensions = (1, 2, 3, 4) rSquares = {} for d in dimensions: rSquares[d] = [] for f in range(numSubsets): trainX, trainY, testX, testY = splitData(xVals, yVals) for d in dimensions: model = numpy.polyfit(trainX, trainY, d) estYVals = numpy.polyval(model, trainX) estYVals = numpy.polyval(model, testX) rSquares[d].append(rSquared(testY, estYVals)) print('Mean R-squares for test data') for d in dimensions: mean = round(sum(rSquares[d])/len(rSquares[d]), 4) sd = round(numpy.std(rSquares[d]), 4) print('For dimensionality', d, 'mean =', mean, 'Std =', sd) print(rSquares[1])