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 |
|---|---|---|---|---|---|
To set the position and rotation of each cell, we use the built in function positions_columinar and xiter_random, which returns a list of values given the parameters. A user could set the values themselves using a list (or function that returns a list) of size N. The parameters like location, ei (potential), params_fil... | """
net.add_nodes(N=200, pop_name='LIF_exc',
positions=positions_columinar(N=200, center=[0, 50.0, 0], min_radius=30.0, max_radius=60.0, height=100.0),
tuning_angle=np.linspace(start=0.0, stop=360.0, num=200, endpoint=False),
location='VisL4',
ei='e',
... | _____no_output_____ | MIT | theta.ipynb | cyneuro/theta |
connectionsNow we want to create connections between the cells. Depending on the model type, and whether or not the presynpatic "source" cell is excitory or inhibitory, we will have different synpatic model and parameters. Using the source and target filter parameters, we can create different connection types.To deter... | import random
import math
# list of all synapses created - used for recurrent connections
syn_list = []
###########################################################
# Build custom connection rules
###########################################################
#See bmtk.builder.auxi.edge_connectors
def hipp_dist_connector... | _____no_output_____ | MIT | theta.ipynb | cyneuro/theta |
This first two parameters of this function is "source" and "target" and are required for all custom connector functions. These are node objects which gives a representation of a single source and target cell, with properties that can be accessed like a python dictionary. When The Network Builder is creating the connect... | dynamics_file = 'CA3o2CA3e.inh.json'
conn = net.add_edges(source={'pop_name': 'CA3o'}, target={'pop_name': 'CA3e'},
connection_rule=hipp_dist_connector,
connection_params={'con_pattern':syn[dynamics_file]['con_pattern'],
'ratio':syn[dynamics_file]['ratio'],
... | _____no_output_____ | MIT | theta.ipynb | cyneuro/theta |
Similarly we create the other types of connections. But since either the source, target, or both cells will not have the tuning_angle parameter, we don't want to use dist_tuning_connector. Instead we can use the built-in distance_connector function which just creates connections determined by distance. | dynamics_file = 'CA3e2CA3o.exc.json'
experiment = 'original'
if experiment == "SFN19-D": #Weight of the synapses are set to 6 from max weight of 2
dynamics_file = 'CA3e2CA3o.exc.sfn19exp2d.json'
conn = net.add_edges(source={'pop_name': 'CA3e'}, target={'pop_name': 'CA3o'},
connection_rule=hipp_recurre... | _____no_output_____ | MIT | theta.ipynb | cyneuro/theta |
Finally we build the network (this may take a bit of time since it's essentially iterating over all 400x400 possible connection combinations), and save the nodes and edges. | net.build()
net.save_nodes(output_dir='sim_theta/network')
net.save_edges(output_dir='sim_theta/network') | _____no_output_____ | MIT | theta.ipynb | cyneuro/theta |
Building external networkNext we want to create an external network consisting of virtual cells that form a feedforward network onto our V1, which will provide input during the simulation. We will call this LGN, since the LGN is the primary input the layer 4 cells of the V1 (if we wanted to we could also create multip... | from bmtk.builder.networks import NetworkBuilder
exp0net = NetworkBuilder('exp0net')
exp0net.add_nodes(N=CA3eTotal, model_type='virtual', pop_name='bgnoisevirtCA3', pop_group='bgnoisevirtCA3')
| _____no_output_____ | MIT | theta.ipynb | cyneuro/theta |
As before, we will use a customized function to determine the number of connections between each source and target pair, however this time our connection_rule is a bit differentIn the previous example, our connection_rule function's first two arguments were the presynaptic and postsynaptic cells, which allowed us to ch... | def target_ind_equals_source_ind(source, targets, offset=0, min_syn=1,max_syn=1):
# Creates a 1 to 1 mapping between source and destination nodes
total_targets = len(targets)
syns = np.zeros(total_targets)
target_index = source['node_id']
syns[target_index-offset] = 1
return syns
conn ... | _____no_output_____ | MIT | theta.ipynb | cyneuro/theta |
2. Setting up BioNet file structure.Before running a simulation, we will need to create the runtime environment, including parameter files, run-script and configuration files. You can copy the files from an existing simuatlion, execute the following command:```bash$ python -m bmtk.utils.sim_setup \ --report-vars v ... | from bmtk.utils.sim_setup import build_env_bionet
build_env_bionet(base_dir='sim_theta',
network_dir='sim_theta/network',
tstop=3000.0, dt=0.1,
report_vars=['v'], # Record membrane potential (default soma)
include_examples=True, # Copies ... | ERROR:bmtk.utils.sim_setup: Was unable to compile mechanism in C:\Users\Tyler\Desktop\git_stage\theta\sim_theta\components\mechanisms
| MIT | theta.ipynb | cyneuro/theta |
This will fill out the **sim_ch04** with all the files we need to get started to run the simulation. Of interest includes* **circuit_config.json** - A configuration file that contains the location of the network files we created above. Plus location of neuron and synpatic models, templates, morphologies and mechanisms ... | import math
from bmtk.simulator.bionet.pyfunction_cache import add_weight_function
def gaussianLL(edge_props, source, target):
src_tuning = source['tuning_angle']
tar_tuning = target['tuning_angle']
w0 = edge_props["syn_weight"]
sigma = edge_props["weight_sigma"]
delta_tuning = abs(abs(abs(180.0 -... | _____no_output_____ | MIT | theta.ipynb | cyneuro/theta |
The weights will be adjusted before each simulation, and the function can be changed between different runs.. Simply opening the edge_types.csv file with a text editor and altering the weight_function column allows users to take an existing network and readjust weights on-the-fly.Finally we are ready to run the simulat... | from bmtk.simulator import bionet
conf = bionet.Config.from_json('sim_theta/simulation_config.json')
conf.build_env()
net = bionet.BioNetwork.from_config(conf)
sim = bionet.BioSimulator.from_config(conf, network=net)
sim.run() | 2020-09-28 22:46:28,632 [INFO] Created log file
| MIT | theta.ipynb | cyneuro/theta |
4. Analyzing resultsResults of the simulation, as specified in the config, are saved into the output directory. Using the analyzer functions, we can do things like plot the raster plot | from bmtk.analyzer.spike_trains import plot_raster, plot_rates_boxplot
plot_raster(config_file='sim_theta/simulation_config.json', group_by='pop_name') | c:\users\tyler\desktop\git_stage\bmtk\bmtk\simulator\utils\config.py:4: UserWarning: Please use bmtk.simulator.core.simulation_config instead.
warnings.warn('Please use bmtk.simulator.core.simulation_config instead.')
| MIT | theta.ipynb | cyneuro/theta |
and the rates of each node | plot_rates_boxplot(config_file='sim_ch04/simulation_config.json', group_by='pop_name') | _____no_output_____ | MIT | theta.ipynb | cyneuro/theta |
In our config file we used the cell_vars and node_id_selections parameters to save the calcium influx and membrane potential of selected cells. We can also use the analyzer to display these traces: | from bmtk.analyzer.compartment import plot_traces
_ = plot_traces(config_file='sim_ch04/simulation_config.json', group_by='pop_name', report_name='v_report') | _____no_output_____ | MIT | theta.ipynb | cyneuro/theta |
问题设定 在小车倒立杆(CartPole)游戏中,我们希望通过强化学习训练一个智能体(agent),尽可能不断地左右移动小车,使得小车上的杆不倒,我们首先定义CartPole游戏: CartPole游戏即是强化学习模型的enviorment,它与agent交互,实时更新state,内部定义了reward function,其中state有以下定义: state每一个维度分别代表了:- 小车位置,它的取值范围是-2.4到2.4- 小车速度,它的取值范围是负无穷到正无穷- 杆的角度,它的取值范围是-41.8°到41.8°- 杆的角速,它的取值范围是负无穷到正无穷 action是一个2维向量,每一个维度分别代表向左和向右移动。 $$ac... | # coding=utf-8
import tensorflow as tf
import numpy as np
import gym
import sys
sys.path.append('..')
from base.model import *
%matplotlib inline
class Agent(BaseRLModel):
def __init__(self, session, env, a_space, s_space, **options):
super(Agent, self).__init__(session, env, a_space, s_space, **option... | [33mWARN: gym.spaces.Box autodetected dtype as <class 'numpy.float32'>. Please provide explicit dtype.[0m
| MIT | note/DQN.ipynb | Ceruleanacg/Learning-Notes |
XGBBOOST | xgb_params = {
'max_depth' : 5,
'n_estimators' : 50,
'learning_rate' : 0.1,
'seed' : 0
}
model = xgb.XGBRegressor(**xgb_params)
run_model(model,cat_feats)
m = xgb.XGBRegressor(**xgb_params)
m.fit(X,Y)
imp = PermutationImportance(m,random_state = 0).fit(X,Y)
eli5.show_weights(imp,feature_names = cat_fe... | _____no_output_____ | MIT | Day4.ipynb | JoachimMakowski/DataScienceMatrix2 |
Data Science Unit 1 Sprint Challenge 2 Data Wrangling and StorytellingTaming data from its raw form into informative insights and stories. Data WranglingIn this Sprint Challenge you will first "wrangle" some data from [Gapminder](https://www.gapminder.org/about-gapminder/), a Swedish non-profit co-founded by Hans Ro... | import pandas as pd
cell_phones = pd.read_csv('https://raw.githubusercontent.com/open-numbers/ddf--gapminder--systema_globalis/master/ddf--datapoints--cell_phones_total--by--geo--time.csv')
population = pd.read_csv('https://raw.githubusercontent.com/open-numbers/ddf--gapminder--systema_globalis/master/ddf--datapoints... | _____no_output_____ | MIT | DS7_Unit_1_Sprint_Challenge_2_Data_Wrangling_and_Storytelling_(3).ipynb | johanaluna/DS-Unit-1-Sprint-2-Data-Wrangling-and-Storytelling |
Part 1. Join data First, join the `cell_phones` and `population` dataframes (with an inner join on `geo` and `time`).The resulting dataframe's shape should be: (8590, 4) | cell_phones.head()
population.head()
geo_country_codes.head()
#join the cell_phones and population dataframes (with an inner join on geo and time).
df=pd.merge(cell_phones,population, on=['geo','time'], how='inner')
print(df.shape)
df.head() | (8590, 4)
| MIT | DS7_Unit_1_Sprint_Challenge_2_Data_Wrangling_and_Storytelling_(3).ipynb | johanaluna/DS-Unit-1-Sprint-2-Data-Wrangling-and-Storytelling |
Then, select the `geo` and `country` columns from the `geo_country_codes` dataframe, and join with your population and cell phone data.The resulting dataframe's shape should be: (8590, 5) | geo_country= geo_country_codes [['geo','country']]
geo_country.head()
df_merged = pd.merge(df, geo_country, on='geo')
print(df_merged.shape)
df_merged.head() | (8590, 5)
| MIT | DS7_Unit_1_Sprint_Challenge_2_Data_Wrangling_and_Storytelling_(3).ipynb | johanaluna/DS-Unit-1-Sprint-2-Data-Wrangling-and-Storytelling |
Part 2. Make features Calculate the number of cell phones per person, and add this column onto your dataframe.(You've calculated correctly if you get 1.220 cell phones per person in the United States in 2017.) | df_merged['cellphone_person']=df_merged['cell_phones_total']/df_merged['population_total']
df_merged.head() | _____no_output_____ | MIT | DS7_Unit_1_Sprint_Challenge_2_Data_Wrangling_and_Storytelling_(3).ipynb | johanaluna/DS-Unit-1-Sprint-2-Data-Wrangling-and-Storytelling |
Modify the `geo` column to make the geo codes uppercase instead of lowercase. | df_merged[(df_merged['country'] == 'United States') & (df_merged['time'] ==2017 )] | _____no_output_____ | MIT | DS7_Unit_1_Sprint_Challenge_2_Data_Wrangling_and_Storytelling_(3).ipynb | johanaluna/DS-Unit-1-Sprint-2-Data-Wrangling-and-Storytelling |
Part 3. Process data Use the describe function, to describe your dataframe's numeric columns, and then its non-numeric columns.(You'll see the time period ranges from 1960 to 2017, and there are 195 unique countries represented.) | import numpy as np
# describe your dataframe's numeric columns
df_merged.describe()
df_merged.describe(exclude = [np.number]) | _____no_output_____ | MIT | DS7_Unit_1_Sprint_Challenge_2_Data_Wrangling_and_Storytelling_(3).ipynb | johanaluna/DS-Unit-1-Sprint-2-Data-Wrangling-and-Storytelling |
In 2017, what were the top 5 countries with the most cell phones total?Your list of countries should have these totals:| country | cell phones total ||:-------:|:-----------------:|| ? | 1,474,097,000 || ? | 1,168,902,277 || ? | 458,923,202 || ? | 395,881,000 || ? | ... | # This optional code formats float numbers with comma separators
pd.options.display.float_format = '{:,}'.format
year2017 = df_merged[df_merged.time == 2017]
year2017.head()
#code to check the values
year2017.sort_values('cell_phones_total', ascending=False)
# Make top5
top5_all=year2017.nlargest(5,'cell_phones_total'... | _____no_output_____ | MIT | DS7_Unit_1_Sprint_Challenge_2_Data_Wrangling_and_Storytelling_(3).ipynb | johanaluna/DS-Unit-1-Sprint-2-Data-Wrangling-and-Storytelling |
2017 was the first year that China had more cell phones than people.What was the first year that the USA had more cell phones than people? | order_celphones=df_merged.sort_values('cell_phones_total', ascending=False)
order_celphones.head(10)
country_usa=df_merged[(df_merged['country'] == 'United States')]
country_usa.head()
# country_usa.country.unique()
condition_usa= country_usa[(country_usa['cell_phones_total'] > country_usa['population_total'])]
conditi... | _____no_output_____ | MIT | DS7_Unit_1_Sprint_Challenge_2_Data_Wrangling_and_Storytelling_(3).ipynb | johanaluna/DS-Unit-1-Sprint-2-Data-Wrangling-and-Storytelling |
Part 4. Reshape data Create a pivot table:- Columns: Years 2007—2017- Rows: China, India, United States, Indonesia, Brazil (order doesn't matter)- Values: Cell Phones TotalThe table's shape should be: (5, 11) | years=[2007,2008,2009,2010,2011,2012,2013,20014,2015,2016,2017]
countries=['China', 'India', 'United States', 'Indonesia', 'Brazil']
#countries_pivot=df_merged.loc[df_merged['country'].isin(countries)]
years_merged=df_merged.loc[df_merged['time'].isin(years)& df_merged['country'].isin(countries)]
years_merged.head()
pi... | _____no_output_____ | MIT | DS7_Unit_1_Sprint_Challenge_2_Data_Wrangling_and_Storytelling_(3).ipynb | johanaluna/DS-Unit-1-Sprint-2-Data-Wrangling-and-Storytelling |
Sort these 5 countries, by biggest increase in cell phones from 2007 to 2017.Which country had 935,282,277 more cell phones in 2017 versus 2007? | flat_pivot= pd.DataFrame(pivot_years.to_records())
flat_pivot.head()
flat_pivot['Percentage Change']=(flat_pivot['2017']-flat_pivot['2007'])/flat_pivot['2017']
flat_pivot.head()
#ANSWER= Sort these 5 countries, by biggest increase in cell phones from 2007 to 2017.
flat_pivot.sort_values('Percentage Change', ascending=F... | _____no_output_____ | MIT | DS7_Unit_1_Sprint_Challenge_2_Data_Wrangling_and_Storytelling_(3).ipynb | johanaluna/DS-Unit-1-Sprint-2-Data-Wrangling-and-Storytelling |
Data StorytellingIn this part of the sprint challenge you'll work with a dataset from **FiveThirtyEight's article, [Every Guest Jon Stewart Ever Had On ‘The Daily Show’](https://fivethirtyeight.com/features/every-guest-jon-stewart-ever-had-on-the-daily-show/)**! Part 0 — Run this starter codeYou don't need to add or ... | %matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
url = 'https://raw.githubusercontent.com/fivethirtyeight/data/master/daily-show-guests/daily_show_guests.csv'
df1 = pd.read_csv(url).rename(columns={'YEAR': 'Year', 'Raw_Guest_List': 'Guest'})
def get_occupation(group):
if g... | _____no_output_____ | MIT | DS7_Unit_1_Sprint_Challenge_2_Data_Wrangling_and_Storytelling_(3).ipynb | johanaluna/DS-Unit-1-Sprint-2-Data-Wrangling-and-Storytelling |
Part 1 — What's the breakdown of guests’ occupations per year?For example, in 1999, what percentage of guests were actors, comedians, or musicians? What percentage were in the media? What percentage were in politics? What percentage were from another occupation?Then, what about in 2000? In 2001? And so on, up through ... | print(df1.shape)
df1.head()
crosstab_profession=pd.crosstab(df1['Year'], df1['Occupation'], normalize='index').round(4)*100
crosstab_profession.head(20) | _____no_output_____ | MIT | DS7_Unit_1_Sprint_Challenge_2_Data_Wrangling_and_Storytelling_(3).ipynb | johanaluna/DS-Unit-1-Sprint-2-Data-Wrangling-and-Storytelling |
Part 2 — Recreate this explanatory visualization: **Hints:**- You can choose any Python visualization library you want. I've verified the plot can be reproduced with matplotlib, pandas plot, or seaborn. I assume other libraries like altair or plotly would work too.- If you choose to use seaborn, you may want to upgrad... | from IPython.display import display, Image
png = 'https://fivethirtyeight.com/wp-content/uploads/2015/08/hickey-datalab-dailyshow.png'
example = Image(png, width=500)
display(example)
import seaborn as sns
sns.__version__
flat_df1= pd.DataFrame(crosstab_profession.to_records())
flat_df1
flat_df1=flat_df1.drop(['Other']... | _____no_output_____ | MIT | DS7_Unit_1_Sprint_Challenge_2_Data_Wrangling_and_Storytelling_(3).ipynb | johanaluna/DS-Unit-1-Sprint-2-Data-Wrangling-and-Storytelling |
Sicherman Dice*Note: This notebook takes the form of a conversation between two problem solvers. One speaks in* **bold**, *the other in* plain. *Also note, for those who are not native speakers of English: "dice" is the plural form; "die" is the singular.*Huh. This is interesting. You know how in many games, such as ... | def sicherman():
"""The set of pairs of 6-sided dice that have the same
distribution of sums as a regular pair of dice."""
return {pair for pair in pairs(all_dice())
if pair != regular_pair
and sums(pair) == regular_sums}
# TODO: pairs, all_dice, regular_pair, sums, regular_sums | _____no_output_____ | MIT | ipynb/Sicherman Dice.ipynb | awesome-archive/pytudes |
**Looks good to me.**Now we can tick off the items in the TO DO list. The function `pairs` is first, and it is easy: | def pairs(collection):
"Return all pairs (A, B) from collection where A <= B."
return [(A, B) for A in collection for B in collection if A <= B]
# TODO: all_dice, regular_pair, sums, regular_sums | _____no_output_____ | MIT | ipynb/Sicherman Dice.ipynb | awesome-archive/pytudes |
**That's good. We could have used the library function `itertools.combinations_with_replacement`, but let's just leave it as is. We should test to make sure it works:** | pairs(['A', 'B', 'C']) | _____no_output_____ | MIT | ipynb/Sicherman Dice.ipynb | awesome-archive/pytudes |
TO DO: `sums(pair)`Now for `sums`: we need some way to represent all the 36 possible sums from a pair of dice. We want a representation that will be the same for two different pairs if all 36 sums are the same, but where the order or composition of the sums doesn't matter. **So we want a set of the sums?**Well, it ca... | def sums(pair):
"All possible sums of a side from one die plus a side from the other."
(A, B) = pair
return Bag(a + b for a in A for b in B)
Bag = sorted # Implement a bag as a sorted list
def ints(start, end):
"A tuple of the integers from start to end, inclusive."
return tuple(range(start, end ... | _____no_output_____ | MIT | ipynb/Sicherman Dice.ipynb | awesome-archive/pytudes |
Let's check the `regular_sums`: | len(regular_sums)
print(regular_sums) | [2, 3, 3, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 10, 10, 10, 11, 11, 12]
| MIT | ipynb/Sicherman Dice.ipynb | awesome-archive/pytudes |
**And we can see what that would look like to a `Counter`:** | from collections import Counter
Counter(regular_sums) | _____no_output_____ | MIT | ipynb/Sicherman Dice.ipynb | awesome-archive/pytudes |
**Looks good! Now only one more thing on our TODO list:** TO DO: `all_dice()``all_dice` should generate all possible dice, where by "possible" I mean the dice that could feasibly be part of a pair that is a solution to the Sicherman problem. Do we know how many dice that will be? Is it a large enough number that effici... | def all_dice():
"A list of all feasible 6-sided dice for the Sicherman problem."
return [(1, s2, s3, s4, s5, s6)
for s2 in ints(2, 8)
for s3 in ints(s2, 8)
for s4 in ints(s3, 8)
for s5 in ints(s4, 8)
for s6 in ints(s5+1, 9)] | _____no_output_____ | MIT | ipynb/Sicherman Dice.ipynb | awesome-archive/pytudes |
I think we're ready to run `sicherman()`. Any bets on what we'll find out?**I bet that Sicherman is remembered because he discovered a pair of dice that works. If he just proved the non-existence of a pair, I don't think that would be noteworthy.**Makes sense. Here goes: The Answer | sicherman() | _____no_output_____ | MIT | ipynb/Sicherman Dice.ipynb | awesome-archive/pytudes |
**Look at that!**It turns out you can buy a pair of dice with just these numbers.Here's a table I borrowed from [Wikipedia](https://en.wikipedia.org/wiki/Sicherman_dice) that shows both pairs of dice have the same sums. 23456789101112Regular dice:(1, 2, 3, 4, 5, 6)(1, 2, 3, 4, 5, 6)1+11+22+11+32+23+11+42+33+24+11+52+4... | def all_dice():
"A list of all feasible 6-sided dice for the Sicherman problem."
return [(1, s2, s3, s4, s5, s6)
for s2 in ints(2, 7)
for s3 in ints(s2, 7)
for s4 in ints(max(s3, 3), 7)
for s5 in ints(s4, 7)
for s6 in ints(s5+1, 8)] | _____no_output_____ | MIT | ipynb/Sicherman Dice.ipynb | awesome-archive/pytudes |
I'll count how many dice and how many pairs there are now: | len(all_dice())
len(pairs(all_dice())) | _____no_output_____ | MIT | ipynb/Sicherman Dice.ipynb | awesome-archive/pytudes |
**Nice—we got down from a trillion pairs to 26,000. I don't want to print `all_dice()`, but I can sample a few:** | import random
random.sample(all_dice(), 10) | _____no_output_____ | MIT | ipynb/Sicherman Dice.ipynb | awesome-archive/pytudes |
`sicherman(N)`OK, I think we're ready to update `sicherman()` to `sicherman(N)`. **Sure, most of that will be easy, just parameterizing with `N`:** | def sicherman(N=6):
"""The set of pairs of N-sided dice that have the same
distribution of sums as a regular pair of N-sided dice."""
reg_sums = regular_sums(N)
reg_pair = regular_pair(N)
return {pair for pair in pairs(all_dice(N))
if pair != reg_pair
and sums(pair) == reg_su... | _____no_output_____ | MIT | ipynb/Sicherman Dice.ipynb | awesome-archive/pytudes |
Good. I think it would be helpful for me to look at a table of `regular_sums`: | for N in ints(1, 7):
print("N:", N, dict(Counter(regular_sums(N)))) | N: 1 {2: 1}
N: 2 {2: 1, 3: 2, 4: 1}
N: 3 {2: 1, 3: 2, 4: 3, 5: 2, 6: 1}
N: 4 {2: 1, 3: 2, 4: 3, 5: 4, 6: 3, 7: 2, 8: 1}
N: 5 {2: 1, 3: 2, 4: 3, 5: 4, 6: 5, 7: 4, 8: 3, 9: 2, 10: 1}
N: 6 {2: 1, 3: 2, 4: 3, 5: 4, 6: 5, 7: 6, 8: 5, 9: 4, 10: 3, 11: 2, 12: 1}
N: 7 {2: 1, 3: 2, 4: 3, 5: 4, 6: 5, 7: 6, 8: 7, 9: 6, 10: 5, 11:... | MIT | ipynb/Sicherman Dice.ipynb | awesome-archive/pytudes |
**That is helpful. I can see that any `regular_sums` must have one 2 and two 3s, and three 4s, and so on, not just for `N=6` but for any `N` (except for trivially small `N`). And that means that any regular die can have at most two 2s, three 3s, four 4s, and so on. So we have this picture:** 1 <2+ ≤2+ ... | def lower_bounds(N):
"A list of lower bounds for respective sides of an N-sided die."
lowers = [1]
for _ in range(N-1):
m = lowers[-1] # The last number in lowers so far
lowers.append(m if (lowers.count(m) < m) else m + 1)
lowers[-1] = lowers[-2] + 1
return lowers
lower_bounds(6)
low... | _____no_output_____ | MIT | ipynb/Sicherman Dice.ipynb | awesome-archive/pytudes |
And `upper_bounds(N)`: | def upper_bounds(N):
"A list of upper bounds for respective sides of an N-sided die."
U = 2 * N - lower_bounds(N)[-1]
return [1] + (N - 2) * [U - 1] + [U]
upper_bounds(6)
upper_bounds(10) | _____no_output_____ | MIT | ipynb/Sicherman Dice.ipynb | awesome-archive/pytudes |
Now, what do we have to do for `all_dice(N)`? When we knew we had six sides, we wrote six nested loops. We can't do that for *N*, so what do we do?**Here's an iterative approach: we keep track of a list of partially-formed dice, and on each iteration, we add a side to all the partially-formed dice in all possible ways... | def all_dice(N):
"Return a list of all possible N-sided dice for the Sicherman problem."
lowers = lower_bounds(N)
uppers = upper_bounds(N)
def possibles(die, i):
"The possible numbers for the ith side of an N-sided die."
return ints(max(lowers[i], die[-1] + int(i == N-1)),
... | _____no_output_____ | MIT | ipynb/Sicherman Dice.ipynb | awesome-archive/pytudes |
**The tricky part was with the `max`: the actual lower bound at least `lowers[i]`, but it must be as big as the previous side, `die[-1]`. And just to make things complicated, the very last side has to be strictly bigger than the previous; `" + int(i == N-1)"` does that by adding 1 just in case we're on the last side,... | len(all_dice(6)) | _____no_output_____ | MIT | ipynb/Sicherman Dice.ipynb | awesome-archive/pytudes |
Reassuring that we get the same number we got with the old version of `all_dice()`. | random.sample(all_dice(6), 8) | _____no_output_____ | MIT | ipynb/Sicherman Dice.ipynb | awesome-archive/pytudes |
Running `sicherman(N)` for small `N`Let's try `sicherman` for some small values of `N`: | {N: sicherman(N)
for N in ints(2, 6)} | _____no_output_____ | MIT | ipynb/Sicherman Dice.ipynb | awesome-archive/pytudes |
Again, reassuring that we get the same result for `sicherman(6)`. And interesting that there is a result for `sicherman(4)` but not for the other *N*.Let's go onwards from *N*=6, but let's check the timing as we go: | %time sicherman(6)
%time sicherman(7) | CPU times: user 18.2 s, sys: 209 ms, total: 18.4 s
Wall time: 21.4 s
| MIT | ipynb/Sicherman Dice.ipynb | awesome-archive/pytudes |
Estimating run time of `sicherman(N)` for larger `N`OK, it takes 50 or 60 times longer to do 7, compared to 6. At this rate, *N*=8 will take 15 minutes, 9 will take 15 hours, and 10 will take a month.**Do we know it will continue to rise at the same rate? You're saying the run time is exponential in *N*? **I think so... | %matplotlib inline
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
def logplot(X, Y, *options):
"Plot Y on a log scale vs X."
fig, ax = plt.subplots()
ax.set_yscale('log')
ax.plot(X, Y, *options) | _____no_output_____ | MIT | ipynb/Sicherman Dice.ipynb | awesome-archive/pytudes |
Now we can plot and display the number of pairs: | def plot_pairs(Ns):
"Given a list of N values, plot the number of pairs and return a dict of them."
Ds = [len(all_dice(N)) for N in Ns]
Npairs = [D * (D + 1) // 2 for D in Ds]
logplot(Ns, Npairs, 'bo-')
return {Ns[i]: Npairs[i] for i in range(len(Ns))}
plot_pairs(ints(2, 12)) | _____no_output_____ | MIT | ipynb/Sicherman Dice.ipynb | awesome-archive/pytudes |
OK, we've learned two things. One, it *is* roughly a straight line, so the number of pairs is roughly exponential. Two, there are a *lot* of pairs. 1014, just for *N*=12. I don't want to even think about *N*=20.**So if we want to get much beyond *N*=8, we're either going to need a brand new approach, or we need to make... | sum((1, 2, 2, 3, 3, 4) + (1, 3, 4, 5, 6, 8))
sum((1, 2, 3, 4, 5, 6) + (1, 2, 3, 4, 5, 6)) | _____no_output_____ | MIT | ipynb/Sicherman Dice.ipynb | awesome-archive/pytudes |
**They're the same. Is that [the question](http://hitchhikers.wikia.com/wiki/42) that 42 is the answer to? But does a Sicherman pair always have to have the same sum as a regular pair? I guess it doea, because the sum of `sums(pair)` is just all the sides added up *N* times each, so two pairs have the same sum of `sums... | {die for die in all_dice(6) if max(die) == 12 - 5 and sum(die) == 42 - 19 and die.count(2) == 2} | _____no_output_____ | MIT | ipynb/Sicherman Dice.ipynb | awesome-archive/pytudes |
**There's only 1. So, (1, 3, 3, 3, 4, 5) only has to try to pair with one die, rather than 230. Nice improvement!**In general, I wonder what the sum of the sides of a regular pair is?**Easy, that's `N * (N + 1)`. [Gauss](http://betterexplained.com/articles/techniques-for-adding-the-numbers-1-to-100/) knew that when he ... | from collections import defaultdict
def tabulate(dice):
"""Put all dice into bins in a hash table, keyed by bin_label(die).
Each bin holds a list of dice with that key."""
# Example: {(21, 6, 1): [(1, 2, 3, 4, 5, 6), (1, 2, 3, 4, 4, 7), ...]
table = defaultdict(list)
for die in dice:
table[... | _____no_output_____ | MIT | ipynb/Sicherman Dice.ipynb | awesome-archive/pytudes |
**Let's make sure it works:** | {N: sicherman(N)
for N in ints(2, 6)} | _____no_output_____ | MIT | ipynb/Sicherman Dice.ipynb | awesome-archive/pytudes |
Good, those are the same answers as before. But how much faster is it? | %time sicherman(7) | CPU times: user 24.9 ms, sys: 1.23 ms, total: 26.1 ms
Wall time: 153 ms
| MIT | ipynb/Sicherman Dice.ipynb | awesome-archive/pytudes |
Wow, that's 1000 times faster than before. **I want to take a peek at what some of the bins look like:** | tabulate(all_dice(5)) | _____no_output_____ | MIT | ipynb/Sicherman Dice.ipynb | awesome-archive/pytudes |
**Pretty good: four of the bins have two dice, but the rest have only one die.**And let's see how many pairs we're producing now. We'll tabulate *N* (the number of sides); *D* (the number of *N*-sided dice), the number `pairs(dice)` using the new `pairs`, and the number using the old `pairs`: | print(' N: D #pairs(dice) D*(D-1)/2')
for N in ints(2, 11):
dice = list(all_dice(N))
D = len(dice)
print('{:2}: {:9,d} {:12,d} {:17,d}'.format(N, D, len(list(pairs(dice))), D*(D-1)//2)) | N: D #pairs(dice) D*(D-1)/2
2: 1 1 0
3: 1 1 0
4: 10 3 45
5: 31 9 465
6: 231 71 26,565
7: 1,596 670 1,272,810
8: ... | MIT | ipynb/Sicherman Dice.ipynb | awesome-archive/pytudes |
OK, we're doing 100,000 times better for *N*=11. But it would still take a long time to test 11 million pairs. Let's just get the answers up to *N*=10: | %%time
{N: sicherman(N)
for N in ints(2, 10)} | CPU times: user 26.2 s, sys: 129 ms, total: 26.3 s
Wall time: 26.6 s
| MIT | ipynb/Sicherman Dice.ipynb | awesome-archive/pytudes |
APG-MLE performanceReconstructing the `cat` state from measurements of the Husimi Q function. The cat state is defined as:$$|\psi_{\text{cat}} \rangle = \frac{1}{\mathcal N} ( |\alpha \rangle + |-\alpha \rangle \big ) $$with $\alpha=2$ and normalization $\mathcal N$. Husimi Q function measurementsThe Husimi Q function... | import numpy as np
from qutip import coherent, coherent_dm, expect, Qobj, fidelity, rand_dm
from qutip.wigner import wigner, qfunc
from scipy.io import savemat, loadmat
import matplotlib
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
%load_ext autoreload
tf.keras.backen... | _____no_output_____ | MIT | paper-figures/fig3a-apg-mle-data.ipynb | quantshah/qst-cgan |
Construct the measurement operators and simulated data (without any noise) | X, Y = np.meshgrid(xvec, yvec)
betas = (X + 1j*Y).ravel()
m_ops = [coherent_dm(hilbert_size, beta) for beta in betas]
data = expect(m_ops, rho) | _____no_output_____ | MIT | paper-figures/fig3a-apg-mle-data.ipynb | quantshah/qst-cgan |
APG-MLEThe APG-MLE method implementation in MATLAB provided in https://github.com/qMLE/qMLE requires an input density matrix and a set of measurement operators. Here, we will export the same data to a matlab format and use the APG-MLE method for reconstruction of the density matrix of the state. | ops_numpy = np.array([op.data.toarray() for op in m_ops]) # convert the QuTiP Qobj to numpy arrays
ops = np.transpose(ops_numpy, [1, 2, 0])
mdic = {"measurements": ops}
savemat("data/measurements.mat", mdic)
mdic = {"rho": rho.full()}
savemat("data/rho.mat", mdic) | _____no_output_____ | MIT | paper-figures/fig3a-apg-mle-data.ipynb | quantshah/qst-cgan |
Reconstruct using the APG-MLE MATLAB code | fidelities = loadmat("data/fidelities-apg-mle.mat")
fidelities = fidelities['flist1'].ravel()
iterations = np.arange(len(fidelities))
plt.plot(iterations, fidelities, color="black", label="APG-MLE")
plt.legend()
plt.xlabel("Iterations")
plt.ylabel("Fidelity")
plt.ylim(0, 1)
plt.grid(which='minor', alpha=0.2)
plt.grid(w... | _____no_output_____ | MIT | paper-figures/fig3a-apg-mle-data.ipynb | quantshah/qst-cgan |
MMU Confusion matrix & Metrics walkthroughThis notebook briefly demonstrates the various capabilities of the package on the computation of confusion matrix/matrices and binary classification metrics. | import pandas as pd
import numpy as np
import mmu | _____no_output_____ | Apache-2.0 | notebooks/metrics_tutorial.ipynb | RUrlus/ModelMetricUncertainty |
Data generationWe generate predictions and true labels where:* `scores`: classifier scores* `yhat`: estimated labels* `y`: true labels | scores, yhat, y = mmu.generate_data(n_samples=10000) | _____no_output_____ | Apache-2.0 | notebooks/metrics_tutorial.ipynb | RUrlus/ModelMetricUncertainty |
Confusion matrix onlyWe can compute the confusion matrix for a single run using the estimated labels or based on the probability and a classification threshold.Based on the esstimated labels `yhat` | # based on yhat
mmu.confusion_matrix(y, yhat) | _____no_output_____ | Apache-2.0 | notebooks/metrics_tutorial.ipynb | RUrlus/ModelMetricUncertainty |
based on classifier score with classification threshold | mmu.confusion_matrix(y, scores=scores, threshold=0.5) | _____no_output_____ | Apache-2.0 | notebooks/metrics_tutorial.ipynb | RUrlus/ModelMetricUncertainty |
Precision-Recallmmu has a specialised function for the positive precision and recall | cm, prec_rec = mmu.precision_recall(y, scores=scores, threshold=0.5, return_df=True) | _____no_output_____ | Apache-2.0 | notebooks/metrics_tutorial.ipynb | RUrlus/ModelMetricUncertainty |
Next to the point precision and recall there is also a function to compute the precision recall curve.`precision_recall_curve` also available under alias `pr_curve` requires you to pass the discrimination/classification thresholds. Auto thresholdsmmu provides an utility function `auto_thresholds` that returns the all t... | thresholds = mmu.auto_thresholds(scores) | _____no_output_____ | Apache-2.0 | notebooks/metrics_tutorial.ipynb | RUrlus/ModelMetricUncertainty |
Confusion matrix and metricsThe ``binary_metrics*`` functions compute ten classification metrics: * 0 - neg.precision aka Negative Predictive Value * 1 - pos.precision aka Positive Predictive Value * 2 - neg.recall aka True Negative Rate & Specificity * 3 - pos.recall aka True Positive Rate aka Sensitivity... | col_index = mmu.metrics.col_index
col_index | _____no_output_____ | Apache-2.0 | notebooks/metrics_tutorial.ipynb | RUrlus/ModelMetricUncertainty |
For a single test set | cm, metrics = mmu.binary_metrics(y, yhat)
# the confusion matrix
cm
metrics | _____no_output_____ | Apache-2.0 | notebooks/metrics_tutorial.ipynb | RUrlus/ModelMetricUncertainty |
We can also request dataframes back: | cm, metrics = mmu.binary_metrics(y, yhat, return_df=True)
metrics | _____no_output_____ | Apache-2.0 | notebooks/metrics_tutorial.ipynb | RUrlus/ModelMetricUncertainty |
A single run using probabilities | cm, metrics = mmu.binary_metrics(y, scores=scores, threshold=0.5, return_df=True)
cm
metrics | _____no_output_____ | Apache-2.0 | notebooks/metrics_tutorial.ipynb | RUrlus/ModelMetricUncertainty |
A single run using multiple thresholdsCan be used when you want to compute a precision-recall curve for example | thresholds = mmu.auto_thresholds(scores)
cm, metrics = mmu.binary_metrics_thresholds(
y=y,
scores=scores,
thresholds=thresholds,
return_df=True
) | _____no_output_____ | Apache-2.0 | notebooks/metrics_tutorial.ipynb | RUrlus/ModelMetricUncertainty |
The confusion matrix is now an 2D array where the rows contain the confusion matrix for a single threshold | cm | _____no_output_____ | Apache-2.0 | notebooks/metrics_tutorial.ipynb | RUrlus/ModelMetricUncertainty |
Similarly, `metrics` is now an 2D array where the rows contain the metrics for a single threshold | metrics | _____no_output_____ | Apache-2.0 | notebooks/metrics_tutorial.ipynb | RUrlus/ModelMetricUncertainty |
Generate multiple runs for the below functions | scores, yhat, y = mmu.generate_data(n_samples=10000, n_sets=100) | _____no_output_____ | Apache-2.0 | notebooks/metrics_tutorial.ipynb | RUrlus/ModelMetricUncertainty |
Multiple runs using a single thresholdYou have performed bootstrap or multiple train-test runs and want to evaluate the distribution of the metrics you can use `binary_metrics_runs`.`cm` and `metrics` are now two dimensional arrays where the rows are the confusion matrices/metrics for that a run | cm, metrics = mmu.binary_metrics_runs(
y=y,
scores=scores,
threshold=0.5,
)
cm[:5, :] | _____no_output_____ | Apache-2.0 | notebooks/metrics_tutorial.ipynb | RUrlus/ModelMetricUncertainty |
Multiple runs using multiple thresholdsYou have performed bootstrap or multiple train-test runs and, for example, want to evaluate the different precision recall curves | cm, metrics = mmu.binary_metrics_runs_thresholds(
y=y,
scores=scores,
thresholds=thresholds,
fill=1.0
) | _____no_output_____ | Apache-2.0 | notebooks/metrics_tutorial.ipynb | RUrlus/ModelMetricUncertainty |
The confusion matrix and metrics are now cubes.For the confusion matrix the:* row -- the thresholds* colomns -- the confusion matrix elements* slices -- the runsFor the metrics:* row -- thresholds* colomns -- the metrics* slices -- the runsThe stride is such that the biggest stride is over the thresholds for the confus... | print('shape confusion matrix: ', cm.shape)
print('strides confusion matrix: ', cm.strides)
print('shape metrics: ', metrics.shape)
print('strides metrics: ', metrics.strides)
pos_recalls = metrics[:, mmu.metrics.col_index['pos.rec'], :]
pos_precisions = metrics[:, mmu.metrics.col_index['pos.prec'], :] | _____no_output_____ | Apache-2.0 | notebooks/metrics_tutorial.ipynb | RUrlus/ModelMetricUncertainty |
Binary metrics over confusion matricesThis can be used when you have a methodology where you model and generate confusion matrices | # We use confusion_matrices to create confusion matrices based on some output
cm = mmu.confusion_matrices(
y=y,
scores=scores,
threshold=0.5,
)
metrics = mmu.binary_metrics_confusion_matrices(cm, 0.0)
mmu.metrics_to_dataframe(metrics) | _____no_output_____ | Apache-2.0 | notebooks/metrics_tutorial.ipynb | RUrlus/ModelMetricUncertainty |
- https://github.com/tidyverse/tidyr/tree/master/vignettes - https://cran.r-project.org/web/packages/tidyr/vignettes/tidy-data.html - https://github.com/cmrivers/ebola | pd.read_csv('../data/preg.csv')
pd.read_csv('../data/preg2.csv')
pd.melt(pd.read_csv('../data/preg.csv'), 'name') | _____no_output_____ | MIT | 01-notes/04-tidy.ipynb | chilperic/scipy-2017-tutorial-pandas |
``` Each variable forms a column. Each observation forms a row. Each type of observational unit forms a table.``` Some common data problems``` Column headers are values, not variable names. Multiple variables are stored in one column. Variables are stored in both rows and columns. Multiple types of... | pew = pd.read_csv('../data/pew.csv')
pew.head()
pd.melt(pew, id_vars=['religion'])
pd.melt(pew, id_vars='religion', var_name='income', value_name='count') | _____no_output_____ | MIT | 01-notes/04-tidy.ipynb | chilperic/scipy-2017-tutorial-pandas |
Keep multiple columns fixed | billboard = pd.read_csv('../data/billboard.csv')
billboard.head()
pd.melt(billboard,
id_vars=['year', 'artist', 'track', 'time', 'date.entered'],
value_name='rank', var_name='week') | _____no_output_____ | MIT | 01-notes/04-tidy.ipynb | chilperic/scipy-2017-tutorial-pandas |
Multiple variables are stored in one column. | tb = pd.read_csv('../data/tb.csv')
tb.head()
ebola = pd.read_csv('../data/ebola_country_timeseries.csv')
ebola.head()
# first let's melt the data down
ebola_long = ebola.melt(id_vars=['Date', 'Day'],
value_name='count',
var_name='cd_country')
ebola_long.head()
var_split =... | _____no_output_____ | MIT | 01-notes/04-tidy.ipynb | chilperic/scipy-2017-tutorial-pandas |
above in a single step | variable_split = ebola_long['cd_country'].str.split('_', expand=True)
variable_split.head()
variable_split.columns = ['status1', 'country1']
ebola = pd.concat([ebola_long, variable_split], axis=1)
ebola.head() | _____no_output_____ | MIT | 01-notes/04-tidy.ipynb | chilperic/scipy-2017-tutorial-pandas |
Variables in both rows and columns | weather = pd.read_csv('../data/weather.csv')
weather.head()
weather_melt = pd.melt(weather,
id_vars=['id', 'year', 'month', 'element'],
var_name='day',
value_name='temp')
weather_melt.head()
weather_tidy = weather_melt.pivot_table(
index=['id', 'year... | _____no_output_____ | MIT | 01-notes/04-tidy.ipynb | chilperic/scipy-2017-tutorial-pandas |
This notebook was prepared by [Donne Martin](https://github.com/donnemartin). Source and license info is on [GitHub](https://github.com/donnemartin/interactive-coding-challenges). Challenge Notebook Problem: Implement breadth-first search on a graph.* [Constraints](Constraints)* [Test Cases](Test-Cases)* [Algorithm](... | %run ../graph/graph.py
class GraphBfs(Graph):
def bfs(self, root, visit_func):
# TODO: Implement me
pass | _____no_output_____ | Apache-2.0 | graphs_trees/graph_bfs/bfs_challenge.ipynb | janhak/ica-answers |
Unit Test **The following unit test is expected to fail until you solve the challenge.** | %run ../utils/results.py
# %load test_bfs.py
from nose.tools import assert_equal
class TestBfs(object):
def __init__(self):
self.results = Results()
def test_bfs(self):
nodes = []
graph = GraphBfs()
for id in range(0, 6):
nodes.append(graph.add_node(id))
g... | _____no_output_____ | Apache-2.0 | graphs_trees/graph_bfs/bfs_challenge.ipynb | janhak/ica-answers |
ScottPlot Notebook Quickstart_How to use ScottPlot to plot data in a Jupyter / .NET Interactive notebook_ | // Install the ScottPlot NuGet package
#r "nuget:ScottPlot"
// Plot some data
double[] dataX = new double[] { 1, 2, 3, 4, 5 };
double[] dataY = new double[] { 1, 4, 9, 16, 25 };
var plt = new ScottPlot.Plot(400, 300);
plt.AddScatter(dataX, dataY);
// Display the result as a HTML image
display(HTML(plt.GetImageHTML()))... | _____no_output_____ | MIT | src/ScottPlot4/ScottPlot.Sandbox/Notebook/ScottPlotQuickstart.ipynb | p-rakash/ScottPlot |
PyTorch Image Classification Single GPU using Vertex Training with Custom Container View on GitHub Setup | PROJECT_ID = "YOUR PROJECT ID"
BUCKET_NAME = "gs://YOUR BUCKET NAME"
REGION = "YOUR REGION"
SERVICE_ACCOUNT = "YOUR SERVICE ACCOUNT"
content_name = "pt-img-cls-gpu-cust-cont-torchserve" | _____no_output_____ | Apache-2.0 | community-content/pytorch_image_classification_single_gpu_with_vertex_sdk_and_torchserve/vertex_training_with_custom_container.ipynb | nayaknishant/vertex-ai-samples |
Local Training | ! ls trainer
! cat trainer/requirements.txt
! pip install -r trainer/requirements.txt
! cat trainer/task.py
%run trainer/task.py --epochs 5 --local-mode
! ls ./tmp
! rm -rf ./tmp | _____no_output_____ | Apache-2.0 | community-content/pytorch_image_classification_single_gpu_with_vertex_sdk_and_torchserve/vertex_training_with_custom_container.ipynb | nayaknishant/vertex-ai-samples |
Vertex Training using Vertex SDK and Custom Container Build Custom Container | hostname = "gcr.io"
image_name_train = content_name
tag = "latest"
custom_container_image_uri_train = f"{hostname}/{PROJECT_ID}/{image_name_train}:{tag}"
! cd trainer && docker build -t $custom_container_image_uri_train -f Dockerfile .
! docker run --rm $custom_container_image_uri_train --epochs 5 --local-mode
! docke... | _____no_output_____ | Apache-2.0 | community-content/pytorch_image_classification_single_gpu_with_vertex_sdk_and_torchserve/vertex_training_with_custom_container.ipynb | nayaknishant/vertex-ai-samples |
Initialize Vertex SDK | ! pip install -r requirements.txt
from google.cloud import aiplatform
aiplatform.init(
project=PROJECT_ID,
staging_bucket=BUCKET_NAME,
location=REGION,
) | _____no_output_____ | Apache-2.0 | community-content/pytorch_image_classification_single_gpu_with_vertex_sdk_and_torchserve/vertex_training_with_custom_container.ipynb | nayaknishant/vertex-ai-samples |
Create a Vertex Tensorboard Instance | tensorboard = aiplatform.Tensorboard.create(
display_name=content_name,
) | _____no_output_____ | Apache-2.0 | community-content/pytorch_image_classification_single_gpu_with_vertex_sdk_and_torchserve/vertex_training_with_custom_container.ipynb | nayaknishant/vertex-ai-samples |
Option: Use a Previously Created Vertex Tensorboard Instance```tensorboard_name = "Your Tensorboard Resource Name or Tensorboard ID"tensorboard = aiplatform.Tensorboard(tensorboard_name=tensorboard_name)``` Run a Vertex SDK CustomContainerTrainingJob | display_name = content_name
gcs_output_uri_prefix = f"{BUCKET_NAME}/{display_name}"
machine_type = "n1-standard-4"
accelerator_count = 1
accelerator_type = "NVIDIA_TESLA_K80"
container_args = [
"--batch-size",
"256",
"--epochs",
"100",
]
custom_container_training_job = aiplatform.CustomContainerTraini... | _____no_output_____ | Apache-2.0 | community-content/pytorch_image_classification_single_gpu_with_vertex_sdk_and_torchserve/vertex_training_with_custom_container.ipynb | nayaknishant/vertex-ai-samples |
Training Artifact | ! gsutil ls $gcs_output_uri_prefix | _____no_output_____ | Apache-2.0 | community-content/pytorch_image_classification_single_gpu_with_vertex_sdk_and_torchserve/vertex_training_with_custom_container.ipynb | nayaknishant/vertex-ai-samples |
PostImages UploaderThis notebook provide an easy way to upload your images to [postimages.org](https://postimages.org). How to use:- Modify the **configurations** if needed.- At menu bar, select Run > Run All Cells.- Scroll to the end of this notebook for outputs. Configurations ---Path to a directory which contains... | INPUT_DIR = '../outputs/images' | _____no_output_____ | MIT | notebooks/uploader/postimages.ipynb | TheYoke/PngBin |
---Path to a file which will contain a list of uploaded image urls used for updating metadata database file.> Append if exists. | URLS_PATH = '../outputs/urls.txt' | _____no_output_____ | MIT | notebooks/uploader/postimages.ipynb | TheYoke/PngBin |
--- Import | import os
import sys
from modules.PostImages import PostImages | _____no_output_____ | MIT | notebooks/uploader/postimages.ipynb | TheYoke/PngBin |
Basic Configuration Validation | assert os.path.isdir(INPUT_DIR), 'INPUT_DIR must exist and be a directory.'
assert any(x.is_file() for x in os.scandir(INPUT_DIR)), 'INPUT_DIR top level directory must have at least one file.'
assert not os.path.exists(URLS_PATH) or os.path.isfile(URLS_PATH), 'URLS_PATH must be a file if it exists.' | _____no_output_____ | MIT | notebooks/uploader/postimages.ipynb | TheYoke/PngBin |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.