コード例 #1
0
def fitData2(fileName):
    '''
    Models predictions using Terman's law model (cubic fit) and 
    Hooks Law (linear fit).

    Hook's Law functions up to the point where the spring reaches 
    it's elastic limit - when it stops behaving as a spring but instead 
    as a rope, etc (doesn't get longer b/c hang more weight on it)
    '''
    xVals, yVals = getData(fileName)
    extX = pylab.array(xVals + [1.05, 1.1, 1.15, 1.2, 1.25])
    xVals = pylab.array(xVals)
    yVals = pylab.array(yVals)
    xVals = xVals*9.81  # convert mass to force (F = mg)
    extX = extX*9.81    # convert mass to force (F = mg)
    pylab.plot(xVals, yVals, 'bo', label = 'Measured displacements')
    pylab.title('Measured Displacement of Spring')
    pylab.xlabel('|Force| (Newtons)')
    pylab.ylabel('Distance (meters)')
    a,b = pylab.polyfit(xVals, yVals, 1)
    estYVals = a*extX + b
    pylab.plot(extX, estYVals, label = 'Linear fit')
    a,b,c,d = pylab.polyfit(xVals, yVals, 3)
    estYVals = a*(extX**3) + b*extX**2 + c*extX + d
    pylab.plot(extX, estYVals, label = 'Cubic fit')
    pylab.legend(loc = 'best')
def tryFits1(fName):
    distances, heights = getTrajectoryData(fName)
    distances = pylab.array(distances)*36
    totHeights = pylab.array([0]*len(distances))
    for h in heights:
        totHeights = totHeights + pylab.array(h)
    pylab.title('Trajectory of Projectile (Mean of 4 Trials)')
    pylab.xlabel('Inches from Launch Point')
    pylab.ylabel('Inches Above Launch Point')
    meanHeights = totHeights/float(len(heights))
    pylab.plot(distances, meanHeights, 'bo')
    a,b = pylab.polyfit(distances, meanHeights, 1)
    altitudes = a*distances + b
    pylab.plot(distances, altitudes, 'r',
               label = 'Linear Fit' + ', R2 = '
               + str(round(rSquare(meanHeights, altitudes), 4)))
    a,b,c = pylab.polyfit(distances, meanHeights, 2)
    altitudes = a*(distances**2) + b*distances + c
    pylab.plot(distances, altitudes, 'g',
               label = 'Quadratic Fit' + ', R2 = '
               + str(round(rSquare(meanHeights, altitudes), 4)))
    pylab.legend()

##tryFits1('launcherData.txt')
##pylab.show()

# Calculating the location of the peak of height:
# −(b/2a)=547.1

# Once we have the curve fitting value, we can derrive from it other measurements like speed, strenght etc, using known physics.
コード例 #3
0
def visualise(fileName, title="", linearFit=False, polyFit=False):
    """ Draw graph representing the result. A bit verbose as that seem to be the only way to make borders gray.
    fileName = path and name of the pickled results
    """
    with open(fileName, "rb") as f:
        data = pickle.load(f)
        fig = plt.figure()
        p = fig.add_subplot(111)
        if not linearFit and not polyfit:
            p.plot(data[0], data[1], 'bo-', label="sentiment")
            p.plot([data[0][0], data[0][-1]], [data[1][0], data[1][-1]],
                   'g', label="straight line through first and last point")
        elif linearFit:
            fit = polyfit(data[0], data[1], 1)
            fitFunc = poly1d(fit)
            p.plot(data[0], data[1], '-ro', label='sentiment')
            p.plot(data[0], fitFunc(data[0]), "--k", label="linear fit")
        elif polyFit:
            fit = polyfit(data[0], data[1], 2)
            f = [d*d*fit[0] + d*fit[1] + fit[2] for d in data[0]]
            p.plot(data[0], data[1], '-ro', label='sentiment')
            p.plot(data[0], f, "--k", label="polynomial fit")
        p.legend(prop={'size': 10}, frameon=False)
        plt.ylabel("Average happiness")
        plt.xlabel("Rating")
        for e in ['bottom', 'top', 'left', 'right']:
            p.spines[e].set_color('gray')
        if title:
            plt.title(title)
        plt.show()
コード例 #4
0
ファイル: projectile.py プロジェクト: mbhushan/incompy
def processTrajectories(filename):
    dist, heights = getTrajectory(filename)
    trials = len(heights)
    dist = pylab.array(dist)

    # get array combiming mean height at each distances
    totHeights = pylab.array([0] * len(dist))
    for h in heights:
        totHeights = totHeights + pylab.array(h)
    meanHeights = totHeights/len(heights)

    # start plotting :)
    pylab.title("Trajectile of Projectile " + "(Mean of " + str(trials)
                + " trails)")
    pylab.xlabel("Inches from launch point")
    pylab.ylabel("Inches above launch point")
    pylab.plot(dist, meanHeights, 'bo')

    a, b = pylab.polyfit(dist, meanHeights, 1)
    altitudes = a * dist + b
    pylab.plot(dist, altitudes, 'b', label='linear fit')
    print 'RSquared of linear fit: ', rSquared(meanHeights, altitudes)

    a, b, c = pylab.polyfit(dist, meanHeights, 2)
    altitudes = a*(dist**2) + b*(dist) + c
    pylab.plot(dist, altitudes, 'b:', label="Quadratic Fit")
    print 'RSquared of quadratic fit: ', rSquared(meanHeights, altitudes)
    pylab.legend()

    pylab.show()
コード例 #5
0
ファイル: Lec_18__code.py プロジェクト: Sabinu/6.00x
def tryFits1(fName):
    distances, heights = getTrajectoryData(fName)
    distances = pylab.array(distances)*36
    totHeights = pylab.array([0]*len(distances))
    for h in heights:
        totHeights = totHeights + pylab.array(h)
    pylab.title('Trajectory of Projectile (Mean of 4 Trials)')
    pylab.xlabel('Inches from Launch Point')
    pylab.ylabel('Inches Above Launch Point')
    meanHeights = totHeights/float(len(heights))
    pylab.plot(distances, meanHeights, 'bo')
    a,b = pylab.polyfit(distances, meanHeights, 1)
    altitudes = a*distances + b
    pylab.plot(distances, altitudes, 'r',
               label = 'Linear Fit' + ', R2 = '
               + str(round(rSquare(meanHeights, altitudes), 4)))
    a,b,c = pylab.polyfit(distances, meanHeights, 2)
    altitudes = a*(distances**2) + b*distances + c
    pylab.plot(distances, altitudes, 'g',
               label = 'Quadratic Fit' + ', R2 = '
               + str(round(rSquare(meanHeights, altitudes), 4)))
    pylab.legend()

##tryFits1('launcherData.txt')
##pylab.show()
コード例 #6
0
ファイル: baudrate_parser.py プロジェクト: salkinium/bachelor
def plot_dco_values(ax, values, color="k"):
    interpol1 = {"temperature": values["temperature"][0:7], "values": values["values"][0:7]}
    fit1 = pylab.polyfit(interpol1["temperature"], interpol1["values"], 1)
    print "m={} b={}".format(fit1[0], fit1[1])
    fit_fn1 = pylab.poly1d(fit1)

    interpol2 = {"temperature": values["temperature"][6:14], "values": values["values"][6:14]}
    fit2 = pylab.polyfit(interpol2["temperature"], interpol2["values"], 1)
    print "m={} b={}".format(fit2[0], fit2[1])
    fit_fn2 = pylab.poly1d(fit2)

    plot = ax.plot(
        interpol1["temperature"],
        fit_fn1(interpol1["temperature"]),
        "k-",
        interpol2["temperature"],
        fit_fn2(interpol2["temperature"]),
        "k-",
        # values['temperature'], values['values'], '{}-'.format(color),
        values["temperature"],
        values["values"],
        "{}o".format(color),
        markersize=5,
    )
    pylab.setp(plot[0], linewidth=2)
    pylab.setp(plot[1], linewidth=2)

    return plot
コード例 #7
0
ファイル: problem3.py プロジェクト: franzip/edx
def plotFittingCurve(rabbits, foxes):
    r_coeff = pylab.polyfit(range(len(rabbits)), rabbits, 2) 
    f_coeff = pylab.polyfit(range(len(foxes)), foxes, 2)
    pylab.plot(pylab.polyval(r_coeff, range(len(rabbits))), label = "Rabbits Curve")
    pylab.plot(pylab.polyval(f_coeff, range(len(foxes))), label = "Foxes Curve")
    pylab.legend()
    pylab.show()
コード例 #8
0
def tryFits(fName):
    '''
    Linear fit does not fit the data. Not a logical assumption that the arrow
    flies in a straight line to the target.

    Quadratic fit mirrors a parabolic pathway.
    '''
    distances, heights = getTrajectoryData(fName)
    distances = pylab.array(distances)*36 # Convert yards to feet
    totHeights = pylab.array([0]*len(distances))
    for h in heights:
        totHeights = totHeights + pylab.array(h) # Get one avg measurement of height
    pylab.title('Trajectory of Projectile (Mean of 4 Trials)')
    pylab.xlabel('Inches from Launch Point')
    pylab.ylabel('Inches Above Launch Point')
    meanHeights = totHeights/float(len(heights))
    pylab.plot(distances, meanHeights, 'bo')
    a,b = pylab.polyfit(distances, meanHeights, 1)
    altitudes = a*distances + b
    pylab.plot(distances, altitudes, 'r',
               label = 'Linear Fit')
    a,b,c = pylab.polyfit(distances, meanHeights, 2)
    altitudes = a*(distances**2) + b*distances + c 
    pylab.plot(distances, altitudes, 'g',
               label = 'Quadratic Fit')
    pylab.legend()
コード例 #9
0
def runSimulation2(numSteps):
    """
    Runs the simulation for `numSteps` time steps.

    Returns a tuple of two lists: (rabbit_populations, fox_populations)
      where rabbit_populations is a record of the rabbit population at the
      END of each time step, and fox_populations is a record of the fox population
      at the END of each time step.

    Both lists should be `numSteps` items long.
    """

    rabbitPopulationOverTime = []
    foxPopulationOverTime = []
    for step in range(numSteps):
        rabbitGrowth()
        rabbitPopulationOverTime.append(CURRENTRABBITPOP)
        foxGrowth()
        foxPopulationOverTime.append(CURRENTFOXPOP)
    print "CURRENTRABBITPOP", CURRENTRABBITPOP, rabbitPopulationOverTime
    print "CURRENTFOXPOP", CURRENTFOXPOP, foxPopulationOverTime
    pylab.plot(range(numSteps), rabbitPopulationOverTime, '-g', label='Rabbit population')
    pylab.plot(range(numSteps), foxPopulationOverTime, '-o', label='Fox population')
    rabbit_coeff = pylab.polyfit(range(len(rabbitPopulationOverTime)), rabbitPopulationOverTime, 2)
    pylab.plot(pylab.polyval(rabbit_coeff, range(len(rabbitPopulationOverTime))))
    fox_coeff = pylab.polyfit(range(len(foxPopulationOverTime)), foxPopulationOverTime, 2)
    pylab.plot(pylab.polyval(fox_coeff, range(len(rabbitPopulationOverTime))))
    pylab.title('Fox and rabbit population in the wood')
    xlabel = "Plot for simulation of {} steps".format(numSteps)
    pylab.xlabel(xlabel)
    pylab.ylabel('Current fox and rabbit population')
    pylab.legend(loc='upper right')
    pylab.tight_layout()
    pylab.show()
    pylab.clf()
コード例 #10
0
ファイル: exam_problem3.py プロジェクト: ansh5441/code
def runSimulation(numSteps):
    """
    Runs the simulation for `numSteps` time steps.

    Returns a tuple of two lists: (rabbit_populations, fox_populations)
      where rabbit_populations is a record of the rabbit population at the 
      END of each time step, and fox_populations is a record of the fox population
      at the END of each time step.

    Both lists should be `numSteps` items long.
    """
    
    rabbitPop = []
    foxPop = []
    for i in range(numSteps):
        rabbitGrowth()
        foxGrowth()
        rabbitPop.append(CURRENTRABBITPOP)
        foxPop.append(CURRENTFOXPOP)
    #return (rabbitPop,foxPop)
    pylab.plot(rabbitPop)
    pylab.plot(foxPop)
    pylab.show()
    rabbitPopulationOverTime = rabbitPop[:]
    coeff = pylab.polyfit(range(len(rabbitPopulationOverTime)), rabbitPopulationOverTime, 2)
    pylab.plot(pylab.polyval(coeff, range(len(rabbitPopulationOverTime))))
    pylab.show()
    rabbitPopulationOverTime = foxPop[:]
    coeff = pylab.polyfit(range(len(rabbitPopulationOverTime)), rabbitPopulationOverTime, 2)
    pylab.plot(pylab.polyval(coeff, range(len(rabbitPopulationOverTime))))
    pylab.show()
コード例 #11
0
def tryFits1(fName):
    '''
    Calculate the coefficient of determination (R**2) to determine how
    well the model fits the data and ergo could make predictions.
    '''
    distances, heights = getTrajectoryData(fName)
    distances = pylab.array(distances)*36
    totHeights = pylab.array([0]*len(distances))
    for h in heights:
        totHeights = totHeights + pylab.array(h)
    pylab.title('Trajectory of Projectile (Mean of 4 Trials)')
    pylab.xlabel('Inches from Launch Point')
    pylab.ylabel('Inches Above Launch Point')
    meanHeights = totHeights/float(len(heights))
    pylab.plot(distances, meanHeights, 'bo')
    a,b = pylab.polyfit(distances, meanHeights, 1)
    altitudes = a*distances + b
    pylab.plot(distances, altitudes, 'r',
               label = 'Linear Fit' + ', R2 = '
               + str(round(rSquare(meanHeights, altitudes), 4)))
    a,b,c = pylab.polyfit(distances, meanHeights, 2)
    altitudes = a*(distances**2) + b*distances + c
    pylab.plot(distances, altitudes, 'g',
               label = 'Quadratic Fit' + ', R2 = '
               + str(round(rSquare(meanHeights, altitudes), 4)))
    pylab.legend()
コード例 #12
0
def plotPopulations(numSteps):
    """ Plots populations of Foxes & Rabbits for given timesteps. """
    rab_pop, fox_pop = runSimulation(numSteps)
    # for i in range(len(rab_pop)):
    #     print(rab_pop[i], fox_pop[i])

    r_style = 'bo'    # blue - continuous line
    f_style = 'ro'    # red  - continuous line

    pylab.figure('Fox / Rabit Populations')

    pylab.plot(rab_pop, r_style, label='Rabbit Pop')
    pylab.plot(fox_pop, f_style, label='Fox Pop')

    pylab.title('Fox / Rabit Populations: {} timesteps'.format(numSteps))
    pylab.xlabel('Time Steps')
    pylab.ylabel('Population')
    pylab.legend(loc='best')

    degree = 2
    rab_coeff = pylab.polyfit(range(len(rab_pop)), rab_pop, degree)
    pylab.plot(pylab.polyval(rab_coeff, range(len(rab_pop))), 'b-')
    fox_coeff = pylab.polyfit(range(len(fox_pop)), fox_pop, degree)
    pylab.plot(pylab.polyval(fox_coeff, range(len(fox_pop))), 'r-')

    pylab.show()
コード例 #13
0
ファイル: exam_problem3.py プロジェクト: adolphlwq/MIT6002x
def plotFitSimulation(numSteps):
    ans = runSimulation(numSteps)
    rabbitCoeff = pylab.polyfit(range(numSteps), ans[0], 2)
    foxCoeff = pylab.polyfit(range(numSteps), ans[1], 2)
    print rabbitCoeff, foxCoeff
    pylab.plot(pylab.polyval(rabbitCoeff, range(numSteps)), 'r')
    pylab.plot(pylab.polyval(foxCoeff, range(numSteps)), 'g')
    pylab.title("polyfit result")
    pylab.show()
コード例 #14
0
ファイル: P8.py プロジェクト: leanton/6.00x
def findOrder(xVals, yVals, accuracy = 1.0e-1):
    # Your Code Here
    i = 0
    r = pylab.polyfit(xVals, yVals, 0, full=True)[1][0]
    while r > accuracy:
        i += 1
        r = pylab.polyfit(xVals, yVals, i, full=True)[1][0]
    s = pylab.polyfit(xVals, yVals, i, full=True)[0]
    return s
コード例 #15
0
    def fitAverage(self,
                   linear_fit_min_value,
                   linear_fit_max_value,

                   degree,

                   # function taking the list of parameters
                   # and translating it into a label for writing 
                   # a text on the graph
                   # with the fit result
                   label_func,
                   ):
        """ perform a linear fit to the average values """
        import utils
        global linear_fit_min_num_vertices, linear_fit_max_num_vertices

        # filter the values for the fit
        xpos_for_fit = []
        ypos_for_fit = []
        uncert_for_fit = []

        oneSigmaIndex = 2
        assert standardQuantileHistoDefs[oneSigmaIndex]['title'] == '1 sigma'

        for x,y, sigmaUp, sigmaDown in zip(self.xpos, self.avg_values, self.quantile_values_upper[oneSigmaIndex], self.quantile_values_lower[oneSigmaIndex]):
            if x >= linear_fit_min_value and \
               x <= linear_fit_max_value:

                xpos_for_fit.append(x)

                # mean
                ypos_for_fit.append(y)
                
                # 1 sigma 
                uncert_for_fit.append(0.5 * (sigmaUp - sigmaDown))

        if len(xpos_for_fit) < 2:
            raise Exception("must have at least two points for a linear fit (linear_fit_min_value=" + str(linear_fit_min_value) + " linear_fit_max_value=" + str(linear_fit_max_value) + ")")

        # perform fit to means
        # note that pylab.polyfit returns coefficients in an order
        # where the first coefficient corresponds to the highest power of x, 
        # we reverse this
        import pylab

        fittedCoeffs = pylab.polyfit(xpos_for_fit, ypos_for_fit, degree)
        fittedCoeffs = fittedCoeffs[::-1]
        self.addFitResult('mean', linear_fit_min_value, linear_fit_max_value, self.meanFitResult, fittedCoeffs)

        self.fitResultLabel = label_func(fittedCoeffs * self.y_scale_factor, self.yaxis_unit_label)
        
        # perform fit to symmetrized 1 sigma bands
        fittedCoeffs = pylab.polyfit(xpos_for_fit, uncert_for_fit, degree)
        fittedCoeffs = fittedCoeffs[::-1]
        self.addFitResult('uncert', linear_fit_min_value, linear_fit_max_value, self.uncertFitResult, fittedCoeffs)
コード例 #16
0
ファイル: exam_problem3.py プロジェクト: vduenasg/edX
def plotSimulation():
    rabbits, foxes = runSimulation(200)
    pylab.plot(rabbits, label='Rabbits')
    pylab.plot(foxes, label='Foxes')
    a, b, c = pylab.polyfit(range(len(rabbits)), rabbits, 2)
    pylab.plot(pylab.polyval([a, b, c], range(len(rabbits))), label='Rabbits')
    d, e, f = pylab.polyfit(range(len(foxes)), foxes, 2)
    pylab.plot(pylab.polyval([d, e, f], range(len(foxes))), label='Foxes')
    pylab.grid()
    pylab.legend()
    pylab.show()
コード例 #17
0
def main(filename):
	pOut = parse( filename)
	oM, oB = polyfit(pOut[0], pOut[1], 1)
	tM, tB = polyfit(pOut[2], pOut[3], 1)
	print("rep_overlap = {} * overlap + {}".format(oM, oB))
	print("rep_tanimoto = {} * tanimoto + {}".format(tM, tB))
	oC = polyfit(pOut[0], pOut[1], 0)
	tC = polyfit(pOut[2], pOut[3], 0)
	print("rep_overlap = {} * overlap".format(oM, oB))
	print("rep_tanimoto = {} * tanimoto + {}".format(tM, tB))
	makeGraphs( pOut)
コード例 #18
0
def plotLineFit():
    rabbitPops, foxPops = runSimulation(200)
    steps = [n for n in range(1, 201)]
    coeff = pylab.polyfit(range(len(rabbitPops)), rabbitPops, 2)
    pylab.plot(pylab.polyval(coeff, range(len(rabbitPops))))
    coeff = pylab.polyfit(range(len(foxPops)), foxPops, 2)
    pylab.plot(pylab.polyval(coeff, range(len(foxPops))))
    pylab.title('Fox vs. Rabbit')
    pylab.legend(('Rabbit Pop', 'Fox Pop'))
    pylab.xlabel('Step')
    pylab.ylabel('Population')
    pylab.show()
コード例 #19
0
def plot(rabbits, foxes):
    N = len(rabbits)
    pylab.plot(range(N), rabbits, 'go', label = "rabbit pop")
    pylab.plot(range(N), foxes, 'ro', label = "foxes pop")
    rab_coeff = pylab.polyfit(range(N), rabbits, 2)
    fox_coeff = pylab.polyfit(range(N), foxes, 2)
    pylab.plot(pylab.polyval(rab_coeff, range(N)), 'g-', label = "rabbit polyfit")
    pylab.plot(pylab.polyval(fox_coeff, range(N)), 'r-', label = "fox polyfit")
    pylab.xlabel("Time")
    pylab.ylabel("Population")
    pylab.title("Dynamics of Rabbit and Fox Population")
    pylab.legend()
    pylab.show()
コード例 #20
0
def anscombe(plotPoints):
    dataFile = open('anscombe.txt', 'r')
    X1,X2,X3,X4,Y1,Y2,Y3,Y4 = [],[],[],[],[],[],[],[]
    for line in dataFile:
        x1,y1,x2,y2,x3,y3,x4,y4 = line.split()
        X1.append(float(x1))
        X2.append(float(x2))
        X3.append(float(x3))
        X4.append(float(x4))
        Y1.append(float(y1))
        Y2.append(float(y2))
        Y3.append(float(y3))
        Y4.append(float(y4))
    dataFile.close()
    xVals = pylab.array(range(21))
    if plotPoints: pylab.plot(X1, Y1, 'o')
    a, b = pylab.polyfit(X1, Y1, 1)
    yVals = a*xVals + b
    pylab.plot(xVals, yVals)
    pylab.xlim(0, 20)
    mean = sum(Y1)/float(len(Y1))
    median = Y1[len(Y1)/2 + 1]
    pylab.title('Mean = ' + str(mean) + ', Median = ' + str(median))
    pylab.figure()
    if plotPoints: pylab.plot(X2, Y2, 'o')
    a, b = pylab.polyfit(X2, Y2, 1)
    yVals = a*xVals + b
    pylab.plot(xVals, yVals)
    pylab.xlim(0, 20)
    mean = sum(Y1)/float(len(Y1))
    median = Y1[len(Y1)/2 + 1]
    pylab.title('Mean = ' + str(mean) + ', Median = ' + str(median))
    pylab.figure()
    if plotPoints: pylab.plot(X3, Y3, 'o')
    a, b = pylab.polyfit(X3, Y3, 1)
    yVals = a*xVals + b
    pylab.plot(xVals, yVals)
    pylab.xlim(0, 20)
    mean = sum(Y1)/float(len(Y1))
    median = Y1[len(Y1)/2 + 1]
    pylab.title('Mean = ' + str(mean) + ', Median = ' + str(median))
    pylab.figure()
    if plotPoints: pylab.plot(X4, Y4, 'o')
    a, b = pylab.polyfit(X4, Y4, 1)
    yVals = a*xVals + b
    pylab.plot(xVals, yVals)
    pylab.xlim(0, 20)
    mean = sum(Y1)/float(len(Y1))
    median = Y1[len(Y1)/2 + 1]
    pylab.title('Mean = ' + str(mean) + ', Median = ' + str(median))
    pylab.show()
コード例 #21
0
def findOrder(xVals, yVals, accuracy = 1.0e-1):
    order = 0
    x = pylab.polyfit(xVals, yVals, order, full=True)
    residual = x[1][0]
    while residual > accuracy:
        
        order +=1
        try:            
            x = pylab.polyfit(xVals, yVals, order, full=True)
            residual = x[1][0]
            print 'residual', residual
        except:
            print 'fell to here'
    return x[0]
コード例 #22
0
ファイル: exam_problem3.py プロジェクト: ouxiaogu/Python
def plotSim():
    numSim = 400
    rabbit_populations, fox_populations = runSimulation(numSim)
    pylab.figure(1)
    pylab.plot(range(numSim), rabbit_populations, label = "rabit")
    pylab.plot(range(numSim), fox_populations, label = "fox")

#    pylab.figure(2)
    coeff = pylab.polyfit(range(numSim), rabbit_populations, 2)
    pylab.plot(pylab.polyval(coeff, range(numSim)), label = "rabit fitting")
    coeff = pylab.polyfit(range(numSim), fox_populations, 2)
    pylab.plot(pylab.polyval(coeff, range(numSim)), label = "fox fitting") 
    
    pylab.legend()
    pylab.show()
コード例 #23
0
ファイル: plot.py プロジェクト: LionelR/pyair_utils
def regression(x, y, df, ax=None):
    """
    Trace x contre y et calcul la fonction de régression
    Paramètres:
        x: Nom de la colonne des x
        y: Nom de la colonne des y
        df: Dataframe contenant les valeurs
        ax: Axes où tracer le qqplot, sinon en créait un

    Retourne: ax, eq, corr
        ax: Axes (graphique)
        eq: equation de regression linéaire de premier degré
        corr: coefficient de corrélation

    """

    if ax is None:
        ax = _new_default_axe('defaut')

    _x = df[x]
    _y = df[y]
    fit = plb.polyfit(_x, _y, 1)
    fit_fn = plb.poly1d(fit)  # fit_fn is now a function which takes in x and returns an estimate for y
    plt.plot(_x, _y, 'yo', _x, fit_fn(_x), '--k', axes=ax)
    try:
        ax = plt.gca()
        ax.set_xlabel(x)
        ax.set_ylabel(y)
        plt.draw()
    except:
        pass

    eq = plb.poly1d(fit_fn)
    corr = stats.correlation(_y, _x)
    return ax, eq, corr
コード例 #24
0
ファイル: plot.py プロジェクト: LionelR/pyair_utils
def qqplot(x, y, df, interval=0.5, ax=None):
    """
    Trace un QQPlot de x contre y, avec un interval de confiance autour de la
    droite de régression.
    Paramètres:
        x: Nom de la colonne des x
        y: Nom de la colonne des y
        df: Dataframe contenant les valeurs
        nb: Nombre de quantiles à calculer dans la plage [0, 1.]
        interval: (défaut=0.5) [0-1.], interval de confiance autour de la droite
            de régression
        ax: Axes où tracer le qqplot, sinon en créait un

    """

    if ax is None:
        ax = _new_default_axe('defaut')

    _x = df[x]
    _y = df[y]
    fit = plb.polyfit(_x, _y, 1)
    fit_fn = plb.poly1d(fit)  # fit_fn is now a function which takes in x and returns an estimate for y

    # Trace les points et la droite de régression
    fit_y = fit_fn(_x)
    plt.plot(_x, _y, 'yo', _x, fit_y, '--k', axes=ax)

    ax.set_xlabel(x)
    ax.set_ylabel(y)

    # Puis trace les lignes d'interval autour de la droite de régression
    plt.plot(_x, fit_y + fit_y * interval, '-r')
    plt.plot(_x, fit_y - fit_y * interval, '-r')

    return ax
コード例 #25
0
ファイル: misc.py プロジェクト: MMaus/mutils
def get_minmax(data, deg=2):
    """
    returns the interpolated extremum and position (in fractions of frames)

    :args:
        data (iterable): data to be fitted with a <deg> degree polynomial
        deg (int): degree of polynomial to fit

    :returns:
        val, pos: a tuple of floats indicating the position
    """

    x = arange(len(data))
    p = polyfit(x, data, deg)
    d = (arange(len(p))[::-1] * p)[:-1]
    r = roots(d)
    cnt = 0
    idx = None
    for nr, rx in enumerate(r):
        if isreal(r):
            idx = nr
            cnt +=1
            if cnt > 1:
                raise ValueError("Too many real roots found." + 
                        "Reduce order of polynomial!")
    x0 = r[nr].real
    return x0, polyval(p, x0)
コード例 #26
0
ファイル: L7_p4.py プロジェクト: jacindaz/6.00.2x
def fitData1(fileName):
    xVals, yVals = getData(fileName)
    xVals = pylab.array(xVals)
    yVals = pylab.array(yVals)
    xVals = xVals*9.81  # convert mass to force (F = mg)
    pylab.plot(xVals, yVals, 'bo', label = 'Measured displacements')
    pylab.title('Measured Displacement of Spring')
    pylab.xlabel('|Force| (Newtons)')
    pylab.ylabel('Distance (meters)')
    a,b = pylab.polyfit(xVals, yVals, 1)
    estYVals = a*xVals + b
    pylab.plot(xVals, estYVals, label = 'Linear fit')
    a,b,c,d = pylab.polyfit(xVals, yVals, 3)
    estYVals = a*(xVals**3) + b*xVals**2 + c*xVals + d
    pylab.plot(xVals, estYVals, label = 'Cubic fit')
    pylab.legend(loc = 'best')
コード例 #27
0
def lsq_fit(e, v):
    import pylab
    import numpy as np
    import scipy.optimize as optimize

    e = np.array(e)
    v = np.array(v)

    # Fit with parabola for first guess
    a, b, c, d = pylab.polyfit(v , e, 3)

    #a = 1
    #b = 2
    #c = 3
    #d = 4

    def fitfunc(strain, parameters):
        a = parameters[0]
        b = parameters[1]
        c = parameters[2]
        d = parameters[3]

        EM = d + c * strain + b * strain ** 2 + a * strain ** 3 

        return EM

    # Minimization function
    def residuals(pars, y, x): # array of residuals
        # we will minimize this function
        err = y - fitfunc(x, pars)
        return err

    p0 = [a, b, c, d]

    return optimize.leastsq(residuals, p0, args=(e, v))
コード例 #28
0
def linFitData(resistance_series, max_power = 1000, min_power = 0, max_speed =65):
    """
    Fits linear regression lines to resistance series, and returns
    points extrapolated across the range of powers between
    min_power and MaxPower. 
    
    Speed > max_speed are filtered to get rid of non-linear behaviour
    """
    speed = []
    power = []
    resistance = []
    for data_list in resistance_series:
        speed_data = []
        power_data = []
        #Extract the current resistance level for the series
        res_level = data_list[0][2]
        #Iterate over the speed, power readings in the series
        for item in data_list:
            #Filter out high speeds with non-linear behaviour
            if (item[0] < max_speed):
                speed_data.append(item[0])
                power_data.append(item[1])
        #Fit linear regression lines to each speed-power series
        m,c = polyfit(power_data, speed_data, 1)
        #Evaluate data points cross linear regression line
        powerFit = np.arange(min_power, max_power, 10)
        speedFit = np.polyval([m,c], powerFit)
        #Synthesis 'linear fitted' list of speed, power measurements
        for i in range(len(powerFit)):
            speed.append(speedFit[i])
            power.append(powerFit[i])
            resistance.append(res_level)
    return np.array(speed), np.array(power), np.array(resistance)
コード例 #29
0
ファイル: L7_p4.py プロジェクト: jacindaz/6.00.2x
def fitData3(fileName):

    # xVals is type 'numpy.ndarray'
    # xVals[0] will return the 1st item in array
    xVals, yVals = getData(fileName)
    xVals = pylab.array(xVals[:-6])
    yVals = pylab.array(yVals[:-6])
    xVals = xVals*9.81  # convert mass to force (F = mg)

    observed_data_variance = calcVariance(xVals)

    # need to grab the Y values from somewhere ??? maybe estYVals
    # to compare with observed data Y values
    # to calculate the variance of errors
    # errors_variance = calcVariance(xVals)

    coefficient_determination = 0


    pylab.plot(xVals, yVals, 'bo', label = 'Measured points')
    pylab.title('Measured Displacement of Spring')
    pylab.xlabel('Force (Newtons)')
    pylab.ylabel('Distance (meters)')
    a,b = pylab.polyfit(xVals, yVals, 1)  # fix y = ax + b

    # use line equation to graph predicted values
    estYVals = a*xVals + b
    k = 1/a
    pylab.plot(xVals, estYVals, label = 'Linear fit, k = '
               + str(round(k, 5)))
    pylab.legend(loc = 'best')
コード例 #30
0
ファイル: detector.py プロジェクト: MRO-MROI/mroi_scripts
def main():
    #get list of files
    files = filelist("files")
    #set up plotting
    
    # run through each channel
    for ch in range(32):
        means = np.zeros(len(files)/2)
        varis = np.zeros(len(files)/2)
        #process pairs of images
        for i in range(0, len(files), 2):
            im1 = readfile(files[i])[:,ch*64:ch*64+64]
            im2 = readfile(files[i+1])[:,ch*64:ch*64+64]
            print "processing: ", files[i], files[i+1]
            #get sum of means
            som = summean(im1, im2)
            #get variance of difference)
            vod = diffvar(im1, im2)
            means[i/2] = som
            varis[i/2] = vod

        print 'means:', means
        print 'variances: ', varis
        fit = pl.polyfit(varis, means, 1)
        fit_fn = pl.poly1d(fit)
        print "e-/ADU = ", fit[0]
        plt.plot(varis, means, 'o', varis, fit_fn(varis), '--')
        plt.legend(['Channel '+str(ch), str(round(fit[0],3))+' e-/ADU'], loc=9)
        plt.xlabel('Variance')
        plt.ylabel('Mean')
        plt.title('Conversion Gain')
        plt.savefig('ch'+str(ch).zfill(2)+'.png', bbox_inches='tight')
        plt.clf()
    return 0
コード例 #31
0
ファイル: Curve Fitting.py プロジェクト: Funnylaksa/ML
def tryFits(fileN):
    distance,height = getData(fileN)
    distance = pylab.array(distance)
    totalHeight = pylab.zeros(len(height[0]))
    for i in height:
        totalHeight = totalHeight+ pylab.array(i)
    meanHeight = totalHeight/len(height)
    
    pylab.plot(distance,meanHeight,"bo",label ="raw data")
    pylab.xlabel("distance travelled(m)")
    pylab.ylabel("height(m)")
       
    a,b = pylab.polyfit(distance,meanHeight,1)
    estYVals = a*distance + b
    pylab.plot(distance,estYVals,label = "Linear Fit" + ",R2 =" + str(R2(estYVals,meanHeight)))
    a,b,c = pylab.polyfit(distance,meanHeight,2)
    estYVals = a*distance**2 + b*distance + c
    pylab.plot(distance,estYVals,label = "Quadratic Fit" + ",R2 = " +str(R2(estYVals,meanHeight)))
    
    a,b,c,d = pylab.polyfit(distance,meanHeight,3)
    estYVals = a*distance**3 + b*distance**2 + c*distance + d
    pylab.plot(distance,estYVals,label = "Polynomial Fit" + ",R2 = " +str(R2(estYVals,meanHeight)))
    
    pylab.legend()
コード例 #32
0
def fitData(fileName):
    xVals, yVals = getData(fileName)
    xVals = pylab.array(xVals)
    yVals = pylab.array(yVals)
    xVals = xVals * 9.81  #get force
    pylab.plot(xVals, yVals, 'bo', label='Measured points')
    labelPlot()
    a, b = pylab.polyfit(xVals, yVals, 1)
    estYVals = a * pylab.array(xVals) + b
    print('a =', a, 'b =', b)
    pylab.plot(xVals,
               estYVals,
               'r',
               label='Linear fit, k = ' + str(round(1 / a, 5)))
    pylab.legend(loc='best')
コード例 #33
0
def fitData3(fileName):
    xVals, yVals = getData(fileName)
    xVals = pylab.array(xVals[:-6])
    yVals = pylab.array(yVals[:-6])
    xVals = xVals * 9.81  # convert mass to force (F = mg)
    pylab.plot(xVals, yVals, 'bo', label='Measured points')
    pylab.title('Measured Displacement of Spring')
    pylab.xlabel('Force (Newtons)')
    pylab.ylabel('Distance (meters)')
    a, b = pylab.polyfit(xVals, yVals, 1)  # fix y = ax + b
    # use line equation to graph predicted values
    estYVals = a * xVals + b
    k = 1 / a
    pylab.plot(xVals, estYVals, label='Linear fit, k = ' + str(round(k, 5)))
    pylab.legend(loc='best')
コード例 #34
0
def doit():
    a = 1.0
    b = 2.0
    c = 4.0
    yVals = []
    xVals = range(-20, 20)
    for x in xVals:
        yVals.append(a*x**2 + b*x + c)
    yVals = 2*pylab.array(yVals)
    xVals = pylab.array(xVals)
    try:
        a, b, c, d = pylab.polyfit(xVals, yVals, 3)
        print a, b, c, d
    except:
        print 'fell to here'
コード例 #35
0
ファイル: LectureCode.py プロジェクト: meking03/MIT6002
def fitData1(fileName):
    xVals, yVals = getData(fileName)
    xVals = pylab.array(xVals)
    yVals = pylab.array(yVals)
    xVals = xVals*9.81 #get force
    pylab.plot(xVals, yVals, 'bo',
               label = 'Measured points')
    labelPlot()                 
    model = pylab.polyfit(xVals, yVals, 1)
    estYVals = pylab.polyval(model, xVals)
    pylab.plot(xVals, estYVals, 'r',
               label = 'Linear fit, k = '
               + str(round(1/model[0], 5)))
    pylab.legend(loc = 'best')
    pylab.show()
コード例 #36
0
ファイル: ICPP_ch18.py プロジェクト: rameshjay/ICPP_notes
def fit_data_cubic_fe(input_file):
    masses, distances = get_data(input_file)
    distances = pylab.array(distances)
    forces = pylab.array(masses) * 9.81
    pylab.plot(forces, distances, 'ko', label='Measured displacements')
    pylab.title('Measured Displacement of Spring')
    pylab.xlabel('|Force| (Newtons)')
    pylab.ylabel('Distance (meters)')
    # find linear fit
    a, b = pylab.polyfit(forces, distances, 1)
    predicted_distances = a * pylab.array(forces) + b
    k = 1.0 / a  # slope a is delta(distance) / delta(force)
    # k is the reciprocal of slope
    pylab.plot(forces,
               predicted_distances,
               label='Displacements predicted by\n linear fit, k =' +
               str(round(k, 5)))
    pylab.legend(loc='best')
    fit = pylab.polyfit(forces, distances, 3)
    predicted_distances = pylab.polyval(fit, forces)
    forces_fe = np.append(forces, np.array([15]))
    predicted_distances_fe = pylab.polyval(fit, forces_fe)
    pylab.plot(forces_fe, predicted_distances_fe, 'k:', label='cubic fit')
    pylab.xlim([0, 16])
コード例 #37
0
ファイル: lec17.py プロジェクト: flip-in/CS6.00
def fitData(fileName):
    xVals, yVals = getData(fileName)
    xVals = pylab.array(xVals[:-6])  #discard the last 6 points
    yVals = pylab.array(yVals[:-6])  #where spring seems to exceed limit
    xVals = xVals * 9.81
    pylab.plot(xVals, yVals, 'bo', label='Measured displacements')
    pylab.title('Measured Displacement of Spring')
    pylab.xlabel('|Force| (Newtons)')
    pylab.ylabel('Distance (meters)')
    a, b = pylab.polyfit(xVals, yVals,
                         1)  #polyfit(observedx, observedy, degree)
    estYVals = a * pylab.array(
        xVals) + b  #unnecessary: xvals was already an array
    k = 1 / a
    pylab.plot(xVals, estYVals, label='Linear fit, k = ' + str(round(k, 5)))
    pylab.legend(loc='best')
コード例 #38
0
def generate_models(x, y, degs):
    """
    Generate regression models by fitting a polynomial for each degree in degs
    to points (x, y).
    Args:
        x: an 1-d pylab array with length N, representing the x-coordinates of
            the N sample points
        y: an 1-d pylab array with length N, representing the y-coordinates of
            the N sample points
        degs: a list of degrees of the fitting polynomial
    Returns:
        a list of pylab arrays, where each array is a 1-d array of coefficients
        that minimizes the squared error of the fitting polynomial
    """
    # generates models
    return [pylab.polyfit(x, y, deg) for deg in degs]
コード例 #39
0
def generate_models(x, y, degs):
    """
    Generate regression models by fitting a polynomial for each degree in degs
    to points (x, y).
    Args:
        x: a list with length N, representing the x-coords of N sample points
        y: a list with length N, representing the y-coords of N sample points
        degs: a list of degrees of the fitting polynomial
    Returns:
        a list of numpy arrays, where each array is a 1-d array of coefficients
        that minimizes the squared error of the fitting polynomial
    """
    # TODO
    #    pass
    #    return list(map(lambda deg : pylab.polyfit(x ,y ,deg), degs))
    return [pylab.polyfit(x, y, deg) for deg in degs]
コード例 #40
0
def polyFit(x, y, degree):
    """
    Find the best fit polynomial curve z of the specified degree for the data
    contained in x and y and returns the expected y values for the best fit
    polynomial curve for the original set of x values.

    Parameters:
    x - a Pylab array of x values
    y - a Pylab array of y values
    degree - the degree of the desired best fit polynomial

    Returns:
    a Pylab array of coefficients for the polynomial fit function of the
    specified degree, corresponding to the input domain x.
    """
    return pylab.polyfit(x, y, degree)
def generate_models(x, y, degs):
    """
    Generate regression models by fitting a polynomial for each degree in degs
    to points (x, y).
    
    x: a list with length N, representing the x-coords of N sample points
    y: a list with length N, representing the y-coords of N sample points
    degs: a list of degrees of the fitting polynomial
    Returns: a list of numpy arrays, where each array is a 1-d array of coefficients
    that minimizes the squared error of the fitting polynomial
    """
    array_list = []
    for degree in degs:
        model = pylab.polyfit(x, y, degree)
        array_list.append(model)
    return array_list
コード例 #42
0
def fitData(inputFile):
    masses, distances = getData(inputFile)
    masses = pylab.array(masses)
    distances = pylab.array(distances)
    forces = masses * 9.81
    pylab.plot(forces, distances, 'bo', label='Measured displacements')
    pylab.title('Measured Displacement of Spring')
    pylab.xlabel('|Force| (Newtons)')
    pylab.ylabel('Distance (meters)')
    #find cubic fit
    a, b, c, d = pylab.polyfit(forces, distances, 3)
    inc = forces[1] - forces[0]
    for i in range(9):
        forces = pylab.append(forces, forces[len(forces) - 1] + inc)
    predictedDistances = a * (forces**3) + b * forces**2 + c * forces + d
    pylab.plot(forces, predictedDistances, 'b:', label='cubic fit')
    pylab.legend(loc='best')
コード例 #43
0
def evaluate_models_on_training(x, y, models):
    """
    For each regression model, compute the R-squared value for this model with the
    standard error over slope of a linear regression line (only if the model is
    linear), and plot the data along with the best fit curve.

    For the plots, you should plot data points (x,y) as blue dots and your best
    fit curve (aka model) as a red solid line. You should also label the axes
    of this figure appropriately and have a title reporting the following
    information:
        degree of your regression model,
        R-square of your model evaluated on the given data points,
        and SE/slope (if degree of this model is 1 -- see se_over_slope). 

    Args:
        x: an 1-d pylab array with length N, representing the x-coordinates of
            the N sample points
        y: an 1-d pylab array with length N, representing the y-coordinates of
            the N sample points
        models: a list containing the regression models you want to apply to
            your data. Each model is a pylab array storing the coefficients of
            a polynomial.

    Returns:
        None
    """
    # TODO

    for model in models:
        fit = pylab.polyfit(x, y, model)
        predictor = pylab.poly1d(fit)
        predictions = predictor(x)
        pylab.scatter(x, y, color='b')
        pylab.plot(x, predictions, 'r')

        if model == 1:
            pylab.title("Degree: " + str(model) + ", $R^{2}$ : " +
                        str(r_squared(y, predictions)) + "\n" +
                        str(se_over_slope(x, y, predictions, fit)))
            pylab.show()
        else:
            pylab.title("Degree: " + str(model) + ", $R^{2}$ : " +
                        str(r_squared(y, predictions)))

        pylab.show()
    pass
コード例 #44
0
def fitData(fileName):
    xVals, yVals = getSpringData(fileName)
    xVals = pylab.array(xVals)
    yVals = pylab.array(yVals)
    pylab.plot(xVals, yVals, 'bo', label='Measured displacements')

    model = pylab.polyfit(xVals, yVals, 1)  # fit data to line (degree = 1)
    estYVals = pylab.polyval(model,
                             xVals)  # generate array of estimated y values
    estimatedK = round(1 / model[0], 3)

    pylab.plot(xVals, estYVals, 'r', label = "Linear Fit, k = " + str(estimatedK)\
               + ", r^2 = " + str(round(rSquared(yVals, estYVals), 3)))
    pylab.title("Measured Displacement of Spring")
    pylab.xlabel('Force (Newtons)')
    pylab.ylabel('Distance (meters)')
    pylab.legend()
コード例 #45
0
def p5test():
    a = 1.0
    b = 2.0
    c = 4.0
    yVals = []
    xVals = range(-20, 20)
    for x in xVals:
        yVals.append(a*x**2 + b*x + c)
    yVals = 2*pylab.array(yVals)
    print yVals
    xVals = pylab.array(xVals)
    print xVals
    try:
        z = pylab.polyfit(xVals, yVals, 3)
        print z
    except:
        print 'fell to here'
コード例 #46
0
def fitData3(fileName):
    xVals, yVals = getData(fileName)
    xVals = pylab.array(xVals[:-6])
    yVals = pylab.array(yVals[:-6])
    xVals = xVals * 9.81  #get force
    pylab.plot(xVals, yVals, 'bo', label='Measured points')
    labelPlot()
    model = pylab.polyfit(xVals, yVals, 3)
    # add_point = pylab.array([15])
    # xVals = numpy.hstack((xVals, add_point))
    estYVals = pylab.polyval(model, xVals)
    pylab.plot(
        xVals,
        estYVals,
        'k--',
    )
    pylab.legend(loc='best')
コード例 #47
0
def getFluidLevel(data,slope_threshold=1.5,window_size=15):
    """
    Automatically determine the fluid level from the slope change
    """
    found = False
    n = data.shape[0]
    for i in range(window_size,n-window_size):
        window_ind  = range(i-window_size,i+window_size)
        window_data = data[i-window_size:i+window_size]
        fit = pylab.polyfit(window_ind, window_data,1)
        if fit[0] > slope_threshold:
            found = True
            break
    if found:
        return i, data[i]
    else:
        return None
コード例 #48
0
def fitData(inputFile):
    masses, distances = getData(inputFile)
    distances = pylab.array(distances)
    forces = pylab.array(masses) * 9.81
    pylab.plot(forces, distances, 'ko', label='Measured displacements')
    pylab.title('Measured Displacement of Spring')
    pylab.xlabel('|Force| (Newtons)')
    pylab.ylabel('Distance (meters)')
    #find linear fit
    a, b = pylab.polyfit(forces, distances, 1)
    predictedDistances = a * pylab.array(forces) + b
    k = 1.0 / a  #see explanation in text
    pylab.plot(forces,
               predictedDistances,
               label='Displacements predicted by\nlinear fit, k = ' +
               str(round(k, 5)))
    pylab.legend(loc='best')
コード例 #49
0
    def ajuste_lineal(self,
                      magnitud1,
                      magnitud2,
                      ObjectCatalog,
                      quitarOutliers=False):
        """
        Method that performs a linear adjustment of the parameters magnitud1 and magnitud2

        Parameters
        ----------
        magnitud1 : `str`
            X magnitude for the linear adjustment.
        magnitud2 : `str`
            Y magnitude for the linear adjustment.
        ObjectCatalog : `str`
            Catalog from which magnitud1 comes from.
        ObjectCatalog1 : `str`
            DESCRIPTION.
        quitarOutliers : `bool`, optional
            Catalog from which magnitud1 comes from.. The default is False.

        Returns
        -------
        None.

        """
        import pylab as plt
        plt.figure(2)
        self.p = plt.polyfit(self.datos[magnitud1], self.datos[magnitud2], 1)
        Y = self.p[0] * self.datos[magnitud1] + self.p[1]
        plt.figure(1)
        plt.plot(self.datos[magnitud1],
                 Y,
                 label="Ajuste y = %.3f + %.3f x" % (self.p[1], self.p[0]),
                 zorder=10)
        plt.plot(self.datos[magnitud1],
                 self.datos[magnitud2],
                 '.',
                 label='Datos',
                 alpha=0.5)
        plt.legend()
        plt.title('Ajuste sin errores y con outliers')
        plt.xlabel(magnitud1)
        plt.ylabel(magnitud2)
        plt.savefig('plot1.png')
def build_models(train_data_file_name, polynomial_degrees):
    """

    :param train_data_file_name:  训练数据文件名
    :param polynomial_degrees: 预拟合模型的多项式系数,e.g(1,2,4,8,16)
    :return: 根据不同维度训练好的模型
    """
    x_vals, y_vals = getData(train_data_file_name)
    # 处理成array,将来作为实际参数传到polyfit
    x_vals = pylab.array(x_vals)
    y_vals = pylab.array(y_vals)

    models = []

    for degree in polynomial_degrees:
        model = pylab.polyfit(x_vals, y_vals, degree)
        models.append(model)
    return models
コード例 #51
0
ファイル: testing.py プロジェクト: th4tkh13m/python3_learning
def Regression(xVals, yVals, degrees, verbose=True):
    yVals_predicted = {}
    for degree in degrees:
        model = pylab.polyfit(xVals, yVals, degree)
        yVals_predicted[degree] = pylab.polyval(model, xVals)
    if verbose:
        pylab.figure("Regression")
        pylab.title("Regression of various degree polynomials")
        pylab.plot(xVals, yVals, 'ko')
        pylab.xlabel("x Values")
        pylab.ylabel("y Values")
        for degree in yVals_predicted:
            pylab.plot(xVals, yVals_predicted[degree],\
                label = f"Regression degree : {degree}, R^2 = " +\
                    str(rSquare2(pylab.array(yVals), yVals_predicted[degree])))
        pylab.legend(loc="best")
        pylab.show()
    return yVals_predicted
コード例 #52
0
def fitData(filename):
    xVals, yVals = getData(filename)
    xVals = pylab.array(xVals)
    yVals = pylab.array(yVals)
    xVals = xVals * 9.81  #converting the mass to force (F = mg)
    pylab.plot(xVals, yVals, 'bo', label='Measured Displacement')
    pylab.title('Measured Displacement of Springs')
    pylab.xlabel('Force (Newtons)')
    pylab.ylabel('Distance (Meters)')
    # polyfit finds the values of the parameters for the predictin that minimize the
    # sum of the squares of the errors or SSE, also called least squares
    # pylab.polyfit(xVals, yVals, degree)
    a, b = pylab.polyfit(xVals, yVals, 1)  # fit y = ax + b
    # use line equation to graph predicted values
    estYVals = a * xVals + b
    k = 1 / a
    pylab.plot(xVals, estYVals, label='Linear fit, k = ' + str(round(k, 5)))
    pylab.legend(loc='best')
コード例 #53
0
ファイル: ICPP_ch18.py プロジェクト: rameshjay/ICPP_notes
def fit_data2(input_file):
    masses, distances = get_data(input_file)
    distances = pylab.array(distances[:-6])
    forces = pylab.array(masses[:-6]) * 9.81
    pylab.plot(forces, distances, 'ko', label='Measured displacements')
    pylab.title('Measured Displacement of Spring')
    pylab.xlabel('|Force| (Newtons)')
    pylab.ylabel('Distance (meters)')
    # find linear fit
    a, b = pylab.polyfit(forces, distances, 1)
    predicted_distances = a * pylab.array(forces) + b
    k = 1.0 / a  # slope a is delta(distance) / delta(force)
    # k is the reciprocal of slope
    pylab.plot(forces,
               predicted_distances,
               label='Displacements predicted by\n linear fit, k =' +
               str(round(k, 5)))
    pylab.legend(loc='best')
コード例 #54
0
def fitData(inputFile):
    masses, distances = getData(inputFile)
    distances = pylab.array(distances)
    masses = pylab.array(masses)
    forces = pylab.array(masses) * 9.81
    pylab.plot(forces, distances, 'ko', label="Measurement Displacements")
    pylab.title("Measured Displacement of Spring")
    pylab.xlabel("|Force| (Newtons)")
    pylab.ylabel("Distance (Meters)")
    # find linear fit
    a, b = pylab.polyfit(forces, distances, 1)
    predictedDistances = a * pylab.array(forces) + b
    k = 1.0 / a  # a is dDist/dForce, k is dForce/dDist or a inverse
    pylab.plot(forces,
               predictedDistances,
               label="Displacements Predicted by \nLinear Fit, k = " +
               str(round(k, 5)))
    pylab.legend(loc='best')
コード例 #55
0
ファイル: ps4.py プロジェクト: akuroodi/MIT-Python-Courses
def generate_models(x, y, degs):
    """
    Generate regression models by fitting a polynomial for each degree in degs
    to points (x, y).
    Args:
        x: a list with length N, representing the x-coords of N sample points
        y: a list with length N, representing the y-coords of N sample points
        degs: a list of degrees of the fitting polynomial
    Returns:
        a list of numpy arrays, where each array is a 1-d array of coefficients
        that minimizes the squared error of the fitting polynomial
    """
    coeffs = []

    for i in range(len(degs)):
        coeffs.append(pylab.polyfit(x, y, degs[i]))

    return coeffs
def leave_one_out_model(file_names, degrees, to_print):
    """
    :param to_print: 是否打印每个维度的平均R2
    :param file_names: 所有实验数据文件名.list 或 tuple皆可,比如 ["Dataset 1.txt","Dataset 2.txt"]
    :param degrees:测试维度
    :return:
    """
    x_vals, y_vals = get_total_date(file_names)

    SE = [0] * len(degrees)
    # 共计n次
    for i in range(len(x_vals)):
        """
            留一法,取样本中的一份做为测试数据,另外数据作为训练数据,设评估结果为p.然后取p的平均。
        """
        SE_for_this_trial = []

        for degree in degrees:
            x_vals_copy = x_vals[:]
            y_vals_copy = y_vals[:]
            test_x_val = pylab.array(x_vals_copy.pop(i))
            test_y_val = y_vals_copy.pop(i)
            train_x_vals = pylab.array(x_vals_copy)
            train_y_vals = pylab.array(y_vals_copy)
            model = pylab.polyfit(train_x_vals, train_y_vals, degree)
            # 如果传入的ndarry的大小是1的话,est_y_val就是一个数字,而不是ndarry
            est_y_val = pylab.polyval(model, test_x_val)
            SE_for_this_trial.append((est_y_val - test_y_val) ** 2)
        for j in range(len(SE)):
            SE[j] += SE_for_this_trial[j]

    if to_print:
        for index in range(len(degrees)):
            print("Degree of " + str(degrees[index]) + ",SUM Of SE  = " + str(SE[index]))
    degree_str_list = []
    for degree in degrees:
        # x轴
        degree_str_list.append(str(degree))
    pylab.title("SUM OF SE for Degree" + str(degrees))
    pylab.xlabel("Degree")
    pylab.ylabel("SUM OF SE")
    pylab.plot(degree_str_list, SE)
    pylab.legend(loc="best")
    pylab.show()
コード例 #57
0
def processTrajectories(fName):
    distances, heights = getTrajectoryData(fName)
    distances = pylab.array(distances)*36
    totHeights = pylab.array([0]*len(distances))
    for h in heights:
        totHeights = totHeights + pylab.array(h)
    pylab.title('Trajectory of Projectile (Mean of 4 Trials)')
    pylab.xlabel('Inches from Launch Point')
    pylab.ylabel('Inches Above Launch Point')
    meanHeights = totHeights/len(heights)
    pylab.plot(distances, meanHeights, 'bo')
    a,b,c = pylab.polyfit(distances, meanHeights, 2)
    altitudes = a*(distances**2) +  b*distances + c
    speed = getXSpeed(a, b, c, distances[-1], distances[0])
    pylab.plot(distances, altitudes, 'g',
               label = 'Quad. Fit' + ', R2 = '
               + str(round(rSquare(meanHeights, altitudes), 2))
               + ', Speed = ' + str(round(speed, 2)) + 'feet/sec')
    pylab.legend()
コード例 #58
0
def err_N():
    err = []
    Ni = []
    for i in range(17):
        N = 2**i
        Ni.append(N)

        err_v = abs(mc_integrate(f2, [0, 2], [0, 2], N) - np.pi)
        err.append(err_v)

    p = pylab.polyfit(np.log(Ni), np.log(err), 1)

    line = np.log(Ni) * p[0] + (p[1])
    print(p)
    pylab.plot((Ni), np.exp(line), 'b')
    pylab.loglog()
    pylab.plot((Ni), (err), 'ro')
    pylab.loglog()
    pylab.show
コード例 #59
0
def fitData(fileName):
    xVals, yVals = getData(fileName)
    xVals = pylab.array(xVals)
    yVals = pylab.array(yVals)
    xVals = xVals * 9.81  # convert mass to force (F = mg)
    pylab.plot(xVals, yVals, 'bo', label='Measured points')
    pylab.title('Measured Displacement of Spring')
    pylab.xlabel('Force (Newtons)')
    pylab.ylabel('Distance (meters)')
    # polyfit now will try to find the a, b values that minimize the
    # sum((yVals -(a*xVals +b))**2) =
    a, b = pylab.polyfit(xVals, yVals, 1)  # fit y = ax + b
    # Now I will calculate the predicted estimate y-values for the given
    # observed x-values, assuming that the predicted estimated y-values should
    #  follow a linear ax+b equation
    # use line equation to graph predicted values
    estYVals = a * xVals + b
    k = 1 / a  # calculate and display the spring constant k=1/a
    pylab.plot(xVals, estYVals, label='Linear fit, k = ' + str(round(k, 5)))
    pylab.legend(loc='best')
コード例 #60
0
def p5():
    a = 1.0
    b = 2.0
    c = 4.0
    yVals = []
    xVals = range(-20, 20)
    for x in xVals:
        yVals.append(a*x**2 + b*x + c)
    yVals = 2*pylab.array(yVals)
    xVals = pylab.array(xVals)
    pylab.plot(xVals, yVals,'bo')
    try:        
        a, b, c, d = pylab.polyfit(xVals, yVals, 3)
        print a, b, c, d
        estYVals = a*(xVals**3) + b*xVals**2 + c*xVals + d
        pylab.plot(xVals, estYVals, label = 'Cubic fit')
        pylab.legend(loc = 'best')
        pylab.show()
    except:
        print 'fell to here'