markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
As expected, the first time we try to set the value for california, it doesn't exist in the dictionary so the right handside of the equal sign errors. Thats easy to fix like this
summed = dict() for row in data: key, value = row if key not in summed: summed[key] = int() summed[key] = summed[key] + value summed
python-tutorials/defaultdict.ipynb
Pinafore/ds-hw
mit
Lets see one more example that instead of summing the numbers we wan't to collect everything into a list. So lets replace int() with list() since we wan't to make an empty list. We also need to change the summing term to use append instead
merged = dict() for row in data: key, value = row if key not in merged: merged[key] = list() merged[key].append(value) merged
python-tutorials/defaultdict.ipynb
Pinafore/ds-hw
mit
Its inconvenient to do this check every time so python has a nice way to make this pattern simpler. This is what collections.defaultdict was designed for. It does the following: Takes a single argument which is a function which we will call func When a key is accessed (for example with merged[key], check if it exists....
from collections import defaultdict summed = defaultdict(int) for row in data: key, value = row summed[key] = summed[key] + value summed merged = defaultdict(list) for row in data: key, value = row merged[key].append(value) merged def myinit(): return -100 summed = defaultdict(myinit) for row ...
python-tutorials/defaultdict.ipynb
Pinafore/ds-hw
mit
As expected, the results are exactly the same, and it is based on the initial method you pass it. This function is called a factory method since each time a key needs to be initialized you can imagine that the function acts as a factory which creates new values. Lets cover one of the common mistakes with default dictio...
d = defaultdict(str) # initially this is empty so all of these should be false print('pedro in dictionary:', 'pedro' in d) print('jordan in dictionary:', 'jordan' in d) # Lets set something in the dictionary now and check that again d['jordan'] = 'professor' print('jordan is in dictionary:', 'jordan' in d) print('p...
python-tutorials/defaultdict.ipynb
Pinafore/ds-hw
mit
So this is odd! You never set a key (only accessed it), but nonetheless pedro is in the dictionary. This is because when the 'pedro' key was accessed and not there, python set it to the return of str which returns an empty string. Lets set this to the real value and be done
d['pedro'] = 'PhD Student' print('pedro is in dictionary:', 'pedro' in d) print(d) print('-->', d['pedro'], '<--', type(d['pedro']))
python-tutorials/defaultdict.ipynb
Pinafore/ds-hw
mit
This notebook reproduces both MAML and the similar Reptile. The Problem https://towardsdatascience.com/fun-with-small-image-data-sets-8c83d95d0159 The goal of both of these algorithms is to learn to do well at the K-shot learning problem. In K-shot learning, we need to train a neural network to generalize based on a ve...
class SineWaveTask: def __init__(self): self.a = np.random.uniform(0.1, 5.0) self.b = np.random.uniform(0, 2*np.pi) self.train_x = None def f(self, x): return self.a * np.sin(x + self.b) def training_set(self, size=10, force_new=False): if self.train...
pytorch/ANIML.ipynb
vermouth1992/tf-playground
apache-2.0
To understand why this is going to be a problem for transfer learning, let's plot 1,000 of them:
for _ in range(1000): SineWaveTask().plot(color='black')
pytorch/ANIML.ipynb
vermouth1992/tf-playground
apache-2.0
Looks like there is a lot of overlap at each x value, to say the least... Since there are multiple possible values for each x across multiple tasks, if we train a single neural net to deal with multiple tasks at the same time, its best bet will simply be to return the average y value across all tasks for each x. What d...
all_x, all_y = [], [] for _ in range(10000): curx, cury = SineWaveTask().test_set(size=100) all_x.append(curx.numpy()) all_y.append(cury.numpy()) avg, = plt.plot(all_x[0], np.mean(all_y, axis=0)) rand, = SineWaveTask().plot() plt.legend([avg, rand], ['Average', 'Random']) plt.show()
pytorch/ANIML.ipynb
vermouth1992/tf-playground
apache-2.0
The average is basically 0, which means a neural network trained on a lot of tasks would simply return 0 everywhere! It is unclear that this will actually help very much, and yet this is the transfer learning approach in this case... Let's see how well it does by actually implementing the model:
TRAIN_SIZE = 10000 TEST_SIZE = 1000 class ModifiableModule(nn.Module): def params(self): return [p for _, p in self.named_params()] def named_leaves(self): return [] def named_submodules(self): return [] def named_params(self): subparams = [] for n...
pytorch/ANIML.ipynb
vermouth1992/tf-playground
apache-2.0
Basically it looks like our transfer model learns a constant function and that it is really hard to fine tune it to something better than a constant function. It's not even clear that our transfer learning is any better than random initialization...
def plot_sine_learning(models, fits=(0, 1), lr=0.01, marker='s', linestyle='--'): data = {'model': [], 'fits': [], 'loss': [], 'set': []} for name, models in models: if not isinstance(models, list): models = [models] for n_model, model in enumerate(models): for n_test, te...
pytorch/ANIML.ipynb
vermouth1992/tf-playground
apache-2.0
MAML We now come to MAML, the first of the two algorithms we will look at today. As mentioned before, we are trying to find a set of weights such that running gradient descent on similar tasks makes progress as quickly as possible. MAML takes this extremely literally by running one iteration of gradient descent and the...
def maml_sine(model, epochs, lr_inner=0.01, batch_size=1, first_order=False): optimizer = torch.optim.Adam(model.params()) for _ in tqdm(range(epochs)): # Note: the paper doesn't specify the meta-batch size for this task, # so I just use 1 for now. for i, t in enumerate(random.sampl...
pytorch/ANIML.ipynb
vermouth1992/tf-playground
apache-2.0
So MAML works much better than transfer learning or random initialization for this problem. Yay! However, it is a bit annoying that we have to use second order derivatives for this... it forces the code to be complicated and it also makes things a fair bit slower (around 33% according to the paper, which matches what w...
SINE_MAML_FIRST_ORDER = [SineModel() for _ in range(5)] for m in SINE_MAML_FIRST_ORDER: maml_sine(m, 4, first_order=True) plot_sine_test(SINE_MAML_FIRST_ORDER[0], SINE_TEST[0], fits=[0, 1, 10], lr=0.01) plt.show() plot_sine_learning( [('MAML', SINE_MAML), ('MAML First Order', SINE_MAML_FIRST_ORDER)], lis...
pytorch/ANIML.ipynb
vermouth1992/tf-playground
apache-2.0
Reptile The first order approximation for MAML tells us that something interesting is going on: after all, it seems like how the gradients were generated should be relevant for a good initialization, and yet it apparently isn't so much. Reptile takes this idea even further by telling us to do the following: run SGD for...
def reptile_sine(model, epochs, lr_inner=0.01, lr_outer=0.001, k=32, batch_size=32): optimizer = torch.optim.Adam(model.params(), lr=lr_outer) name_to_param = dict(model.named_params()) for _ in tqdm(range(epochs)): for i, t in enumerate(random.sample(SINE_TRAIN, len(SINE_TRAIN))): ...
pytorch/ANIML.ipynb
vermouth1992/tf-playground
apache-2.0
<h2 style='color:green'>Reviewing XML Parsing</h2> See if you can use the pattern displayed above to read in and then print the text within "Rom.xml". Note that this file does not contain an "eebo" tag. Filtering Selections Sometimes an HTML selection returns a mixture of elements we wish to process and others we wish...
import bs4 # read in the xml file soup = bs4.BeautifulSoup(open('Ode.xml'), 'html.parser') # get a list of the div1 tags elems = soup.find_all('div1') # iterate over the div1 tags in soup for i in elems: # only proceed if the current tag has the attribute type="ode" if i['type'] == 'ode': # print the...
beautifulsoup/next-steps-with-html-parsing.ipynb
YaleDHLab/lab-workshops
mit
閾値$r$を変えたときに意見の総数に対するクラスターの数との関係。横軸$r$、縦軸$1- (\text{クラスターの数})/(\text{意見の総数})$の通常のプロット(上段)と両対数プロット(下段)。
trial = 100 r = np.logspace(-2, np.log10(0.2), num=50) phi1 = [] for _r in r: _phi = 0. for t in range(trial): meeting = Meeting(K=50, N=6, r=_r, draw=False) meeting.init() _phi += len(uniq_list([x[1][1] for x in meeting.ideas]))/float(len(meeting.ideas)) phi1.append(1 - _phi/trial)...
07_model_3_4_1.ipynb
ssh0/sotsuron_for_public
mit
通常のプロット
myplot1({r'$r$': r}, {r'$\phi$': phi1})
07_model_3_4_1.ipynb
ssh0/sotsuron_for_public
mit
フィッティング用関数
def myfit(fit_func, parameter, x, y, xmin, xmax): """my fitting and plotting function. fit_func: function (parameter(type:list), x) parameter: list of tuples: [('param1', param1), ('param2', param2), ...] x, y: dict xmin, xmax: float """ xkey, xdata = x.items()[0] ykey, ydata = y.i...
07_model_3_4_1.ipynb
ssh0/sotsuron_for_public
mit
$\phi(r) = 10^{b}r^{a}$として最小2乗法でフィッティング
param = [('a', 1.5), ('b', 0.)] xmin, xmax = 0., 0.07 x = {r'$r$': r} y = {r'$\phi$': phi1} def fit_func(parameter, x): a = parameter[0] b = parameter[1] return np.power(x, a)*np.power(10, b) myfit(fit_func, param, x, y, xmin, xmax)
07_model_3_4_1.ipynb
ssh0/sotsuron_for_public
mit
両変数を対数にした状態で直線としてフィットしてみる。得られたパラメータによるフィッティング関数のプロットは、元の状態に戻してから行う。後に示す直接べき関数として求めた場合に比べて、$r$の小さい領域での直線の傾きがよく合っているように見える。
a = 1.5 b = 0. param = [a, b] rmin, rmax = 0., 0.07 def fit_func(parameter, x): a = parameter[0] b = parameter[1] return a*np.log10(x) + b def fit(parameter, x, y): return np.log10(y) - fit_func(parameter, x) i = 0 while r[i] < rmin: i += 1 imin, imax = i, i while r[i] < rmax: i += 1 imax = i...
07_model_3_4_1.ipynb
ssh0/sotsuron_for_public
mit
S字型の曲線であるので、 $$\phi (r) = 1 - \exp \left[ - \left( \frac{r}{\omega} \right)^{a} \right]$$ としてパラメータ$\omega$に関して最小2乗法でフィッティングを行った場合。
omega = 0.06 a = 2.0 param = [omega, a] rmin, rmax = 0.01, 0.2 def fit_func(parameter, x): omega = parameter[0] a = parameter[1] return 1 - np.exp(-(x/omega)**a) def fit(parameter, x, y): return y - fit_func(parameter, x) i = 0 while r[i] < rmin: i += 1 imin, imax = i, i while r[i] < rmax: i ...
07_model_3_4_1.ipynb
ssh0/sotsuron_for_public
mit
$r$を固定して$N$を変更したときのクラスター数と点の総数の間の関係 横軸を$X_{i}$の数$N$、縦軸を$1-(\text{クラスタ数}/\text{点の総数})$としたときのグラフを書いてみる。
trial = 100 N = np.arange(1, 20) phi6 = [] for _N in N: _phi = 0. for t in range(trial): meeting = Meeting(K=50, N=_N, r=0.07, draw=False) meeting.init() _phi += len(uniq_list([x[1][1] for x in meeting.ideas]))/float(len(meeting.ideas)) phi6.append(1 - _phi/trial) myplot1({r'$N$': ...
07_model_3_4_1.ipynb
ssh0/sotsuron_for_public
mit
このとき、意見の総数と参加者の数、一人あたりの意見の数の間には比例の関係が成り立っており、この数のみに依存して、どちらを変えるかは問題ではない。したがって、より刻みを多く取ることのできる一人あたりの意見の数$S$を変えて計算した場合を見てみることにする。
trial = 100 S = np.arange(10, 70) phi7 = [] for _S in S: _phi = 0. for t in range(trial): meeting = Meeting(K=50, S=_S, N=6, r=0.07, draw=False) meeting.init() _phi += len(uniq_list([x[1][1] for x in meeting.ideas]))/float(len(meeting.ideas)) phi7.append(1 - _phi/trial) myplot1({r'...
07_model_3_4_1.ipynb
ssh0/sotsuron_for_public
mit
グラフの形から、 $$\phi(S) = 1- \exp\left[- \left( \frac{S}{\omega} \right)^{a}\right]$$ であるとしてフィッティングを行ってみる。
omega = 20. a = 1. param = [omega, a] def fit_func(parameter, x): omega = parameter[0] a = parameter[1] return 1. - np.exp(-(x/omega)**a) def fit(parameter, x, y): return y - fit_func(parameter, x) res = leastsq(fit, param, args=(S, phi7)) print u"omega: " + str(res[0][0]) print u"a: " + str(res[0][1...
07_model_3_4_1.ipynb
ssh0/sotsuron_for_public
mit
閾値$r$を決めたときに、領域$\Omega$内の任意の点を一様に選んだとき、その中に点が存在する確率の期待値は、解析的計算によって $$p'(r) = \frac{1}{2}r^{4} -\frac{8}{3}r^{3} + \pi r^{2}$$ $r$を定めたとき、すべての点の個数が$M$個であるとすると、一つの点の点がもつ次数の期待値$l$は $$l = p'(r)(M-1) = \left( \frac{1}{2}r^{4} -\frac{8}{3}r^{3} + \pi r^{2} \right)(M-1)$$ となる。これを実際のシミュレーションの結果と照らして確かめる。
trial = 100 r = np.linspace(0.01, 0.5, num=50) phi3 = [] for _r in r: _phi = 0. for t in range(trial): meeting = Meeting(K=50, N=6, r=_r, draw=False) meeting.init() _phi += meeting.ave_l phi3.append(_phi/trial) fig = plt.figure(figsize=(8,6)) ax = fig.add_subplot(111) r = np.linsp...
07_model_3_4_1.ipynb
ssh0/sotsuron_for_public
mit
It looks like we can use culmen length to identify Adelie penguins. Exercise: Use make_kdeplots to display the distributions of one of the other two features: 'Body Mass (g)' 'Culmen Depth (mm)'
# Solution goes here
notebooks/clustering.ipynb
AllenDowney/ThinkBayes2
mit
Exercise: Make a scatter plot using any other pair of variables.
# Solution goes here
notebooks/clustering.ipynb
AllenDowney/ThinkBayes2
mit
Summary The k-means algorithm does unsupervised clustering, which means that we don't tell it where the clusters are; we just provide the data and ask it to find a given number of clusters. In this notebook, we asked it to find clusters in a group of penguins based on two features, flipper length and culmen length. Th...
# Solution goes here # Solution goes here # Solution goes here # Solution goes here # Solution goes here # Solution goes here
notebooks/clustering.ipynb
AllenDowney/ThinkBayes2
mit
Modelo Reverchon Mathematical Modeling of Supercritical Extraction of Sage Oil
P = 9 #MPa T = 323 # K Q = 8.83 #g/min e = 0.4 rho = 285 #kg/m3 miu = 2.31e-5 # Pa*s dp = 0.75e-3 # m Dl = 0.24e-5 #m2/s De = 8.48e-12 # m2/s Di = 6e-13 u = 0.455e-3 #m/s kf = 1.91e-5 #m/s de = 0.06 # m W = 0.160 # kg kp = 0.2 r = 0.31 #m n = 10 V = 12 #C = kp * qE C = 0.1 qE = C / kp Cn = 0.05 Cm = 0.02 t = np.l...
Modelo de impregnacion/modelo2/Activité 10_Viernes.ipynb
pysg/pyther
mit
Trabajo futuro Realizar modificaciones de los parametros para observar cómo afectan al comportamiento del modelo. Realizar un ejemplo de optimización de parámetros utilizando el modelo de Reverchon. Referencias [1] E. Reverchon, Mathematical modelling of supercritical extraction of sage oil, AIChE J. 42 (1996) 1765–1...
#Datos experimentales x_data = np.linspace(0,9,10) y_data = np.array([0.000,0.416,0.489,0.595,0.506,0.493,0.458,0.394,0.335,0.309]) def f(y, t, k): """ sistema de ecuaciones diferenciales ordinarias """ return (-k[0]*y[0], k[0]*y[0]-k[1]*y[1], k[1]*y[1]) def my_ls_func(x,teta): f2 = lambda y, t: f(y, t...
Modelo de impregnacion/modelo2/Activité 10_Viernes.ipynb
pysg/pyther
mit
Using the awesome Panda library, we can parse the .csv file of the training set and hold the data in a table
def getTrainingData(): print("Get training data ...\n") trainingData = pnd.read_csv("./train.csv") trainingData['id'] = range(1, len(trainingData) + 1) #For 1-base index return trainingData
Easy/PokerRuleInduction/PokerRuleInduction.ipynb
AhmedHani/Kaggle-Machine-Learning-Competitions
mit
Second, We need to extract the features and the label from the table
trainingData = getTrainingData() labels = trainingData['hand'] features = trainingData.drop(['id', 'hand'], axis=1)
Easy/PokerRuleInduction/PokerRuleInduction.ipynb
AhmedHani/Kaggle-Machine-Learning-Competitions
mit
When dealing with Machine Learning algorithms, you need to calculate the effiency of the algorithm with the data, this could be done using several techniques such as K-Fold cross validation https://en.wikipedia.org/wiki/Cross-validation_(statistics)#k-fold_cross-validation and Precision and recall https://en.wikipedia....
def kFoldCrossValidation(kFold): trainingData = getTrainingData() label = trainingData['hand'] features = trainingData.drop(['id'], axis=1) crossValidationResult = dict() print("Start Cross Validation ...\n") randomForest = RandomForestClassifier(n_estimators=100) kNearestNeighbour = KNeig...
Easy/PokerRuleInduction/PokerRuleInduction.ipynb
AhmedHani/Kaggle-Machine-Learning-Competitions
mit
I've decided to use K Nearest Neighbour and Random Forest according to the recommendation and the benchmark of the problem. Above, I've created instances from the Random Forest and K Nearest Neighbour modules, then get the score of each one to help me to decide which one is better.
if __name__ == '__main__': trainingData = getTrainingData() labels = trainingData['hand'] features = trainingData.drop(['id', 'hand'], axis=1) KNN, RF = kFoldCrossValidation(5) classifier = None if KNN > RF: classifier = KNeighborsClassifier(n_neighbors=100) else: classifie...
Easy/PokerRuleInduction/PokerRuleInduction.ipynb
AhmedHani/Kaggle-Machine-Learning-Competitions
mit
Read the CSV We use pandas read_csv(path/to/csv) method to read the csv file. Next, replace the missing values with np.NaN i.e. Not a Number. This way we can count the number of missing values per column.
df = pd.read_csv('../datasets/UCIrvineCrimeData.csv'); df = df.replace('?',np.NAN) features = [x for x in df.columns if x not in ['state', 'community', 'communityname', 'county' , 'ViolentCrimesPerPop']]
exploratory_data_analysis/.ipynb_checkpoints/UCIrvine_Crime_data_analysis-checkpoint.ipynb
WenboTien/Crime_data_analysis
mit
Sklearn fundamentals A convenient way to randomly partition the dataset into a separate test & training dataset is to use the train_test_split function from scikit-learn's cross_validation submodule
#df = df.drop(["communityname", "state", "county", "community"], axis=1) X, y = imputed_data, df['ViolentCrimesPerPop'] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0);
exploratory_data_analysis/.ipynb_checkpoints/UCIrvine_Crime_data_analysis-checkpoint.ipynb
WenboTien/Crime_data_analysis
mit
First, we assigned the NumPy array representation of features columns to the variable X, and we assigned the predicted variable to the variable y. Then we used the train_test_split function to randomly split X and y into separate training & test datasets. By setting test_size=0.3 we assigned 30 percent of samples to X_...
class SBS(): def __init__(self, estimator, features, scoring=r2_score, test_size=0.25, random_state=1): self.scoring = scoring self.estimator = estimator self.features = features self.test_size = test_size self.random_state = random_state ...
exploratory_data_analysis/.ipynb_checkpoints/UCIrvine_Crime_data_analysis-checkpoint.ipynb
WenboTien/Crime_data_analysis
mit
I want to import Vgg16 as well because I'll want it's low-level features
# import os, sys # sys.path.insert(1, os.path.join('../utils/'))
FAI_old/lesson3/L3HW_MNIST.ipynb
WNoxchi/Kaukasos
mit
Actually, looks like Vgg's ImageNet weights won't be needed.
# from vgg16 import Vgg16 # vgg = Vgg16()
FAI_old/lesson3/L3HW_MNIST.ipynb
WNoxchi/Kaukasos
mit
II. Load Data
(x_train, y_train), (x_test, y_test) = mnist.load_data()
FAI_old/lesson3/L3HW_MNIST.ipynb
WNoxchi/Kaukasos
mit
III. Preprocessing Keras Convolutional layers expect color channels, so expand an empty dimension in the input data, to account for no colors.
x_train = np.expand_dims(x_train, 1) # can also enter <axis=1> for <1> x_test = np.expand_dims(x_test, 1) x_train.shape
FAI_old/lesson3/L3HW_MNIST.ipynb
WNoxchi/Kaukasos
mit
One-Hot Encoding the outputs:
y_train, y_test = to_categorical(y_train), to_categorical(y_test)
FAI_old/lesson3/L3HW_MNIST.ipynb
WNoxchi/Kaukasos
mit
Since this notebook's models are all mimicking Vgg16, the input data should be preprocessed in the same way: in this case normalized by subtracting the mean and dividing by the standard deviation. It turns out this is a good idea generally.
x_mean = x_train.mean().astype(np.float32) x_stdv = x_train.std().astype(np.float32) def norm_input(x): return (x - x_mean) / x_stdv
FAI_old/lesson3/L3HW_MNIST.ipynb
WNoxchi/Kaukasos
mit
Create Data Batch Generator ImageDataGenerator with no arguments will return a generator. Later, when data is augmented, it'll be told how to do so. I don't know what batch-size should be set to: in Lecture it was 64.
gen = image.ImageDataGenerator() trn_batches = gen.flow(x_train, y_train, batch_size=64) tst_batches = gen.flow(x_test, y_test, batch_size=64)
FAI_old/lesson3/L3HW_MNIST.ipynb
WNoxchi/Kaukasos
mit
General workflow, going forward: * Define the model's architecture. * Run 1 Epoch at default learning rate (0.01 ~ 0.001 depending on optimizer) to get it started. * Jack up the learning to 0.1 (as high as you'll ever want to go) and run 1 Epoch, possibly more if you can get away with it. * Lower the learning rate by a...
def LinModel(): model = Sequential([ Lambda(norm_input, input_shape=(1, 28, 28)), Flatten(), Dense(10, activation='softmax') ]) model.compile(Adam(), loss='categorical_crossentropy', metrics=['accuracy']) return model Linear_model = LinModel() Linear_model.fit_generator(trn_batc...
FAI_old/lesson3/L3HW_MNIST.ipynb
WNoxchi/Kaukasos
mit
2. Single Dense Layer This is what people in the 80s & 90s thought of as a 'Neural Network': a single Fully-Connected hidden layer. I don't yet know why the hidden layer is ouputting 512 units. For natural-image recognition it's 4096. I'll see whether a ReLU or Softmax hidden layer works better. By the way, the trainin...
def FCModel(): model = Sequential([ Lambda(norm_input, input_shape=(1, 28, 28)), Dense(512, activation='relu'), Flatten(), Dense(10, activation='softmax') ]) model.compile(Adam(), loss='categorical_crossentropy', metrics=['accuracy']) return model FC_model = FCModel() FC...
FAI_old/lesson3/L3HW_MNIST.ipynb
WNoxchi/Kaukasos
mit
With an accuracy of 0.9823 and validation accuracy of 0.9664, the model's starting to overfit significantly and hit its limits, so it's time to go on to the next technique. 3. Basic 'VGG' style Convolutional Neural Network I'm specifying an output shape equal to the input shape, to suppress the warnings keras was givin...
def ConvModel(): model = Sequential([ Lambda(norm_input, input_shape=(1, 28, 28), output_shape=(1, 28, 28)), Convolution2D(32, 3, 3, activation='relu'), Convolution2D(32, 3, 3, activation='relu'), MaxPooling2D(), Convolution2D(64, 3, 3, activation='relu'), Convolution...
FAI_old/lesson3/L3HW_MNIST.ipynb
WNoxchi/Kaukasos
mit
4. Data Augmentation
gen = image.ImageDataGenerator(rotation_range=8, width_shift_range=0.08, shear_range=0.3, height_shift_range=0.08, zoom_range=0.08) trn_batches = gen.flow(x_train, y_train, batch_size=64) tst_batches = gen.flow(x_test, y_test, batch_size=64) CNN_Aug_model = ConvModel() CNN_Aug_model.fit_gene...
FAI_old/lesson3/L3HW_MNIST.ipynb
WNoxchi/Kaukasos
mit
5. Batch Normalization + Data Augmentation See this thread for info on BatchNorm axis.
def ConvModelBN(): model = Sequential([ Lambda(norm_input, input_shape=(1, 28, 28), output_shape=(1, 28, 28)), Convolution2D(32, 3, 3, activation='relu'), BatchNormalization(axis=1), Convolution2D(32, 3, 3, activation='relu'), MaxPooling2D(), BatchNormalization(axis=1...
FAI_old/lesson3/L3HW_MNIST.ipynb
WNoxchi/Kaukasos
mit
6. Dropout + Batch Normalization + Data Augmentation
def ConvModelBNDo(): model = Sequential([ Lambda(norm_input, input_shape=(1, 28, 28), output_shape=(1, 28, 28)), Convolution2D(32, 3, 3, activation='relu'), BatchNormalization(axis=1), Convolution2D(32, 3, 3, activation='relu'), MaxPooling2D(), BatchNormalization(axis...
FAI_old/lesson3/L3HW_MNIST.ipynb
WNoxchi/Kaukasos
mit
7. Ensembling Define a function to automatically train a model:
# I'll set it to display progress at the start of each LR-change def train_model(): model = ConvModelBNDo() model.fit_generator(trn_batches, trn_batches.n, nb_epoch=1, verbose=1, validation_data=tst_batches, nb_val_samples=tst_batches.n) model.optimizer.lr=0.1 mo...
FAI_old/lesson3/L3HW_MNIST.ipynb
WNoxchi/Kaukasos
mit
I finally got my GPU running on my workstation. Decided to leave the ghost of Bill Gates alone and put Ubuntu Linux on the second harddrive. This nvidia GTX 870M takes 17 seconds to get through the 60,000 images. The Core i5 on my Mac took an average of 340. A 20x speed up. This also means, at those numbers, a 6-strong...
# this'll take some time models = [train_model() for m in xrange(6)]
FAI_old/lesson3/L3HW_MNIST.ipynb
WNoxchi/Kaukasos
mit
Save the models' weights -- bc this wasn't computationally cheap
from os import getcwd path = getcwd() + 'data/mnist/' model_path = path + 'models/' for i,m in enumerate(models): m.save_weights(model_path + 'MNIST_CNN' + str(i) + '.pkl')
FAI_old/lesson3/L3HW_MNIST.ipynb
WNoxchi/Kaukasos
mit
Create an array of predictions from the models on the test-set. I'm using a batch size of 256 because that's what was done in lecture, and prediction is such an easier task that I think the large size just helps things go faster.
ensemble_preds = np.stack([m.predict(x_test, batch_size=256) for m in models])
FAI_old/lesson3/L3HW_MNIST.ipynb
WNoxchi/Kaukasos
mit
Finally, take the average of the predictions:
avg_preds = ensemble_preds.mean(axis=0) keras.metrics.categorical_accuracy(y_test, avg_preds).eval()
FAI_old/lesson3/L3HW_MNIST.ipynb
WNoxchi/Kaukasos
mit
Boom. 0.99699.. ~ 99.7% accuracy. Same as achieved in lecture; took roughly 50 minutes to train. Unfortunately I didn't have the h5py module installed when I ran this, so the weight's can't be saved easily -- simple fix of rerunning after install. Trying the above again, this time having h5py installed.
# this'll take some time models = [train_model() for m in xrange(6)] from os import getcwd import os path = getcwd() + '/data/mnist/' model_path = path + 'models/' if not os.path.exists(path): os.mkdir('data') os.mkdir('data/mnist') if not os.path.exists(model_path): os.mkdir(model_path) for i,m in enumerate...
FAI_old/lesson3/L3HW_MNIST.ipynb
WNoxchi/Kaukasos
mit
Setup This installs a few dependencies: PyTorch, CLIP, GPT-3.
!pip install -U --no-cache-dir gdown --pre !pip install -U sentence-transformers !pip install openai ftfy !nvidia-smi # Show GPU info. import json import os import numpy as np import openai import pandas as pd import pickle from sentence_transformers import SentenceTransformer from sentence_transformers import util ...
socraticmodels/SocraticModels_MSR_VTT.ipynb
google-research/google-research
apache-2.0
Load RoBERTa (masked LM)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu") roberta_model = SentenceTransformer('stsb-roberta-large').to(device)
socraticmodels/SocraticModels_MSR_VTT.ipynb
google-research/google-research
apache-2.0
Wrap GPT-3 (causal LM)
gpt_version = "text-davinci-002" def prompt_llm(prompt, max_tokens=64, temperature=0, stop=None): response = openai.Completion.create(engine=gpt_version, prompt=prompt, max_tokens=max_tokens, temperature=temperature, stop=stop) return response["choices"][0]["text"].strip()
socraticmodels/SocraticModels_MSR_VTT.ipynb
google-research/google-research
apache-2.0
Evaluate on MSR-Full
# Load raw text captions from MSR-Full. with open('test_videodatainfo.json', 'r') as j: msr_full_info = json.loads(j.read()) msr_full_vid_id_to_captions = {} for info in msr_full_info['sentences']: if info['video_id'] not in msr_full_vid_id_to_captions: msr_full_vid_id_to_captions[info['video_id']] = [] msr_f...
socraticmodels/SocraticModels_MSR_VTT.ipynb
google-research/google-research
apache-2.0
We use the same setup here as we do in the 'Simulating Experimental Fluorescence Binding Data' notebook.
# We define a Kd, Kd = 2e-9 # M # a protein concentration, Ptot = 1e-9 * np.ones([12],np.float64) # M # and a gradient of ligand concentrations for our experiment. Ltot = 20.0e-6 / np.array([10**(float(i)/2.0) for i in range(12)]) # M def two_component_binding(Kd, Ptot, Ltot): """ Parameters ---------- ...
examples/direct-fluorescence-assay/2c Bayesian fit for two component binding - simulated data- WITH EMCEE.ipynb
choderalab/assaytools
lgpl-2.1
Now make this a fluorescence experiment
# Making max 1400 relative fluorescence units, and scaling all of PL (complex concentration) # to that, adding some random noise npoints = len(Ltot) sigma = 10.0 # size of noise F_PL_i = (1400/1e-9)*PL + sigma * np.random.randn(npoints) # y will be complex concentration # x will be total ligand concentration plt.semi...
examples/direct-fluorescence-assay/2c Bayesian fit for two component binding - simulated data- WITH EMCEE.ipynb
choderalab/assaytools
lgpl-2.1
That works, but the equilibration seems to happen quite late in our sampling! Let's look at some of the other parameters.
well_area = 0.1586 # well area, cm^2 # half-area wells were used here path_length = assay_volume / well_area from assaytools import plots plots.plot_mcmc_results(Ltot, Ptot, path_length, mcmc)
examples/direct-fluorescence-assay/2c Bayesian fit for two component binding - simulated data- WITH EMCEE.ipynb
choderalab/assaytools
lgpl-2.1
Now let's see if we can get better results using the newly implemented emcee option. Following instructions as described here: http://twiecki.github.io/blog/2013/09/23/emcee-pymc/
mcmc_emcee = pymcmodels.run_mcmc_emcee(pymc_model)
examples/direct-fluorescence-assay/2c Bayesian fit for two component binding - simulated data- WITH EMCEE.ipynb
choderalab/assaytools
lgpl-2.1
Load image The code expects a local image filepath through the image_path variable below.
"""User Parameters""" # The train image will be scaled to a square of dimensions `train_size x train_size` train_size = 32 # When generating the image, the network will generate for an image of # size `test_size x test_size` test_size = 2048 # Path to load the image you want upscaled image_path = '../img/colors.jpg' i...
notebooks/super-resolution_coordinates.ipynb
liviu-/notebooks
mit
Model For simplicity, the model below is an MLP created with TF. Input The input is just a matrix of floats of shape (None, 2): - 2 refers to the 2 x, y coordinates - and None is just a placeholder that allows for training multiple coordinates at one time for speed (i.e. using batches of unknown size)
X = tf.placeholder('float32', (None, 2))
notebooks/super-resolution_coordinates.ipynb
liviu-/notebooks
mit
Architecture An MLP with several fully connected layers. The architecture was inspired from here.
def model(X, w): h1 = tf.nn.tanh(tf.matmul(X, w['h1'])) h2 = tf.nn.tanh(tf.matmul(h1, w['h2'])) h3 = tf.nn.tanh(tf.matmul(h2, w['h3'])) h4 = tf.nn.tanh(tf.matmul(h3, w['h4'])) h5 = tf.nn.tanh(tf.matmul(h4, w['h4'])) h6 = tf.nn.tanh(tf.matmul(h5, w['h4'])) h7 = tf.nn.tanh(tf.matmul(h6, w['h4'...
notebooks/super-resolution_coordinates.ipynb
liviu-/notebooks
mit
Training The model is trained to minimise MSE (common loss for regression problems) and uses Adam as an optimiser (any other optimiser will likely also work).
cost = tf.reduce_mean(tf.squared_difference(out, Y)) train_op = tf.train.AdamOptimizer().minimize(cost) # Feel free to adjust the number of epochs to your liking. n_epochs = 5e+4 # Create function to generate a coordinate matrix (i.e. matrix of normalised coordinates) # Pardon my lambda generate_coord = lambda size:...
notebooks/super-resolution_coordinates.ipynb
liviu-/notebooks
mit
Evaluation aka plotting the generated image and carefully considering whether it meets the desired standards or there's a need for readjusting either the hyperparameters or the expectations.
plt.imshow(new_image.reshape(test_size, test_size, -1))
notebooks/super-resolution_coordinates.ipynb
liviu-/notebooks
mit
Passive Linear Time Delays Networks The first component of the project takes as inputs a description of a model, which can be thought of as a graph where the nodes and edges have some special properties. These properties are outlines below.
G = nx.DiGraph(selfloops=True)
graph_to_matrices.ipynb
tabakg/potapov_interpolation
gpl-3.0
We use a directed graph with various properties along the nodes and edges. The direction describes the propagation of signals in the system. There are three kinds of nodes: inputs nodes, internal nodes, and output nodes. There is the same number of input and output nodes (say n). The number of internal nodes may be dif...
rs = np.asarray([0.9,0.5,0.8]) ## some sample values ts = np.sqrt(1.-rs**2) ## ts are determined from rs N = 2 ## number of input nodes for i in range(N): ## make the input and output nodes G.add_node(i*2,label='x_in_'+str(i)) G.add_node(i*2+1,label='x_out_'+str(i)) for i,(r,t) in enumerate(zip(rs,ts)): ## ...
graph_to_matrices.ipynb
tabakg/potapov_interpolation
gpl-3.0
Each (directed) edge $j$ has a time delay $\tau_j$. In general a delay line may have an additional phase shift $\exp(i\theta_j)$ which is determined by a number $\theta_j$. We will also include a pair of indices for each edge. The first index corresponds to the previous node and the second index corresponds to the next...
## edges to inputs G.add_edge(0,4,delay=0.,indices=(0,0),theta=0.,edge_type = 'input',edge_num=0) G.add_edge(2,6,delay=0.,indices=(0,1),theta=0.,edge_type = 'input',edge_num=1) ## edges to outputs G.add_edge(4,1,delay=0.,indices=(1,0),theta=0.,edge_type = 'output',edge_num=2) G.add_edge(6,3,delay=0.,indices=(0,0),thet...
graph_to_matrices.ipynb
tabakg/potapov_interpolation
gpl-3.0
Convert the network of nodes and edges to the framework used in the paper. This would take the graph structure above and generate matrices $M1,M2,M2,M3$ in the notation used in Potapov_Code.Time_Delay_Network.py. This would allow generating an instance of Time_Delay_Network.
internal_edges = {(edge[0],edge[1]):edge[2] for edge in G.edges(data=True) if edge[2]['edge_type'] == 'internal'} m = len(internal_edges) # input_edges = [edge for edge in G.edges(data=True) if edge[2]['edge_type'] == 'input'] # output_edges = [edge for edge in G.edges(data=True) if edge[2]['edge_type'] == 'output'] ...
graph_to_matrices.ipynb
tabakg/potapov_interpolation
gpl-3.0
Usage Description Using the run_Potapov function of this method generates the variables that will be used for the first part of the visualization. Those are contained in an instance of the Time_Delay_Network. Specifically, the outputs we will want to plot are (1) Time_Delay_Network.roots (2) Time_Delay_Network.spatial_...
import Potapov_Code Network = Potapov_Code.Time_Delay_Network.Example3() ## an example network with hardcoded values Network.run_Potapov(commensurate_roots=True) ## run the analysis roots = Network.roots ## roots plt.scatter(map(lambda z: z.real, roots), map(lambda z: z.imag, roots)) Network.spatial_modes ## the s...
graph_to_matrices.ipynb
tabakg/potapov_interpolation
gpl-3.0
First thing is to read in your data. This example uses the Australian Geofabric V2 and V3 data. Other datasets would need their own customised data prep code. In the next 2 steps ignore the duplicate catchment warnings for the case of testing the code. I havent dealt with all the minor details of the geofabric quite ri...
DG2 = rc.read_geofabric_data(netGDB2) rc.remove_geofabric_catch_duplicates(DG2) nx.write_gpickle(DG2, os.path.join(pkl_path, 'PG_conflation2.p')) DG2_idx = rc.build_index(DG2) DG1 = rc.read_geofabric_data(netGDB1,DG2_idx.bounds) rc.remove_geofabric_catch_duplicates(DG1) nx.write_gpickle(DG1, os.path.join(pkl_path, 'PG...
conflationExample.ipynb
artttt/RiverConflation
mit
you can start from here by loading in the pickles that were created with the above code earlier. Run the imports and global variables code at the top first though
DG1 = nx.read_gpickle(os.path.join(pkl_path, 'PG_conflation.p')) DG2 = nx.read_gpickle(os.path.join(pkl_path, 'PG_conflation2.p')) DG2_idx = rc.build_index(DG2) # starting from pickles = 1 minute 2GB #starting from scratch = 12 minutes #This is done seperate to finding matches because it takes a while so its nice to s...
conflationExample.ipynb
artttt/RiverConflation
mit
The next step is to sum up areas to find the catchment overlap for every combination. We are only interested in the best or a short list of the overlaps that match well The simple approach is a brute force exhustive test of all combinations. This works well for a few thousand (75 minutes for 17k x 17k) sub catchments i...
#%%timeit -n1 -r1 rc.upstream_edge_set(DG2) #<10sec approx 2GB sizeRatio=0.5 matches = rc.find_all_matches(DG1,DG2,DG2_idx,searchRadius,sizeRatio,maxMatchKeep) # depends on the search radius used. # 8 minutes with searchRadius=0.005 (500m) and a sizeRatio=0 # 7.5 minutes with searchRadius=0.01 (1km) and a sizeRatio=0....
conflationExample.ipynb
artttt/RiverConflation
mit
To kick us off, I will draw this landscape, using a matplotlib heatmap function that shows the highest altitude in red, down to the lowest altitudes in blue:
%matplotlib inline import matplotlib.pyplot as plt import matplotlib.dates plt.rcParams['figure.figsize'] = (20.0, 8.0) plt.figure() plt.imshow(heights , interpolation='nearest', cmap='jet') plt.title('heights') plt.show()
python_notebooks/Watershed Problem.ipynb
learn1do1/learn1do1.github.io
mit
We have to make a decision. Should the water always flow down the steepest slope? Let's assume yes, even tho it may upset Ian Malcolm from Jurassic Park: Should it pool together when the slope is 0? This describes the 3 adjacent blocks of height Zero in the heights matrix, drawn above. I'd argue yes. In order to guara...
watersheds = [[None] * len(heights) for x in range(len(heights))] slopes = [[-1] * len(heights) for x in range(len(heights))]
python_notebooks/Watershed Problem.ipynb
learn1do1/learn1do1.github.io
mit
The watershed matrix stores an integer for each cell. When Cells in that matrix that share the same integer, it means they belong to the same watershed. The slopes matrix stores the steepest slope that the water can flow in each cell
import operator def initialize_positions(heights): positions = [] for i in range(len(heights)): for j in range(len(heights)): positions.append(position((i,j), heights[i][j])) positions.sort(key=operator.attrgetter('height')) return positions positions = initialize_positions(h...
python_notebooks/Watershed Problem.ipynb
learn1do1/learn1do1.github.io
mit
Our strategy is to sort positions from deepest to highest. Starting at the deepest, let's find all adjacent positions that would flow into it. We determine those positions by using the flow_up function. We continue this search from each of the new positions we have just moved up to, until every cell in the slopes array...
# Will return all neighbors where the slope to the current position is steeper than we have yet seen. def flow_up(heights, (i, j)): up_coordinates = set() neighbor_coordinates = set() local_height = heights[i][j] # look up, down, left, right neighbor_coordinates.add((max(i - 1, 0),j)) neigh...
python_notebooks/Watershed Problem.ipynb
learn1do1/learn1do1.github.io
mit
Let's do a simple test of our functions. Let's give it a landscape that looks like a wide staircase and make sure the output is just a single watershed.
n = 10 heights = [[x] * n for x in range(n)] watersheds = [[None] * len(heights) for x in range(len(heights))] slopes = [[-1] * len(heights) for x in range(len(heights))] positions = initialize_positions(heights) positions.sort(key=operator.attrgetter('height')) main() plt.figure() plt.imshow(heights , interpolation='...
python_notebooks/Watershed Problem.ipynb
learn1do1/learn1do1.github.io
mit
It's interesting in this single-watershed case to see how simple the slopes object becomes. Either water is spreading in a flat basin (slope of 0) or it is flowing down the staircase (slope of 1). Now we can showcase the watershed code on a random input landscape
import random heights = [[random.randint(0, n) for x in range(n)] for x in range(n)] watersheds = [[None] * len(heights) for x in range(len(heights))] slopes = [[-1] * len(heights) for x in range(len(heights))] positions = initialize_positions(heights) main() plt.figure() plt.imshow(heights , interpolation='nearest', ...
python_notebooks/Watershed Problem.ipynb
learn1do1/learn1do1.github.io
mit
What happens in this program? The program starts out with a list of desserts, and one dessert is identified as a favorite. The for loop runs through all the desserts. Inside the for loop, each item in the list is tested. If the current value of dessert is equal to the value of favorite_dessert, a message is printed th...
5 == 5 3 == 5 5 == 5.0 'eric' == 'eric' 'Eric' == 'eric' 'Eric'.lower() == 'eric'.lower() '5' == 5 '5' == str(5)
notebooks/if_statements.ipynb
nntisapeh/intro_programming
mit
Data Analysis In this section we will run a Cross Validation routine
from tpot import TPOTClassifier from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = preprocess() tpot = TPOTClassifier(generations=5, population_size=20, verbosity=2,max_eval_time_mins=20, max_time_mins=100,scoring='f1_micro', ...
LA_Team/Facies_classification_LA_TEAM_05.ipynb
seg/2016-ml-contest
apache-2.0
Working with Python Classes Encapsulation is seen as the bundling of data with the methods that operate on that data. It is often accomplished by providing two kinds of methods for attributes: The methods for retrieving or accessing the values of attributes are called getter methods. Getter methods do not change the va...
class A: def __init__(self): self.__priv = "I am private" self._prot = "I am protected" self.pub = "I am public" x = A() print(x.pub) # Whenever we assign or retrieve any object attribute # Python searches it in the object's __dict__ dictionary print(x.__dict__)
python/class.ipynb
ethen8181/machine-learning
mit
When the Python compiler sees a private attribute, it actually transforms the actual name to _[Class name]__[private attribute name]. However, this still does not prevent the end-user from accessing the attribute. Thus in Python land, it is more common to use public and protected attribute, write proper docstrings and ...
class Celsius: def __init__(self, temperature = 0): self.set_temperature(temperature) def to_fahrenheit(self): return (self.get_temperature() * 1.8) + 32 def get_temperature(self): return self._temperature def set_temperature(self, value): if value < -273: ...
python/class.ipynb
ethen8181/machine-learning
mit
Instead of that, now the property way. Where we define the @property and the @[attribute name].setter.
class Celsius: def __init__(self, temperature = 0): self._temperature = temperature def to_fahrenheit(self): return (self.temperature * 1.8) + 32 # have access to the value like it is an attribute instead of a method @property def temperature(self): return self._te...
python/class.ipynb
ethen8181/machine-learning
mit
@classmethod and @staticmethod @classmethods create alternative constructors for the class. An example of this behavior is there are different ways to construct a dictionary.
print(dict.fromkeys(['raymond', 'rachel', 'mathew'])) import time class Date: # Primary constructor def __init__(self, year, month, day): self.year = year self.month = month self.day = day # Alternate constructor @classmethod def today(cls): t = time.localtime() ...
python/class.ipynb
ethen8181/machine-learning
mit
The cls is critical, as it is an object that holds the class itself. This makes them work with inheritance.
class NewDate(Date): pass # Creates an instance of Date (cls=Date) c = Date.today() print(c.__dict__) # Creates an instance of NewDate (cls=NewDate) d = NewDate.today() print(d.__dict__)
python/class.ipynb
ethen8181/machine-learning
mit
The purpose of @staticmethod is to attach functions to classes. We do this to improve the findability of the function and to make sure that people are using the function in the appropriate context.
class Date: # Primary constructor def __init__(self, year, month, day): self.year = year self.month = month self.day = day # Alternate constructor @classmethod def today(cls): t = time.localtime() return cls(t.tm_year, t.tm_mon, t.tm_mday) # the logi...
python/class.ipynb
ethen8181/machine-learning
mit
Simple Dataset Usually when working with data we have one or more independent variables, taking the form of categories, labels, discrete sample coordinates, or bins. These variables are what we refer to as key dimensions (or kdims for short) in HoloViews. The observer or dependent variables, on the other hand, are ref...
xs = range(10) ys = np.exp(xs) table = hv.Table((xs, ys), kdims=['x'], vdims=['y']) table
doc/Tutorials/Columnar_Data.ipynb
vascotenner/holoviews
bsd-3-clause
However, this data has many more meaningful visual representations, and therefore the first important concept is that Dataset objects are interchangeable as long as their dimensionality allows it, meaning that you can easily create the different objects from the same data (and cast between the objects once created):
hv.Scatter(table) + hv.Curve(table) + hv.Bars(table)
doc/Tutorials/Columnar_Data.ipynb
vascotenner/holoviews
bsd-3-clause
Each of these three plots uses the same data, but represents a different assumption about the semantic meaning of that data -- the Scatter plot is appropriate if that data consists of independent samples, the Curve plot is appropriate for samples chosen from an underlying smooth function, and the Bars plot is appropria...
print(repr(hv.Scatter({'x': xs, 'y': ys}) + hv.Scatter(np.column_stack([xs, ys])) + hv.Scatter(pd.DataFrame({'x': xs, 'y': ys}))))
doc/Tutorials/Columnar_Data.ipynb
vascotenner/holoviews
bsd-3-clause
Literals In addition to the main storage formats, Dataset Elements support construction from three Python literal formats: (a) An iterator of y-values, (b) a tuple of columns, and (c) an iterator of row tuples.
print(repr(hv.Scatter(ys) + hv.Scatter((xs, ys)) + hv.Scatter(zip(xs, ys))))
doc/Tutorials/Columnar_Data.ipynb
vascotenner/holoviews
bsd-3-clause
For these inputs, the data will need to be copied to a new data structure, having one of the three storage formats above. By default Dataset will try to construct a simple array, falling back to either pandas dataframes (if available) or the dictionary-based format if the data is not purely numeric. Additionally, the ...
df = pd.DataFrame({'x': xs, 'y': ys, 'z': ys*2}) print(type(hv.Scatter(df).data))
doc/Tutorials/Columnar_Data.ipynb
vascotenner/holoviews
bsd-3-clause
Dataset will attempt to parse the supplied data, falling back to each consecutive interface if the previous could not interpret the data. The default list of fallbacks and simultaneously the list of allowed datatypes is:
hv.Dataset.datatype
doc/Tutorials/Columnar_Data.ipynb
vascotenner/holoviews
bsd-3-clause
To select a particular storage format explicitly, supply one or more allowed datatypes:
print(type(hv.Scatter((xs, ys), datatype=['array']).data)) print(type(hv.Scatter((xs, ys), datatype=['dictionary']).data)) print(type(hv.Scatter((xs, ys), datatype=['dataframe']).data))
doc/Tutorials/Columnar_Data.ipynb
vascotenner/holoviews
bsd-3-clause
Sharing Data Since the formats with labelled columns do not require any specific order, each Element can effectively become a view into a single set of data. By specifying different key and value dimensions, many Elements can show different values, while sharing the same underlying data source.
overlay = hv.Scatter(df, kdims='x', vdims='y') * hv.Scatter(df, kdims='x', vdims='z') overlay
doc/Tutorials/Columnar_Data.ipynb
vascotenner/holoviews
bsd-3-clause
We can quickly confirm that the data is actually shared:
overlay.Scatter.I.data is overlay.Scatter.II.data
doc/Tutorials/Columnar_Data.ipynb
vascotenner/holoviews
bsd-3-clause
For columnar data, this approach is much more efficient than creating copies of the data for each Element, and allows for some advanced features like linked brushing in the Bokeh backend. Converting to raw data Column types make it easy to export the data to the three basic formats: arrays, dataframes, and a dictionary...
table.array()
doc/Tutorials/Columnar_Data.ipynb
vascotenner/holoviews
bsd-3-clause