Python matplotlib.pyplot.scatter() Examples

The following are code examples for showing how to use matplotlib.pyplot.scatter(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: deep-learning-note   Author: wdxtub   File: 3_linear_regression_raw.py    MIT License 7 votes vote down vote up
def generate_dataset(true_w, true_b):
    num_examples = 1000

    features = torch.tensor(np.random.normal(0, 1, (num_examples, num_inputs)), dtype=torch.float)
    # 真实 label
    labels = true_w[0] * features[:, 0] + true_w[1] * features[:, 1] + true_b
    # 添加噪声
    labels += torch.tensor(np.random.normal(0, 0.01, size=labels.size()), dtype=torch.float)
    # 展示下分布
    plt.scatter(features[:, 1].numpy(), labels.numpy(), 1)
    plt.show()
    
    return features, labels


# batch 读取数据集 
Example 2
Project: Electrolyte_Analysis_FTIR   Author: Samuel-Buteau   File: quality_control_dataset.py    MIT License 6 votes vote down vote up
def handle(self, *args, **kwargs):
        if update_eli:
            for spec in FTIRSpectrum.objects.filter(preparation=HUMAN):
                print('filename: ', spec.filename, 'Supervized? ', spec.supervised)
                print('LiPF6: {}, EC: {}, EMC: {}, DMC: {}, DEC: {}'.format(
                    spec.LIPF6_mass_ratio,
                    spec.EC_mass_ratio,
                    spec.EMC_mass_ratio,
                    spec.DMC_mass_ratio,
                    spec.DEC_mass_ratio))

                samples = FTIRSample.objects.filter(spectrum=spec).order_by('index')
                plt.scatter([s.wavenumber for s in samples], [s.absorbance for s in samples])
                plt.show()
                x = input('Please enter KEEP/DELETE/UNSUPERVISED:')
                if 'KEEP' in x:
                    continue
                elif 'DELETE' in x:
                    spec.delete()
                elif 'UNSUPERVISED' in x:
                    spec.supervised = False
                    spec.save()
                else:
                    continue 
Example 3
Project: beta3_IRT   Author: yc14600   File: plots.py    MIT License 6 votes vote down vote up
def plot_noisy_points(xtest, disc=None):
    sns.set_context('paper')
    cls = sns.color_palette("BuGn_r")
    lgd = []
    f = plt.figure()
    
    plt.scatter(xtest.x[xtest.noise==0],xtest.y[xtest.noise==0],facecolors='none',edgecolors='k',s=60)
    lgd.append('non-noise item')
    plt.scatter(xtest.x[xtest.noise>0],xtest.y[xtest.noise>0],c=cls[3],s=60)
    lgd.append('noise item')
    if not disc is None:
        plt.scatter(xtest.x[disc<0],xtest.y[disc<0],c=cls[0],marker='+',facecolors='none')
        lgd.append('detected noise item')
    
    plt.title('True and detected noise items')
    l = plt.legend(lgd,frameon=True,fontsize=12)
    l.get_frame().set_edgecolor('g')
    return f 
Example 4
Project: beta3_IRT   Author: yc14600   File: plots.py    MIT License 6 votes vote down vote up
def plot_item_parameters_corr(irt_prob_avg,difficulty,noise,disc=None):
    sns.set_context('paper')
    cls = sns.color_palette("BuGn_r")
    lgd = []

    f = plt.figure()
    plt.xlim([0.,1.])
    plt.ylim([0.,1.])
    
    
    plt.scatter(irt_prob_avg[noise>0],difficulty[noise>0],c=cls[3],s=60)
    lgd.append('noise item')
    if not disc is None:
        plt.scatter(irt_prob_avg[disc<0],difficulty[disc<0],c=cls[0],marker='+',facecolors='none')
        lgd.append('detected noise item')
    plt.scatter(irt_prob_avg[noise==0],difficulty[noise==0],facecolors='none',edgecolors='k',s=60)
    lgd.append('non-noise item')

    plt.title('Correlation between difficulty and response')
    plt.xlabel('Average response',fontsize=14)
    plt.ylabel('Difficulty',fontsize=14)
    l=plt.legend(lgd,frameon=True,fontsize=12)
    l.get_frame().set_edgecolor('g')
    return f 
Example 5
Project: euclid   Author: njpayne   File: regressors.py    GNU General Public License v2.0 6 votes vote down vote up
def run_linear_regression(training_features, training_labels, test_features, test_labels, passed_parameters = None, headings = ["Linear"]):
    

    #set up linear regressor
    estimator = linear_model.LinearRegression(fit_intercept = True)

    estimator.fit(training_features, training_labels)

    prediction = estimator.predict(X = test_features)
    score = estimator.score(X = test_features, y = test_labels)

    if(training_features.shape[1] == 1):

        fig, ax = plt.subplots()
        ax.scatter(training_labels, prediction)
        ax.plot([training_labels.min(), training_labels.max()], [training_labels.min(), training_labels.max()], 'k--', lw=4)
        ax.set_xlabel('Measured')
        ax.set_ylabel('Predicted')
        pylab.savefig(os.path.join(results_location, "Linear - " + headings[-1] + '.png'))

    return prediction, score 
Example 6
Project: SLiPy   Author: glentner   File: Profile.py    GNU General Public License v2.0 6 votes vote down vote up
def Pick(event):
    """
    Used to hand selection events.
    """
    if isinstance(event.artist, Line2D):
        # get the x, y data from the pick event
        thisline = event.artist
        xdata = thisline.get_xdata()
        ydata = thisline.get_ydata()
        ind = event.ind
        # update the selection dictionary
        global selected
        selected['wave'].append(np.take(xdata,ind)[0])
        selected['data'].append(np.take(ydata,ind)[0])
        # display points as a visual aid
        plt.scatter(np.take(xdata,ind)[0], np.take(ydata,ind)[0],
            marker = 'o', s=75, edgecolor='red', facecolor='None', lw=2)
        plt.draw()

# empty selection dictionary is filled with the Select() function 
Example 7
Project: imgcomp-cvpr   Author: fab-jul   File: plotter.py    GNU General Public License v3.0 6 votes vote down vote up
def plot_ours_mean(measures_readers, metric, color, show_ids):
    if not show_ids:
        show_ids = []
    ops = []
    for first, measures_reader in flag_first_iter(measures_readers):
        this_op_bpps = []
        this_op_values = []
        for img_name, bpp, value in measures_reader.iter_metric(metric):
            this_op_bpps.append(bpp)
            this_op_values.append(value)
        ours_mean_bpp, ours_mean_value = np.mean(this_op_bpps), np.mean(this_op_values)
        ops.append((ours_mean_bpp, ours_mean_value))
        plt.scatter(ours_mean_bpp, ours_mean_value, marker='x', zorder=10, color=color,
                    label='Ours' if first else None)
    for (bpp, value), job_id in zip(sorted(ops), show_ids):
        plt.annotate(job_id, (bpp + 0.04, value),
                     horizontalalignment='bottom', verticalalignment='center') 
Example 8
Project: remixt   Author: amcpherson   File: cn_plot.py    MIT License 6 votes vote down vote up
def gc_plot(gc_table_filename, plot_filename):
    """ Plot the probability distribution of GC content for sampled reads

    Args:
        gc_table_filename (str): table of binned gc values
        plot_filename (str): plot PDF filename

    """
    gc_binned = pd.read_csv(gc_table_filename, sep='\t')

    fig = plt.figure(figsize=(4,4))

    plt.scatter(gc_binned['gc_bin'].values, gc_binned['mean'].values, c='k', s=4)
    plt.plot(gc_binned['gc_bin'].values, gc_binned['smoothed'].values, c='r')

    plt.xlabel('gc %')
    plt.ylabel('density')
    plt.xlim((-0.5, 100.5))
    plt.ylim((-0.01, gc_binned['mean'].max() * 1.1))

    plt.tight_layout()

    fig.savefig(plot_filename, format='pdf', bbox_inches='tight') 
Example 9
Project: scanorama   Author: brianhie   File: utils.py    MIT License 6 votes vote down vote up
def visualize_cluster(coords, cluster, cluster_labels,
                      cluster_name=None, size=1, viz_prefix='vc',
                      image_suffix='.svg'):
    if not cluster_name:
        cluster_name = cluster
    labels = [ 1 if c_i == cluster else 0
               for c_i in cluster_labels ]
    c_idx = [ i for i in range(len(labels)) if labels[i] == 1 ]
    nc_idx = [ i for i in range(len(labels)) if labels[i] == 0 ]
    colors = np.array([ '#cccccc', '#377eb8' ])
    image_fname = '{}_cluster{}{}'.format(
        viz_prefix, cluster, image_suffix
    )
    plt.figure()
    plt.scatter(coords[nc_idx, 0], coords[nc_idx, 1],
                c=colors[0], s=size)
    plt.scatter(coords[c_idx, 0], coords[c_idx, 1],
                c=colors[1], s=size)
    plt.title(str(cluster_name))
    plt.savefig(image_fname, dpi=500) 
Example 10
Project: NNLM   Author: kanoh-k   File: corpus.py    GNU General Public License v3.0 6 votes vote down vote up
def plot(self, filename="./corpus/model/blog.png"):
        tsne = TSNE(perplexity=30, n_components=2, init="pca", n_iter=5000)
        plot_only=500
        low_dim_embeddings = tsne.fit_transform(self.final_embeddings[:plot_only, :])
        reversed_dictionary = dict(zip(self.dictionary.values(), self.dictionary.keys()))
        labels = [reversed_dictionary[i] for i in range(plot_only)]

        plt.figure(figsize=(18, 18))
        for i, label in enumerate(labels):
            x, y = low_dim_embeddings[i, :]
            plt.scatter(x, y)
            plt.annotate(label,
                        xy=(x, y),
                        xytext=(5, 2),
                        textcoords="offset points",
                        ha="right",
                        va="bottom")
        plt.savefig(filename)
        print("Scatter plot was saved to", filename) 
Example 11
Project: EarlyWarning   Author: wjlei1990   File: train_eew_linear.py    GNU General Public License v3.0 6 votes vote down vote up
def plot_y(train_y, train_y_pred, test_y, test_y_pred, figname=None):
    plt.figure(figsize=(20, 10))
    plt.subplot(1, 2, 1)
    plt.scatter(train_y, train_y_pred, alpha=0.2, label="train")
    plt.plot([2, 8], [2, 8], '--', color="k")
    # plt.xlim([2.5, 7.5])
    # plt.ylim([2.5, 7.5])
    plt.title("Train")
    plt.legend()

    plt.subplot(1, 2, 2)
    plt.scatter(test_y, test_y_pred, color="r", alpha=0.2, label="test")
    plt.plot([2, 8], [2, 8], '--', color="k")
    plt.title("Test")
    plt.legend()
    # plt.xlim([2.5, 7.5])
    # plt.ylim([2.5, 7.5])
    if figname is None:
        plt.show()
    else:
        plt.savefig(figname) 
Example 12
Project: Aegis   Author: jlillywh   File: sliding_ts_chart.py    GNU General Public License v3.0 6 votes vote down vote up
def update(self, new_value):
        """Adds a value to the end of the array and removes the first.
        
            Parameters
            ----------
            new_value : Quantity
                The value that is added to the front of the list.
        """
        self.queue.append(new_value)
        self.queue.popleft()
        self.last_date += pd.Timedelta('1 days')

        plt.axis([0, 10, 0, 1])

        for i in range(10):
            y = np.random.random()
            plt.scatter(i, y)
            plt.pause(0.05)

        plt.show() 
Example 13
Project: aco-tsp   Author: rochakgupta   File: aco_tsp.py    MIT License 6 votes vote down vote up
def plot(self, line_width=1, point_radius=math.sqrt(2.0), annotation_size=8, dpi=120, save=True, name=None):
        x = [self.nodes[i][0] for i in self.global_best_tour]
        x.append(x[0])
        y = [self.nodes[i][1] for i in self.global_best_tour]
        y.append(y[0])
        plt.plot(x, y, linewidth=line_width)
        plt.scatter(x, y, s=math.pi * (point_radius ** 2.0))
        plt.title(self.mode)
        for i in self.global_best_tour:
            plt.annotate(self.labels[i], self.nodes[i], size=annotation_size)
        if save:
            if name is None:
                name = '{0}.png'.format(self.mode)
            plt.savefig(name, dpi=dpi)
        plt.show()
        plt.gcf().clear() 
Example 14
Project: smote_variants   Author: gykovacs   File: 007_paper_examples.py    MIT License 6 votes vote down vote up
def plot_mc(X, y, title, label_0, label_1, label_2, filename):
    plt.figure(figsize= (4, 3))
    plt.scatter(X[:,0][y == label_0], X[:,1][y == label_0], label='class 0', color='red', s=25)
    plt.scatter(X[:,0][y == label_1], X[:,1][y == label_1], label='class 1', color='black', marker='*', s=25)
    plt.scatter(X[:,0][y == label_2], X[:,1][y == label_2], label='class 2', color='blue', marker='^', s=25)
    plt.xlabel('feature 0')
    plt.ylabel('feature 1')
    plt.title(title)
    plt.legend()
    plt.tight_layout()
    plt.savefig(filename)
    plt.show()


# In[5]:


# setting the random seed 
Example 15
Project: student-resources   Author: djgroen   File: make-animation.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def main():

    if len(sys.argv)>1:
        global data_path
        data_path = sys.argv[1]

    fig, ax = plt.subplots(figsize=(5, 3))
    #ax.set(xlim=(-10, 110), ylim=(-10, 110))

    num_files = len(glob.glob('%s/agents*.csv' % data_path))
    scat = ax.scatter([], [])
    plot_location()

    print("# of frames: ",num_files)

    dataframe_list = read_csv_to_df()
    # time between frames can be changed by adjusting the interval param which is in milliseconds
    anim = FuncAnimation(
        fig, animate, interval=1000, frames=range(num_files), fargs=(dataframe_list, scat))

    plt.draw()
    # shows the output on screen
    plt.show()
    # uncomment line below to save as mp4 video file
    # save_animation(anim) 
Example 16
Project: ESL   Author: jayshonzs   File: SmoothingSplines.py    MIT License 6 votes vote down vote up
def draw(inputs, outputs, male_theta, female_theta, male_knots, female_knots, resolution=50):
    mycm = mpl.cm.get_cmap('Paired')
    
    minx = inputs[:,0].min()
    maxx = inputs[:,0].max()
    X = np.arange(minx, maxx, 100)
    male_N = []
    for k in range(len(X)):
        male_N.append(N(X[k], k, male_knots))
    female_N = []
    for k in range(len(X)):
        female_N.append(N(X[k], k, female_knots))
    male_N_array = np.array(male_N)
    female_N_array = np.array(female_N)
    
    male_Y = male_N_array.dot(male_theta)
    female_Y = female_N_array.dot(female_theta)
    
    plt.scatter(inputs[:, 0], outputs, s=50, c=inputs[:,1], cmap=mycm)
    plt.plot(X, male_Y)
    plt.plot(X, female_Y)
    
    plt.show() 
Example 17
Project: ESL   Author: jayshonzs   File: LDA.py    MIT License 6 votes vote down vote up
def draw(data, classes, means, thegma, pi, resolution):
    mycm = mpl.cm.get_cmap('Paired')
    
    one_min, one_max = data[:, 0].min()-0.1, data[:, 0].max()+0.1
    two_min, two_max = data[:, 1].min()-0.1, data[:, 1].max()+0.1
    xx1, xx2 = np.meshgrid(np.arange(one_min, one_max, (one_max-one_min)/resolution),
                     np.arange(two_min, two_max, (two_max-two_min)/resolution))
    
    inputs = np.c_[xx1.ravel(), xx2.ravel()]
    z = []
    for i in range(len(inputs)):
        z.append(classify(inputs[i], means, thegma, pi, 3))
    result = np.array(z).reshape(xx1.shape)
    plt.contourf(xx1, xx2, result, cmap=mycm)
    
    plt.scatter(data[:, 0], data[:, 1], s=50, c=classes, cmap=mycm)
    
    plt.show() 
Example 18
Project: ESL   Author: jayshonzs   File: QDA.py    MIT License 6 votes vote down vote up
def draw(data, classes, means, thegmas, pi, resolution):
    mycm = mpl.cm.get_cmap('Paired')
    
    one_min, one_max = data[:, 0].min()-0.1, data[:, 0].max()+0.1
    two_min, two_max = data[:, 1].min()-0.1, data[:, 1].max()+0.1
    xx1, xx2 = np.meshgrid(np.arange(one_min, one_max, (one_max-one_min)/resolution),
                     np.arange(two_min, two_max, (two_max-two_min)/resolution))
    
    inputs = np.c_[xx1.ravel(), xx2.ravel()]
    z = []
    for i in range(len(inputs)):
        z.append(classify(inputs[i], means, thegmas, pi, 3))
    result = np.array(z).reshape(xx1.shape)
    plt.contourf(xx1, xx2, result, cmap=mycm)
    
    plt.scatter(data[:, 0], data[:, 1], s=50, c=classes, cmap=mycm)
    
    plt.show() 
Example 19
Project: ESL   Author: jayshonzs   File: Fisher.py    MIT License 6 votes vote down vote up
def draw(data, outputs, centroids, resolution):
    mycm = mpl.cm.get_cmap('Paired')
    
    one_min, one_max = data[:, 0].min()-0.1, data[:, 0].max()+0.1
    two_min, two_max = data[:, 1].min()-0.1, data[:, 1].max()+0.1
    xx1, xx2 = np.meshgrid(np.arange(one_min, one_max, (one_max-one_min)/resolution),
                     np.arange(two_min, two_max, (two_max-two_min)/resolution))
    
    inputs = np.c_[xx1.ravel(), xx2.ravel()]
    z = []
    for i in range(len(inputs)):
        z.append(classify(centroids, inputs[i]))
    result = np.array(z).reshape(xx1.shape)
    np.savetxt('result.out', result, delimiter=',', fmt='%2d')
    plt.contourf(xx1, xx2, result, 12, cmap=mycm)
    
    plt.scatter(data[:, 0], data[:, 1], s=50, c=outputs, cmap=mycm)
    plt.scatter(centroids[:, 0], centroids[:, 1], c=np.array([1,2,3,4,5,6,7,8,9,10,11]), marker='^', s=200, cmap=mycm)
    
    plt.show() 
Example 20
Project: ESL   Author: jayshonzs   File: knn.py    MIT License 6 votes vote down vote up
def drawclass(X, Y, resolution):
    mycm = mpl.cm.get_cmap('Paired')
    
    one_min, one_max = X[:, 0].min()-0.1, X[:, 0].max()+0.1
    two_min, two_max = X[:, 1].min()-0.1, X[:, 1].max()+0.1
    xx1, xx2 = np.meshgrid(np.arange(one_min, one_max, (one_max-one_min)/resolution),
                     np.arange(two_min, two_max, (two_max-two_min)/resolution))
    
    inputs = np.c_[xx1.ravel(), xx2.ravel()]
    z = []
    for i in range(len(inputs)):
        res = knn(X, Y, 15, inputs[i])
        z.append(res)
    result = np.array(z).reshape(xx1.shape)
    
    plt.contourf(xx1, xx2, result, cmap=mycm)
    
    plt.scatter(X[:,0], X[:,1], s=30, c=Y, cmap=mycm)
    
    plt.show() 
Example 21
Project: projection-methods   Author: akshayka   File: circles.py    GNU General Public License v3.0 5 votes vote down vote up
def plot_iterates(iterates, label):
    x = [float(i[0]) for i in iterates]
    y = [float(i[1]) for i in iterates]
    plt.scatter(x=x, y=y)
    plt.plot(x, y, label=label) 
Example 22
Project: fenics-topopt   Author: zfergus   File: triangulate.py    MIT License 5 votes vote down vote up
def plot_mesh(V, F, plot_f=False):
    plt.scatter(V[:, 0], V[:, 1])
    if not plot_f:
        return
    for i in range(F.shape[0]):
        vf = V[F[i, :], :]
        plt.plot(vf[:, 0], vf[:, 1]) 
Example 23
Project: ml_news_popularity   Author: khaledJabr   File: lr.py    MIT License 5 votes vote down vote up
def plot(self):
        lw = 2
        plt.scatter(range(len(self.targets)), self.targets, color='darkorange', label='data')
        plt.scatter(range(len(self.predicted)), self.predicted, color='cornflowerblue', lw=lw, label='Polynomial model')
        plt.xlabel('Data')
        plt.ylabel('Target')
        plt.title('Lasso Regression')
        plt.legend()
        plt.show() 
Example 24
Project: Sessile.drop.analysis   Author: mvgorcum   File: GUI_sessile_drop_analysis.py    GNU General Public License v3.0 5 votes vote down vote up
def plotstuff(typexplot,typeyplot,logxbool,logybool,pxscale,fps):
    x=np.float()
    y=np.float()
    if typexplot==1:
        x=thetal
    elif typexplot==2:
        x=thetar
    elif typexplot==3:
        x=dropvolume*pxscale**3
    elif typexplot==3:
        x=leftspeed*pxscale*fps
    elif typexplot==4:
        x=rightspeed*pxscale*fps
    else:
        print('no x variable set')
    if typeyplot==1:
        y=thetal
    elif typeyplot==2:
        y=thetar
    elif typeyplot==3:
        y=dropvolume
    elif typeyplot==3:
        y=leftspeed
    elif typeyplot==4:
        y=rightspeed
    else:
        print('no y variable set')
    if x.size==1 or y.size==1:
        plt.scatter(x,y)
    else:
        plt.plot(x,y)
    
    if logxbool:
        plt.xscale('log')
    if logybool:
        plt.yscale('log')
    plt.show() 
Example 25
Project: voice-recognition   Author: golabies   File: cluster.py    MIT License 5 votes vote down vote up
def show(self):
        y = self.signal
        x = np.arange(len(y))
        plt.scatter(x, y, c=self.labels, s=0.1)
        plt.show() 
Example 26
Project: deep-learning-note   Author: wdxtub   File: 4_linear_regression_torch.py    MIT License 5 votes vote down vote up
def generate_dataset(true_w, true_b):
    num_examples = 1000

    features = torch.tensor(np.random.normal(0, 1, (num_examples, num_inputs)), dtype=torch.float)
    # 真实 label
    labels = true_w[0] * features[:, 0] + true_w[1] * features[:, 1] + true_b
    # 添加噪声
    labels += torch.tensor(np.random.normal(0, 0.01, size=labels.size()), dtype=torch.float)
    # 展示下分布
    plt.scatter(features[:, 1].numpy(), labels.numpy(), 1)
    plt.show()

    return features, labels 
Example 27
Project: beta3_IRT   Author: yc14600   File: plots.py    MIT License 5 votes vote down vote up
def plot_probabilities(X, probabilities, titles, suptitle):
    norm = plt.Normalize(0, 1)
    n = len(titles)

    nrows = int(np.ceil(n / 2))

    sns.set_context('paper')
    cmap = sns.cubehelix_palette(rot=-.5,light=1.5,dark=-.5,as_cmap=True)

    f, axarr = plt.subplots(nrows, min(n,2))
    if n < 2:
        axarr.scatter(X[:, 0], X[:, 1], c=probabilities[0],
                            cmap=cmap, norm=norm, edgecolor='k',s=60)
        axarr.set_title(titles[0])
        #f.set_size_inches(8, 8)
    else:

        i = j = 0
        for idx, t in enumerate(titles):
            axarr[i, j].scatter(X[:, 0], X[:, 1], c=probabilities[idx],
                                cmap=cmap, norm=norm, edgecolor='k')
            axarr[i, j].set_title(t)
            j += 1
            if j == 2:
                j = 0
                i += 1
        if n % 2 != 0:
            axarr[-1, -1].axis('off')
        f.set_size_inches(10, 30)

    f.suptitle(suptitle)    
    f.subplots_adjust(hspace=0.7)
    return f 
Example 28
Project: beta3_IRT   Author: yc14600   File: plots.py    MIT License 5 votes vote down vote up
def plot_parameters(X, delta, a):
    sns.set_context('paper')
    cmap1 = sns.cubehelix_palette(rot=-.5,light=1.5,dark=-.5,as_cmap=True)
    gs = gridspec.GridSpec(2, 2, height_ratios=[4, 2]) 
    f = plt.figure(figsize=(12,6))
    axarr = np.array([[None]*2]*2)
    for i in range(2):
        for j in range(2):
            axarr[i,j] = plt.subplot(gs[i*2+j])

    axarr[0, 0].scatter(X[:, 0], X[:, 1], c=delta, cmap=cmap1,
                        edgecolor='k',s=40)
    axarr[0, 0].set_title('$\mathbf{\delta}$ (Difficulty)',fontsize=16)

    
    axarr[0, 1].scatter(X[:, 0], X[:, 1], c=a, cmap=cmap1,
                        edgecolor='k',s=40)
    axarr[0, 1].set_title('$\mathbf{a}$ (Discrimination)',fontsize=16)

    #axarr[1, 0].hist(delta,bins=100)
    sns.distplot(delta,bins=100,ax=axarr[1,0])
    axarr[1, 0].set_title('Histogram of $\mathbf{\delta}$',fontsize=16)
    #axarr[1, 1].hist(a,bins=100)
    sns.distplot(a,bins=100,ax=axarr[1,1])
    axarr[1, 1].set_title('Histogram of $\mathbf{a}$',fontsize=16)
    f.suptitle('IRT item parameters')
    #f.set_size_inches(20, 20)
    f.subplots_adjust(hspace=0.3)
    return f 
Example 29
Project: DataSciUF-Tutorial-Student   Author: jdamiani27   File: class_vis.py    MIT License 5 votes vote down vote up
def prettyPicture(clf, X_test, y_test):
    x_min = 0.0; x_max = 10.5
    y_min = 0.0; y_max = 10.5
    
    # Plot the decision boundary. For that, we will assign a color to each
    # point in the mesh [x_min, m_max]x[y_min, y_max].
    h = .01  # step size in the mesh
    xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
    Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])

    # Put the result into a color plot
    Z = Z.reshape(xx.shape)
    plt.xlim(xx.min(), xx.max())
    plt.ylim(yy.min(), yy.max())

    plt.pcolormesh(xx, yy, Z, cmap=pl.cm.seismic)

    # Plot also the test points
    grade_sig = [X_test[ii][0] for ii in range(0, len(X_test)) if y_test[ii]==2]
    bumpy_sig = [X_test[ii][1] for ii in range(0, len(X_test)) if y_test[ii]==2]
    grade_bkg = [X_test[ii][0] for ii in range(0, len(X_test)) if y_test[ii]==4]
    bumpy_bkg = [X_test[ii][1] for ii in range(0, len(X_test)) if y_test[ii]==4]

    plt.scatter(grade_sig, bumpy_sig, color = "b", label="benign")
    plt.scatter(grade_bkg, bumpy_bkg, color = "r", label="malignant")
    plt.legend()
    plt.xlabel("uniformity_cell_shape")
    plt.ylabel("bare_nuclei")

    plt.savefig("test.png") 
Example 30
Project: Parallel.GAMIT   Author: demiangomez   File: test_voronoi.py    GNU General Public License v3.0 5 votes vote down vote up
def plot_v(pc, sv):

    from matplotlib import colors
    from mpl_toolkits.mplot3d.art3d import Poly3DCollection
    import matplotlib.pyplot as plt
    from mpl_toolkits.mplot3d import proj3d

    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    # plot the unit sphere for reference (optional)
    u = np.linspace(0, 2 * np.pi, 100)
    v = np.linspace(0, np.pi, 100)
    x = np.outer(np.cos(u), np.sin(v))
    y = np.outer(np.sin(u), np.sin(v))
    z = np.outer(np.ones(np.size(u)), np.cos(v))
    ax.plot_surface(x, y, z, color='y', alpha=0.1)
    # plot generator points
    # ax.scatter(points[:, 0], points[:, 1], points[:, 2], c='b')
    ax.scatter(pc[:, 0], pc[:, 1], pc[:, 2], c='b')
    # plot Voronoi vertices
    ax.scatter(sv.vertices[:, 0], sv.vertices[:, 1], sv.vertices[:, 2], c='g')
    # indicate Voronoi regions (as Euclidean polygons)

    for region in sv.regions:
        random_color = colors.rgb2hex(np.random.rand(3))
        polygon = Poly3DCollection([sv.vertices[region]], alpha=1.0)
        polygon.set_color(random_color)
        ax.add_collection3d(polygon)
    set_axes_equal(ax)
    plt.show() 
Example 31
Project: Parallel.GAMIT   Author: demiangomez   File: test_voronoi.py    GNU General Public License v3.0 5 votes vote down vote up
def plot_clusters(data, algorithm, args, kwds):
    start_time = time.time()
    labels = algorithm(*args, **kwds).fit_predict(data)
    end_time = time.time()
    palette = sns.color_palette('deep', np.unique(labels).max() + 1)
    colors = [palette[x] if x >= 0 else (0.0, 0.0, 0.0) for x in labels]
    plt.scatter(data.T[0], data.T[1], c=colors, **plot_kwds)
    frame = plt.gca()
    frame.axes.get_xaxis().set_visible(False)
    frame.axes.get_yaxis().set_visible(False)
    plt.title('Clusters found by {}'.format(str(algorithm.__name__)), fontsize=24)
    plt.text(-0.5, 0.7, 'Clustering took {:.2f} s'.format(end_time - start_time), fontsize=14) 
Example 32
Project: lirpg   Author: Hwhitetooth   File: results_plotter.py    MIT License 5 votes vote down vote up
def plot_curves(xy_list, xaxis, title):
    plt.figure(figsize=(8,2))
    maxx = max(xy[0][-1] for xy in xy_list)
    minx = 0
    for (i, (x, y)) in enumerate(xy_list):
        color = COLORS[i]
        plt.scatter(x, y, s=2)
        x, y_mean = window_func(x, y, EPISODES_WINDOW, np.mean) #So returns average of last EPISODE_WINDOW episodes
        plt.plot(x, y_mean, color=color)
    plt.xlim(minx, maxx)
    plt.title(title)
    plt.xlabel(xaxis)
    plt.ylabel("Episode Rewards")
    plt.tight_layout() 
Example 33
Project: euclid   Author: njpayne   File: main.py    GNU General Public License v2.0 5 votes vote down vote up
def plot_residual_vs_fit(y_act, y_pred, r_value, name):

    #make a scatterplot
    plt.figure()
    plt.scatter(y_pred, y_act - y_pred)
    plt.xlabel("Fitted Value")
    plt.ylabel("Residual")
    plt.text(x = 25, y = 45, s = "R^2: %.3f" % r_value)
    plt.title("Residuals " + name)
    plt.axhline(0, color= 'b', linestyle='-')
    pylab.savefig(os.path.join(os.getcwd(),"Results","Residual Plots",name))

    plt.close()

    return 
Example 34
Project: where   Author: kartverket   File: sisre_report.py    MIT License 5 votes vote down vote up
def _plot_scatter_satellite_bias(fid, figure_dir, dset):
    """Scatter plot of used broadcast and precise satellite bias by determination of SISRE

    Args:
       fid (_io.TextIOWrapper):  File object.
       figure_dir (PosixPath):   Figure directory
       dset (Dataset):           A dataset containing the data.
    """

    for sys in dset.unique("system"):
        idx = dset.filter(system=sys)

        for field, orbit in {"bias_brdc": "Broadcast", "bias_precise": "Precise"}.items():
            if np.sum(dset[field][idx]) != 0:
                figure_path = figure_dir / f"plot_scatter_{field}_{GNSS_NAME[sys].lower()}.{FIGURE_FORMAT}"
                plt.scatter(dset.time.gps.datetime[idx], dset[field][idx], alpha=0.7)
                plt.ylabel(f"{orbit} satellite bias [dset.unit(field)]")
                plt.xlim([min(dset.time.gps.datetime[idx]), max(dset.time.gps.datetime[idx])])
                plt.xlabel("Time [GPS]")
                plt.title(f"{GNSS_NAME[sys]}")
                plt.savefig(figure_path, dpi=FIGURE_DPI)
                plt.clf()  # clear the current figure

                fid.write(
                    f"![Satellite bias applied for {orbit.lower()} satellite clock corrections]({figure_path})\n"
                )
                fid.write("\n\\clearpage\n\n") 
Example 35
Project: where   Author: kartverket   File: sisre_report.py    MIT License 5 votes vote down vote up
def _plot_scatter_subplots(xdata, subplots, figure_path, xlabel="", title=""):
    """Generate scatter subplot
    Args:
       xdata (numpy.ndarray):       X-axis data to plot.
       subplots (tuple):            Tuple like (ylabel, color, ydata), whereby:
                                        ylabel (str):           Y-axis label
                                        color (str):            Color of scatter plot
                                        ydata (numpy.ndarray):  Y-axis data
       figure_path (PosixPath):     Figure path.
       xlabel (str):                X-axis label.
       title (str):                 Title of subplot.
    """
    marker = "."  # point marker type

    fig, axes = plt.subplots(len(subplots), 1, sharex=True, sharey=True, figsize=(6, 8))
    # fig.set_figheight(8)  # inches
    fig.suptitle(f"{title}", y=1.0)
    for idx, ax in enumerate(axes):
        ax.set(ylabel=subplots[idx].ylabel)
        ax.set_xlim([min(xdata), max(xdata)])  # otherwise time scale of x-axis is not correct -> Why?
        text = f"mean $= {np.mean(subplots[idx].ydata):.2f} \pm {np.std(subplots[idx].ydata):.2f}$ m"
        ax.text(0.98, 0.98, text, horizontalalignment="right", verticalalignment="top", transform=ax.transAxes)
        ax.scatter(xdata, subplots[idx].ydata, marker=marker, color=subplots[idx].color)
        ax.set(xlabel=xlabel)

    fig.autofmt_xdate()  # rotates and right aligns the x labels, and moves the bottom of the
    # axes up to make room for them
    plt.tight_layout()
    plt.savefig(figure_path, dpi=FIGURE_DPI)
    plt.clf()  # clear the current figure 
Example 36
Project: phoneticSimilarity   Author: ronggong   File: tsne_plot.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def plot_tsne_profess(embeddings, labels, le):
    tsne = TSNE(n_components=2, verbose=1, perplexity=30, n_iter=3000)
    for ii_class in range(27):
        len_stu = len(embeddings[labels == 2*ii_class, :])
        label_class_name0 = le.inverse_transform(2 * ii_class)
        label_class_name1 = le.inverse_transform(2 * ii_class+1)

        # plot t_sne for teacher and student
        try:
            tsne_results = tsne.fit_transform(np.vstack((embeddings[labels == 2*ii_class, :],
                                                         embeddings[labels == 2*ii_class+1, :])))
            plt.figure()

            plt.scatter(tsne_results[:len_stu, 0],
                        tsne_results[:len_stu, 1],
                        label=label_class_name0)

            plt.scatter(tsne_results[len_stu:, 0],
                        tsne_results[len_stu:, 1],
                        label=label_class_name1,
                        marker='v')
            plt.legend()
            plt.savefig(os.path.join('./figs/professionality/MTL/', label_class_name0.split('_')[0]+'.png'),
                        bbox_inches='tight')
            # plt.show()
        except:
            pass 
Example 37
Project: phoneticSimilarity   Author: ronggong   File: tsne_plot.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def plot_tsne_profess_all(embeddings, labels, dense=False):
    tsne = TSNE(n_components=2, verbose=1, perplexity=30, n_iter=5000)
    # phonemes = ['S', 'EnEn', 'O', 'nvc', 'N', 'j', 'in', 'y', '@n', 'i', 'MM', 'oU^', 'SN', 'aI^', 'an', 'AU^', 'rr', 'ANAN', '@', 'a', 'vc', 'iNiN', 'eI^', 'UN', 'u', 'E', 'ONE']  # perplexity 30
    # phonemes = ['S', 'O', 'nvc', 'N', 'j', '@n', 'i', 'oU^', 'aI^', 'AU^', 'ANAN', 'a', 'vc', 'iNiN', 'u', 'an', 'EnEn']
    # phonemes = ['nvc']  # perplexity 5
    phonemes = ['O']  # perplexity 30

    for p in phonemes:
        index_teacher = np.where(labels == p+"_teacher")[0]
        index_student = np.where(labels == p+"_student")[0]
        index_test = np.where(labels == p+"_extra_test")[0]
        # plot t_sne for teacher and student
        try:
            tsne_results = tsne.fit_transform(np.vstack((embeddings[index_teacher, :],
                                                         embeddings[index_student, :],
                                                         embeddings[index_test, :])))
            plt.figure()

            plt.scatter(tsne_results[:len(index_teacher), 0],
                        tsne_results[:len(index_teacher), 1],
                        label=p+" Professional")

            plt.scatter(tsne_results[len(index_teacher):len(index_teacher)+len(index_student), 0],
                        tsne_results[len(index_teacher):len(index_teacher)+len(index_student), 1],
                        label=p+" Amateur\ntrain val",
                        marker='v')

            plt.scatter(tsne_results[len(index_teacher) + len(index_student):, 0],
                        tsne_results[len(index_teacher) + len(index_student):, 1],
                        label=p+" Amateur\ntest",
                        marker='+')

            plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,
                       ncol=3, mode='expand', borderaxespad=0.)

            dense_str = "dense_all" if dense else "all"
            plt.savefig(os.path.join('./figs/professionality/'+dense_str+'/', p+'.png'),
                        bbox_inches='tight')
            # plt.show()
        except:
            pass 
Example 38
Project: phoneticSimilarity   Author: ronggong   File: tsne_plot_professionality.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def plot_tsne_profess(embeddings, labels, le):
    tsne = TSNE(n_components=2, verbose=1, perplexity=30, n_iter=3000)
    for ii_class in range(27):
        len_stu = len(embeddings[labels == 2*ii_class, :])
        label_class_name0 = le.inverse_transform(2 * ii_class)
        label_class_name1 = le.inverse_transform(2 * ii_class+1)

        # plot t_sne for teacher and student
        try:
            tsne_results = tsne.fit_transform(np.vstack((embeddings[labels == 2*ii_class, :],
                                                         embeddings[labels == 2*ii_class+1, :])))
            plt.figure()

            plt.scatter(tsne_results[:len_stu, 0],
                        tsne_results[:len_stu, 1],
                        label=label_class_name0)

            plt.scatter(tsne_results[len_stu:, 0],
                        tsne_results[len_stu:, 1],
                        label=label_class_name1,
                        marker='v')
            plt.legend()
            plt.savefig(os.path.join('./figs/professionality/MTL/', label_class_name0.split('_')[0]+'.png'),
                        bbox_inches='tight')
            # plt.show()
        except:
            pass 
Example 39
Project: HardRLWithYoutube   Author: MaxSobolMark   File: results_plotter.py    MIT License 5 votes vote down vote up
def plot_curves(xy_list, xaxis, title):
    plt.figure(figsize=(8,2))
    maxx = max(xy[0][-1] for xy in xy_list)
    minx = 0
    for (i, (x, y)) in enumerate(xy_list):
        color = COLORS[i]
        plt.scatter(x, y, s=2)
        x, y_mean = window_func(x, y, EPISODES_WINDOW, np.mean) #So returns average of last EPISODE_WINDOW episodes
        plt.plot(x, y_mean, color=color)
    plt.xlim(minx, maxx)
    plt.title(title)
    plt.xlabel(xaxis)
    plt.ylabel("Episode Rewards")
    plt.tight_layout() 
Example 40
Project: bem   Author: soleneulmer   File: bem.py    MIT License 5 votes vote down vote up
def plot_dataset(dataset, predicted_radii=[], rv=False):

    if not rv:
        # Remove outlier planets
        dataset = dataset.drop(['Kepler-11 g'])
        dataset = dataset.drop(['K2-95 b'])
        dataset = dataset.drop(['HATS-12 b'])

        # Plot the original dataset
        fig = plt.figure()
        ax = fig.add_subplot(111)
        ax.set_xscale('log')
        ax.set_yscale('log')

        size = dataset.temp_eq
        plt.scatter(dataset.mass, dataset.radius, c=size,
                    cmap=cm.magma_r, s=4, label='Verification sample')
        plt.colorbar(label=r'Equilibrium temperature (K)')
        plt.xlabel(r'Mass ($M_\oplus$)')
        plt.ylabel(r'Radius ($R_\oplus$)')
        plt.legend(loc='lower right', markerscale=0,
                   handletextpad=0.0, handlelength=0)

    if rv:
        # Plot the radial velocity dataset
        fig = plt.figure()
        ax = fig.add_subplot(111)
        ax.set_xscale('log')
        ax.set_yscale('log')

        size = dataset.temp_eq
        plt.scatter(dataset.mass, predicted_radii, c=size,
                    cmap=cm.magma_r, s=4, label='RV sample')
        plt.colorbar(label=r'Equilibrium temperature (K)')
        plt.xlabel(r'Mass ($M_\oplus$)')
        plt.ylabel(r'Radius ($R_\oplus$)')
        plt.legend(loc='lower right', markerscale=0,
                   handletextpad=0.0, handlelength=0)

    return None 
Example 41
Project: Pesquisas   Author: danilopcarlotti   File: statistical_analysis.py    Apache License 2.0 5 votes vote down vote up
def kMeans(self,k,dataFrame,title,xLabel,yLabel):
		kmeans = KMeans(n_clusters=k)
		kmeans.fit(dataFrame)
		labels = kmeans.predict(dataFrame)
		centroids = kmeans.cluster_centers_
		plt.title(title)
		plt.xlabel(xLabel)
		plt.ylabel(yLabel)
		plt.scatter(dataFrame['x'], dataFrame['y'], alpha=0.5, edgecolor='k')
		for idx, centroid in enumerate(centroids):
			plt.scatter(*centroid)
		plt.savefig(title+".png", dpi=80) 
Example 42
Project: Pesquisas   Author: danilopcarlotti   File: statistical_analysis.py    Apache License 2.0 5 votes vote down vote up
def plotScatter3D(title,list_x,list_y,list_z,xLabel,yLabel,zLabel,tickerT=1.0):
		fig = plt.figure()
		ax = fig.add_subplot(111, projection='3d')
		ax.scatter(np.array(list_x),np.array(list_y),np.array(list_z),zdir='z', s=20, c=None, depthshade=True)
		ax.xaxis.set_major_locator(ticker.MultipleLocator(base=tickerT))
		ax.yaxis.set_major_locator(ticker.MultipleLocator(base=tickerT))
		ax.zaxis.set_major_locator(ticker.MultipleLocator(base=tickerT))
		ax.set_xlabel(xLabel)
		ax.set_ylabel(yLabel)
		ax.set_zlabel(zLabel)
		plt.savefig(title+".png", dpi=80) 
Example 43
Project: Pesquisas   Author: danilopcarlotti   File: topicModelling.py    Apache License 2.0 5 votes vote down vote up
def pca_topics(self, topics, name, n_components=2, num_topics=5, n_words=15):
		X = self.topics_to_vectorspace(topics, num_topics=num_topics, n_words=n_words)
		X_array = X.toarray()
		pca = PCA(n_components=n_components)
		X_pca = pca.fit(X_array).transform(X_array)
		plt.figure()
		for i in range(X_pca.shape[0]):
			plt.scatter(X_pca[i, 0], X_pca[i, 1], alpha=.5)
			plt.text(X_pca[i, 0], X_pca[i, 1], s=' ' + str(i))
		plt.title('PCA Topics of %s' % (name,))
		plt.savefig("pca_topics_%s.png" % (name,))
		plt.close()
		return X_pca 
Example 44
Project: scanorama   Author: brianhie   File: utils.py    MIT License 5 votes vote down vote up
def visualize_expr(X, coords, genes, viz_gene, image_suffix='.svg',
                   new_fig=True, size=1, viz_prefix='ve'):
    genes = [ gene.upper() for gene in genes ]
    viz_gene = viz_gene.upper()
    
    if not viz_gene.upper() in genes:
        sys.stderr.write('Warning: Could not find gene {}\n'.format(viz_gene))
        return
    
    image_fname = '{}_{}{}'.format(
        viz_prefix, viz_gene, image_suffix
    )

    # Color based on percentiles.
    x_gene = X[:, list(genes).index(viz_gene)].toarray()
    colors = np.zeros(x_gene.shape)
    n_tiles = 100
    prev_percentile = min(x_gene)
    for i in range(n_tiles):
        q = (i+1) / float(n_tiles) * 100.
        percentile = np.percentile(x_gene, q)
        idx = np.logical_and(prev_percentile <= x_gene,
                             x_gene <= percentile)
        colors[idx] = i
        prev_percentile = percentile

    colors = colors.flatten()

    if new_fig:
        plt.figure()
        plt.title(viz_gene)
    plt.scatter(coords[:, 0], coords[:, 1],
                c=colors, cmap=cm.get_cmap('Reds'), s=size)
    plt.savefig(image_fname, dpi=500) 
Example 45
Project: scanorama   Author: brianhie   File: utils.py    MIT License 5 votes vote down vote up
def visualize_dropout(X, coords, image_suffix='.svg',
                      new_fig=True, size=1, viz_prefix='dropout'):
    image_fname = '{}{}'.format(
        viz_prefix, image_suffix
    )

    # Color based on percentiles.
    x_gene = np.array(np.sum(X != 0, axis=1))
    colors = np.zeros(x_gene.shape)
    n_tiles = 100
    prev_percentile = min(x_gene)
    for i in range(n_tiles):
        q = (i+1) / float(n_tiles) * 100.
        percentile = np.percentile(x_gene, q)
        idx = np.logical_and(prev_percentile <= x_gene,
                             x_gene <= percentile)
        colors[idx] = i
        prev_percentile = percentile

    colors = colors.flatten()

    if new_fig:
        plt.figure()
        plt.title(viz_prefix)
    plt.scatter(coords[:, 0], coords[:, 1],
                c=colors, cmap=cm.get_cmap('Reds'), s=size)
    plt.savefig(image_fname, dpi=500) 
Example 46
Project: design_embeddings_jmd_2016   Author: IDEALLab   File: manifold_clustering.py    MIT License 5 votes vote down vote up
def cluster_manifold(X, verbose=0):
    ''' First apply pairwise distance kernel, then use curved level kernel to get subclusters '''
    
    W = rmmsl(X, sigma_c=.2, verbose=verbose) # higher weight on the curved level kernel
    labels = get_labels(W, verbose=verbose)
#    n_clusters = max(labels) + 1
#    n_subc = 1
#    for i in range(n_clusters):
#        # Rearrange labels
#        c = i + n_subc - 1
#        W_sub = rmmsl(X[labels==c], sigma_c=.2, verbose=verbose) # higher weight on the pairwise distance kernel
#        sub_labels = get_labels(W_sub, verbose=verbose)
#        n_subc = max(sub_labels) + 1
#        labels[labels>c] += n_subc-1
#        labels[labels==c] += sub_labels
        
    print 'Number of clusters: ', max(labels)+1

    if verbose:
        # Visualize clustering result
        if X.shape[1] > 3:
            pca = PCA(n_components=3)
            X_plot = pca.fit_transform(X)
        if X.shape[1] < 3:
            X_plot = np.zeros((X.shape[0], 3))
            X_plot[:,:X.shape[1]] = X
        else:
            X_plot = X
        fig3d = plt.figure()
        ax3d = fig3d.add_subplot(111, projection = '3d')#, aspect='equal')
        colorcycler = cycle(colors)
        for c in range(max(labels)+1):
            color = next(colorcycler)
            ax3d.scatter(X_plot[np.array(labels)==c,0], X_plot[np.array(labels)==c,1], 
                         X_plot[np.array(labels)==c,2], s=20, c=color)
        plt.show()

    return labels 
Example 47
Project: OCDVAE_ContinualLearning   Author: MrtnMndt   File: visualization.py    MIT License 5 votes vote down vote up
def visualize_classification_uncertainty(data_mus, data_sigmas, other_data_dicts, other_data_mu_key,
                                         other_data_sigma_key,
                                         data_name, num_samples, save_path):
    """
    Visualization of prediction uncertainty computed over multiple samples for each input.

    Parameters:
        data_mus (list or torch.Tensor): Encoded mu values for trained dataset's validation set.
        data_sigmas (list or torch.Tensor): Encoded sigma values for trained dataset's validation set.
        other_data_dicts (dictionary of dictionaries): A dataset with values per dictionary, among them mus and sigmas
        other_data_mu_key (str): Dictionary key for the mus
        other_data_sigma_key (str): Dictionary key for the sigmas
        data_name (str): Original dataset's name.
        num_samples (int): Number of used samples to obtain prediction values.
        save_path (str): Saving path.
    """

    data_mus = [y for x in data_mus for y in x]
    data_sigmas = [y for x in data_sigmas for y in x]

    plt.figure(figsize=(20, 14))
    plt.scatter(data_mus, data_sigmas, label=data_name, s=75, c=colors[0], alpha=1.0)

    c = 0
    for other_data_name, other_data_dict in other_data_dicts.items():
        other_data_mus = [y for x in other_data_dict[other_data_mu_key] for y in x]
        other_data_sigmas = [y for x in other_data_dict[other_data_sigma_key] for y in x]
        plt.scatter(other_data_mus, other_data_sigmas, label=other_data_name, s=75, c=colors[c], alpha=0.3,
                    marker='*')
        c += 1

    plt.xlabel("Prediction mean", fontsize=axes_font_size)
    plt.ylabel("Prediction standard deviation", fontsize=axes_font_size)
    plt.xlim(left=-0.05, right=1.05)
    plt.ylim(bottom=-0.05, top=0.55)
    plt.legend(loc=1, fontsize=legend_font_size)
    plt.savefig(os.path.join(save_path, data_name + '_vs_' + ",".join(list(other_data_dicts.keys())) +
                             '_classification_uncertainty_' + str(num_samples) + '_samples.pdf'),
                bbox_inches='tight') 
Example 48
Project: EarlyWarning   Author: wjlei1990   File: stats.py    GNU General Public License v3.0 5 votes vote down vote up
def plot_y(train_y, train_y_pred, test_y, test_y_pred):
    plt.figure()
    plt.subplot(1, 2, 1)
    plt.scatter(train_y, train_y_pred, alpha=0.5)
    plt.plot([2, 8], [2, 8])
    #plt.xlim([2.5, 7.5])
    #plt.ylim([2.5, 7.5])
    plt.title("Train")
    plt.subplot(1, 2, 2)
    plt.scatter(test_y, test_y_pred, alpha=0.5)
    plt.plot([2, 8], [2, 8])
    plt.title("Test")
    #plt.xlim([2.5, 7.5])
    #plt.ylim([2.5, 7.5])
    plt.show() 
Example 49
Project: neurips19-graph-protein-design   Author: jingraham   File: protein_features.py    MIT License 5 votes vote down vote up
def _dist(self, X, mask, eps=1E-6):
        """ Pairwise euclidean distances """
        # Convolutional network on NCHW
        mask_2D = torch.unsqueeze(mask,1) * torch.unsqueeze(mask,2)
        dX = torch.unsqueeze(X,1) - torch.unsqueeze(X,2)
        D = mask_2D * torch.sqrt(torch.sum(dX**2, 3) + eps)

        # Identify k nearest neighbors (including self)
        D_max, _ = torch.max(D, -1, keepdim=True)
        D_adjust = D + (1. - mask_2D) * D_max
        D_neighbors, E_idx = torch.topk(D_adjust, self.top_k, dim=-1, largest=False)
        mask_neighbors = gather_edges(mask_2D.unsqueeze(-1), E_idx)

        # Debug plot KNN
        # print(E_idx[:10,:10])
        # D_simple = mask_2D * torch.zeros(D.size()).scatter(-1, E_idx, torch.ones_like(knn_D))
        # print(D_simple)
        # fig = plt.figure(figsize=(4,4))
        # ax = fig.add_subplot(111)
        # D_simple = D.data.numpy()[0,:,:]
        # plt.imshow(D_simple, aspect='equal')
        # plt.axis('off')
        # plt.tight_layout()
        # plt.savefig('D_knn.pdf')
        # exit(0)
        return D_neighbors, E_idx, mask_neighbors 
Example 50
Project: DeepLearningMugenKnock   Author: yoyoyo-yo   File: vae_latent_change2_mnist_pytorch.py    MIT License 5 votes vote down vote up
def test_latent_show():
    device = torch.device("cuda" if GPU else "cpu")
    
    model_encoder = Encoder().to(device)
    model_sampler = Sampler().to(device)
    model_decoder = Decoder().to(device)
    model = torch.nn.Sequential(model_encoder, model_sampler, model_decoder)
    
    model.eval()
    model.load_state_dict(torch.load('cnn.pt'))

    train_x, train_y, test_x, test_y = load_mnist()
    xs = test_x / 255
    xs = xs.transpose(0, 3, 1, 2)

    plt.figure(figsize=[10, 10])
    
    colors = ["red", "blue", "orange", "green", "purple", 
              "magenta", "yellow", "aqua", "black", "khaki"]
    
    for i in range(len(xs)):
        x = xs[i]
        
        x = np.expand_dims(x, axis=0)
        x = torch.tensor(x, dtype=torch.float).to(device)
        
        y = model(x)
        mu = model_encoder.mu
        sigma = model_encoder.sigma
        sample_z = model_sampler.sample_z
        
        mu = mu.detach().cpu().numpy()[0]
        sigma = sigma.detach().cpu().numpy()[0]
        sample_z = sample_z.detach().cpu().numpy()[0]
        
        t = test_y[i]
        
        plt.scatter(sample_z[0], sample_z[1], c=colors[t])
    
    plt.savefig('vae_latent_show.png')
    plt.show()