def plot_gaze_data(sample_df_filt, fig_path, subj_id, session_n, reward_code, id_str=None, fig_name='test', display_resolution=(1280, 1024)): from jupyterthemes import jtplot plt.rcParams['pdf.fonttype'] = 42 plt.rcParams['font.family'] = 'Calibri' jtplot.style(context='poster', fscale=2, spines=False, theme='grade3') sns.set_context('poster', font_scale=2) sns.set_color_codes("muted") max_gaze_x, max_gaze_y = display_resolution fig_name = ('gaze_map' + '_sub-' + str(subj_id) + '_sess-' + str(session_n) + '_cond-' + str(reward_code)) if id_str: fig_name = fig_name + '_' + id_str fig = plt.figure() plt.plot(sample_df.gaze_x, sample_df.gaze_y, '.') plt.xlim([0, max_gaze_x]) plt.ylim( [max_gaze_y, 0] ) # ensure that the screen coordinate system is accurate represented (origin at upper left) center_x_dist = display_resolution[ 0] / 5 # as specified in experimental code center_x, center_y = (max_gaze_x / 2, max_gaze_y / 2) target_y = center_y + 15 # as specified in experimental code left_target_x, left_target_y = center_x - center_x_dist, target_y right_target_x, right_target_y = center_x + center_x_dist, target_y marker_size = 3000 plt.scatter(center_x, center_y, color='gray', marker='+', s=marker_size) plt.scatter(left_target_x, left_target_y, color='purple', marker='d', s=marker_size) plt.scatter(right_target_x, right_target_y, color='purple', marker='d', s=marker_size) if fig_name: plt.savefig(os.path.join(fig_path, fig_name + '.png')) return fig, fig_name
def gruvbox_style(pallete="higher_contrast"): """Set the current plotting style to gruvbox with higher contrast pallete """ palletes = { "higher_contrast": [ '#3572C6', '#83a83b', '#c44e52', '#d5c4a1', '#8172b2', '#b57614', '#8ec07c', '#ff711a', '#d3869b', '#6C7A89', '#77BEDB', '#4168B7', '#27ae60', '#e74c3c', '#ff914d', '#bc89e0', '#3498db', '#fabd2f', '#fb4934', '#b16286', '#83a598', '#fe8019', '#b8bb26', '#a89984' ], "bright": [ '#77BEDB', '#fb4934', '#8ec07c', '#ff914d', '#bc89e0', '#fabd2f', '#fbf1c7', '#3498db' ], "paired": [ '#77BEDB', '#4168B7', '#8ec07c', '#b8bb26', '#d3869b', '#fb4934', '#bdae93', '#ebdbb2' ] } new_cycler = cycler.cycler("color", palletes[pallete]) jtplot.style(theme='gruvboxd', context='notebook', figsize=style.figsize) mpl.rcParams["axes.prop_cycle"] = new_cycler mpl.rcParams["axes.axisbelow"] = True style.minor_grid_color = "#32302f" style.current_style = "gruvbox"
def visualize(x,y, subj_id, session_n, reward_code, stimulus_onset=500, trial_end=2000, interval_end=4000, id_str=None, estimator=np.mean): """ Visualize the trial-averaged task-evoked pupillary response. """ from jupyterthemes import jtplot plt.rcParams['pdf.fonttype'] = 42 plt.rcParams['font.family'] = 'Calibri' fig_name = ('tepr' + '_sub-' + str(subj_id) + '_sess-' + str(session_n) + '_cond-' + str(reward_code)) if id_str: fig_name = fig_name + '_' + id_str jtplot.style(context='poster', fscale=2, spines=False, theme='grade3') sns.set_context('poster', font_scale=2) sns.set_color_codes("muted") fig = plt.figure() sns.lineplot(x, y, estimator=estimator) plt.axvline(x=stimulus_onset, linestyle='dashed', color='k') # plt.axvline(x=trial_end, linestyle='dashed', color='k') plt.xlabel('time from stimulus onset (ms)'); plt.ylabel('pupil diameter (a.u.)') # plt.title(fig_name) plt.xticks(np.arange(0, interval_end+stimulus_onset, stimulus_onset), np.arange(-1*stimulus_onset, interval_end, stimulus_onset)) plt.xlim([0, trial_end]) # plt.ylim([3000, 10000]) return fig, fig_name
def plot_evoked_response_map(ordered_samples_df, ordered_message_df, fig_name, fig_path, trial_end_sample_idx=1500): """call signature: _, samples_pivot = plot_evoked_response_map(sample_df, message_df, fig_name='trial_ordered_evoked_responses') _= plot_evoked_response_map(rt_ordered_samples_df, rt_ordered_msg_df, fig_name='RT_ordered_evoked_responses') _= plot_evoked_response_map(random_ordered_samples_df, random_ordered_msg_df, fig_name='random_ordered_evoked_responses') """ n_trials = len(ordered_samples_df.trial_epoch.unique()) jtplot.style('grade3', context='poster', fscale=1.4, spines=False, gridlines='--') ordered_samples_df = ordered_samples_df.loc[ ordered_samples_df.trial_sample < trial_end_sample_idx] samples_sparse = ordered_samples_df[[ 'trial_sample', 'trial_epoch', 'z_pupil_diameter' ]] samples_sparse['reset_trial_epoch_idx'] = np.repeat( np.arange(0, n_trials), trial_end_sample_idx) # hack to get pivot to respect the stated order of the trial epochs # otherwise, will sort the index ... samples_pivot = samples_sparse.pivot(index='reset_trial_epoch_idx', columns='trial_sample', values='z_pupil_diameter') plt.ioff() plt.figure(1) fig, ax = plt.subplots(figsize=(10, 10)) sns.heatmap(samples_pivot, fmt="g", cmap='viridis', cbar_kws={'label': 'pupil diameter'}, robust=True, vmin=0, vmax=2) ax.scatter(x=ordered_message_df.trial_response_time, y=range(n_trials), marker='.', color='white', s=30) plt.title(fig_name) plt.ylabel('trial') plt.savefig(os.path.join(fig_path, fig_name + '.png')) plt.close() return fig_name, samples_pivot
def plot_config(theme='grade3', context='poster', fscale=1.4, spines=False, gridlines='--'): """Configure plots.""" jtplot.style(theme=theme, context=context, fscale=fscale, spines=spines, gridlines=gridlines) return None
def init_mpl(): import matplotlib as mpl from jupyterthemes import jtplot jtplot.style(theme='monokai', context='notebook', ticks=True, grid=True) colors = mpl.rcParams['axes.prop_cycle'].by_key()['color'] i = 6 colors[i] = hex(int(colors[i].replace('#', '0x'), 16) ^ 0xFFFFFF).replace('0x', '#') mpl.rcParams['axes.prop_cycle'] = mpl.cycler(color=colors) mpl.rcParams['path.simplify'] = True mpl.rcParams['path.simplify_threshold'] = 1 mpl.rcParams['agg.path.chunksize'] = 100000
def _create_figure(self): # the following import is here in order to avoid a circular import error from spb.defaults import cfg use_jupyterthemes = cfg["matplotlib"]["use_jupyterthemes"] mpl_jupytertheme = cfg["matplotlib"]["jupytertheme"] if (self._get_mode() == 0) and use_jupyterthemes: # set matplotlib style to match the used Jupyter theme try: from jupyterthemes import jtplot jtplot.style(mpl_jupytertheme) except: pass is_3Dvector = any([s.is_3Dvector for s in self.series]) aspect = self.aspect if aspect != "auto": if aspect == "equal" and is_3Dvector: # vector_plot uses an aspect="equal" by default. In that case # we would get: # NotImplementedError: Axes3D currently only supports the aspect # argument 'auto'. You passed in 1.0. # This fixes it aspect = "auto" elif aspect == "equal": aspect = 1.0 else: aspect = float(aspect[1]) / aspect[0] if self._kwargs.get("fig", None) is not None: # We assume we are generating a PlotGrid object, hence the figure # and the axes are provided by the user. self._fig = self._kwargs.pop("fig", None) self.ax = self._kwargs.pop("ax", None) else: self._fig = plt.figure(figsize=self.size) is_3D = [s.is_3D for s in self.series] if any(is_3D) and (not all(is_3D)): raise ValueError( "The matplotlib backend can not mix 2D and 3D.") kwargs = dict(aspect=aspect) if all(is_3D): kwargs["projection"] = "3d" self.ax = self._fig.add_subplot(1, 1, 1, **kwargs)
def plot_workers(l, centr_time, centr_acc): t = [] a = [] try: for i in l: name1 = "np_arrays/total_time" + str(i) + ".npy" name2 = "np_arrays/total_acc" + str(i) + ".npy" t.append(np.load(name1)) a.append(np.load(name2)) t1 = [i[0] for i in t] t2 = [i[1] for i in t] a1 = [i[0] for i in a] a2 = [i[1] for i in a] jtplot.style(theme='grade3') figure(figsize=(15, 15)) plt.subplot(221) plt.plot(l, t1, label='1st pass', marker='x', markersize=4) plt.plot(l, t2, label='2nd pass', marker='x', markersize=4) plt.axhline(y=centr_time[0], linestyle='-', label='centr 1') plt.axhline(y=centr_time[1], linestyle='-', label='centr 2') plt.xlabel("Number of workers") plt.ylabel("Time (s)") title = 'Total time for 1 and 2 passes on the dataset to number of workers' plt.title(title) plt.legend() plt.subplot(222) plt.plot(l, a1, label='1st pass', marker='x', markersize=4) plt.plot(l, a2, label='2nd pass', marker='x', markersize=4) plt.axhline(y=centr_acc[0], linestyle='-', label='centr 1') plt.axhline(y=centr_acc[1], linestyle='-', label='centr 2') plt.xlabel("Number of workers") plt.ylabel("Accuracy") title = 'Total accuracy for 1 and 2 passes on the dataset to number of workers' plt.title(title) plt.legend() plt.savefig('B_Plots/workers') plt.show() except: print("Something went wrong") return
def anim_plot(data, lim=None, delta=1e-3): from jupyterthemes import jtplot from time import sleep if lim is None: data_min, data_max = data.min(0), data.max(0) lim = ((data_min[0], data_max[0]), (data_min[1], data_max[1])) %matplotlib notebook plt.ion() fig, ax = plt.subplots() for i in tqdm_notebook(range(len(data))): ax.scatter(data[:i, 0], data[:i, 1], marker='.') if lim[0] is not None: ax.set_xlim(lim[0][0], lim[0][1]) if lim[1] is not None: ax.set_ylim(lim[1][0], lim[1][1]) fig.set_size_inches(10, 8) fig.canvas.draw() sleep(delta) ax.clear() %matplotlib inline jtplot.style(context='notebook', fscale=2, figsize=(15, 10))
import matplotlib.pyplot as plt from jupyterthemes import jtplot jtplot.style(theme='onedork') def linear_regression(X_train, y_train, X_test, y_test, y_prediction): plt.plot(X_train, y_train, '.', color='r', label='Train Data') plt.plot(X_test, y_test, '.', color='r', label='Test Data') plt.plot(X_test, y_prediction, color='m', label='Prediction') plt.legend() plt.show() return 0
import itertools import matplotlib.pyplot as plt import networkx as nx import numpy as np import pandas as pd import seaborn as sns import scipy.sparse as sparse from ipywidgets import * from jupyterthemes import jtplot jtplot.style(theme='grade3', figsize=(16, 10)) ################### COLOUR MAPS ###################### from matplotlib.colors import LinearSegmentedColormap optum_cmap = LinearSegmentedColormap.from_list( 'optum', ["#E87722", "#A32A2E", "#422C88", "#078576", "#627D32"]) optum_cmap_simple = LinearSegmentedColormap.from_list( 'optum', ["#E87722", "#078576"]) # for gradients ######################################################## def make_sequences(df, elements_field="new_elements", exits_field="new_exits"): """ Generates sequences of item-exit_code and yields them """ for _, row in df.iterrows(): try: elements = np.array(row[elements_field].split("|")).astype(int)
def butter_bandpass(lowcut, highcut, nyq_rate, order=6): normal_lowcut = lowcut / nyq_rate normal_highcut = highcut / nyq_rate Wn = [normal_lowcut, normal_highcut] b, a = butter(order, Wn, btype='bandpass', analog=False) return b, a #%% # Plot freq response of filters import matplotlib.pyplot as plt from jupyterthemes import jtplot jtplot.style('chesterish') # Filter inputs samp_rate = 44100 nyq_rate = 0.5 * samp_rate lowcut = 10000 highcut = 8000 b_lowcut = 3000 b_highcut = 10000 lfilt_order = 6 hfilt_order = 6 bfilt_order = 6 # Get filter coefficients b_low, a_low = butter_lowpass(lowcut, nyq_rate, order=lfilt_order) b_high, a_high = butter_highpass(highcut, nyq_rate, hfilt_order)
# 기본 패키지 불러오기 import numpy as np import pandas as pd import warnings import mglearn import matplotlib.pyplot as plt from jupyterthemes import jtplot %matplotlib inline # jtplot style 설정 jtplot.style(theme='gruvboxd', grid=False) # matplotlib 한글 폰트 설정 plt.rcParams['font.family'] = 'NanumGothic' # -부호 깨지지 않게 하기 plt.rcParams['axes.unicode_minus'] = False # 경고 무시 warnings.filterwarnings("ignore")
from tqdm.auto import tqdm from datetime import datetime from pytz import timezone, utc KST = datetime.now(timezone('Asia/Seoul')) fmt = "%Y_%m_%d_%H_%M_%S" now_time = KST.strftime(fmt) print(now_time) physical_devices_list = tf.config.list_physical_devices('GPU') physical_devices = physical_devices_list[:4] tf.config.set_visible_devices(physical_devices, 'GPU') print(physical_devices) tf.config.set_soft_device_placement(True) for idx, device in enumerate(physical_devices): tf.config.experimental.set_memory_growth(device, True) from jupyterthemes import jtplot jtplot.style(theme='grade3') import logging logger = logging.getLogger() logger.setLevel(logging.CRITICAL) logging.disable(sys.maxsize) from cal_score import scoring from pathlib import Path from collections import Counter import seaborn as sns import json from sklearn.utils import class_weight # In[2]: np_load_old = np.load np.load = lambda *a, **k: np_load_old(*a, allow_pickle=True, **k)
from sys import platform import os import numpy as np from jupyterthemes import jtplot import matplotlib.pyplot as plt plt.rcParams['pdf.fonttype'] = 42 plt.rcParams['font.family'] = 'DejaVu Sans' import seaborn as sns import pandas as pd pd.options.mode.chained_assignment = None # default='warn' import glob import scipy.stats as stats jtplot.style('grade3', context='poster', fscale=1.4, spines=False, gridlines='--') def rt_order_df(samples_df, messages_df): rt_ordered_msg_df = messages_df.sort_values( by='trial_response_time', ascending=True).reset_index(drop=True) rt_ordered_trials = rt_ordered_msg_df.trial.values rt_ordered_samples_df_temp = pd.DataFrame() rt_ordered_samples_df_temp = [ rt_ordered_samples_df_temp.append(
tqdm.pandas() # constants ML20MPATH = "../data/ml-20m/" MODELSPATH = "../models/" DATAPATH = "../data/streamlit/" SHOW_TOPN_MOVIES = ( 200 # recommend me a movie. show only top ... movies, higher values lead to slow ux ) # disable it if you get an error from jupyterthemes import jtplot jtplot.style(theme="grade3") def render_header(): st.write( """ <p align="center"> <img src="https://raw.githubusercontent.com/awarebayes/RecNN/master/res/logo%20big.png"> </p> <p align="center"> <iframe src="https://ghbtns.com/github-btn.html?user=awarebayes&repo=recnn&type=star&count=true&size=large" frameborder="0" scrolling="0" width="160px" height="30px"></iframe> <iframe src="https://ghbtns.com/github-btn.html?user=awarebayes&repo=recnn&type=fork&count=true&size=large" frameborder="0" scrolling="0" width="158px" height="30px"></iframe> <iframe src="https://ghbtns.com/github-btn.html?user=awarebayes&type=follow&count=true&size=large" frameborder="0" scrolling="0" width="220px" height="30px"></iframe> </p>
# coding: utf-8 # # 你的第一个神经网络 # # 在此项目中,你将构建你的第一个神经网络,并用该网络预测每日自行车租客人数。我们提供了一些代码,但是需要你来实现神经网络(大部分内容)。提交此项目后,欢迎进一步探索该数据和模型。 # In[1]: get_ipython().magic('matplotlib inline') get_ipython().magic("config InlineBackend.figure_format = 'retina'") import numpy as np import pandas as pd import matplotlib.pyplot as plt from jupyterthemes import jtplot jtplot.style(ticks=True) # ## 加载和准备数据 # # 构建神经网络的关键一步是正确地准备数据。不同尺度级别的变量使网络难以高效地掌握正确的权重。我们在下方已经提供了加载和准备数据的代码。你很快将进一步学习这些代码! # In[2]: data_path = 'Bike-Sharing-Dataset/hour.csv' rides = pd.read_csv(data_path) # In[3]:
from matplotlib.colors import LinearSegmentedColormap import matplotlib.pylab as plt import matplotlib from sklearn.manifold import TSNE import pandas as pd import numpy as np import datetime import copy import time from robusta import utils, metrics import seaborn as sns from jupyterthemes import jtplot jtplot.style('gruvboxd') matplotlib.use('nbagg') __all__ = ['plot_fold', 'print_fold'] def plot_fold(cv): if not cv.plot: return scores = cv.get_results('score') k_folds = len(scores) n_folds = cv.n_folds if k_folds == 1:
import pandas as pd import numpy as np from os import environ as env # Pandas options pd.options.display.max_columns = 30 # Visualization import matplotlib.pyplot as plt import seaborn as sns try: from jupyterthemes import jtplot jtplot.style(theme = 'oceans16') except ImportError: plt.style.use('bmh') # If in ipython, load autoreload extension & run plots inline if 'ipython' in globals(): print('\nWelcome to IPython!') ipython.magic('load_ext autoreload') ipython.magic('autoreload 2') ipython.magic('matplotlib inline') print('Usual libraries have been loaded.')
import torch, fastai, sys, os from fastai.vision import * from fastai.vision.data import SegmentationProcessor import ants from ants.core.ants_image import ANTsImage from jupyterthemes import jtplot sys.path.insert(0, './exp') jtplot.style(theme='gruvboxd') # Set a root directory path = Path('/home/ubuntu/MultiCampus/MICCAI_BraTS_2019_Data_Training') def is_mod(fn: str, mod: str) -> bool: "Check if file path contains a specified name of modality used for MRI" import re r = re.compile('.*' + mod, re.IGNORECASE) return True if r.match(fn) else False def is_mods(fn: str, mods: Collection[str]) -> bool: "Check if file path contains specified names of modality used for MRI" import re return any([is_mod(fn, mod) for mod in mods]) def _path_to_same_str(p_fn): "path -> str, but same on nt+posix, for alpha-sort only" s_fn = str(p_fn) s_fn = s_fn.replace('\\', '.') s_fn = s_fn.replace('/', '.')
""" These is the standard setup for the notebooks. """ %matplotlib inline %load_ext autoreload %autoreload 2 from jupyterthemes import jtplot jtplot.style(theme='onedork', context='notebook', ticks=True, grid=False) import pandas as pd pd.options.display.max_rows = 999 pd.options.display.max_columns = 999 pd.set_option("display.max_columns", None) import numpy as np import os import matplotlib.pyplot as plt #plt.style.use('paper') #import data import copy from rolldecay.bis_system import BisSystem from rolldecay import database from mdldb.run from sklearn.pipeline import Pipeline from rolldecayestimators.transformers import CutTransformer, LowpassFilterDerivatorTransformer, ScaleFactorTransformer, OffsetTransformer from rolldecayestimators.direct_estimator_cubic import EstimatorQuadraticB, EstimatorCubic from rolldecayestimators.ikeda_estimator import IkedaQuadraticEstimator import rolldecayestimators.equations as equations
#!/usr/bin/env python # coding: utf-8 # In[ ]: import matplotlib.pyplot as plt import pandas as pd import numpy as np try: from jupyterthemes import jtplot jtplot.style() except: pass # In[ ]: ip = pd.read_csv('../../../data/cleandata/Info pluviometricas/Merged Data/merged.csv', sep = ';', dtype = {'Local_0': object, 'Local_1':object, 'Local_2':object, 'Local_3':object}) print(list(ip.columns)) ip.head() # #### Umidade Relativa
#!/usr/bin/env python # coding: utf-8 # In[7]: import matplotlib.pyplot as plt import numpy as np import pandas as pd from IPython.display import IFrame from jupyterthemes import jtplot # In[10]: jtplot.style(theme='monokai') # In[2]: plt.rc('font', size=14) plt.rc('figure', figsize=(8, 6)) plt.rc('text', usetex=True) # lo que me pregunto es qué tan mal estaba el voumen. efectivamente los cambios de parametro de red son demasiado pequeños y estan pasando cosas raras. # Notar que hay cambios de pendiente para a = 1.005 # In[3]: datavol = pd.read_csv('datavol.dat', sep=' ') # In[4]: datavol
import numpy as np import seaborn as sns from matplotlib import pyplot as plt import xgboost as xgb from datetime import datetime from sklearn.metrics import classification_report, accuracy_score, roc_curve, auc, roc_auc_score, plot_roc_curve from sklearn.model_selection import train_test_split from sklearn.model_selection import cross_val_score, cross_validate from sklearn.model_selection import GridSearchCV from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix, classification_report from jupyterthemes import jtplot jtplot.style(theme='monokai', context='notebook', ticks=True, grid=False) def plot_roc(testy, lr_probs): # calculate scores ns_probs = [0 for _ in range(len(testy))] ns_auc = roc_auc_score(testy, ns_probs) lr_auc = roc_auc_score(testy, lr_probs) # summarize scores print('No Skill: ROC AUC=%.3f' % (ns_auc)) print('Logistic: ROC AUC=%.3f' % (lr_auc)) # calculate roc curves ns_fpr, ns_tpr, _ = roc_curve(testy, ns_probs) lr_fpr, lr_tpr, _ = roc_curve(testy, lr_probs) # plot the roc curve for the model plt.plot(ns_fpr, ns_tpr, linestyle='--', label='No Skill')
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from jupyterthemes import jtplot from sklearn.linear_model import LinearRegression from sklearn.model_selection import train_test_split, cross_val_score from sklearn.metrics import mean_squared_error jtplot.style(theme="monokai") data = pd.read_csv("data/reg_demo_data.csv") data.head() data.drop(list(data.columns)[0], axis=1, inplace=True) data.head() print(list(data.columns)) X = np.array(data['x']).reshape(-1, 1) Y = np.array(data['y']).reshape(-1, 1) X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2, random_state=5) # Linear Regression Model model = LinearRegression() model.fit(X_train, Y_train) y_train_pred = model.predict(X_train) # Regression Assessment
curve_df = pd.DataFrame() curve_df['curve 1'] = df[df['Curves'].str.startswith("curve 1")]['Values'].reset_index(drop=True) curve_df['curve 2'] = df[df['Curves'].str.startswith("curve 2")]['Values'].reset_index(drop=True) curve_df['curve 3'] = df[df['Curves'].str.startswith("curve 3")]['Values'].reset_index(drop=True) return curve_df processed_df = process(df) processed_df.head() # Plot from jupyterthemes import jtplot jtplot.style(theme="monokai", grid=False) x = np.arange(-1000, 1000) fig, ((ax1, ax2, ax3)) = plt.subplots(1,3, figsize=(30,15)) ax1.scatter(x, processed_df['curve 1']) ax1.set_xlabel("Values", size=20, color="silver") ax1.set_ylabel("Curve 1 Function", size=16, color="silver") ax2.scatter(x, processed_df['curve 2']) ax2.set_xlabel("Values", size=20, color="silver") ax2.set_ylabel("Curve 2 Function", size=20, color="silver") ax3.scatter(x, processed_df['curve 3']) ax3.set_xlabel("Values", size=20, color="silver") ax3.set_ylabel("Curve 3 Function", size=20, color="silver") plt.suptitle("Scatter Plots from Curve Data Frame", size=30, color="gold") fig.tight_layout(rect=[0, 0.03, 1, 0.95])
# ***** LEGEND ***** # * States = {no lights blinking, left light blinking, right light blinking, both lights blinking} # * State Keys(respectively) = {nlb, llb, rlb, blb} # * Switches(appended to reciever vert to express input value) = {left-blinker, right-blinker, panic-button} # * Switch Keys = {L-B, R-B, P-B} #### Jupyter notebook cell start #### %matplotlib inline from jupyterthemes import jtplot jtplot.style(context='talk', fscale=1, spines=False, gridlines='--') import matplotlib as mpl import matplotlib.pyplot as plt import pandas as pd import numpy as np import networkx as nx df = pd.DataFrame({'from': ['start (nlb)', 'start (nlb)', 'start (nlb)', '<- (L-B) -> llb', '(P-B) -> blb' ], 'to': ['<- (L-B) -> llb', '(R-B) -> rlb ->', '(P-B) -> blb', '(R-B) -> rlb ->', 'start (nlb)']}) G=nx.from_pandas_edgelist(df, 'to', 'from') nx.draw(G, with_labels=True, pos=nx.shell_layout(G), nodecolor='r', edge_color='b') plt.show() #### Jupyter notebook cell end ####
import pandas as pd import GPy from jupyterthemes import jtplot import numpy as np import pylab as pb import matplotlib.pyplot as plt jtplot.style(theme='default') # funcion para plotear multi-task GP (Ricardo Andrade-Pacheco) def plot_2outputs(modelo, xlim): fig = pb.figure(figsize=(12, 8)) # Output 1 ax1 = fig.add_subplot(211) ax1.set_xlim(xlim) ax1.set_title('Output 1') modelo.plot(plot_limits=xlim, fixed_inputs=[(1, 0)], which_data_rows=slice(0, 100), ax=ax1) # Output 2 ax2 = fig.add_subplot(212) ax2.set_xlim(xlim) ax2.set_title('Output 2') modelo.plot(plot_limits=xlim, fixed_inputs=[(1, 1)], which_data_rows=slice(100, 200), ax=ax2)
# format_version: '1.2' # jupytext_version: 1.2.3 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # %% import matplotlib.pyplot as plt import numpy as np import torch import pandas as pd import pickle from jupyterthemes import jtplot jtplot.style('oceans16') # %% [markdown] # # Position Change to the Nearest Car between Frames # %% t1 = torch.load( '../traffic-data/state-action-cost/data_i80_v0/trajectories-0400-0415/all_data.pth' ) t2 = torch.load( '../traffic-data/state-action-cost/data_i80_v0/trajectories-0500-0515/all_data.pth' ) t3 = torch.load( '../traffic-data/state-action-cost/data_i80_v0/trajectories-0515-0530/all_data.pth' ) t_states_full = t1['states'] + t2['states'] + t3['states']
import matplotlib.pyplot as plt import seaborn as sns sns.set() import numpy as np from jupyterthemes import jtplot jtplot.style(ticks=True, grid=True) class MatrixClassifier: def __init__(self): 0 == 0 def analyze(self, M): self.isSquare = M.shape[0] == M.shape[1] if self.isSquare: self.det = np.linalg.det(M) self.columnLengths = np.diag(M.T @ M) self.areAxesOrderPreserved = True if self.det > 0 else False self.stretch = np.abs(self.det) self.isStretchOne = np.abs(self.stretch - 1) < 0.00001 self.areAllColumnsUnitLength = np.all( np.abs(self.columnLengths - 1) < 0.00001) return { "isSquare":self.isSquare, \ "isStretchOne":self.isStretchOne, \ "areAxesOrderPreserved": self.areAxesOrderPreserved,