Python matplotlib.pyplot.stem() Examples

The following are code examples for showing how to use matplotlib.pyplot.stem(). 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: dockerizeme   Author: dockerizeme   File: snippet.py    Apache License 2.0 6 votes vote down vote up
def plot_reconstruction():
    # init
    np.random.seed(42)
    D = generate_dict(n_features=512, n_components=100)
    sparsity = 17
    (indices, x), y = generate_data(D, sparsity)
    pl.subplot(3, 1, 1)
    pl.title("Sparse signal")
    pl.stem(indices, x[indices])
    y_noise = y + np.random.normal(0, 0.05, y.shape)
    
    #x_r, i_r = cholesky_omp(D, y, sparsity)
    x_r, i_r = _batch_omp_step(np.dot(D.T, D), np.dot(D.T,y), sparsity)
    pl.subplot(3, 1, 2)
    pl.title("Recovered signal from noise-free measurements")    
    pl.stem(i_r, x_r)
    
    #x_r, i_r = cholesky_omp(D, y_noise, sparsity)
    x_r, i_r = _batch_omp_step(np.dot(D.T, D), np.dot(D.T,y_noise), sparsity)
    pl.subplot(3, 1, 3)
    pl.title("Recovered signal from noisy measurements")    
    pl.stem(i_r, x_r)
    pl.show() 
Example 2
Project: vnpy_crypto   Author: birforce   File: otherdist.py    MIT License 6 votes vote down vote up
def plot(self, x, *args, **kwds):

        clip_lower, kwds = self._get_clip_lower(kwds)
        mass = self.pdf(clip_lower, *args, **kwds)
        xr = np.concatenate(([clip_lower+1e-6], x[x>clip_lower]))
        import matplotlib.pyplot as plt
        #x = np.linspace(-4, 4, 21)
        #plt.figure()
        plt.xlim(clip_lower-0.1, x.max())
        #remove duplicate calculation
        xpdf = self.pdf(x, *args, **kwds)
        plt.ylim(0, max(mass, xpdf.max())*1.1)
        plt.plot(xr, self.pdf(xr, *args, **kwds))
        #plt.vline(clip_lower, self.pdf(clip_lower, *args, **kwds))
        plt.stem([clip_lower], [mass],
                 linefmt='b-', markerfmt='bo', basefmt='r-')
        return 
Example 3
Project: AcousticsLab   Author: cksajil   File: Designer.py    MIT License 6 votes vote down vote up
def SecondaryPathGraphs(e_iden, Sw, Shw, width = width, height = width/1.618):
	fig3 = plt.figure()
	fig3.subplots_adjust(left=.19, bottom=.17, right=.99, top=.97)

	plt.subplot(2,1,1)
	plt.plot(e_iden[0], label='Identification error')
	plt.ylabel('Amplitude')
	plt.xlabel('Discrete time k')
	plt.legend()

	plt.subplot(2,1,2)
	plt.stem(Sw, markerfmt='o',label='Coefficients of Sz') 
	#plt.stem(Shw[0, :], markerfmt='*',label='Coefficients of Shz')
	plt.stem(Shw, markerfmt='*',label='Coefficients of Shz')
	plt.ylabel('Amplitude');
	plt.xlabel('Numbering of filter tap');
	plt.legend()
	plt.show()

	# fig3.set_size_inches(width, height)
	# fig3.savefig('SecondaryPathDetails.pdf') 
Example 4
Project: delira   Author: delira-dev   File: base_backend.py    BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _stem(self, plot_kwargs=None, figure_kwargs=None, **kwargs):
        """
        Function to create a stem plot and push it

        Parameters
        ----------
        plot_kwargs : dict
            the arguments for plotting
        figure_kwargs : dict
            the arguments to actually create the figure
        **kwargs :
            additional keyword arguments for pushing the created figure to the
            logging writer

        """
        if figure_kwargs is None:
            figure_kwargs = {}
        if plot_kwargs is None:
            plot_kwargs = {}
        with self.FigureManager(self._figure, figure_kwargs, kwargs):
            from matplotlib.pyplot import stem
            stem(**plot_kwargs) 
Example 5
Project: Splunking-Crime   Author: nccgroup   File: otherdist.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def plot(self, x, *args, **kwds):

        clip_lower, kwds = self._get_clip_lower(kwds)
        mass = self.pdf(clip_lower, *args, **kwds)
        xr = np.concatenate(([clip_lower+1e-6], x[x>clip_lower]))
        import matplotlib.pyplot as plt
        #x = np.linspace(-4, 4, 21)
        #plt.figure()
        plt.xlim(clip_lower-0.1, x.max())
        #remove duplicate calculation
        xpdf = self.pdf(x, *args, **kwds)
        plt.ylim(0, max(mass, xpdf.max())*1.1)
        plt.plot(xr, self.pdf(xr, *args, **kwds))
        #plt.vline(clip_lower, self.pdf(clip_lower, *args, **kwds))
        plt.stem([clip_lower], [mass],
                 linefmt='b-', markerfmt='bo', basefmt='r-')
        return 
Example 6
Project: PoPPy   Author: HongtengXu   File: ExogenousIntensity.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def plot_and_save(self, mu_all: torch.Tensor, output_name: str = None):
        """
        Plot the stem plot of exogenous intensity functions for all event types
        Args:
        :param mu_all: a (num_type, 1) FloatTensor containing all exogenous intensity functions
        :param output_name: the name of the output png file
        """
        mu_all = mu_all.squeeze(1)  # (C,)
        mu_all = mu_all.data.cpu().numpy()

        plt.figure(figsize=(5, 5))
        plt.stem(range(mu_all.shape[0]), mu_all, '-')
        plt.ylabel('Exogenous intensity')
        plt.xlabel('Index of event type')
        if output_name is None:
            plt.savefig('exogenous_intensity.png')
        else:
            plt.savefig(output_name)
        plt.close("all")
        logger.info("Done!") 
Example 7
Project: DOTA_models   Author: ringringyi   File: plot_lfads.py    Apache License 2.0 5 votes vote down vote up
def _plot_item(W, name, full_name, nspaces):
  plt.figure()
  if W.shape == ():
    print(name, ": ", W)
  elif W.shape[0] == 1:
    plt.stem(W.T)
    plt.title(full_name)
  elif W.shape[1] == 1:
    plt.stem(W)
    plt.title(full_name)
  else:
    plt.imshow(np.abs(W), interpolation='nearest', cmap='jet');
    plt.colorbar()
    plt.title(full_name) 
Example 8
Project: DOTA_models   Author: ringringyi   File: plot_lfads.py    Apache License 2.0 5 votes vote down vote up
def plot_priors():
  g0s_prior_mean_bxn = train_modelvals['prior_g0_mean']
  g0s_prior_var_bxn = train_modelvals['prior_g0_var']
  g0s_post_mean_bxn = train_modelvals['posterior_g0_mean']
  g0s_post_var_bxn = train_modelvals['posterior_g0_var']

  plt.figure(figsize=(10,4), tight_layout=True);
  plt.subplot(1,2,1)
  plt.hist(g0s_post_mean_bxn.flatten(), bins=20, color='b');
  plt.hist(g0s_prior_mean_bxn.flatten(), bins=20, color='g');

  plt.title('Histogram of Prior/Posterior Mean Values')
  plt.subplot(1,2,2)
  plt.hist((g0s_post_var_bxn.flatten()), bins=20, color='b');
  plt.hist((g0s_prior_var_bxn.flatten()), bins=20, color='g');
  plt.title('Histogram of Prior/Posterior Log Variance Values')

  plt.figure(figsize=(10,10), tight_layout=True)
  plt.subplot(2,2,1)
  plt.imshow(g0s_prior_mean_bxn.T, interpolation='nearest', cmap='jet')
  plt.colorbar(fraction=0.025, pad=0.04)
  plt.title('Prior g0 means')

  plt.subplot(2,2,2)
  plt.imshow(g0s_post_mean_bxn.T, interpolation='nearest', cmap='jet')
  plt.colorbar(fraction=0.025, pad=0.04)
  plt.title('Posterior g0 means');

  plt.subplot(2,2,3)
  plt.imshow(g0s_prior_var_bxn.T, interpolation='nearest', cmap='jet')
  plt.colorbar(fraction=0.025, pad=0.04)
  plt.title('Prior g0 variance Values')

  plt.subplot(2,2,4)
  plt.imshow(g0s_post_var_bxn.T, interpolation='nearest', cmap='jet')
  plt.colorbar(fraction=0.025, pad=0.04)
  plt.title('Posterior g0 variance Values')

  plt.figure(figsize=(10,5))
  plt.stem(np.sort(np.log(g0s_post_mean_bxn.std(axis=0))));
  plt.title('Log standard deviation of h0 means'); 
Example 9
Project: dragonphy   Author: StanfordVLSI   File: demo_cmp5.py    Apache License 2.0 5 votes vote down vote up
def plot_adapt_input(codes, chan_out, n, plt_mode='normal'):
    if plt_mode == 'stem':
        plt.stem(codes[:n], markerfmt='C0o', basefmt='C0-')
        plt.stem(chan_out[:n], markerfmt='C1o', basefmt='C1-')
    else:
        plt.plot(codes[:n], 'o-')
        plt.plot(chan_out[:n], 'o-')
    plt.show() 
Example 10
Project: dragonphy   Author: StanfordVLSI   File: verif_cmp.py    Apache License 2.0 5 votes vote down vote up
def plot_adapt_input(codes, chan_out, n, plt_mode='normal'):
    if plt_mode == 'stem':
        plt.stem(codes[:n], markerfmt='C0o', basefmt='C0-')
        plt.stem(chan_out[:n], markerfmt='C1o', basefmt='C1-')
    else:
        plt.plot(codes[:n], 'o-')
        plt.plot(chan_out[:n], 'o-')
    plt.show() 
Example 11
Project: dragonphy   Author: StanfordVLSI   File: demo_cmp7.py    Apache License 2.0 5 votes vote down vote up
def plot_adapt_input(codes, chan_out, n, plt_mode='normal'):
    if plt_mode == 'stem':
        plt.stem(codes[:n], markerfmt='C0o', basefmt='C0-')
        plt.stem(chan_out[:n], markerfmt='C1o', basefmt='C1-')
    else:
        plt.plot(codes[:n], 'o-')
        plt.plot(chan_out[:n], 'o-')
    plt.show() 
Example 12
Project: dragonphy   Author: StanfordVLSI   File: demo_cmp3.py    Apache License 2.0 5 votes vote down vote up
def plot_adapt_input(codes, chan_out, n, plt_mode='normal'):
    if plt_mode == 'stem':
        plt.stem(codes[:n], markerfmt='C0o', basefmt='C0-')
        plt.stem(chan_out[:n], markerfmt='C1o', basefmt='C1-')
    else:
        plt.plot(codes[:n], 'o-')
        plt.plot(chan_out[:n], 'o-')
    plt.show() 
Example 13
Project: dragonphy   Author: StanfordVLSI   File: demo_cmp6.py    Apache License 2.0 5 votes vote down vote up
def plot_adapt_input(codes, chan_out, n, plt_mode='normal'):
    if plt_mode == 'stem':
        plt.stem(codes[:n], markerfmt='C0o', basefmt='C0-')
        plt.stem(chan_out[:n], markerfmt='C1o', basefmt='C1-')
    else:
        plt.plot(codes[:n], 'o-')
        plt.plot(chan_out[:n], 'o-')
    plt.show() 
Example 14
Project: SyntheticStatistics   Author: BlissChapman   File: tst.py    MIT License 5 votes vote down vote up
def visual_test(self, tst_data):
        results = self.perform_test(tst_data)
        s = results['test_stat']
        pval = results['pvalue']
        J = self.test_locs.shape[0]
        domain = np.linspace(stats.chi2.ppf(0.001, J), stats.chi2.ppf(0.9999, J), 200)
        plt.plot(domain, stats.chi2.pdf(domain, J), label='$\chi^2$ (df=%d)'%J)
        plt.stem([s], [old_div(stats.chi2.pdf(J, J),2)], 'or-', label='test stat')
        plt.legend(loc='best', frameon=True)
        plt.title('%s. p-val: %.3g. stat: %.3g'%(type(self).__name__, pval, s))
        plt.show()

    #=============================== 
Example 15
Project: FaceJam   Author: ctralie   File: ExpressionsModel.py    Apache License 2.0 5 votes vote down vote up
def getFaceModel(n_components=10, doPlot = False):
    allkeypts = sio.loadmat("allkeypts.mat")["allkeypts"]
    Y = allkeypts[0, :, :].T
    
    ## Step 1: Do procrustes to align all frames to first frame
    for i in range(1, allkeypts.shape[0]):
        X = allkeypts[i, :, :].T
        Cx, Cy, R = getProcrustesAlignment(X[:, 0:-4], Y[:, 0:-4], np.arange(X.shape[1]-4))
        XNew = X - Cx
        XNew = R.dot(XNew)
        XNew += Cy
        XNew[:, -4::] = Y[:, -4::]
        allkeypts[i, :, :] = XNew.T
    
    ## Step 2: Now do PCA on the keypoints
    X = np.reshape(allkeypts, (allkeypts.shape[0], allkeypts.shape[1]*allkeypts.shape[2]))
    XC = np.mean(X, 0)[None, :]
    X -= XC
    pca = PCA(n_components=n_components)
    pca.fit(X)
    P = pca.components_.T
    sv = np.sqrt(pca.singular_values_)

    face = MorphableFace("MyExpressions_InitialFrame.jpg")
    if doPlot:
        plt.subplot(141)
        plt.stem(sv)
        plt.title("Principal Component Standard Deviation")
        for k in range(3):
            Y = XC + sv[k]*P[:, k]
            XKey2 = np.reshape(Y, (allkeypts.shape[1], allkeypts.shape[2]))
            plt.subplot(1, 4, k+2)
            img = face.getForwardMap(XKey2)
            plt.imshow(img)
            plt.title("Principal Component %i"%k)
        plt.show()
    
    return (face, XC.flatten(), P, sv) 
Example 16
Project: AlisonProject   Author: VincentErb   File: test_nmf.py    GNU General Public License v3.0 5 votes vote down vote up
def test_sound_recognition_v2():
    files = [
        "samples/Sonnette/sonnette", "samples/Fire_Alarm/fire_alarm",
        "samples/Phone_Ring/phone"
    ]

    dico = np.zeros([513, 0])
    print(dico.shape)

    for file in files:
        stft = np.zeros([513, 0])

        for i in range(1, 5):
            rate, signal = wav.read(file + str(i) + ".wav")
            stft = np.concatenate((stft, spectrum.get_stft(signal / 1.0)),
                                  axis=1)

        dico_plus, _ = get_nmf(stft, 3)
        dico = np.concatenate((dico, dico_plus), axis=1)

    for file in files:
        rate2, signal2 = wav.read(file + "5.wav")
        stft2 = spectrum.get_stft(signal2 * 1.0)
        activations = get_activations(stft2, dico, 3)

        plt.clf()

        for i in range(0, 9):
            plt.subplot(3, 3, i + 1)
            plt.title("Ligne " + str(i))
            plt.stem(activations[i, :])

        plt.show() 
Example 17
Project: AlisonProject   Author: VincentErb   File: test_nmf.py    GNU General Public License v3.0 5 votes vote down vote up
def demo_nmf():
    """
    Show main components from nmf decomposition of an example sound
    """

    # D = get_dictionnary(0).components_
    # print(D.shape)

    rate, signal = wav.read("samples/door-bell01.wav")
    stft = spectrum.get_stft(signal[:, 0] / 1.0)
    components, activation = dcp.decompose(stft)

    i = 0
    # first frame spectrum
    spectrum = stft[:, i]
    # first frame component activation
    line = activation[:, i]

    # Extract spectrum for the 4 strongest activation on the first frame
    ind = np.argsort(line)[-4:]
    maincomps = components[:, ind]

    # Plot
    plt.figure(figsize=(7, 7))

    plt.subplot(6, 1, 1)
    plt.title("Spectrum")
    plt.stem(spectrum)

    plt.subplot(6, 1, 2)
    plt.title("Components")
    plt.stem(line)

    for n in range(4):
        plt.subplot(6, 1, n + 3)
        plt.stem(maincomps[:, n])

    plt.show() 
Example 18
Project: AlisonProject   Author: VincentErb   File: __init__.py    GNU General Public License v3.0 5 votes vote down vote up
def plot_dictionary(recognizer):
    import matplotlib.pyplot as plt

    plt.figure(figsize=(7, 7))
    sizex = recognizer.components_per_tag
    sizey = recognizer.dictionary.shape[1] / sizex

    for i in range(0, recognizer.dictionary.shape[1]):
        plt.subplot(sizey, sizex, i + 1)
        plt.stem(recognizer.dictionary[:, i])

    plt.show() 
Example 19
Project: AlisonProject   Author: VincentErb   File: __init__.py    GNU General Public License v3.0 5 votes vote down vote up
def plot_nmf_results(recognizer):
    import matplotlib.pyplot as plt

    plt.figure(figsize=(7, 7))

    for i in range(0, recognizer.current_nmf_results.shape[0]):
        plt.subplot(6, 4, i + 1)
        plt.stem(recognizer.current_nmf_results[i, :])

    plt.show() 
Example 20
Project: dmdtools   Author: cwrowley   File: streaming_dmd_example.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def main(streaming):
    modes, evals = streaming_dmd() if streaming else standard_dmd()
    fdmd = np.abs(np.angle(evals)) / (2 * np.pi * dt)
    n_modes = len(fdmd)
    ydmd = np.zeros(n_modes)
    for i in range(n_modes):
        ydmd[i] = np.linalg.norm(modes[:, i] * np.abs(evals[i]))
    ydmd /= max(ydmd)
    plt.stem(fdmd, ydmd)
    plt.show() 
Example 21
Project: hands-detection   Author: loicmarie   File: plot_lfads.py    MIT License 5 votes vote down vote up
def _plot_item(W, name, full_name, nspaces):
  plt.figure()
  if W.shape == ():
    print(name, ": ", W)
  elif W.shape[0] == 1:
    plt.stem(W.T)
    plt.title(full_name)
  elif W.shape[1] == 1:
    plt.stem(W)
    plt.title(full_name)
  else:
    plt.imshow(np.abs(W), interpolation='nearest', cmap='jet');
    plt.colorbar()
    plt.title(full_name) 
Example 22
Project: hands-detection   Author: loicmarie   File: plot_lfads.py    MIT License 5 votes vote down vote up
def plot_priors():
  g0s_prior_mean_bxn = train_modelvals['prior_g0_mean']
  g0s_prior_var_bxn = train_modelvals['prior_g0_var']
  g0s_post_mean_bxn = train_modelvals['posterior_g0_mean']
  g0s_post_var_bxn = train_modelvals['posterior_g0_var']

  plt.figure(figsize=(10,4), tight_layout=True);
  plt.subplot(1,2,1)
  plt.hist(g0s_post_mean_bxn.flatten(), bins=20, color='b');
  plt.hist(g0s_prior_mean_bxn.flatten(), bins=20, color='g');

  plt.title('Histogram of Prior/Posterior Mean Values')
  plt.subplot(1,2,2)
  plt.hist((g0s_post_var_bxn.flatten()), bins=20, color='b');
  plt.hist((g0s_prior_var_bxn.flatten()), bins=20, color='g');
  plt.title('Histogram of Prior/Posterior Log Variance Values')

  plt.figure(figsize=(10,10), tight_layout=True)
  plt.subplot(2,2,1)
  plt.imshow(g0s_prior_mean_bxn.T, interpolation='nearest', cmap='jet')
  plt.colorbar(fraction=0.025, pad=0.04)
  plt.title('Prior g0 means')

  plt.subplot(2,2,2)
  plt.imshow(g0s_post_mean_bxn.T, interpolation='nearest', cmap='jet')
  plt.colorbar(fraction=0.025, pad=0.04)
  plt.title('Posterior g0 means');

  plt.subplot(2,2,3)
  plt.imshow(g0s_prior_var_bxn.T, interpolation='nearest', cmap='jet')
  plt.colorbar(fraction=0.025, pad=0.04)
  plt.title('Prior g0 variance Values')

  plt.subplot(2,2,4)
  plt.imshow(g0s_post_var_bxn.T, interpolation='nearest', cmap='jet')
  plt.colorbar(fraction=0.025, pad=0.04)
  plt.title('Posterior g0 variance Values')

  plt.figure(figsize=(10,5))
  plt.stem(np.sort(np.log(g0s_post_mean_bxn.std(axis=0))));
  plt.title('Log standard deviation of h0 means'); 
Example 23
Project: object_detection_kitti   Author: sshleifer   File: plot_lfads.py    Apache License 2.0 5 votes vote down vote up
def _plot_item(W, name, full_name, nspaces):
  plt.figure()
  if W.shape == ():
    print(name, ": ", W)
  elif W.shape[0] == 1:
    plt.stem(W.T)
    plt.title(full_name)
  elif W.shape[1] == 1:
    plt.stem(W)
    plt.title(full_name)
  else:
    plt.imshow(np.abs(W), interpolation='nearest', cmap='jet');
    plt.colorbar()
    plt.title(full_name) 
Example 24
Project: basic-image-editor   Author: shyama95   File: main.py    GNU General Public License v3.0 5 votes vote down vote up
def view_histogram(self):
        # count the no of values corresponding to each value in the V channel of
        # image matrix give a minimum length of 256 to the counting to ensure all 256 pixel
        # values are covered or pixel values not available in image are set to zero
        histogram = np.bincount(self.currentImage[:, :, 2].ravel(), minlength=256)
        # start a new figure to show histogram - assign title and axes label
        plt.figure(num='Image Histogram')
        # assign a discrete plot of histogram to figure
        plt.stem(histogram)
        plt.xlabel('Intensity levels')
        plt.ylabel('No. of pixels')
        # show the stem plot
        plt.show() 
Example 25
Project: imips_open   Author: uzh-rpg   File: plot_analysis.py    GNU General Public License v3.0 4 votes vote down vote up
def main(_):

    print('\n\n%s\n\n' % hyperparams.shortString())

    _, _, stats, _, _ = cache.getOrEval()

    frequencies = np.zeros(128)
    for i in range(128):
        frequencies[i] = np.mean(stats[stats[:, 0] == i, 2])

    # Inlierness over channel
    plt.figure(0, figsize=[5, 2.5])
    plt.stem(frequencies)
    plt.xlabel('Channel #')
    plt.ylim(ymin=0)
    plt.ylabel('Inlier frequency')
    plt.tight_layout()
    ax = plt.axes()
    ax.yaxis.grid()
    plt.show()

    # Inlierness VS prediction
    num_bins = 20
    bins = [[] for _ in range(num_bins)]
    for row in range(stats.shape[0]):
        index = int(stats[row, 1] * num_bins)
        bins[index].append(stats[row, 2])

    bin_frequencies = np.array([np.mean(bin_) for bin_ in bins])

    counts = np.array([len(bin_) for bin_ in bins])

    bin_width = float(1) / num_bins

    fig, ax1 = plt.subplots(figsize=[5, 2.5])
    ax1.hlines(bin_frequencies, bin_width * np.arange(num_bins),
               bin_width * (np.arange(num_bins) + 1), colors='red', linewidth=3)
    ax1.set_xlabel('Response')
    ax1.set_ylabel('Inlierness frequency', color='r')
    ax1.grid()
    ax1.set_xlim([0, 1])

    ax2 = ax1.twinx()
    ax2.set_ylabel('# points with given prediction', color='b')
    ax2.stem(bin_width * (np.arange(num_bins) + 0.5), counts, color='b',
             basefmt='')
    print(counts)
    ax2.set_ylim(bottom=0)
    ax1.set_ylim(bottom=0)
    plt.tight_layout()

    plt.show() 
Example 26
Project: Speaker-Recognition   Author: orchidas   File: train.py    MIT License 4 votes vote down vote up
def training(nfiltbank, orderLPC):
    nSpeaker = 8
    nCentroid = 16
    codebooks_mfcc = np.empty((nSpeaker,nfiltbank,nCentroid))
    codebooks_lpc = np.empty((nSpeaker, orderLPC, nCentroid))
    directory = os.getcwd() + '/train';
    fname = str()

    for i in range(nSpeaker):
        fname = '/s' + str(i+1) + '.wav'
        print('Now speaker ', str(i+1), 'features are being trained' )
        (fs,s) = read(directory + fname)
        mel_coeff = mfcc(s, fs, nfiltbank)
        lpc_coeff = lpc(s, fs, orderLPC)
        codebooks_mfcc[i,:,:] = lbg(mel_coeff, nCentroid)
        codebooks_lpc[i,:,:] = lbg(lpc_coeff, nCentroid)
        
        plt.figure(i)
        plt.title('Codebook for speaker ' + str(i+1) + ' with ' + str(nCentroid) +  ' centroids')
        for j in range(nCentroid):
            plt.subplot(211)
            plt.stem(codebooks_mfcc[i,:,j])
            plt.ylabel('MFCC')
            plt.subplot(212)
            markerline, stemlines, baseline = plt.stem(codebooks_lpc[i,:,j])
            plt.setp(markerline,'markerfacecolor','r')
            plt.setp(baseline,'color', 'k')
            plt.ylabel('LPC')
            plt.axis(ymin = -1, ymax = 1)
            plt.xlabel('Number of features')
    
    plt.show()
    print('Training complete')
    
    #plotting 5th and 6th dimension MFCC features on a 2D plane
    #comment lines 54 to 71 if you don't want to see codebook
    codebooks = np.empty((2, nfiltbank, nCentroid))
    mel_coeff = np.empty((2, nfiltbank, 68))
   
    for i in range(2):
        fname = '/s' + str(i+2) + '.wav'
        (fs,s) = read(directory + fname)
        mel_coeff[i,:,:] = mfcc(s, fs, nfiltbank)[:,0:68]
        codebooks[i,:,:] = lbg(mel_coeff[i,:,:], nCentroid)
        
    
    plt.figure(nSpeaker + 1)
    s1 = plt.scatter(mel_coeff[0,6,:], mel_coeff[0,4,:],s = 100,  color = 'r', marker = 'o')
    c1 = plt.scatter(codebooks[0,6,:], codebooks[0,4,:], s = 100, color = 'r', marker = '+')
    s2 = plt.scatter(mel_coeff[1,6,:], mel_coeff[1,4,:],s = 100,  color = 'b', marker = 'o')
    c2 = plt.scatter(codebooks[1,6,:], codebooks[1,4,:], s = 100, color = 'b', marker = '+')
    plt.grid()
    plt.legend((s1, s2, c1, c2), ('Sp1','Sp2','Sp1 centroids', 'Sp2 centroids'), scatterpoints = 1, loc = 'upper left')    
    plt.show()
   
    
    return (codebooks_mfcc, codebooks_lpc) 
Example 27
Project: jamespy_py3   Author: jskDr   File: kcell.py    MIT License 4 votes vote down vote up
def show_both( self, c):
		X1part = self.X1part
		X2part = self.X2part
		y = self.y
		cell = self.cell
		X1_ylim = self.X1_ylim
		X2_ylim = self.X2_ylim
		cmethod = self.cmethod
		cparam_d = self.cparam_d

		#print("Cluster:", c)
		X3_int = X2part[ np.where(y==c)[0],:]
		X3_vel = X1part[ np.where(y==c)[0],:]
		
		#km = cluster.KMeans(2)
		#km = getattr(cluster, cmethod)(2)
		km = getattr(cluster, cmethod)(**cparam_d)
		y3 = km.fit_predict( X3_int)

		plt.figure(figsize=(9,4))
		plt.subplot(1,2,1)
		#print("Intensity")
		n_0 = X3_int[ np.where( y3==0)[0]].shape[0]
		n_1 = X3_int[ np.where( y3==1)[0]].shape[0]

		sns.tsplot( X3_int[ np.where( y3==0)[0],:], color="blue")
		sns.tsplot( X3_int[ np.where( y3==1)[0],:], color="green")
		plt.ylim(X2_ylim)
		plt.title("Cluster{0}:X2 {1}:{2}".format(c, n_0, n_1))
		#plt.show()

		plt.subplot(1,2,2)
		#print("Velocity")
		sns.tsplot( X3_vel[ np.where( y3==0)[0],:], color="blue")
		sns.tsplot( X3_vel[ np.where( y3==1)[0],:], color="green")
		plt.ylim(X1_ylim)
		plt.title("Cluster{0}:X1 {1}:{2}".format(c, n_0, n_1))
		plt.show()
		
		cell3 = cell[ np.where(y==c)[0]]
		plt.subplot(1,2,1)
		plt.stem( cell3[np.where( y3==0)[0]], linefmt='b-', markerfmt='bo')
		plt.title("Cell Index - Subcluster 1")
		plt.subplot(1,2,2)
		plt.stem( cell3[np.where( y3==1)[0]], linefmt='g-', markerfmt='go')   
		plt.title("Cell Index - Subcluster 2")
		plt.show()
		
		return y3 
Example 28
Project: jamespy_py3   Author: jskDr   File: kcell.py    MIT License 4 votes vote down vote up
def show_both( self, c):
		X1part = self.X1part
		X2part = self.X2part
		y = self.y
		cell = self.cell
		X1_ylim = self.X1_ylim
		X2_ylim = self.X2_ylim
		cmethod = self.cmethod
		cparam_d = self.cparam_d

		#print("Cluster:", c)
		X3_int = X2part[ np.where(y==c)[0],:]
		X3_vel = X1part[ np.where(y==c)[0],:]
		
		#km = cluster.KMeans(2)
		#km = getattr(cluster, cmethod)(2)
		km = getattr(cluster, cmethod)(**cparam_d)
		y3 = km.fit_predict( X3_int)

		plt.figure(figsize=(9,4))
		plt.subplot(1,2,1)
		#print("Intensity")
		n_0 = X3_int[ np.where( y3==0)[0]].shape[0]
		n_1 = X3_int[ np.where( y3==1)[0]].shape[0]

		sns.tsplot( X3_int[ np.where( y3==0)[0],:], color="blue")
		sns.tsplot( X3_int[ np.where( y3==1)[0],:], color="green")
		plt.ylim(X2_ylim)
		plt.title("Cluster{0}:X2 {1}:{2}".format(c, n_0, n_1))
		#plt.show()

		plt.subplot(1,2,2)
		#print("Velocity")
		sns.tsplot( X3_vel[ np.where( y3==0)[0],:], color="blue")
		sns.tsplot( X3_vel[ np.where( y3==1)[0],:], color="green")
		plt.ylim(X1_ylim)
		plt.title("Cluster{0}:X1 {1}:{2}".format(c, n_0, n_1))
		plt.show()
		
		cell3 = cell[ np.where(y==c)[0]]
		plt.subplot(1,2,1)
		plt.stem( cell3[np.where( y3==0)[0]], linefmt='b-', markerfmt='bo')
		plt.title("Cell Index - Subcluster 1")
		plt.subplot(1,2,2)
		plt.stem( cell3[np.where( y3==1)[0]], linefmt='g-', markerfmt='go')   
		plt.title("Cell Index - Subcluster 2")
		plt.show()
		
		return y3 
Example 29
Project: hemolearn   Author: hcherkaoui   File: plotting.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def plotting_temporal_comp(z, variances, t_r, onset=False, plot_dir='.',
                           fname=None, aux_plots=None, aux_plots_kwargs=dict(),
                           verbose=False):
    """ Plot, and save as pdf, each temporal estimated component.

    Parameters
    ----------
    z : array, shape (n_atoms, n_times_valid), the temporal components
    variances : array, shape (n_atoms, ) the order variances for each
        components
    t_r : float, Time of Repetition, fMRI acquisition parameter, the temporal
        resolution
    onset : bool, (default=False), whether or not to plot the first order
        derivative of z
    plot_dir : str, (default='.'), directory under which the pdf is saved
    fname : str, (default='z.pdf'), filename under which the pdf is saved
    aux_plots : func, to plot a additional features on the figure
    aux_plots_kwargs : dict, keywords arguments for the aux_plots func
    verbose : bool, (default=False), verbosity level
    """
    n_atoms, n_times_valid = z.shape
    if onset:
        plt.figure("Onset Temporal atoms", figsize=(8, 5 * n_atoms))
    else:
        plt.figure("Temporal atoms", figsize=(8, 5 * n_atoms))
    _xticks = [0, int(n_times_valid / 2.0), int(n_times_valid)]
    _xticks_labels = [
        0,
        time.strftime("%Mm%Ss", time.gmtime(int(t_r * n_times_valid / 2.0))),
        time.strftime("%Mm%Ss", time.gmtime(int(t_r * n_times_valid)))
        ]
    for k in range(1, n_atoms + 1):
        expl_var = variances[k - 1]
        z_k = z[k - 1, :].T
        plt.subplot(n_atoms, 1, k)
        if onset:
            plt.stem(np.diff(z_k))
            if fname is None:
                fname = "Dz.pdf"
        else:
            plt.plot(z_k, lw=2.0)
            if fname is None:
                fname = "z.pdf"
        plt.axhline(0.0, color='black', lw=2.0)
        if aux_plots is not None:
            aux_plots(**aux_plots_kwargs)
        plt.title("Atom-{} (explained variance = {:.2e})".format(k, expl_var),
                  fontsize=20)
        plt.xlabel("Time", fontsize=20)
        plt.ylabel("Signal change [%]", fontsize=20)
        plt.xticks(_xticks, _xticks_labels, fontsize=20)
        plt.yticks([np.min(z_k), 0, np.max(z_k)], fontsize=20)
        plt.grid()
    plt.tight_layout()
    filename = os.path.join(plot_dir, fname)
    if verbose:
        print("Saving plot under '{0}'".format(filename))
    plt.savefig(filename, dpi=150)