Esempio n. 1
0
def plot_commit_differences(project, log=False):
    # retrieve all commit sizes for xz
    conn = sql.connect('../database.db')
    c = conn.cursor()
    command = Template("SELECT * FROM Revision WHERE project = '$project'")
    command = command.safe_substitute(project=project)
    c.execute(command)

    xs = []
    ys = []
    for row in c:
        xs.append(row[2])
        ys.append(row[4] + row[5])

    conn.commit()

    zs = []  # time until next commit
    for i in xrange(1, len(xs)):
        zs.append(xs[i - 1] - xs[i])

    #zs = sorted(zs, key=lambda x: x[1], reverse = True)
    plt.hist(zs, alpha=0.75)
    plt.xlabel('time to next commit [ms]')
    plt.ylabel('frequency')
    plt.title("Histogram of time between two commits for '" + project + "'")

    if log:
        plt.yscale('log', nonposy='clip')
    #plt.axis([40, 160, 0, 0.03])
    plt.grid(True)
    plt.show()
Esempio n. 2
0
def musicType_plot(rap, randb, classical, indie, pop, df):
    plt.figure()

    # declaring testing data
    xs = [1, 2, 3, 4, 5]
    ys = [randb, rap, classical, pop, indie]

    # setting range
    xrng = np.arange(len(xs))
    yrng = np.arange(0, max(ys)+60, 50)

    #labeling data
    plt.xlabel('Music Type')
    plt.ylabel('Music volume')

    # spacing and declare bar chart
    plt.bar(xrng, ys, 0.45, align="center") 


    # labeling
    plt.xticks(xrng, ["randb", "rap", "classical", "pop", "indie"])
    plt.yticks(yrng)

    plt.grid(True)
    plt.show()
Esempio n. 3
0
        def GraficarFuncion(self, entrada_tiempo):

            # generacion de la grafica del tiempo ingresado
            time = np.arange(0, entrada_tiempo, 0.01)
            x = cord_x(self, time)
            y = cord_y(self, time)

            # grafica completa del lanzamiento
            time_complete = np.arange(0, time_impact(self) + 4, 0.01)
            x2 = cord_x(self, time_complete)
            y2 = cord_y(self, time_complete)

            # generacion del punto de posicion a medir
            x3 = cord_x(self, entrada_tiempo)
            y3 = cord_y(self, entrada_tiempo)

            # estetica de la grafica
            mpl.title("Aceleracion")
            mpl.xlim(0, alcance_max(self) + self.x0)
            mpl.ylim(0, altura_max(self) + self.y0)
            mpl.xlabel("-Distancia-")
            mpl.ylabel("-Altura-")

            # generamiento de las curvas
            mpl.plot(self.x0, self.y0, "k-o")  # punto pos inicial
            mpl.plot(x, y, "y-")  # curva del usuario
            mpl.plot(x2, y2, "k--")  # lanzamiento completo
            mpl.plot(x3, y3, "r-o")  # punto del usuario
            mpl.grid()  # cuadriculado

            # generacion del vector con origen en el punto de posicion
            mpl.plot(x3, y3 - time_impact(self), "g-o")

            mpl.show()
            return 0
Esempio n. 4
0
def animate_plotting(subdir_path,):
    average_filename = 'averaged_out.txt'  
    if os.path.exists( os.path.join(subdir_path,average_filename) ):
            print(subdir_path+average_filename+' already exists please use hotPlot.py')        
            #import existing data for average at the end           
#            data_out = numpy.genfromtxt(os.path.join(subdir_path,average_filename))
#            averaged_data = numpy.array(data_out[:,1])
#            angles = data_out[:,0]
            #os.remove( os.path.join(subdir_path,average_filename))
    else:
        files = os.listdir(subdir_path)     
            #files = [d for d in os.listdir(subdir_path) if os.path.isdir(os.path.join(subdir_path, d))]
        onlyfiles_path = [os.path.join(subdir_path,f) for f in files if os.path.isfile(os.path.join(subdir_path,f))]
        onlyfiles_path = natsort.natsorted(onlyfiles_path)          
        averaged_data = []
        angles = []
        for f in onlyfiles_path:
            data = numpy.genfromtxt(f,delimiter = ',')       
            #data = pandas.read_csv(f)
            averaged_data.append(numpy.mean(data))
            angle = os.path.basename(f).split('_')[0]
            angles.append(float(angle))
        fig = plt.plot(angles, averaged_data,'o')
        plt.yscale('log')
        plt.xscale('log')
        plt.legend(loc='upper right')
        plt.title(base_path)
        plt.grid(True)
        plt.xlabel(r'$\theta$ $[deg.]}$')
        #plt.xlabel(r'$\mathrm{xlabel\;with\;\LaTeX\;font}$')
        plt.ylabel(r'I($\theta$) $[a.u.]$')
Esempio n. 5
0
def plot_df(
    df1, df2, plot_title, x_axis, y_axis, plot, save
):  # function for plotting high-dimension and low-dimension eigenvalues
    y1 = df1[df1.columns[1]]
    x1 = df1['M']
    y2 = df2[df2.columns[1]]
    x2 = df2['M']

    plt.figure(figsize=(8, 8))
    plt.plot(x1, y1, color='red')
    plt.plot(x2, y2, color='blue')
    plt.grid(color='black', linestyle='-',
             linewidth=0.1)  # parameters for plot grid
    plt.xticks(np.arange(0,
                         max(x1) * 1.1,
                         int(max(x1) / 10)))  # adjusting the intervals to 250
    plt.yticks(np.arange(0, max(y1) * 1.1, int(max(y1) / 10)))
    plt.title(plot_title).set_position([0.5, 1.05])
    plt.xlabel(x_axis)
    plt.ylabel(y_axis)
    plt.legend(loc='best')  # creating legend and placing in at the top right
    if save == 'yes':
        plt.savefig(plot_title)
    if plot == 'yes':
        plt.show()
    plt.close()
def draw_learning_curves(X, y, estimator, num_trainings):
    train_sizes, train_scores, test_scores = learning_curve(
        estimator,
        X2,
        y2,
        cv=None,
        n_jobs=1,
        train_sizes=np.linspace(.1, 1.0, num_trainings))

    train_scores_mean = np.mean(train_scores, axis=1)
    train_scores_std = np.std(train_scores, axis=1)
    test_scores_mean = np.mean(test_scores, axis=1)
    test_scores_std = np.std(test_scores, axis=1)

    plt.grid()

    plt.title("Learning Curves")
    plt.xlabel("Training examples")
    plt.ylabel("Score")

    plt.plot(train_scores_mean, 'o-', color="g", label="Training score")
    plt.plot(test_scores_mean, 'o-', color="y", label="Cross-validation score")

    plt.legend(loc="best")

    plt.show()
Esempio n. 7
0
def plot_dataset(X, y, axes):
    plt.plot(X[:, 0][y == 0], X[:, 1][y == 0], "bs")
    plt.plot(X[:, 0][y == 1], X[:, 1][y == 1], "ms")
    plt.axis(axes)
    plt.grid(True, which='both')
    plt.xlabel(r"$x_1$", fontsize=20)
    plt.ylabel(r"$x_2$", fontsize=20, rotation=0)
Esempio n. 8
0
 def initial(ax):
     ax.axis("equal")  #设置图像显示的时候XY轴比例
     ax.set_xlabel('Horizontal Position')
     ax.set_ylabel('Vertical Position')
     ax.set_title('Vessel trajectory')
     plt.grid(True)  #添加网格
     return ax
Esempio n. 9
0
def generate_plot(platforms, output_file):
    """Generates a bar chart and writes the output on a image"""

    labels = []
    values = []
    for platform in platforms:
        name = platform["name"]
        adapted_price = platform["adjusted_price"]
        price = platform["original_price"]
        if price > 2000:
            continue
        if len(name) > 15:
            name = platform["abreviation"]
        labels.insert(
            0, u"{0}\n$ {1}\n$ {2}".format(name, price,
                                           round(adjusted_price, 2)))
        values.insert(0, adapted_price)
    width = 0.3
    ind = np.arange(len(values))
    fig = plt.figure(figsize=(len(labels) * 1.8, 10))

    ax = fig.add_subplot(1, 1, 1)
    ax.bar(ind, values, width, align='center')

    plt.ylabel('Adjusted price')
    plt.xlabel('Year / Console')
    ax.set_xticks(ind + 0.3)
    ax.set_xticklabels(labels)
    fig.autofmt_xdate()
    plt.grid(True)

    plt.savefig(output_file, dpi=72)
Esempio n. 10
0
    def __init__(self, x, y):
        self.x = x
        self.y = y
        n = len(x)  # cantidad de datos
        xSum = self.suma(x)
        ySum = self.suma(y)
        xySum = self.columnaXy(x, y, n)
        xCuadrado, sumXCuadrado = self.columnaCuadrado(x, n)

        xMedia = self.media(xSum, n)
        yMedia = self.media(ySum, n)

        num = xySum * n - (xSum + ySum)
        den = n * sumXCuadrado - (xSum**2)
        m = num / den
        b = yMedia - (m * xMedia)

        #graficar
        x1 = np.linspace(min(x) - 1, max(x) + 1)
        linea = m * x1 + b
        plt.plot(x1, linea)
        plt.scatter(x, y)
        plt.xlabel('x')
        plt.ylabel('y')
        plt.grid(True)
        plt.show()
Esempio n. 11
0
def plot_test_image(testX, image_index, predictions_array, true_binary_labels):
    """
        testX: this is the test dataset
        image_index: index of the image that we will plot from the test dataset
        predictions_array: it is the array that contains all the predictions of the test dataset as output of model.predict(testX)
        true_binary_labels: these are the true label expressed as INTEGER values. It does not work with hot-encoding and string labels. 
    """
    single_predictions_array, true_binary_label, test_image = predictions_array, true_binary_labels[
        image_index], testX[image_index]
    plt.grid(False)
    plt.xticks([])
    plt.yticks([])

    plt.imshow(test_image, cmap=plt.cm.binary)

    predicted_binary_label = np.argmax(predictions_array)
    #print ("predicted_binary_label:", predicted_binary_label)
    #print ("true_binary_label:",true_binary_label)

    if predicted_binary_label == true_binary_label:
        color = 'blue'
    else:
        color = 'red'

    plt.xlabel("predicted: {} {:2.0f}% (true: {})".format(
        predicted_binary_label, 100 * np.max(single_predictions_array),
        true_binary_label),
               color=color)
Esempio n. 12
0
def plotValues():
    plt.title('Serial value from Arduino')
    plt.grid(True)
    plt.ylabel('Valores del sensor ')
    plt.plot(valuesH, 'rx-', label='values')

    plt.legend(loc='upper right')
def plot_3df(
    df, plot_title, x_axis, y_axis, plot, save
):  # function for plotting high-dimension and low-dimension eigenvalues
    x1 = df[df.columns[0]]
    y1 = df[df.columns[1]]
    y2 = df[df.columns[2]]
    y3 = df[df.columns[3]]
    min1 = df[df.columns[1]].min()
    min2 = df[df.columns[2]].min()
    min3 = df[df.columns[3]].min()
    df_min = min(min1, min2, min3)
    plt.figure(figsize=(8, 8))
    plt.plot(x1, y1, color='red')
    plt.plot(x1, y2, color='blue')
    plt.plot(x1, y3, color='green')
    plt.grid(color='black', linestyle='-',
             linewidth=0.1)  # parameters for plot grid
    plt.xticks(np.arange(0,
                         max(x1) * 1.1,
                         int(max(x1) / 10)))  # adjusting the intervals to 250
    plt.yticks(np.arange(df_min * 0.9, 100, int(max(y1) / 10)))
    plt.title(plot_title).set_position([0.5, 1.05])
    plt.xlabel(x_axis)
    plt.ylabel(y_axis)
    plt.legend(loc='best')  # creating legend and placing in at the top right
    if save == 'yes':
        plt.savefig(plot_title)
    if plot == 'yes':
        plt.show()
    plt.close()
Esempio n. 14
0
def graficolog():
    ax = plt.gca()
    ax.set_yscale('log')
    plt.plot(k, eff, 'go')
    plt.plot(k, eaf, 'ro')
    plt.plot(k, ebf, 'bo')
    
    plt.grid(True)
    plt.show()
Esempio n. 15
0
 def show(self, zones):
     # x_values = gather only x_values from our zones
     # y_values = gather only y_values from our zones
     plt.plot(x_values, y_values, '.')
     plt.xlabel(self.x_label)
     plt.ylabel(self.y_label)
     plt.title(self.title)
     plt.grid(self.show_grid)
     plt.show()
Esempio n. 16
0
def histogram(df, nbin, name, k):
    plt.figure()
    n, bins, patches = plt.hist(df['Mean_' + name],
                                nbin,
                                density=True,
                                facecolor='g',
                                alpha=0.75)
    plt.title('Histogram of ' + name + ' ' + k + 's')
    plt.grid(True)
    plt.show()
Esempio n. 17
0
def grafico(e):
    plt.plot(k, np.repeat(dfa, N+1), 'k-')
    plt.plot(k, vff, 'go')
    plt.plot(k, vaf, 'ro')
    plt.plot(k, vbf, 'bo')
    
    plt.axis([0, N, dfa - e, dfa + e])
    
    plt.grid(True)
    plt.show()
Esempio n. 18
0
def makeFig():
    plt.ylim(0, 40)  # Set y min and max values
    plt.title('Reading Sensor Data')  # Plot title
    plt.grid(True)  # Turn grid on
    plt.ylabel('Temp C')  # Set y-label
    plt.xlabel('Reading count')
    plt.plot(temp_c, 'ro-', label='C`')  # plot temperature
    plt.legend(loc='upper left')  # plot egend

    plt.autoscale()
Esempio n. 19
0
def plot_sample_from_dataset(images, labels,rows=5, colums=5, width=8,height=8):

  plt.figure(figsize=(width,height))
  for i in range(rows*colums):
      plt.subplot(rows,colums,i+1)
      plt.xticks([])
      plt.yticks([])
      plt.grid(False)
      plt.imshow(images[i], cmap=plt.cm.binary)
      plt.xlabel(labels[i])
  plt.show()
Esempio n. 20
0
def createPlot():
    plt.title("Robot Speed")
    plt.ylim(0, 200)
    plt.ylabel("Speed (cm/s)")
    plt.grid(True)
    plt.plot(Left_Speed, 'ro-', label="Left Speed")
    plt.legend(loc='upper left')
    plt2 = plt.twinx()
    plt.ylim(0, 200)
    plt2.plot(Right_Speed, 'bo-', label="Right Speed")
    plt2.legend(loc='upper right')
Esempio n. 21
0
def generate_plot(array, vmin, vmax, figNumber=1):
    plt.figure(figNumber)
    plt.subplot(2,3,i)
    print i
    plt.imshow(array, vmin = vmin, vmax= vmax, interpolation = None) 
    plt.xlabel('Sample')
    plt.ylabel('Line')
    plt.title(row[0])
    cb = plt.colorbar(orientation='hor', spacing='prop',ticks = [vmin,vmax],format = '%.2f')
    cb.set_label('Reflectance / cos({0:.2f})'.format(incAnglerad*180.0/math.pi))
    plt.grid(True)
def Plot3Data(x_data,
              y_data,
              z_data,
              ylabel,
              zlabel,
              plottitle,
              savename,
              LOGFILE,
              participant,
              section,
              savepath,
              verticallineindices=[0],
              grid=1,
              xlabel='Time (in Seconds)'):
    if DEBUG == 1:
        print("Plotting function called for : ", ylabel)
    try:
        #starting the plot
        fig = plt.figure()
        fig.tight_layout()
        plt.title(plottitle)
        plt.plot(x_data, y_data, 'r-', label=ylabel, linewidth=0.1)
        plt.plot(x_data, z_data, 'g--', label=zlabel)
        if DEBUG == 1:
            print("First few elements of the x,y and z data are : ",
                  x_data[0:3], '\n', y_data[0:3], '\n', z_data[0:3])
        if len(verticallineindices
               ) > 1:  #Meaning the verticallineindices array is not empty
            for i in range(len(verticallineindices)):
                if verticallineindices[i] == 1:
                    plt.axvline(x=x_data[i], linewidth='1')
        plt.xlabel(xlabel)
        plt.ylabel(str(ylabel) + ' and ' + str(zlabel))
        plt.legend(loc='upper right')
        if grid == 1:
            plt.grid(color='b', linestyle='-.', linewidth=0.1)
        #plt.show()
        plt.savefig(savepath + savename,
                    bbox_inches='tight',
                    dpi=900,
                    quality=100)
        plt.close()
    except Exception as e:
        print("Exception at the plotting function in PlottingFunctions.py : ",
              e)
        file = open(LOGFILE, 'a')
        writer = csv.writer(file)
        writer.writerow([
            ' Exception in the plotting function ', ' Participant: ',
            participant, ' Section : ', section, '  ', ' Exception: ', e
        ])
        file.close()
Esempio n. 23
0
def makeFig():
    #plt.ylim(-30,50)
    plt.xticks(numpy.arange(-30,50,1.0))
    plt.grid(True)
    plt.ylabel("Temp")
    plt.plot(temp,'ro-',label= "Celsiusta")
    plt.legend(loc= 'upper left')
    plt2 = plt.twinx()
    plt.ylim(0,100)
    plt2.plot(hum,"b^-",label="Ilmankosteus %")
    plt2.set_ylabel("Ilmankosteus %")
    plt2.ticklabel_format(useOffset= False)
    plt2.legend(loc = 'upper right')
Esempio n. 24
0
def grafico(h, vtsaf, cor):
    ax = plt.gca()  # gca stands for 'get current axis'
    ax.spines['right'].set_color('none')
    ax.spines['top'].set_color('none')
    ax.xaxis.set_ticks_position('bottom')
    ax.spines['bottom'].set_position(('data', 0))
    ax.yaxis.set_ticks_position('left')
    ax.spines['left'].set_position(('data', 0))

    plt.plot(X, vf(X), '-r', label='f(x)')
    plt.plot(X, vtsaf(X), cor, label='Derivada atrasada')
    plt.grid(True)
    plt.show()
def main():

    #DEFINITON OF THE PATHS TO THE FILES WITH THE CONTENT
    path_to_train_accuracy = 'accuracy_train_data.csv'
    path_to_train_loss = 'loss_train_data.csv'
    path_to_validation_accuracy = 'accuracy_validation_data.csv'
    path_to_validation_loss = '"loss_validation_data.csv"'

    # CREATE LIST OF NUMBER OF EPOCHS COMPUTED
    eval_indices = range(1, EPOCHS + 1)

    #LOADS THE DATA FROM THE FILES
    accuracy_train, loss_train, accuracy_validation, loss_validation = read_data(path_to_train_accuracy,path_to_train_loss,
                                                                                 path_to_validation_accuracy,path_to_validation_loss)

    #SHOW THE INFORMATION FOR CONTROL OF QUALITY
    print(eval_indices)
    print("Accuracy Train: ",accuracy_train)
    print("Loss Train: " ,loss_train)
    print("Accuracy Validation: ", accuracy_validation)
    print("Loss validation: ", loss_validation)

    # DRAW THE ACCURACY GRAPH FOR VALIDATION AND TRAIN
    plt.clf()
    plt.subplot(211)
    plt.plot(eval_indices, accuracy_train, 'k--', label='TREINO')
    plt.plot(eval_indices, accuracy_validation, 'g-x', label='VALIDAÇÃO')
    plt.legend(loc='upper right')
    plt.xlabel('Épocas')
    plt.ylabel('ACERTO')
    plt.grid(which='major', axis='both')

    # DRAW THE LOSS GRAPH FOR VALIDATION AND TRAIN
    plt.subplot(212)
    # plt.plot(eval_indices, train, 'g-x', label='Train Set Accuracy')
    plt.plot(eval_indices, loss_train, 'r-x', label='TREINO')
    # plt.plot(eval_indices, np.ones(len(eval_indices))/TOT_CLASSES, 'k--')
    plt.plot(eval_indices, loss_validation, 'k--', label='VALIDAÇÃO')
    plt.legend(loc="upper right")
    plt.xlabel('Épocas')
    plt.ylabel('ERRO')
    plt.ylim(0, 1)
    plt.grid(which='both', axis='y')

    plt.subplots_adjust(left=0.2, wspace=0.2, hspace=0.3)

    plt.show()
    plt.pause(0.01)

    #SAVES BOTH OF THE GRAPHICS IN ONE FILE NAMED "Learning.png"
    plt.savefig('Learning.png')
Esempio n. 26
0
def plot_ecdf_comparation(iteration=0, sample_size=1000, replace=False):
    df = scalar_df_parse(
        "csv/analisiScenario/20ms/Nonmonitoring-lognormal.csv")
    df1 = scalar_df_parse(
        "csv/analisiScenario/35ms/Nonmonitoring-lognormal.csv")
    df2 = scalar_df_parse(
        "csv/analisiScenario/50ms/Nonmonitoring-lognormal.csv")
    df3 = scalar_df_parse(
        "csv/analisiScenario/10ms/Nonmonitoring-lognormal.csv")

    sample = df[df.name == "queueLength"]
    x = np.sort(sample['value'].dropna())
    n = x.size
    y = np.arange(1, n + 1) / n

    plt.scatter(x=x, y=y, label="20ms")

    sample1 = df1[df1.name == "queueLength"]

    x = np.sort(sample1['value'].dropna())
    n = x.size
    y = np.arange(1, n + 1) / n

    plt.scatter(x=x, y=y, label="35ms")

    sample2 = df2[df2.name == "queueLength"]

    x = np.sort(sample2['value'].dropna())
    n = x.size
    y = np.arange(1, n + 1) / n

    plt.scatter(x=x, y=y, label="50ms")

    sample3 = df3[df3.name == "queueLength"]

    x = np.sort(sample3['value'].dropna())
    n = x.size
    y = np.arange(1, n + 1) / n

    plt.scatter(x=x, y=y, label="10ms")

    plt.legend(loc='best')
    plt.grid(True)
    plt.xlabel('x')
    plt.ylabel('F(x)')
    plt.title("ECDF for queue length compared")
    plt.savefig(
        './analysis/analisiScenario/queueLength/non-monitoring-lognormal/comparison.png'
    )
    plt.show()
Esempio n. 27
0
def plot_value_array(i, predictions_array, true_label, number_of_classes=3):
    predictions_array, true_label = predictions_array, true_label[i]
    plt.style.use(['classic'])
    plt.grid(False)
    plt.xticks(range(number_of_classes))
    plt.yticks([])
    thisplot = plt.bar(range(number_of_classes), 1, color="#FFFFFF")
    plt.ylim([0, 1])
    predicted_label = np.argmax(predictions_array)
    #print(true_label[0])
    #print(predicted_label)

    thisplot[predicted_label].set_color('red')
    thisplot[true_label].set_color('blue')
Esempio n. 28
0
def draw_line_chart11(csvfile, savename, x_name, y_name):
    import matplotlib.pyplot as plt
    import pandas as pd
    csv = pd.read_csv(csvfile)
    x = csv[x_name]
    y = csv[y_name]
    plt.figure()
    plt.plot(x, y, marker='o')
    plt.xlabel('number of maps')
    plt.ylabel('accuracy')
    plt.grid()
    plt.legend()
    plt.savefig('../eps/' + savename)
    plt.show()
Esempio n. 29
0
def plot_extinction_prob_pn(N, nb_iter):
    rates = np.arange(2, step=0.01)
    extinction_probs = np.zeros(len(rates))

    for i in range(len(rates)):
        extinction_probs[i] = estimate_extinction_prob_pn(N, rates[i], nb_iter)

    plt.figure(figsize=(15, 10))
    plt.plot(rates, extinction_probs, 'o')
    plt.grid()
    plt.title("Probabilité d'extinction (N = {})".format(N))
    plt.xlabel("$\lambda$")
    plt.hlines(0.5, 0, 2, label="$y = 0.5$")
    plt.legend()
    plt.show()
Esempio n. 30
0
def plot_df(df1,plot_title,x_axis,y_axis,plot,save):						# function for plotting high-dimension and low-dimension eigenvalues
	y1 = df1[df1.columns[1]]
	x1 = df1[df1.columns[0]]
	plt.figure(figsize=(8,8))
	plt.plot(x1, y1, color = 'red')																
	plt.grid(color = 'black', linestyle = '-', linewidth = 0.1)			# parameters for plot grid
	plt.title(plot_title).set_position([0.5,1.05])
	plt.xlabel(x_axis)
	plt.ylabel(y_axis)			
	plt.legend(loc = 'best')											# creating legend and placing in at the top right
	if save == 'yes':
		plt.savefig(plot_title)
	if plot == 'yes':
		plt.show()
	plt.close()	
Esempio n. 31
0
def main():
	path1 = "/home/goelshivam12/Desktop/ML_Homework/HW#1/OCRdata/ocr_fold0_sm_train.txt"
	path2 = "/home/goelshivam12/Desktop/ML_Homework/HW#1/OCRdata/ocr_fold0_sm_test.txt"

	C = [10**-4,10**-3,10**-2, 10**-1, 10**0, 10**1, 10**2, 10**3, 10**4]
	accuracy_train = []
	linear = SVM(path1 , path2)

	# for training accuracy
	for i in range (len(C)):
		m, p = linear.classifier_train(0, C[i])
		plot(m)
		svm_save_model('model{}'.format(i+1), m)
		accuracy_train.append(p)
	# This plots the training accuracy of the data set in SVM for all the given C's 
	plt.plot(accuracy_train)


	# for testing accuracy
	accuracy_test = []
	for i in range(len(C)):
		model_name = "model{}".format(i+1)
		p_acc = linear.classifier_test(1, model_name)
		# save the accuracies in a list
		accuracy_test.append(p_acc)

	# plots the testing accuracy of the dataset
	plt.plot(accuracy_test)


	# for validation accuracy
	accuracy_validation = []
	for i in range(len(C)):
		model_name = "model{}".format(i+1)
		p_acc = linear.classifier_test(2, model_name)
		# save the accuracies in a list
		accuracy_validation.append(p_acc)

	# plots the testing accuracy of the dataset
	plt.plot(accuracy_validation)

	plt.xlabel("C's", fontsize = 15)
	plt.ylabel(" Accuracy", fontsize = 15)
	plt.title("Accuracy Curve (SVM)", fontsize = 25)
	# plt.ylim([0.1, 0.8])
	plt.grid(True)
	plt.legend(['Training', ' Testing', 'Validation'])
	plt.show()  
Esempio n. 32
0
 def makeFig(self):  # Create a function that makes our desired plot
     plt.ylim(90, 1024)  # Set y min and max values
     plt.title('')  # Plot the title
     plt.grid(True)  # Turn the grid on
     plt.ylabel('p1')  # Set ylabels
     plt.plot(self.d1, 'ro-', label='Potentiometr_1')
     plt.legend(loc='upper left')  # plot the legend
     plt2 = plt.twinx()  # Create a second y axis
     plt.ylim(
         90, 1024
     )  # Set limits of second y axis- adjust to readings you are getting
     plt2.plot(self.d2, 'b^-', label='Potentiometr_2')
     plt2.set_ylabel('p2')  # label second y axis
     plt2.ticklabel_format(
         useOffset=False)  # Force matplotlib to NOT autoscale y axis
     plt2.legend(loc='upper right')  # plot the legend
Esempio n. 33
0
def draw_line_chart(savename, x, y, xlabel, ylabel):
    import matplotlib.pyplot as plt
    import pandas as pd
    n = range(len(x))
    y = y
    ax = plt.figure()
    plt.plot(n, y, marker='o')
    plt.xlabel(xlabel)

    plt.xticks(n, x, rotation=30)
    # plt.xtickslabel(['1(776)', '2(698)', '3(628)', '4(565)', '5(508)', '6(457)', '7(449)', '8(422)', '9(389)', '10(356)'])
    plt.ylabel(ylabel)
    plt.grid(which='major')
    plt.legend()
    plt.savefig('../eps/' + savename)
    plt.show()
Esempio n. 34
0
 def loss_plot(self, loss_type):
     iters = range(len(self.losses[loss_type]))
     plt.figure()
     # acc
     plt.plot(iters, self.accuracy[loss_type], 'r', label='train acc')
     # loss
     plt.plot(iters, self.losses[loss_type], 'g', label='train loss')
     if loss_type == 'epoch':
         # val_acc
         plt.plot(iters, self.val_acc[loss_type], 'b', label='val acc')
         # val_loss
         plt.plot(iters, self.val_loss[loss_type], 'k', label='val loss')
     plt.grid(True)
     plt.xlabel(loss_type)
     plt.ylabel('acc-loss')
     plt.legend(loc="upper right")
     plt.show()
Esempio n. 35
0
 def __save(self,n,plot,sfile):
     p.figure(figsize=sfile)
     p.xlabel(plot.xlabel)
     p.ylabel(plot.ylabel)
     p.xscale(plot.xscale)
     p.yscale(plot.yscale)
     p.grid()
     for curve in plot.curves: 
         if curve[1] == None: p.plot(curve[0],curve[2], label=curve[3])
         else: p.plot(curve[0],  curve[1], curve[2], label=curve[3])
     p.rc('legend', fontsize='small')
     p.legend(shadow=0, loc='best')
     p.axes().set_aspect(plot.aspect)
     if not plot.dir: plot.dir = './plots/'
     if not plot.name: plot.name = self.__global_name+'_%0*i'%(2,n)
     if not os.path.isdir(plot.dir): os.mkdir(plot.dir)
     if plot.pgf: p.savefig(plot.dir+plot.name+'.pgf')
     else: p.savefig(plot.dir+plot.name+'.pdf', bbox_inches='tight')
     p.close()
        options_data.loc[option]['PRICE'],
        sigma_est=2.,   #Estimate for implied volatility
        it=100)
options_data['IMP_VOL'].loc[option] = imp_vol

futures_data['MATURITY']
    #Select column with name MATURITY
options_data.loc[46170]
#Select Data row for index 46170
options_data.loc[46710]['STRIKE']
#Select only value in column STRIKE
plot_data = options_data[options_data['IMP_VOL'] > 0]
maturities = sorted(set(options_data['MATURITY']))

maturities

#Reiterate over all maturities and plot
import matplotlib as plt
#%matplotlib inline
plt.figure(figsize=(8,6))
for maturity in maturities:
    data = plot_data[options_data.MATURITY == maturity]
    #Select data for this maturity
    plt.plot(data['STRIKE'], data['IMP_VOL'], label=maturity.date(), lw=1.5)
    plt.plot(datadata['STRIKE'], data['IMP_VOL'], 'r.')
plt.grid(True)
plt.xlabel('strike')
plt.ylabel('implied volatility of volatility')
plt.legend()
plt.show()
        f = h5py.File('results/' + filename, 'r')
    else:
        f = h5py.File('results/' + assembly + '-errors.h5', 'r')
    for j, x in enumerate(x_axis):
        value_keys = f[test][sorted_keys[j]].keys()
        for key in value_keys:
            if 'Kinf_Error' in key:
                kinf_list.append(f[test][sorted_keys[j]][key][...]*10**5)
    plt.plot(x_axis,kinf_list, colors[i] + 'o-', ms = 10, lw = 2)
    f.close()

plt.axis([max(x_axis), 0, 0, 400])
plt.title('Error in K-Infinity')
plt.xlabel('Track Spacing [cm]')
plt.ylabel('K-Infinity Error [pcm]')
plt.grid()
plt.legend(legend)
plt.show()
fig.savefig('K-Infinity-Error-TS.png')

fig = plt.figure()
for i, assembly in enumerate(assembly_list):
    mean_list = []
    filename = assembly + '-trackspacing-errors.h5'
    if os.path.isfile('results/' + filename):
        f = h5py.File('results/' + filename, 'r')
    else:
        f = h5py.File('results/' + assembly + '-errors.h5', 'r')
    for j, x in enumerate(x_axis):
        value_keys = f[test][sorted_keys[j]].keys()
        for key in value_keys: