markdown stringlengths 0 1.02M | code stringlengths 0 832k | output stringlengths 0 1.02M | license stringlengths 3 36 | path stringlengths 6 265 | repo_name stringlengths 6 127 |
|---|---|---|---|---|---|
Is there a relationship between the number of groups that a user has sent messages to and the number of messages that user has sent (total, or the median number to groups)? | working.plot.scatter('Number of Groups','Total Messages', xlim=(1,300), ylim=(1,20000), logx=False, logy=True) | _____no_output_____ | MIT | examples/experimental_notebooks/IETF Participants.ipynb | nllz/bigbang |
It appears that there are interesting outliers here. Some who send a couple messages each to a large number of groups, but then a separate group of outliers that sends lots of messages and to lots of groups. That might be an elite component worthy of separate analysis. A density graph will show, however, that while the... | sns.jointplot(x='Number of Groups',y='Total Messages (log)', data=working, kind="kde", xlim=(0,50), ylim=(0,3)); | _____no_output_____ | MIT | examples/experimental_notebooks/IETF Participants.ipynb | nllz/bigbang |
Relationships between groups and participants Can we learn implicit relationships between groups based on the messaging patterns of participants? PCA We want to work with just the data of people and how many messages they sent to each group. | df = people[people['Total Messages'] > 5]
df = df.drop(columns=['email','name','Total Messages','Number of Groups','Median Messages per Group'])
df = df.fillna(0) | _____no_output_____ | MIT | examples/experimental_notebooks/IETF Participants.ipynb | nllz/bigbang |
Principal Component Analysis (PCA) will seek to explain the most variance in the samples (participants) based on the features (messages sent to different lists). Let's try with two components and see what PCA sees as the most distinguishing dimensions of IETF participation. | import sklearn
from sklearn.decomposition import PCA
scaled = sklearn.preprocessing.maxabs_scale(df)
pca = PCA(n_components=2, whiten=True)
pca.fit(scaled)
components_frame = pd.DataFrame(pca.components_)
components_frame.columns = df.columns
components_frame
for i, row in components_frame.iterrows():
print('\nCo... |
Component 0
Most positive correlation:
['93attendees' '88attendees' '77attendees' '87attendees' 'bofchairs']
Most negative correlation:
['tap' 'eos' 'dmarc-report' 'web' 'spam']
Component 1
Most positive correlation:
['89all' '90all' '91all' '82all' '94all']
Most negative correlation:
['ippm' 'rtgwg' 'i-d-announc... | MIT | examples/experimental_notebooks/IETF Participants.ipynb | nllz/bigbang |
Component 0 is mostly routing (Layer 3 and Layer 2 VPNs, the routing area working group, interdomain routing. (IP Performance/Measurement seems different -- is it related?)Component 1 is all Internet area groups, mostly related to IPv6, and specifically different groups working on mobility-related extensions to IPv6. W... | pca.explained_variance_ | _____no_output_____ | MIT | examples/experimental_notebooks/IETF Participants.ipynb | nllz/bigbang |
The explained variance by our components seems extremely tiny. With two components (or the two most significant components), we can attempt a basic visualization as a scatter plot. | component_df = pd.DataFrame(pca.transform(df), columns=['PCA%i' % i for i in range(2)], index=df.index)
component_df.plot.scatter(x='PCA0',y='PCA1') | _____no_output_____ | MIT | examples/experimental_notebooks/IETF Participants.ipynb | nllz/bigbang |
And with a larger number of components? | pca = PCA(n_components=10, whiten=True)
pca.fit(scaled)
components_frame = pd.DataFrame(pca.components_)
components_frame.columns = df.columns
for i, row in components_frame.iterrows():
print('\nComponent %d' % i)
r = row.sort_values(ascending=False)
print('Most positive correlation:\n %s' % r[:5].index.val... |
Component 0
Most positive correlation:
['93attendees' '88attendees' '77attendees' '87attendees' 'bofchairs']
Most negative correlation:
['tap' 'eos' 'dmarc-report' 'web' 'spam']
Component 1
Most positive correlation:
['89all' '90all' '91all' '82all' '94all']
Most negative correlation:
['ippm' 'rtgwg' 'i-d-announc... | MIT | examples/experimental_notebooks/IETF Participants.ipynb | nllz/bigbang |
There are definitely subject domain areas in these lists (the last one, for example, on groups related to phone calls and emergency services). Also interesting is the presence of some meta-topics, like `mtgvenue` or `policy` or `iasa20` (an IETF governance topic). _Future work: we might be able to use this sparse matri... | df = people.sort_values(by="Total Messages",ascending=False)[:5000]
df = df.drop(columns=['email','name','Total Messages','Number of Groups','Median Messages per Group'])
df = df.fillna(0)
import networkx as nx
G = nx.Graph()
for group in df.columns:
G.add_node(group,type="group")
for name, data in df.iterro... | _____no_output_____ | MIT | examples/experimental_notebooks/IETF Participants.ipynb | nllz/bigbang |
Yep, it is bipartite! Now, we can export a graph file for use in visualization software Gephi. | nx.write_gexf(G,'ietf-participation-bipartite.gexf')
people_nodes, group_nodes = nx.algorithms.bipartite.sets(G) | _____no_output_____ | MIT | examples/experimental_notebooks/IETF Participants.ipynb | nllz/bigbang |
We can calculate the "PageRank" of each person and group, using the weights (number of messages) between groups and people to distribute a kind of influence. | pr = nx.pagerank(G, weight="weight")
nx.set_node_attributes(G, "pagerank", pr)
sorted([node for node in list(G.nodes(data=True))
if node[1]['type'] == 'group'],
key=lambda x: x[1]['pagerank'],
reverse =True)[:10]
sorted([node for node in list(G.nodes(data=True))
if node[1]['type'] == '... | _____no_output_____ | MIT | examples/experimental_notebooks/IETF Participants.ipynb | nllz/bigbang |
However, PageRank is probably less informative than usual here, because this is a bipartite, non-directed graph. Instead, let's calculate a normalized, closeness centrality specific to bipartite graphs. | person_nodes = [node[0] for node in G.nodes(data=True) if node[1]['type'] == 'person'] | _____no_output_____ | MIT | examples/experimental_notebooks/IETF Participants.ipynb | nllz/bigbang |
**NB: Slow operation for large graphs.** | cc = nx.algorithms.bipartite.centrality.closeness_centrality(G, person_nodes, normalized=True)
for node, value in list(cc.items()):
if type(node) not in [str, str]:
print(node)
print(value)
del cc[14350.0] # remove a spurious node value
nx.set_node_attributes(G, "closeness", cc)
sorted([node for nod... | _____no_output_____ | MIT | examples/experimental_notebooks/IETF Participants.ipynb | nllz/bigbang |
Data description`alldat` contains 39 sessions from 10 mice, data from Steinmetz et al, 2019. Time bins for all measurements are 10ms, starting 500ms before stimulus onset. The mouse had to determine which side has the highest contrast. For each `dat = alldat[k]`, you have the following fields:* `dat['mouse_name']`: mo... | #@title Boundaries plot
dt_waveforms = 1/30000 # dt of waveform
binsize = dat['bin_size'] # bin times spikes
mean_firing = dat['spks'].mean(axis = (1,2)) * 1/binsize # computing mean firing rate
t_t_peak = dat['trough_to_peak'] * dt_waveforms * 1e3 # computing trough to peak time in ms
plt.scatter(mean_firing,t_t_peak... | _____no_output_____ | MIT | NMA_project.ipynb | AvocadoChutneys/ProjectNMA |
Next, we create a dataframe with the related labels: | #@title Label DataFrame
import plotly.express as px
labeling_df = pd.DataFrame({
"Mean Firing Rate": mean_firing,
"Trough to peak": t_t_peak,
"Region": dat['brain_area'],
"Area":dat['brain_area']
})
labeling_df.replace(
{
"Area": {"CA1":"Hippocampus","DG":"Hippocampus","SUB":"Hippocampus"... | _____no_output_____ | MIT | NMA_project.ipynb | AvocadoChutneys/ProjectNMA |
Raster plot* We are now able to separate the **trials** based on *correct and incorrect* responses and separate the **neurons** based on *putative cell type** Inhibitory cells * Other cells * Excitatory cells | #@title raster visualizer
from ipywidgets import interact
import ipywidgets as widgets
vis_right = dat['contrast_right'] # 0 - low - high
vis_left = dat['contrast_left'] # 0 - low - high
is_correct = np.sign(dat['response'])==np.sign(vis_left-vis_right)
def raster_visualizer(area,trial):
spikes= dat2['ss']
plt.figu... | _____no_output_____ | MIT | NMA_project.ipynb | AvocadoChutneys/ProjectNMA |
Modeling* first cell creates the full data frame: * each column is a neuron (*except the last one which is the target variable*) * each row is a trial * each cell is mean firing rateIn this example we are taking the hippocampal region | #@title DataFrame construction
# selects only correct after incorrect trials and correct after correct trials
correct_after_i = np.where(np.diff(is_correct.astype('float32'))==1)[0]
idx_c_c = []
for i in range(len(is_correct)-1):
if is_correct[i] == 1 & is_correct[i+1]==1:
idx_c_c.append(i)
correct_after_c = n... | _____no_output_____ | MIT | NMA_project.ipynb | AvocadoChutneys/ProjectNMA |
This results make us think that the prestimulus activity **could** carry on information related with the previous trial.We realized that we had a imbalance problem so we proceeded to balance the classes: | !pip install imbalanced-learn --quiet
#@title Balancing function
def balancer(X,y,undersample = 0.5):
from imblearn.pipeline import Pipeline
from imblearn.over_sampling import SMOTE
from imblearn.under_sampling import RandomUnderSampler
print('######################################################')
print... | _____no_output_____ | MIT | NMA_project.ipynb | AvocadoChutneys/ProjectNMA |
After balancing the classes we see a decrease in accuracy but a fairly increase in AUC, which might mean that with the unbalanced dataset our classifier was assinging the most frequent class to every sample. Selection of a better modelNow that we know that pre-estimulus activity might be able to classify a correct tri... | from pycaret.classification import *
resampled_df = construct_df(b_X_pres, b_y_pres,named=True)
exp_clf101 = setup(data = resampled_df, target = 'target', numeric_features=['N1','N22','N32','N143','N148','N153','N183','N184','N189'], session_id=123) |
Setup Succesfully Completed!
| MIT | NMA_project.ipynb | AvocadoChutneys/ProjectNMA |
Here we are comparing different CV classification metrics from 14 different models, **Quadratic Discriminant Analysis** had the best performance | compare_models() | _____no_output_____ | MIT | NMA_project.ipynb | AvocadoChutneys/ProjectNMA |
Quadratic Discriminant AnalysisWe have to classes $k \in \{0,1\}$ that belongs to correct preceded by incorrect trial (0) and correct preceded by correct (1).Every class has a prior probability $P(k) = 0.5$ since is a balanced dataframe and $P(k) = \frac{N_k}{N}$.And basically we are trying to find the posterior proba... | qda = create_model('qda') | _____no_output_____ | MIT | NMA_project.ipynb | AvocadoChutneys/ProjectNMA |
Here we can see the ROC curve and the Precision-Recall curve of the classifier, describing that our classifier is able to discriminate between both clasess very well.Results in the test set: | plot_model(qda, plot = 'auc')
plot_model(qda, plot = 'pr') | _____no_output_____ | MIT | NMA_project.ipynb | AvocadoChutneys/ProjectNMA |
The confusion matrix show us that it is easier to classify correctly a correct trial preceded by a correct trial from only the pre-estimulus activity.Having 3 false positives in the test set: | plot_model(qda, plot = 'confusion_matrix') | _____no_output_____ | MIT | NMA_project.ipynb | AvocadoChutneys/ProjectNMA |
Finally we test out the model and retrieve the metrics with unseen data (our test set): | predict_model(qda); | _____no_output_____ | MIT | NMA_project.ipynb | AvocadoChutneys/ProjectNMA |
Finding the Max Sharpe Ratio PortfolioWe've already seen that given a set of expected returns and a covariance matrix, we can plot the efficient frontier. In this section, we'll extend the code to locate the point on the efficient frontier that we are most interested in, which is the tangency portfolio or the Max Shar... | %load_ext autoreload
%autoreload 2
%matplotlib inline
import edhec_risk_kit_110 as erk
ind = erk.get_ind_returns()
er = erk.annualize_rets(ind["1996":"2000"], 12)
cov = ind["1996":"2000"].cov() | _____no_output_____ | CNRI-Python-GPL-Compatible | Investment Management/Course1/lab_110.ipynb | djoye21school/python |
We already know how to identify points on the curve if we are given a target rate of return. Instead of minimizing the vol based on a target return, we want to find that one point on the curve that maximizes the Sharpe Ratio, given the risk free rate.```pythondef msr(riskfree_rate, er, cov): """ Returns the weigh... | ax = erk.plot_ef(20, er, cov)
ax.set_xlim(left = 0)
# plot EF
ax = erk.plot_ef(20, er, cov)
ax.set_xlim(left = 0)
# get MSR
rf = 0.1
w_msr = erk.msr(rf, er, cov)
r_msr = erk.portfolio_return(w_msr, er)
vol_msr = erk.portfolio_vol(w_msr, cov)
# add CML
cml_x = [0, vol_msr]
cml_y = [rf, r_msr]
ax.plot(cml_x, cml_y, color... | _____no_output_____ | CNRI-Python-GPL-Compatible | Investment Management/Course1/lab_110.ipynb | djoye21school/python |
Let's put it all together by adding the CML to the `plot_ef` code.Add the following code:```python if show_cml: ax.set_xlim(left = 0) get MSR w_msr = msr(riskfree_rate, er, cov) r_msr = portfolio_return(w_msr, er) vol_msr = portfolio_vol(w_msr, cov) add CML cml_x = ... | erk.plot_ef(20, er, cov, style='-', show_cml=True, riskfree_rate=0.1) | _____no_output_____ | CNRI-Python-GPL-Compatible | Investment Management/Course1/lab_110.ipynb | djoye21school/python |
Plotting the results of Man Of the Match Award in IPL 2008 - 2018 | player_names = list(player_of_match.keys())
number_of_times = list(player_of_match.values())
# Plotting the Graph
plt.bar(range(len(player_of_match)), number_of_times)
plt.title('Man Of the Match Award')
plt.show() | _____no_output_____ | MIT | .ipynb_checkpoints/IPL 2008 - 2018 Analysis-checkpoint.ipynb | srimani-programmer/IPL-Analysis |
Number Of Wins Of Each Team | teamWinCounts = dict()
for team in matches_dataset['winner']:
if team == None:
continue
else:
teamWinCounts[team] = teamWinCounts.get(team,0) + 1
for teamName, Count in teamWinCounts.items():
print(teamName,':',Count) | Sunrisers Hyderabad : 52
Rising Pune Supergiant : 10
Kolkata Knight Riders : 86
Kings XI Punjab : 76
Royal Challengers Bangalore : 79
Mumbai Indians : 98
Delhi Daredevils : 67
Gujarat Lions : 13
Chennai Super Kings : 90
Rajasthan Royals : 70
Deccan Chargers : 29
Pune Warriors : 12
Kochi Tuskers Kerala : 6
nan : 3
Risin... | MIT | .ipynb_checkpoints/IPL 2008 - 2018 Analysis-checkpoint.ipynb | srimani-programmer/IPL-Analysis |
Plotting the Results Of Team Winning | numberOfWins = teamWinCounts.values()
teamName = teamWinCounts.keys()
plt.bar(range(len(teamWinCounts)), numberOfWins)
plt.xticks(range(len(teamWinCounts)), list(teamWinCounts.keys()), rotation='vertical')
plt.xlabel('Team Names')
plt.ylabel('Number Of Win Matches')
plt.title('Analysis Of Number Of Matches win by Each ... | _____no_output_____ | MIT | .ipynb_checkpoints/IPL 2008 - 2018 Analysis-checkpoint.ipynb | srimani-programmer/IPL-Analysis |
Total Matches Played by Each team From 2008 - 2018 | totalMatchesCount = dict()
# For Team1
for team in matches_dataset['team1']:
totalMatchesCount[team] = totalMatchesCount.get(team, 0) + 1
# For Team2
for team in matches_dataset['team2']:
totalMatchesCount[team] = totalMatchesCount.get(team, 0) + 1
# Printing the total matches played by each team
for teamNa... | Sunrisers Hyderabad : 93
Mumbai Indians : 171
Gujarat Lions : 30
Rising Pune Supergiant : 16
Royal Challengers Bangalore : 166
Kolkata Knight Riders : 164
Delhi Daredevils : 161
Kings XI Punjab : 162
Chennai Super Kings : 147
Rajasthan Royals : 133
Deccan Chargers : 75
Kochi Tuskers Kerala : 14
Pune Warriors : 46
Risin... | MIT | .ipynb_checkpoints/IPL 2008 - 2018 Analysis-checkpoint.ipynb | srimani-programmer/IPL-Analysis |
Plotting the Total Matches Played by Each Team | teamNames = totalMatchesCount.keys()
teamCount = totalMatchesCount.values()
plt.bar(range(len(totalMatchesCount)), teamCount)
plt.xticks(range(len(totalMatchesCount)), list(teamNames), rotation='vertical')
plt.xlabel('Team Names')
plt.ylabel('Number Of Played Matches')
plt.title('Total Number Of Matches Played By Each... | _____no_output_____ | MIT | .ipynb_checkpoints/IPL 2008 - 2018 Analysis-checkpoint.ipynb | srimani-programmer/IPL-Analysis |
CO460 - Deep Learning - Lab exercise 3 IntroductionIn this exercise, you will develop and experiment with convolutional AEs (CAE) and VAEs (CVAE).You will be asked to:- experiment with the architectures and compare the convolutional models to the fully connected ones. - investigate and implement sampling and interpol... | import os
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
from torchvision import datasets, transforms
from torchvision.utils import save_image
import torch.nn.functional as F
from utils import *
import matplotlib.pyplot as plt
import numpy as np
from utils impor... | _____no_output_____ | MIT | AE_VAE_CAE_CVAE/LabExercise3.ipynb | quantumiracle/Course_Code |
Device selection | GPU = True
device_idx = 0
if GPU:
device = torch.device("cuda:"+str(device_idx) if torch.cuda.is_available() else "cpu")
else:
device = torch.device("cpu")
print(device) | cuda:0
| MIT | AE_VAE_CAE_CVAE/LabExercise3.ipynb | quantumiracle/Course_Code |
Reproducibility | # We set a random seed to ensure that your results are reproducible.
if torch.cuda.is_available():
torch.backends.cudnn.deterministic = True
torch.manual_seed(0) | _____no_output_____ | MIT | AE_VAE_CAE_CVAE/LabExercise3.ipynb | quantumiracle/Course_Code |
Part 1 - CAE Normalization: $ x_{norm} = \frac{x-\mu}{\sigma} $_Thus_ :$ \min{x_{norm}} = \frac{\min{(x)}-\mu}{\sigma} = \frac{0-0.5}{0.5} = -1 $_Similarly_:$ \max{(x_{norm})} = ... = 1 $* Input $\in [-1,1] $* Output should span the same interval $ \rightarrow$ Activation function of the output layer should be chosen... | transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
])
denorm = denorm_for_tanh
train_dat = datasets.MNIST(
"data/", train=True, download=True, transform=transform
)
test_dat = datasets.MNIST("data/", train=False, transform=transform) | Downloading http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz
Downloading http://yann.lecun.com/exdb/mnist/train-labels-idx1-ubyte.gz
Downloading http://yann.lecun.com/exdb/mnist/t10k-images-idx3-ubyte.gz
Downloading http://yann.lecun.com/exdb/mnist/t10k-labels-idx1-ubyte.gz
Processing...
Done!
| MIT | AE_VAE_CAE_CVAE/LabExercise3.ipynb | quantumiracle/Course_Code |
Hyper-parameter selection | if not os.path.exists('./CAE'):
os.mkdir('./CAE')
num_epochs = 20
batch_size = 128
learning_rate = 1e-3 | _____no_output_____ | MIT | AE_VAE_CAE_CVAE/LabExercise3.ipynb | quantumiracle/Course_Code |
Define the dataloaders | train_loader = DataLoader(train_dat, batch_size, shuffle=True)
test_loader = DataLoader(test_dat, batch_size, shuffle=False)
it = iter(test_loader)
sample_inputs, _ = next(it)
fixed_input = sample_inputs[:32, :, :, :]
in_dim = fixed_input.shape[-1]*fixed_input.shape[-2]
save_image(fixed_input, './CAE/image_original.... | _____no_output_____ | MIT | AE_VAE_CAE_CVAE/LabExercise3.ipynb | quantumiracle/Course_Code |
Define the model - CAEComplete the `encoder` and `decoder` methods in the CAE pipeline.To find an effective architecture, you can experiment with the following:- the number of convolutional layers- the kernels' sizes- the stride values- the size of the latent space layer | class CAE(nn.Module):
def __init__(self, latent_dim):
super(CAE, self).__init__()
"""
TODO: Define here the layers (convolutions, relu etc.) that will be
used in the encoder and decoder pipelines.
"""
def encode(self, x):
"""
TODO: Constr... | _____no_output_____ | MIT | AE_VAE_CAE_CVAE/LabExercise3.ipynb | quantumiracle/Course_Code |
Define Loss function | criterion = nn.L1Loss(reduction='sum') # can we use any other loss here?
def loss_function_CAE(recon_x, x):
recon_loss = criterion(recon_x, x)
return recon_loss | _____no_output_____ | MIT | AE_VAE_CAE_CVAE/LabExercise3.ipynb | quantumiracle/Course_Code |
Initialize Model and print number of parameters | model = cv_AE.to(device)
params = sum(p.numel() for p in model.parameters() if p.requires_grad)
print("Total number of parameters is: {}".format(params)) # what would the number actually be?
print(model) | _____no_output_____ | MIT | AE_VAE_CAE_CVAE/LabExercise3.ipynb | quantumiracle/Course_Code |
Choose and initialize optimizer | optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate) | _____no_output_____ | MIT | AE_VAE_CAE_CVAE/LabExercise3.ipynb | quantumiracle/Course_Code |
Train | model.train()
for epoch in range(num_epochs):
train_loss = 0
for batch_idx, data in enumerate(train_loader):
img, _ = data
img = img.to(device)
optimizer.zero_grad()
# forward
recon_batch = model(img)
loss = loss_function_CAE(recon_batch, img)
# backward
... | _____no_output_____ | MIT | AE_VAE_CAE_CVAE/LabExercise3.ipynb | quantumiracle/Course_Code |
Test | # load the model
model.load_state_dict(torch.load("./CAE/model.pth"))
model.eval()
test_loss = 0
with torch.no_grad():
for i, (img, _) in enumerate(test_loader):
img = img.to(device)
recon_batch = model(img)
test_loss += loss_function_CAE(recon_batch, img)
# reconstruct and save the last... | _____no_output_____ | MIT | AE_VAE_CAE_CVAE/LabExercise3.ipynb | quantumiracle/Course_Code |
Interpolations | # Define inpute tensors
x1 =
x2 =
# Create the latent representations
z1 = model.encode(x1)
z2 = model.encode(x2)
"""
TODO: Find a way to create interpolated results from the CAE.
"""
Z =
X_hat = model.decode(Z) | _____no_output_____ | MIT | AE_VAE_CAE_CVAE/LabExercise3.ipynb | quantumiracle/Course_Code |
Part 2 - CVAE Normalization | transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
])
denorm = denorm_for_tanh
train_dat = datasets.MNIST(
"data/", train=True, download=True, transform=transform
)
test_dat = datasets.MNIST("data/", train=False, transform=transform) | _____no_output_____ | MIT | AE_VAE_CAE_CVAE/LabExercise3.ipynb | quantumiracle/Course_Code |
Hyper-parameter selection | if not os.path.exists('./CVAE'):
os.mkdir('./CVAE')
num_epochs = 20
batch_size = 128
learning_rate = 1e-3 | _____no_output_____ | MIT | AE_VAE_CAE_CVAE/LabExercise3.ipynb | quantumiracle/Course_Code |
Define the dataloaders | train_loader = DataLoader(train_dat, batch_size, shuffle=True)
test_loader = DataLoader(test_dat, batch_size, shuffle=False)
it = iter(test_loader)
sample_inputs, _ = next(it)
fixed_input = sample_inputs[:32, :, :, :]
in_dim = fixed_input.shape[-1]*fixed_input.shape[-2]
save_image(fixed_input, './CVAE/image_original... | _____no_output_____ | MIT | AE_VAE_CAE_CVAE/LabExercise3.ipynb | quantumiracle/Course_Code |
Define the model - CVAEComplete the `encoder` and `decoder` methods in the CVAE pipeline.To find an effective architecture, you can experiment with the following:- the number of convolutional layers- the kernels' sizes- the stride values- the size of the latent space layer | class CVAE(nn.Module):
def __init__(self, latent_dim):
super(CVAE, self).__init__()
"""
TODO: Define here the layers (convolutions, relu etc.) that will be
used in the encoder and decoder pipelines.
"""
def encode(self, x):
"""
TODO: Cons... | _____no_output_____ | MIT | AE_VAE_CAE_CVAE/LabExercise3.ipynb | quantumiracle/Course_Code |
Define Loss function | # Reconstruction + KL divergence losses summed over all elements and batch
def loss_function_VAE(recon_x, x, mu, logvar):
BCE = F.binary_cross_entropy(recon_x, x, size_average=False)
KLD = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp())
return BCE + KLD | _____no_output_____ | MIT | AE_VAE_CAE_CVAE/LabExercise3.ipynb | quantumiracle/Course_Code |
Initialize Model and print number of parameters | model = cv_AE.to(device)
params = sum(p.numel() for p in model.parameters() if p.requires_grad)
print("Total number of parameters is: {}".format(params)) # what would the number actually be?
print(model) | _____no_output_____ | MIT | AE_VAE_CAE_CVAE/LabExercise3.ipynb | quantumiracle/Course_Code |
Choose and initialize optimizer | optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate) | _____no_output_____ | MIT | AE_VAE_CAE_CVAE/LabExercise3.ipynb | quantumiracle/Course_Code |
Train | model.train()
for epoch in range(num_epochs):
train_loss = 0
for batch_idx, data in enumerate(train_loader):
img, _ = data
img = img.to(device)
optimizer.zero_grad()
# forward
recon_batch = model(img)
loss = loss_function_CAE(recon_batch, img)
# backward
... | _____no_output_____ | MIT | AE_VAE_CAE_CVAE/LabExercise3.ipynb | quantumiracle/Course_Code |
Test | # load the model
model.load_state_dict(torch.load("./CVAE/model.pth"))
model.eval()
test_loss = 0
with torch.no_grad():
for i, (img, _) in enumerate(test_loader):
img = img.to(device)
recon_batch = model(img)
test_loss += loss_function_CAE(recon_batch, img)
# reconstruct and save the las... | _____no_output_____ | MIT | AE_VAE_CAE_CVAE/LabExercise3.ipynb | quantumiracle/Course_Code |
Sample Sample the latent space and use the `decoder` to generate resutls. | model.load_state_dict(torch.load("./CVAE/model.pth"))
model.eval()
with torch.no_grad():
"""
TODO: Investigate how to sample the latent space of the CVAE.
"""
z =
sample = model.decode(z)
save_image(denorm(sample).cpu(), './CVAE/samples_' + '.png') | _____no_output_____ | MIT | AE_VAE_CAE_CVAE/LabExercise3.ipynb | quantumiracle/Course_Code |
Interpolations | # Define inpute tensors
x1 =
x2 =
# Create the latent representations
z1 = model.encode(x1)
z2 = model.encode(x2)
"""
TODO: Find a way to create interpolated results from the CVAE.
"""
Z =
X_hat = model.decode(Z) | _____no_output_____ | MIT | AE_VAE_CAE_CVAE/LabExercise3.ipynb | quantumiracle/Course_Code |
Fit models code | def AIC(log_likelihood, k):
""" AIC given log_likelihood and # parameters (k)
"""
aic = 2 * k - 2 * log_likelihood
return aic
def BIC(log_likelihood, n, k):
""" BIC given log_likelihood, number of observations (n) and # parameters (k)
"""
bic = np.log(n) * k - 2 * log_likelihood
return... | _____no_output_____ | MIT | notebooks/0.31-compare-sequence-models-bf/0.2-bf-FOMM-SOMM-HDBSCAN-latent-models.ipynb | xingjeffrey/avgn_paper |
Non-Parametric Tests Part IUp until now, you've been using standard hypothesis tests on means of normal distributions to design and analyze experiments. However, it's possible that you will encounter scenarios where you can't rely on only standard tests. This might be due to uncertainty about the true variability of a... | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
% matplotlib inline | _____no_output_____ | MIT | original_notebooks/L2_Non-Parametric_Tests_Part_1_Solution.ipynb | epasseto/ThirdProjectStudies |
BootstrappingBootstrapping is used to estimate sampling distributions by using the actually collected data to generate new samples that could have been hypothetically collected. In a standard bootstrap, a bootstrapped sample means drawing points from the original data _with replacement_ until we get as many points as ... | def quantile_ci(data, q, c = .95, n_trials = 1000):
"""
Compute a confidence interval for a quantile of a dataset using a bootstrap
method.
Input parameters:
data: data in form of 1-D array-like (e.g. numpy array or Pandas series)
q: quantile to be estimated, must be between 0 and 1... | _____no_output_____ | MIT | original_notebooks/L2_Non-Parametric_Tests_Part_1_Solution.ipynb | epasseto/ThirdProjectStudies |
Bootstrapping NotesConfidence intervals coming from the bootstrap procedure will be optimistic compared to the true state of the world. This is because there will be things that we don't know about the real world that we can't account for, due to not having a parametric model of the world's state. Consider the extreme... | def quantile_permtest(x, y, q, alternative = 'less', n_trials = 10_000):
"""
Compute a confidence interval for a quantile of a dataset using a bootstrap
method.
Input parameters:
x: 1-D array-like of data for independent / grouping feature as 0s and 1s
y: 1-D array-like of data for ... | _____no_output_____ | MIT | original_notebooks/L2_Non-Parametric_Tests_Part_1_Solution.ipynb | epasseto/ThirdProjectStudies |
ainda tem mta diferença a predição tentar com menos variáveis. |
sns.heatmap(data_tratada.corr(),annot=True)
X = data_tratada[['CRIM', 'NOX', 'RM','LSTAT']]
y = data_tratada[['Price']]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=66)
lm = LinearRegression()
lm.fit(X_train,y_train)
predictions = lm.predict(X_test)
plot.scatter(y_test,predict... | MAE: 3.25779091361
MSE: 19.0984201753
RMSE: 4.37017392964
| MIT | Machine Learning/Linear-Regression/Boston DataFrame2.ipynb | wagneralbjr/Python_data_science-bootcamp_udemy |
window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-59152712-8'); Tutorial-IllinoisGRMHD: harm_utoprim_2d.c Authors: Leo Werneck & Zach Etienne**This module is currently under development** In this tutorial module we explain the conserva... | # Step 0: Creation of the IllinoisGRMHD source directory
# Step 0a: Add NRPy's directory to the path
# https://stackoverflow.com/questions/16780014/import-file-from-parent-directory
import os,sys
nrpy_dir_path = os.path.join("..","..")
if nrpy_dir_path not in sys.path:
sys.path.append(nrpy_dir_path)
# Step 0b: Loa... | _____no_output_____ | BSD-2-Clause | IllinoisGRMHD/doc/Tutorial-IllinoisGRMHD__harm_utoprim_2d.ipynb | ksible/nrpytutorial |
Step 1: Introduction \[Back to [top](toc)\]$$\label{introduction}$$Comment on license: `HARM` uses GPL, while `IllinoisGRMHD` uses BSD. Step 2: EOS independent routines \[Back to [top](toc)\]$$\label{harm_utoprim_2d__c__eos_indep}$$Let us now start documenting the `harm_utoprim_2d.c`, which is a part of the `Harm` co... | %%writefile $outfile_path__harm_utoprim_2d__c
#ifndef __HARM_UTOPRIM_2D__C__
#define __HARM_UTOPRIM_2D__C__
/***********************************************************************************
Copyright 2006 Charles F. Gammie, Jonathan C. McKinney, Scott C. Noble,
Gabor Toth, and Luca Del Zanna
... | Writing ../src/harm_utoprim_2d.c
| BSD-2-Clause | IllinoisGRMHD/doc/Tutorial-IllinoisGRMHD__harm_utoprim_2d.ipynb | ksible/nrpytutorial |
Step 2.a: The `Utoprim_2d()` function \[Back to [top](toc)\]$$\label{utoprim_2d}$$The `Utoprim_2d()` function is the driver function of the `HARM` conservative-to-primitive algorithm. We remind you from the definitions of primitive and conservative variables used in the code:$$\begin{align}\boldsymbol{P}_{\rm HARM} &=... | %%writefile -a $outfile_path__harm_utoprim_2d__c
int Utoprim_2d(eos_struct eos, CCTK_REAL U[NPR], CCTK_REAL gcov[NDIM][NDIM], CCTK_REAL gcon[NDIM][NDIM],
CCTK_REAL gdet, CCTK_REAL prim[NPR], long &n_iter)
{
CCTK_REAL U_tmp[NPR], prim_tmp[NPR];
int i, ret;
CCTK_REAL alpha;
if( U[0] <= 0. ) {
... | Appending to ../src/harm_utoprim_2d.c
| BSD-2-Clause | IllinoisGRMHD/doc/Tutorial-IllinoisGRMHD__harm_utoprim_2d.ipynb | ksible/nrpytutorial |
Step 2.a.ii: Preparing the variables to be used by the `Utoprim_new_body()` function \[Back to [top](toc)\]$$\label{utoprim_2d__converting}$$The conservative-to-primitive algorithm uses the `Utoprim_new_body()` function. However, this function assumes a *different* set of primitive/conservative variables. Thus, we mus... | %%writefile -a $outfile_path__harm_utoprim_2d__c
/* Transform the CONSERVED variables into the new system */
U_tmp[RHO] = alpha * U[RHO] / gdet;
U_tmp[UU] = alpha * (U[UU] - U[RHO]) / gdet ;
for( i = UTCON1; i <= UTCON3; i++ ) {
U_tmp[i] = alpha * U[i] / gdet ;
}
for( i = BCON1; i <= BCON3; i++ ) {
... | Appending to ../src/harm_utoprim_2d.c
| BSD-2-Clause | IllinoisGRMHD/doc/Tutorial-IllinoisGRMHD__harm_utoprim_2d.ipynb | ksible/nrpytutorial |
Below we list the necessary transformations on the primitive variables:| `Utoprim_2d()` | `Utoprim_new_body()` ||-------------------------------------|----------------------------------------|| $\color{blue}{\textbf{Primitives}}$ | $\color{red}{\textbf{Primitives}}$ || $... | %%writefile -a $outfile_path__harm_utoprim_2d__c
/* Transform the PRIMITIVE variables into the new system */
for( i = 0; i < BCON1; i++ ) {
prim_tmp[i] = prim[i];
}
for( i = BCON1; i <= BCON3; i++ ) {
prim_tmp[i] = alpha*prim[i];
}
ret = Utoprim_new_body(eos, U_tmp, gcov, gcon, gdet, prim_tmp,n_i... | Appending to ../src/harm_utoprim_2d.c
| BSD-2-Clause | IllinoisGRMHD/doc/Tutorial-IllinoisGRMHD__harm_utoprim_2d.ipynb | ksible/nrpytutorial |
Step 2.b: The `Utoprim_new_body()` function \[Back to [top](toc)\]$$\label{utoprim_new_body}$$ | %%writefile -a $outfile_path__harm_utoprim_2d__c
/**********************************************************************/
/**********************************************************************************
Utoprim_new_body():
-- Attempt an inversion from U to prim using the initial guess prim.
-- This... | Appending to ../src/harm_utoprim_2d.c
| BSD-2-Clause | IllinoisGRMHD/doc/Tutorial-IllinoisGRMHD__harm_utoprim_2d.ipynb | ksible/nrpytutorial |
Step 2.b.i: Computing basic quantities \[Back to [top](toc)\]$$\label{utoprim_new_body__basic_quantities}$$We start by computing basic quantities from the input variables. Notice that this conservative-to-primitive algorithm does not need to update the magnetic field, thus$$\boxed{B_{\rm prim}^{i} = B_{\rm conserv}^{i... | %%writefile -a $outfile_path__harm_utoprim_2d__c
for(i = BCON1; i <= BCON3; i++) prim[i] = U[i] ;
// Calculate various scalars (Q.B, Q^2, etc) from the conserved variables:
Bcon[0] = 0. ;
for(i=1;i<4;i++) Bcon[i] = U[BCON1+i-1] ;
lower_g(Bcon,gcov,Bcov) ;
for(i=0;i<4;i++) Qcov[i] = U[QCOV0+i] ;
rais... | Appending to ../src/harm_utoprim_2d.c
| BSD-2-Clause | IllinoisGRMHD/doc/Tutorial-IllinoisGRMHD__harm_utoprim_2d.ipynb | ksible/nrpytutorial |
Step 2.b.ii: Determining $W$ from the previous iteration, $W_{\rm last}$ \[Back to [top](toc)\]$$\label{utoprim_new_body__wlast}$$The quantity $W$ is defined as$$W \equiv w\gamma^{2}\ ,$$where$$\begin{align}w &= \rho_{b} + u + p\ ,\\\gamma^{2} &= 1 + g_{ij}\tilde{u}^{i}\tilde{u}^{j}\ .\end{align}$$Thus the quantities ... | %%writefile -a $outfile_path__harm_utoprim_2d__c
/* calculate W from last timestep and use for guess */
utsq = 0. ;
for(i=1;i<4;i++)
for(j=1;j<4;j++) utsq += gcov[i][j]*prim[UTCON1+i-1]*prim[UTCON1+j-1] ;
if( (utsq < 0.) && (fabs(utsq) < 1.0e-13) ) {
utsq = fabs(utsq);
}
if(utsq < 0. || utsq > U... | Appending to ../src/harm_utoprim_2d.c
| BSD-2-Clause | IllinoisGRMHD/doc/Tutorial-IllinoisGRMHD__harm_utoprim_2d.ipynb | ksible/nrpytutorial |
Step 2.b.iii: Compute $v^{2}_{\rm last}$, then update $v^{2}$ and $W$ \[Back to [top](toc)\]$$\label{utoprim_new_body__vsqlast_and_recompute_w_and_vsq}$$Then we use equation (28) in [Noble *et al.* (2006)](https://arxiv.org/abs/astro-ph/0512420) to determine $v^{2}$:$$\boxed{v^{2} = \frac{\tilde{Q}^{2}W^{2} + \left(Q\... | %%writefile -a $outfile_path__harm_utoprim_2d__c
// Calculate W and vsq:
x_2d[0] = fabs( W_last );
x_2d[1] = x1_of_x0( W_last , Bsq,QdotBsq,Qtsq,Qdotn,D) ;
retval = general_newton_raphson( eos, x_2d, n, n_iter, func_vsq, Bsq,QdotBsq,Qtsq,Qdotn,D) ;
W = x_2d[0];
vsq = x_2d[1];
/* Problem with solver, ... | Appending to ../src/harm_utoprim_2d.c
| BSD-2-Clause | IllinoisGRMHD/doc/Tutorial-IllinoisGRMHD__harm_utoprim_2d.ipynb | ksible/nrpytutorial |
Step 2.b.iv: Computing the primitive variables \[Back to [top](toc)\]$$\label{utoprim_new_body__compute_prims}$$Now that we have $\left\{W,v^{2}\right\}$, we recompute the primitive variables. We start with$$\left\{\begin{align}\tilde{g} &\equiv \sqrt{1-v^{2}}\\\gamma &= \frac{1}{\tilde{g}}\end{align}\right.\implies\b... | %%writefile -a $outfile_path__harm_utoprim_2d__c
// Recover the primitive variables from the scalars and conserved variables:
gtmp = sqrt(1. - vsq);
gamma = 1./gtmp ;
rho0 = D * gtmp;
w = W * (1. - vsq) ;
p = pressure_rho0_w(eos, rho0,w) ;
u = w - (rho0 + p) ; // u = rho0 eps, w = rho0 h
if( (rho0 <... | Appending to ../src/harm_utoprim_2d.c
| BSD-2-Clause | IllinoisGRMHD/doc/Tutorial-IllinoisGRMHD__harm_utoprim_2d.ipynb | ksible/nrpytutorial |
Step 2.c: The `vsq_calc()` function \[Back to [top](toc)\]$$\label{vsq_calc}$$This function implements eq. (28) in [Noble *et al.* (2006)](https://arxiv.org/abs/astro-ph/0512420) to determine $v^{2}$:$$\boxed{v^{2} = \frac{\tilde{Q}^{2}W^{2} + \left(Q\cdot B\right)^{2}\left(B^{2}+2W\right)}{\left(B^{2}+W\right)^{2}W^{... | %%writefile -a $outfile_path__harm_utoprim_2d__c
/**********************************************************************/
/****************************************************************************
vsq_calc():
-- evaluate v^2 (spatial, normalized velocity) from
W = \gamma^2 w
***************... | Appending to ../src/harm_utoprim_2d.c
| BSD-2-Clause | IllinoisGRMHD/doc/Tutorial-IllinoisGRMHD__harm_utoprim_2d.ipynb | ksible/nrpytutorial |
Step 2.d: The `x1_of_x0()` function \[Back to [top](toc)\]$$\label{x1_of_x0}$$This function computes $v^{2}$, as described [above](vsq_calc), then performs physical checks on $v^{2}$ (i.e. whether or not it is superluminal). This function assumes $W$ is physical. | %%writefile -a $outfile_path__harm_utoprim_2d__c
/********************************************************************
x1_of_x0():
-- calculates v^2 from W with some physical bounds checking;
-- asumes x0 is already physical
-- makes v^2 physical if not;
*******************************************... | Appending to ../src/harm_utoprim_2d.c
| BSD-2-Clause | IllinoisGRMHD/doc/Tutorial-IllinoisGRMHD__harm_utoprim_2d.ipynb | ksible/nrpytutorial |
Step 2.e: The `validate_x()` function \[Back to [top](toc)\]$$\label{validate_x}$$This function performs physical tests on $\left\{W,v^{2}\right\}$ based on their definitions. | %%writefile -a $outfile_path__harm_utoprim_2d__c
/********************************************************************
validate_x():
-- makes sure that x[0,1] have physical values, based upon
their definitions:
*********************************************************************/
static void validat... | Appending to ../src/harm_utoprim_2d.c
| BSD-2-Clause | IllinoisGRMHD/doc/Tutorial-IllinoisGRMHD__harm_utoprim_2d.ipynb | ksible/nrpytutorial |
Step 2.f: The `general_newton_raphson()` function \[Back to [top](toc)\]$$\label{general_newton_raphson}$$This function implements a [multidimensional Newton-Raphson method](https://en.wikipedia.org/wiki/Newton%27s_methodk_variables,_k_functions). We will not make the effort of explaining the algorithm exhaustively si... | %%writefile -a $outfile_path__harm_utoprim_2d__c
/************************************************************
general_newton_raphson():
-- performs Newton-Rapshon method on an arbitrary system.
-- inspired in part by Num. Rec.'s routine newt();
**********************************************************... | Appending to ../src/harm_utoprim_2d.c
| BSD-2-Clause | IllinoisGRMHD/doc/Tutorial-IllinoisGRMHD__harm_utoprim_2d.ipynb | ksible/nrpytutorial |
Step 2.g: The `func_vsq()` function \[Back to [top](toc)\]$$\label{func_vsq}$$This function is used by the `general_newton_raphson()` function to compute the residuals and stepping. We will again not describe it in great detail since the method itself is relatively straightforward. | %%writefile -a $outfile_path__harm_utoprim_2d__c
/**********************************************************************/
/*********************************************************************************
func_vsq():
-- calculates the residuals, and Newton step for general_newton_raphson();
-- f... | Appending to ../src/harm_utoprim_2d.c
| BSD-2-Clause | IllinoisGRMHD/doc/Tutorial-IllinoisGRMHD__harm_utoprim_2d.ipynb | ksible/nrpytutorial |
Step 3: EOS dependent routines \[Back to [top](toc)\]$$\label{harm_utoprim_2d__c__eos_dep}$$ | %%writefile -a $outfile_path__harm_utoprim_2d__c
/**********************************************************************
**********************************************************************
The following routines specify the equation of state. All routines
above here should be indpendent of EOS. If the user... | Appending to ../src/harm_utoprim_2d.c
| BSD-2-Clause | IllinoisGRMHD/doc/Tutorial-IllinoisGRMHD__harm_utoprim_2d.ipynb | ksible/nrpytutorial |
Step 3.a: The `pressure_W_vsq()` function \[Back to [top](toc)\]$$\label{pressure_w_vsq}$$This function computes $p\left(W,v^{2}\right)$. For a $\Gamma$-law equation of state,$$p_{\Gamma} = \left(\Gamma-1\right)u\ ,$$and with the definitions$$\begin{align}\gamma^{2} &= \frac{1}{1-v^{2}}\ ,\\W &= \gamma^{2}w\ ,\\D &= \... | %%writefile -a $outfile_path__harm_utoprim_2d__c
/**********************************************************************/
/**********************************************************************
pressure_W_vsq():
-- Hybrid single and piecewise polytropic equation of state;
-- pressure as a function ... | Appending to ../src/harm_utoprim_2d.c
| BSD-2-Clause | IllinoisGRMHD/doc/Tutorial-IllinoisGRMHD__harm_utoprim_2d.ipynb | ksible/nrpytutorial |
Step 3.b: The `dpdW_calc_vsq()` function \[Back to [top](toc)\]$$\label{dpdw_calc_vsq}$$This function computes $\frac{\partial p\left(W,v^{2}\right)}{\partial W}$. For a $\Gamma$-law equation of state, remember that$$p_{\Gamma} = \frac{\left(\Gamma-1\right)}{\Gamma}\left(\frac{W}{\gamma^{2}} - \frac{D}{\gamma}\right)\... | %%writefile -a $outfile_path__harm_utoprim_2d__c
/**********************************************************************/
/**********************************************************************
dpdW_calc_vsq():
-- partial derivative of pressure with respect to W;
********************************************... | Appending to ../src/harm_utoprim_2d.c
| BSD-2-Clause | IllinoisGRMHD/doc/Tutorial-IllinoisGRMHD__harm_utoprim_2d.ipynb | ksible/nrpytutorial |
Step 3.c: The `dpdvsq_calc()` function \[Back to [top](toc)\]$$\label{dpdvsq_calc}$$This function computes $\frac{\partial p\left(W,v^{2}\right)}{\partial W}$. For a $\Gamma$-law equation of state, remember that$$p_{\Gamma} = \frac{\left(\Gamma-1\right)}{\Gamma}\left(\frac{W}{\gamma^{2}} - \frac{D}{\gamma}\right) = \f... | %%writefile -a $outfile_path__harm_utoprim_2d__c
/**********************************************************************/
/**********************************************************************
dpdvsq_calc():
-- partial derivative of pressure with respect to vsq
**********************************************... | Appending to ../src/harm_utoprim_2d.c
| BSD-2-Clause | IllinoisGRMHD/doc/Tutorial-IllinoisGRMHD__harm_utoprim_2d.ipynb | ksible/nrpytutorial |
Step 3.c.ii: Computing $\frac{\partial P_{\rm cold}}{\partial\left(v^{2}\right)}$ \[Back to [top](toc)\]$$\label{dpdvsq_calc__dpcolddvsq}$$Next, remember that $P_{\rm cold} = P_{\rm cold}(\rho_{b}) = P_{\rm cold}(D,v^{2})$ and also $\epsilon_{\rm cold} = \epsilon_{\rm cold}(D,v^{2})$. Therefore, we must start by findi... | %%writefile -a $outfile_path__harm_utoprim_2d__c
/* Now we implement the derivative of P_cold with respect
* to v^{2}, given by
* ----------------------------------------------------
* | dP_cold/dvsq = gamma^{2 + Gamma_{poly}/2} P_{cold} |
* ----------------------------------------------------
*/
... | Appending to ../src/harm_utoprim_2d.c
| BSD-2-Clause | IllinoisGRMHD/doc/Tutorial-IllinoisGRMHD__harm_utoprim_2d.ipynb | ksible/nrpytutorial |
Step 3.c.iii: Computing $\frac{\partial \epsilon_{\rm cold}}{\partial\left(v^{2}\right)}$ \[Back to [top](toc)\]$$\label{dpdvsq_calc__depscolddvsq}$$Now, obtaining $\epsilon_{\rm cold}$ from $P_{\rm cold}$ requires an integration and, therefore, generates an integration constant. Since we are interested in a *derivati... | %%writefile -a $outfile_path__harm_utoprim_2d__c
/* Now we implement the derivative of eps_cold with respect
* to v^{2}, given by
* -----------------------------------------------------------------------------------
* | deps_cold/dvsq = gamma/(D*(Gamma_ppoly_tab-1)) * (dP_cold/dvsq + gamma^{2} P_cold / 2)... | Appending to ../src/harm_utoprim_2d.c
| BSD-2-Clause | IllinoisGRMHD/doc/Tutorial-IllinoisGRMHD__harm_utoprim_2d.ipynb | ksible/nrpytutorial |
Step 3.c.iv: Computing $\frac{\partial p_{\rm hybrid}}{\partial\left(v^{2}\right)}$ \[Back to [top](toc)\]$$\label{dpdvsq_calc__dpdvsq}$$Finally, remembering that$$\begin{align}p_{\rm hybrid} &= \frac{P_{\rm cold}}{\Gamma_{\rm th}} + \frac{\left(\Gamma_{\rm th}-1\right)}{\Gamma_{\rm th}}\left[\frac{W}{\gamma^{2}} - \f... | %%writefile -a $outfile_path__harm_utoprim_2d__c
/* Now we implement the derivative of p_hybrid with respect
* to v^{2}, given by
* -----------------------------------------------------------------------------
* | dp/dvsq = Gamma_th^{-1}( dP_cold/dvsq |
* | ... | Appending to ../src/harm_utoprim_2d.c
| BSD-2-Clause | IllinoisGRMHD/doc/Tutorial-IllinoisGRMHD__harm_utoprim_2d.ipynb | ksible/nrpytutorial |
Step 4: Code validation \[Back to [top](toc)\]$$\label{code_validation}$$First we download the original `IllinoisGRMHD` source code and then compare it to the source code generated by this tutorial notebook. | # Verify if the code generated by this tutorial module
# matches the original IllinoisGRMHD source code
# First download the original IllinoisGRMHD source code
import urllib
from os import path
original_IGM_file_url = "https://bitbucket.org/zach_etienne/wvuthorns/raw/5611b2f0b17135538c9d9d17c7da062abe0401b6/Illinois... | Validation test for harm_utoprim_2d.c: FAILED!
Diff:
0a1,2
> #ifndef __HARM_UTOPRIM_2D__C__
> #define __HARM_UTOPRIM_2D__C__
70,72c72,74
< static int Utoprim_new_body(CCTK_REAL U[], CCTK_REAL gcov[NDIM][NDIM], CCTK_REAL gcon[NDIM][NDIM], CCTK_REAL gdet, CCTK_REAL prim[],long &n_iter);
< static int general_newton_raphs... | BSD-2-Clause | IllinoisGRMHD/doc/Tutorial-IllinoisGRMHD__harm_utoprim_2d.ipynb | ksible/nrpytutorial |
Step 5: Output this notebook to $\LaTeX$-formatted PDF file \[Back to [top](toc)\]$$\label{latex_pdf_output}$$The following code cell converts this Jupyter notebook into a proper, clickable $\LaTeX$-formatted PDF file. After the cell is successfully run, the generated PDF may be found in the root NRPy+ tutorial direct... | latex_nrpy_style_path = os.path.join(nrpy_dir_path,"latex_nrpy_style.tplx")
#!jupyter nbconvert --to latex --template $latex_nrpy_style_path --log-level='WARN' Tutorial-IllinoisGRMHD__harm_utoprim_2d.ipynb
#!pdflatex -interaction=batchmode Tutorial-IllinoisGRMHD__harm_utoprim_2d.tex
#!pdflatex -interaction=batchmode Tu... | _____no_output_____ | BSD-2-Clause | IllinoisGRMHD/doc/Tutorial-IllinoisGRMHD__harm_utoprim_2d.ipynb | ksible/nrpytutorial |
T81-558: Applications of Deep Neural Networks**Module 8: Kaggle Data Sets*** Instructor: [Jeff Heaton](https://sites.wustl.edu/jeffheaton/), McKelvey School of Engineering, [Washington University in St. Louis](https://engineering.wustl.edu/Programs/Pages/default.aspx)* For more information visit the [class website](h... | # Startup CoLab
try:
%tensorflow_version 2.x
COLAB = True
print("Note: using Google CoLab")
except:
print("Note: not using Google CoLab")
COLAB = False
# Nicely formatted time string
def hms_string(sec_elapsed):
h = int(sec_elapsed / (60 * 60))
m = int((sec_elapsed % (60 * 60)) / 60)
s... | Note: not using Google CoLab
| Apache-2.0 | t81_558_class_08_3_keras_hyperparameters.ipynb | rserran/t81_558_deep_learning |
Siamese U-Net Quickstart 1. IntroductionThe Siamese U-Net is an improvement on the original U-Net architecture. It adds an additional additional encoder that encodes an additional frame other than the frame that we are trying to predict. See [this paper](https://pubmed.ncbi.nlm.nih.gov/31927473/). This repository con... | from biu.siam_unet.helpers.generate_siam_unet_input_imgs import generate_coupled_image_from_self
from pathlib import Path
import os
# specify where the training data for vanilla u-net is located
training_data_loc = '/home/longyuxi/Documents/mount/deeptissue_training/training_data/amnioserosa/yokogawa/image'
training_d... | _____no_output_____ | MIT | using_siam_unet.ipynb | danihae/bio-image-unet |
If you know which frame you drew the label with The dataloader in `siam_unet_cosh` takes an image that results from concatenating the previous frame with the current frame. If you already know which frame of which movie you want to train on, you can create this concatenated data using `generate_siam_unet_input_imgs.py... | movie_dir = '/media/longyuxi/H is for HUGE/docmount backup/unet_pytorch/training_data/test_data/new_microscope/21B11-shgGFP-kin-18-bro4.tif' # change this
frame = 10 # change this
out_dir = './training_data/training_data/yokogawa/siam_data/image/' # change this
from biu.siam_unet.helpers.generate_siam_unet_input_img... | _____no_output_____ | MIT | using_siam_unet.ipynb | danihae/bio-image-unet |
If you don't know which frame you drew the label with If you have frames and labels, but you don't know which frame of which movie each frame comes from, you can use `find_frame_of_image`. This function takes your query and compares it against a list of tif files you specify through the parameter `search_space`. | image_name = f'./training_data/training_data/yokogawa/lateral_epidermis/image/83.tif'
razer_local_search_dir = '/media/longyuxi/H is for HUGE/docmount backup/all_movies'
tifs_names = ['21B11-shgGFP-kin-18-bro4', '21B25_shgGFP_kin_1_Pos0', '21C04_shgGFP_kin_2_Pos4', '21C26_shgGFP_Pos12', '21D16_shgGFPkin_Pos7']
search_... | _____no_output_____ | MIT | using_siam_unet.ipynb | danihae/bio-image-unet |
This function not only outputs what it finds to stdout, but also creates a machine readable output, location of which specified by `machine_readable_output_filename`, about which frames it is highly confident with at locating (i.e. an MSE of < 1000 and matching frame numbers). This output can further be used by `genera... | from biu.siam_unet.helpers.generate_siam_unet_input_imgs import utilize_search_result
utilize_search_result(f'./training_data/training_data/yokogawa/amnioserosa/search_result_mr.txt', f'./training_data/test_data/new_microscope', f'./training_data/training_data/yokogawa/amnioserosa/label/', f'./training_data/training_d... | _____no_output_____ | MIT | using_siam_unet.ipynb | danihae/bio-image-unet |
Finally, organize the labels and images in a way similar to this shown. An example can be found at `training_data/lateral_epidermis/yokogawa_siam-u-net` ```training_data/lateral_epidermis/yokogawa_siam-u-net|├── image│ ├── 105.tif│ ├── 111.tif│ ├── 120.tif│ ├── 121.tif│ ├── 1.tif│ ├── 2.tif│ ├── 3.tif│ ... | from biu.siam_unet import *
dataset = 'amnioserosa/old_scope'
base_dir = '/home/longyuxi/Documents/mount/deeptissue_training/training_data/'
# path to training data (images and labels with identical names in separate folders)
dir_images = f'{base_dir}/{dataset}/siam_image/'
dir_masks = f'{base_dir}/{dataset}/label/'
... | _____no_output_____ | MIT | using_siam_unet.ipynb | danihae/bio-image-unet |
Note here that the value of the `n_filter` parameter is set to `32`. The network won't break with a different value of this, but you need to use the same value for the Predict part. 4. Predict Predicting is simple as well. Just swap in the parameters | # load package
from biu.siam_unet import *
import os
os.nice(10)
from biu.siam_unet.helpers import tif_to_mp4
base_dir = './'
out_dir = f'{base_dir}/predicted_out'
model = f'{base_dir}/models/siam_bce_amnio/model_epoch_100.pth'
tif_file = f'{base_dir}/training_data/test_data/new_microscope/21C04_shgGFP_kin_2_Pos4.ti... | _____no_output_____ | MIT | using_siam_unet.ipynb | danihae/bio-image-unet |
Additionally, to evaluate the model's performance with different losses, one can also train the model across different models | """
For each image in the training dataset, run siam unet to predict.
"""
from pathlib import *
from biu.siam_unet import *
import glob
import logging
def predict_all_training_data(image_folder_prefix, model_folder_prefix, model_loss_functions, datasets, output_directory):
image_folder_prefix = Path(image_folder... | _____no_output_____ | MIT | using_siam_unet.ipynb | danihae/bio-image-unet |
EvaluaciónCompleta lo que falta. | # instalacion
!pip install pandas
!pip install matplotlib
!pip install pandas-datareader
# 1 importa las bibliotecas
import pandas as pd
import pandas_datareader.data as web
import matplotlib.pyplot as plt
# 2. Establecer una fecha de inicio "2020-01-01" y una fecha de finalización "2021-08-31"
start_date =
end_date... | _____no_output_____ | BSD-3-Clause | evaluacion_leslytapia.ipynb | LESLYTAPIA/training-python-novice |
* Entender los movimientos del precio, si suben o bajan.* Los precios de las acciones se mueven constantemente a lo largo del día de trading a medida que la oferta y la demanda de acciones cambian (precio mas alto o mas bajo). Cuando el mercado cierra, se registra el precio final de la acción.* EL precio de Apertura: P... | # 5. Muestre un resumen de la información básica sobre este DataFrame y sus datos
# use la funcion dataFrame.info() y dataFrame.describe()
# 6. Devuelve las primeras 5 filas del DataFrame con dataFrame.head() o dataFrame.iloc[]
# 7. Seleccione solo las columnas 'Open','Close' y 'Volume' del DataFrame con dataFrame.l... | _____no_output_____ | BSD-3-Clause | evaluacion_leslytapia.ipynb | LESLYTAPIA/training-python-novice |
PyTorch CIFAR-10 local training PrerequisitesThis notebook shows how to use the SageMaker Python SDK to run your code in a local container before deploying to SageMaker's managed training or hosting environments. This can speed up iterative testing and debugging while using the same familiar Python SDK interface. ... | !/bin/bash ./setup.sh | _____no_output_____ | Apache-2.0 | sagemaker-python-sdk/pytorch_cnn_cifar10/pytorch_local_mode_cifar10.ipynb | nigenda-amazon/amazon-sagemaker-examples |
OverviewThe **SageMaker Python SDK** helps you deploy your models for training and hosting in optimized, productions ready containers in SageMaker. The SageMaker Python SDK is easy to use, modular, extensible and compatible with TensorFlow, MXNet, PyTorch. This tutorial focuses on how to create a convolutional neural ... | import sagemaker
sagemaker_session = sagemaker.Session()
bucket = sagemaker_session.default_bucket()
prefix = 'sagemaker/DEMO-pytorch-cnn-cifar10'
role = sagemaker.get_execution_role()
import os
import subprocess
instance_type = "local"
try:
if subprocess.call("nvidia-smi") == 0:
## Set type to GPU if ... | _____no_output_____ | Apache-2.0 | sagemaker-python-sdk/pytorch_cnn_cifar10/pytorch_local_mode_cifar10.ipynb | nigenda-amazon/amazon-sagemaker-examples |
Download the CIFAR-10 dataset | from utils_cifar import get_train_data_loader, get_test_data_loader, imshow, classes
trainloader = get_train_data_loader()
testloader = get_test_data_loader() | _____no_output_____ | Apache-2.0 | sagemaker-python-sdk/pytorch_cnn_cifar10/pytorch_local_mode_cifar10.ipynb | nigenda-amazon/amazon-sagemaker-examples |
Data Preview | import numpy as np
import torchvision, torch
# get some random training images
dataiter = iter(trainloader)
images, labels = dataiter.next()
# show images
imshow(torchvision.utils.make_grid(images))
# print labels
print(' '.join('%9s' % classes[labels[j]] for j in range(4))) | _____no_output_____ | Apache-2.0 | sagemaker-python-sdk/pytorch_cnn_cifar10/pytorch_local_mode_cifar10.ipynb | nigenda-amazon/amazon-sagemaker-examples |
Upload the dataWe use the ```sagemaker.Session.upload_data``` function to upload our datasets to an S3 location. The return value inputs identifies the location -- we will use this later when we start the training job. | inputs = sagemaker_session.upload_data(path='data', bucket=bucket, key_prefix='data/cifar10') | _____no_output_____ | Apache-2.0 | sagemaker-python-sdk/pytorch_cnn_cifar10/pytorch_local_mode_cifar10.ipynb | nigenda-amazon/amazon-sagemaker-examples |
Construct a script for training Here is the full code for the network model: | !pygmentize source/cifar10.py | _____no_output_____ | Apache-2.0 | sagemaker-python-sdk/pytorch_cnn_cifar10/pytorch_local_mode_cifar10.ipynb | nigenda-amazon/amazon-sagemaker-examples |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.