markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
Multiple Dimensions Just indicate multiple dimensions by using a multidimensional x0. Note that your $x$ becomes a vector! Minimize the following: $$ f(x, y) = \frac{(x - 4)^2} { 2 } + \frac{(y + 3)^2} { 5 } $$
result = minimize(lambda x: (x[0] - 4)**2 / 2 + (x[1] + 3)**2 / 5, x0=[0,0]) print(f'maximum occurs when x = {result.x[0]} and y = {result.x[1]}')
unit_11/lectures/lecture_1.ipynb
whitead/numerical_stats
gpl-3.0
Identifying Convexity for Minimization - Example The best ways to identify convexity are: plot it try optimizing in multiple starting positions
x = np.linspace(-1, 1, 1000) plt.plot(x, 2 * x ** 3 - 0 * x **2 - x) plt.show() from scipy.optimize import minimize minimize(lambda x: 2 * x ** 3 - 0 * x **2 - x, x0=0.05) x = np.linspace(-1, 1, 1000) plt.plot(x, 2 * x ** 3 - 0 * x **2 - x) plt.show() from scipy.optimize import minimize minimize(lambda x: 2 *...
unit_11/lectures/lecture_1.ipynb
whitead/numerical_stats
gpl-3.0
Powell hybrid method Type: Root finding Discrete/Continuous: Continuous Dimensions: N Derivative: optional Non-Convex: not recommended Python: root unless method argument specifies a different method 1D Example This is exactly like newton from above. Solve this equation: $$ \cos x + \sin x = x $$
from scipy.optimize import root #rearranged equation so all terms on one side result = root(lambda x: np.cos(x) + np.sin(x) - x, x0=1) print(result)
unit_11/lectures/lecture_1.ipynb
whitead/numerical_stats
gpl-3.0
The result type is like what we saw for minimize. Similar terms are here, including the root and the value of the function at the root. Notice it's not exactly $0$ at the root.
x = result.x print(np.cos(x) + np.sin(x) - x)
unit_11/lectures/lecture_1.ipynb
whitead/numerical_stats
gpl-3.0
Solve the following system of equations: $$ 3 x^2 - 2 y = 4$$ $$ x - 4 y ^ 2 = -2$$
def sys(v): #I'm using v here to distinguish from the x in the equations #extract x and y x = v[0] y = v[1] #compute equations eq1 = 3 * x ** 2 - 2 * y - 4 eq2 = x - 4 * y**2 + 2 #pack into list sys_eq = [eq1, eq2] return sys_eq root(sys, x0=[1,1])
unit_11/lectures/lecture_1.ipynb
whitead/numerical_stats
gpl-3.0
So the answer is $x = 1.40,\: y = 0.921$ You should not ignore the information in the output of root. Imagine this small modification: $$ 3 x^2 - 2 y^2 = 4$$ $$ x^3 - 4 y = -2$$
def sys2(v): #I'm using v here to distinguish from the x in the equations #extract x and y x = v[0] y = v[1] #compute equations eq1 = 3 * x ** 2 - 2 * y**2 - 4 eq2 = x**3 - 4 * y + 2 #pack into list sys_eq = [eq1, eq2] return sys_eq root(sys2, x0=[1,1])
unit_11/lectures/lecture_1.ipynb
whitead/numerical_stats
gpl-3.0
If you did not read the message or status, you might believe the method succeeded. More compact version:
root(lambda x: [3 * x[0] ** 2 - 2 * x[1] - 4, x[0] - 4 * x[1] ** 2 + 2], x0=[1,1])
unit_11/lectures/lecture_1.ipynb
whitead/numerical_stats
gpl-3.0
Importance of starting position By the way, there are two roots to this function!
root(lambda x: [3 * x[0] ** 2 - 2 * x[1] - 4, x[0] - 4 * x[1] ** 2 + 2], x0=[0, 0])
unit_11/lectures/lecture_1.ipynb
whitead/numerical_stats
gpl-3.0
For a text corpus, I'll load the Quora Duplicate Question dataset
quora = pd.read_csv('datasets/quora_kaggle.csv') quora.head(3)
jupyter_notebooks/Process many find_replace rules in a corpus fast.ipynb
MaxPowerWasTaken/MaxPowerWasTaken.github.io
gpl-3.0
Finally, I'll consolidate our Pandas DataFrames so that we have a single DataFrame of find/replace rules, and a single column/Series of questions text:
find_replace_rules = pd.concat([brit_to_amer, misspellings, contractions], axis=0) questions = pd.concat([quora.question1, quora.question2], axis=0).str.lower()
jupyter_notebooks/Process many find_replace rules in a corpus fast.ipynb
MaxPowerWasTaken/MaxPowerWasTaken.github.io
gpl-3.0
The Naive Approach The simplest way to approach this preprocessing task would be to: - for each row in find_replace_rules: - for each row in questions: - update the question text with the find/replace rule The problem with this approach is that we expect it to take about O(m x n) time, where: - m is the...
find_repl_dict = {row[0]: row[1] for row in find_replace_rules.itertuples(index=False)}
jupyter_notebooks/Process many find_replace rules in a corpus fast.ipynb
MaxPowerWasTaken/MaxPowerWasTaken.github.io
gpl-3.0
We can use this dictionary, along with a compiled regular expression, to process our questions text series in one pass-through using Pandas' Series.str.replace. Series.str.replace takes two required parameters: - pat: A string or regex pattern to search for, and - repl: A replacement string or callable. If a callab...
def mass_find_replace(text_corpus, find_replace_rules): '''thanks for the regex used here to https://stackoverflow.com/a/13824401/1870832''' # Texts in text corpus should be elements in a Pandas Series assert type(text_corpus) == pd.Series # convert find/replace rules from dataframe to dic...
jupyter_notebooks/Process many find_replace rules in a corpus fast.ipynb
MaxPowerWasTaken/MaxPowerWasTaken.github.io
gpl-3.0
Clocking Performance
def clock_performance(text_corpus, num_docs, num_fr_rules, preprocessing_fn): assert type(text_corpus) == pd.Series # take subset of questions, find/replace rules questions_subset = questions.sample(num_docs) fr_rules_subset = find_replace_rules.sample(num_fr_rules) # Process text, clock...
jupyter_notebooks/Process many find_replace rules in a corpus fast.ipynb
MaxPowerWasTaken/MaxPowerWasTaken.github.io
gpl-3.0
Now let's see how performance of this function scales with the size of our text corpus, or our number of find/replace rules. First we'll hold the number of find/replace rules constant, and vary our number of text-documents:
fr_rules = 100 for num_texts in [1e5, 2e5, 4e5, 8e5]: clock_time = clock_performance(questions, int(num_texts), fr_rules, mass_find_replace)[1] print('Clocked time with {} find/replace rules and {} text documents to process: {}'.format(fr_rules, ...
jupyter_notebooks/Process many find_replace rules in a corpus fast.ipynb
MaxPowerWasTaken/MaxPowerWasTaken.github.io
gpl-3.0
Here, in the state space we include states that are not reached due to the constraint that the asset can be serviced at most one per year, i.e., those pairs of the age of asset $a$ and the number of services $s$ such that $s \geq a$. One can alternatively define the state space excluding those states; see the section A...
# We need a routine to get the index of a age-serv pair def getindex(age, serv, S): """ Get the index of [age, serv] in S. We know that elements in S are aligned in a lexicographic order. """ n = len(S) for i in range(n): if S[i, 0] == age: for k in range(n-i): ...
ddp_ex_MF_7_6_3_py.ipynb
QuantEcon/QuantEcon.notebooks
bsd-3-clause
Alternative formulation Define the state space excluding the age-serv pairs that do not realize:
# Construct the state space which is two-dimensional s0 = np.arange(1, maxage+1) # Possible ages s1 = np.arange(maxage) # Possible servicings S = qe.cartesian([s0, s1]) # Including infeasible pairs as previously S = S[S[:, 0] > S[:, 1]] # Exclude infeasible pairs n = len(S) # Number of s...
ddp_ex_MF_7_6_3_py.ipynb
QuantEcon/QuantEcon.notebooks
bsd-3-clause
We follow the state-action pairs formulation approach.
# Reward array R = np.empty((n, m)) for i, (age, serv) in enumerate(S): R[i, 0] = p(age, serv) if age < maxage else -np.infty R[i, 1] = p(age, serv+1) - mancost if age < maxage else -np.infty R[i, 2] = p(0, 0) - repcost R # Remove the state-action pairs yielding a reward negative infinity s_indices, a_ind...
ddp_ex_MF_7_6_3_py.ipynb
QuantEcon/QuantEcon.notebooks
bsd-3-clause
1. Single-subject dataset example Getting started We will use a dataset where one subject was presented with 92 different visual stimuli while brain responses were measured in 100 voxels. The different visual stimuli (each row) are the conditions, and the voxels (each column) are the measurement channels.
# import the measurements for the dataset measurements = io.matlab.loadmat('92imageData/simTruePatterns.mat') measurements = measurements['simTruePatterns'] nCond = measurements.shape[0] nVox = measurements.shape[1] # plot the imported data plt.imshow(measurements,cmap='gray') plt.xlabel('Voxels') plt.ylabel('Conditi...
demos/example_dataset.ipynb
ilogue/pyrsa
lgpl-3.0
Creating the dataset object We will now arrange the loaded data into a dataset object for use in pyrsa. A dataset object contains all the information needed to calculate a representational dissimilarity matrix (RDM). Therefore, the dataest must include: - measurements: [NxP] numpy.ndarray. These are the observations (...
# now create a dataset object des = {'session': 1, 'subj': 1} obs_des = {'conds': np.array(['cond_' + str(x) for x in np.arange(nCond)])} chn_des = {'voxels': np.array(['voxel_' + str(x) for x in np.arange(nVox)])} #obs_des = {'conds': np.array(['cond_' + str(x) for x in np.arange(1,nCond+1)])} # indices from 1 #chn_d...
demos/example_dataset.ipynb
ilogue/pyrsa
lgpl-3.0
Sometimes we wish to consider only a subset of data - either a subset of observations (conditions), or subset of measurement channels. This might be to only consider the measurement channels where all the subjects have data, or conditions which occur across all subjects / sessions. Using dataset functionality, we can ...
# create an example dataset with random data, subset some conditions nChannel = 50 nObs = 12 randomData = np.random.rand(nObs, nChannel) des = {'session': 1, 'subj': 1} obs_des = {'conds': np.array([0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5])} chn_des = {'voxels': np.array(['voxel_' + str(x) for x in np.arange(nChannel)])} da...
demos/example_dataset.ipynb
ilogue/pyrsa
lgpl-3.0
Additionally, you might want to split the data in a certain way and analyze the splits as separate datasets. For instance, if your data is organized such that there are different ROIs, you might wish to perform the subsequent analyses separately for each ROI. Similarly, you could split the observations. This is support...
# Split by channels nChannel = 3 nChannelVox = 10 # three ROIs, each with 10 voxels nObs = 4 randomData = np.random.rand(nObs, nChannel*nChannelVox) des = {'session': 1, 'subj': 1} obs_des = {'conds': np.array([0, 1, 2, 3])} chn_des = np.matlib.repmat(['ROI1','ROI2','ROI3'],1,nChannelVox) chn_des = {'ROIs': np.array(c...
demos/example_dataset.ipynb
ilogue/pyrsa
lgpl-3.0
2. Multi-subject dataset example First, we generate random data for a number of subjects. For simplicity, here we set each subject to have the same number of voxels and conditions.
# create a datasets with random data nVox = 50 # 50 voxels/electrodes/measurement channels nCond = 10 # 10 conditions nSubj = 5 # 5 different subjects randomData = np.random.rand(nConds, nChannel, nSubj)
demos/example_dataset.ipynb
ilogue/pyrsa
lgpl-3.0
We can then create a list of dataset objects by appending each dataset for each subject.
obs_des = {'conds': np.array(['cond_' + str(x) for x in np.arange(nCond)])} chn_des = {'voxels': np.array(['voxel_' + str(x) for x in np.arange(nVox)])} data = [] # list of dataset objects for i in np.arange(nSubj): des = {'session': 1, 'subj': i+1} # append the dataset object to the data list data.append(...
demos/example_dataset.ipynb
ilogue/pyrsa
lgpl-3.0
Figure out RIL make up First I want to count to estimate the number of haplotypes present by looking at SNPs in the coding sequence. I am guessing SNP density for the RILs is low because of the expense, so later I will use King's founder assignment of 10kb blocks. RIL SNP table King et al. 2014 provide SNPs for each...
import bed as mcbed from collections import defaultdict # Import bed with CDS for genes in sd bedName = os.path.join(PROJ, 'exported_data/sd_coding_sequence.bed') bed = mcbed.Bed(bedName) # Create data frame with positions of interest (poi) poi = list() for row in bed: start = min(row[1], row[2]) end = max(ro...
fear_sem_sd_2015/scripts/dspr_ril_allele_table.ipynb
McIntyre-Lab/papers
lgpl-3.0
There are a lot of missing values present in this dataset. Unfortunately, I don't have easy access to the reference base, instead I will set missing values to the most frequent base in that row. This has a lot of caveats, but will give me a better estimate of haplotype frequency.
# Fill missing values with most frequent value dfFull = dfWide.apply(lambda x: x.fillna(x.mode()[0]), axis=1) # Iterate over gene and count the number of haplotypes grp = dfFull.groupby(level='gene') out = list() for name, g in grp: uniq = set([tuple(x) for x in g.T.values]) out.append([name, len(uniq)]) ...
fear_sem_sd_2015/scripts/dspr_ril_allele_table.ipynb
McIntyre-Lab/papers
lgpl-3.0
Most genes were not present in the SNP calls. The RIL SNP density is very low. Fru is the only gene that appears to have a signal, and its haplotype count is similar to the CEGS data. I think the other counts are underestimated. Looking at the King et al. paper they use a HMM with a 10kb sliding windows to determine...
# Import bed with Gene Region bedName = os.path.join(PROJ, 'exported_data/sd_gene_sequence.bed') bed = mcbed.Bed(bedName) # Create data frame with positions of interest (poi). The HMM results are done on 10kb # chunks. Here I round the start down to the nearest 10kb and round the end up to the nearest # 10kb. I then f...
fear_sem_sd_2015/scripts/dspr_ril_allele_table.ipynb
McIntyre-Lab/papers
lgpl-3.0
It looks like most genes are homozygous for one of the parental lines, this is not surprising in a RIL population. When only looking at the genes in SD, there is not an equal frequency of use of the different parental strains. (A3A3, A4A4, A7A7) are the most common in the A population, while (B1B1, B2B2, B3B3, B6B6...
# Iterate over each F1-hybrid and Pull genotypes. # Create list of genes in SD genes = genotypesA.keys() # Create a dictionary with F1-hybrid genotypes hybName = os.path.join(MCLAB, 'dspr_data/mel_expression_head_F/FemaleHeadExpression.txt') F1Geno = defaultdict(dict) with open(hybName, 'r') as FH: # skip header ...
fear_sem_sd_2015/scripts/dspr_ril_allele_table.ipynb
McIntyre-Lab/papers
lgpl-3.0
Numeric stability of propagator elements For the lines $\tau_s\rightarrow\tau_m$ the entry $PA_{32}$ becomes numerically unstable, since denominator and enumerator go to zero. 1. We show that $PAs_{32}$ is the limit of $PA_{32}(\tau_s)$ for $\tau_s\rightarrow\tau_m$.:
PA_32 = PA.row(2).col(1)[0] sp.limit(PA_32, tau_s, tau_m)
doc/userdoc/model_details/IAF_neurons_singularity.ipynb
stinebuu/nest-simulator
gpl-2.0
2. The Taylor-series up to the second order of the function $PA_{32}(\tau_s)$ is:
PA_32_series = PA_32.series(x=tau_s,x0=tau_m,n=2) PA_32_series
doc/userdoc/model_details/IAF_neurons_singularity.ipynb
stinebuu/nest-simulator
gpl-2.0
Therefore we have $T(PA_{32}(\tau_s,\tau_m))=PAs_{32}+PA_{32}^{lin}+O(2)$ where $PA_{32}^{lin}=h^2(-\tau_m + \tau_s)*exp(-h/\tau_m)/(2C\tau_m^2)$ 3. We define $dev:=|PA_{32}-PAs_{32}|$ We also define $PA_{32}^{real}$ which is the correct value of P32 without misscalculation (instability). In the following we assume $0...
import nest import numpy as np import pylab as pl
doc/userdoc/model_details/IAF_neurons_singularity.ipynb
stinebuu/nest-simulator
gpl-2.0
Loop through epsilon array
for i,epsilon in enumerate(epsilon_array): nest.ResetKernel() # reset simulation kernel nest.SetKernelStatus({'resolution':dt}) # Current based alpha neuron neuron = nest.Create('iaf_psc_alpha') neuron.set(C_m=C_m, tau_m=taum, t_ref=0., V_reset=-70., V_th=1e32, tau_syn_ex=taum+eps...
doc/userdoc/model_details/IAF_neurons_singularity.ipynb
stinebuu/nest-simulator
gpl-2.0
Read the list of European countries
eu_countries = {} with open(EU_FILE) as f: for line in f: if line[0] == '#': continue fields = line.strip().split(';') if len(fields) == 3: (name, iso2, iso3) = fields eu_countries[iso2] = dict(iso3=iso3, name=name) for (i, (iso2, info)) in enumerate(sorted(eu_countri...
static/tools/country_compose/.ipynb_checkpoints/countries-checkpoint.ipynb
Dans-labs/dariah
mit
Read and filter the country file
with open(COUNTRIES) as f: countries = json.load(f) print('Total number of countries: {}'.format(len(countries))) i = 0 coord_fmt = '{{:>{}.{}f}}'.format(4+CENTER_PRECISION, CENTER_PRECISION) pair_fmt = '({}, {})'.format(coord_fmt, coord_fmt) line_fmt = '{{:>2}} {{}} {} {{}}'.format(pair_fmt) for country in countr...
static/tools/country_compose/.ipynb_checkpoints/countries-checkpoint.ipynb
Dans-labs/dariah
mit
Gather the boundary information
def n_points(tp, data): if tp == 'll': return len(data) if tp == 'Polygon': return sum(len(ll) for ll in data) if tp == 'MultiPolygon': return sum(sum(len(ll) for ll in poly) for poly in data) return -1 def n_ll(tp, data): if tp == 'Polygon': return len(data) if tp == 'MultiPolygon': return sum...
static/tools/country_compose/.ipynb_checkpoints/countries-checkpoint.ipynb
Dans-labs/dariah
mit
Condense coordinates We are going to reduce the information in the boundaries in a number of ways. A shape is organized as follows: Multipolygon: a set of Polygons Polygon: a set of linear rings Linear rings: a list of coordinates, of which the last is equal to the first Coordinate: a longitude and a latitude GEO_PRECI...
# maximal GEO_PRECISION = 3 # number of digits in coordinates of shapes MIN_POINTS = 1 # minimum number of points in a linear ring MAX_POINTS = 500 # maximum number of points in a linear ring MAX_POLY = 100 # maximum number of polygons in a multipolygon # minimal GEO_PRECISION = 1 # number of digits in co...
static/tools/country_compose/.ipynb_checkpoints/countries-checkpoint.ipynb
Dans-labs/dariah
mit
Produce geojson file
features = dict( type='FeatureCollection', features=[], ) for (iso2, info) in sorted(eu_countries.items()): feature = dict( type='Feature', properties=dict( iso2=iso2, lng=info['lng'], lat=info['lat'], ), geometry=info['geometry'], ) ...
static/tools/country_compose/.ipynb_checkpoints/countries-checkpoint.ipynb
Dans-labs/dariah
mit
The process is quite simple and only requires the user to store the .qasm file in an appropriate location and maintain the absolute path of the file. This will reading the file simpler. For this demonstration, we already saved a few qasm circuit examples in the directory qasm_files. You can find more examples at OpenQA...
path = "qasm_files/swap.qasm" qasm_file = open(path, "r") print(qasm_file.read())
examples/qasm.ipynb
qutip/qutip-notebooks
lgpl-3.0
Qasm Import This QASM file imitates the SWAP gate native to QuTiP in the QASM format. To import it, we use the read_qasm function with the arguments being the file path, the mode which defaults to "qiskit" and the version which defaults to "2.0". We can check that the circuit indeed implements the swap gate by checki...
from qutip_qip.operations.gates import gate_sequence_product from qutip import tensor, basis qc = read_qasm(path, mode="qiskit", version="2.0") gate_sequence_product(qc.propagators())
examples/qasm.ipynb
qutip/qutip-notebooks
lgpl-3.0
The mode refers to the internal way in which QuTiP processes the QASM files. With "qiskit" mode, QASM skips the include command for the file qelib1.inc and maps all custom gates defined in it to QuTiP gates without parsing the gate definitions. Note: "qelib1.inc" is a "header" file that contains some QASM gate defini...
from qutip_qip.qasm import print_qasm print_qasm(qc)
examples/qasm.ipynb
qutip/qutip-notebooks
lgpl-3.0
Custom Gates QASM also offers the option to define custom gates in terms of already defined gates using the "gate" keyword. In "qiskit" mode, our QASM interpreter can be assumed to already allow for all the gates defined in the file qelib1.inc provided by the OpenQASM repository. In the file swap_custom.qasm, we define...
path = "qasm_files/swap_custom.qasm" qasm_file = open(path, "r") print(qasm_file.read())
examples/qasm.ipynb
qutip/qutip-notebooks
lgpl-3.0
Furthermore, the circuit also measures the two qubits q[0] and q[1] and stores the results in the classical registers c[0] and c[1]
qc = read_qasm(path)
examples/qasm.ipynb
qutip/qutip-notebooks
lgpl-3.0
We can now run the circuit to confirm that the circuit is correctly loaded and performs the correct operations. To do this, we can use the QubitCircuit.run function with the appropriate input state. In our case, we can take the state |01⟩.
from qutip import tensor, basis qc.run(tensor(basis(2, 0), basis(2, 1)))
examples/qasm.ipynb
qutip/qutip-notebooks
lgpl-3.0
As predicted the output is the state after swapping which is |10⟩ Measurements and Classical Control The QASM format also allows for other circuit features such as measurement and control of gates by classical bits. This is also supported by QuTiP. For an example, we can refer to the example of quantum teleportation. ...
path = "qasm_files/teleportation.qasm" qasm_file = open(path, "r") qasm_str = qasm_file.read() print(qasm_str)
examples/qasm.ipynb
qutip/qutip-notebooks
lgpl-3.0
We can also read in a QASM file from a string by specifying strmode=True to read_qasm
teleportation = read_qasm(qasm_str, strmode=True)
examples/qasm.ipynb
qutip/qutip-notebooks
lgpl-3.0
Note: The above warning is expected to inform the user that the import from QASM to QuTiP does not retain any information about the different qubit/classical bit register names. This could potentially be an issue when the circuit is exported if the user wants to maintain the consistency. We can quickly check that the...
state = tensor(rand_ket(2), basis(2, 0), basis(2, 0)) initial_measurement = Measurement("start", targets=[0]) _, initial_probabilities = initial_measurement.measurement_comp_basis(state) state_final = teleportation.run(state) final_measurement = Measurement("start", targets=[2]) _, final_probabilities = final_measur...
examples/qasm.ipynb
qutip/qutip-notebooks
lgpl-3.0
Note: Custom gates imported in the QASM format cannot be easily exported. Currently, only gates that are defined native to QuTiP can be exported. QuTiP also produces custom gate definitions for gates not provided in the qelib1.inc "header" file. In these cases, QuTiP will add it's own gate definitions directly to the t...
from qutip.ipynbtools import version_table version_table()
examples/qasm.ipynb
qutip/qutip-notebooks
lgpl-3.0
You may have encountered vectors before in high school or college -- to use Python terms, a vector is like a list of numbers. The mathematical notation is quite similar to Python code, e.g. [5,4], but numpy has its own way of instantiating a vector:
v = np.array([5, 4])
examples/fundamentals/fundamentals.ipynb
ml4a/ml4a-guides
gpl-2.0
$$ v = \begin{bmatrix} 5 \ 4 \end{bmatrix} $$ Vectors are usually represented with lowercase variables. Note that we never specified how many numbers (also called components) a vector has - because it can have any amount. The amount of components a vector has is called its dimensionality. The example vector above has t...
np.array([6, 2]) + np.array([-4, 4])
examples/fundamentals/fundamentals.ipynb
ml4a/ml4a-guides
gpl-2.0
$$ \begin{bmatrix} 6 \ 2 \end{bmatrix} + \begin{bmatrix} -4 \ 4 \end{bmatrix} = \begin{bmatrix} 6 + -4 \ 2 + 4 \end{bmatrix} = \begin{bmatrix} 2 \ 6 \end{bmatrix} $$ However, when it comes to vector multiplication there are many different kinds. The simplest is vector-scalar multiplication:
3 * np.array([2, 1])
examples/fundamentals/fundamentals.ipynb
ml4a/ml4a-guides
gpl-2.0
$$ 3\begin{bmatrix} 2 \ 1 \end{bmatrix} = \begin{bmatrix} 3 \times 2 \ 3 \times 1 \end{bmatrix} = \begin{bmatrix} 6 \ 3 \end{bmatrix} $$ But when you multiply two vectors together you have a few options. I'll cover the two most important ones here. The one you might have thought of is the element-wise product, also cal...
np.array([6, 2]) * np.array([-4, 4])
examples/fundamentals/fundamentals.ipynb
ml4a/ml4a-guides
gpl-2.0
$$ \begin{bmatrix} 6 \ 2 \end{bmatrix} \odot \begin{bmatrix} -4 \ 4 \end{bmatrix} = \begin{bmatrix} 6 \times -4 \ 2 \times 4 \end{bmatrix} = \begin{bmatrix} -24 \ 8 \end{bmatrix} $$ The other vector product, which you'll encounter a lot, is the dot product, also called inner product, usually notated with $\cdot$ (thoug...
np.dot(np.array([6, 2]), np.array([-4, 4]))
examples/fundamentals/fundamentals.ipynb
ml4a/ml4a-guides
gpl-2.0
$$ \begin{bmatrix} 6 \ 2 \end{bmatrix} \cdot \begin{bmatrix} -4 \ 4 \end{bmatrix} = (6 \times -4) + (2 \times 4) = -16 $$ The more general formulation is:
# a slow pure-Python dot product def dot(a, b): assert len(a) == len(b) return sum(a_i * b_i for a_i, b_i in zip(a,b))
examples/fundamentals/fundamentals.ipynb
ml4a/ml4a-guides
gpl-2.0
$$ \begin{aligned} \vec{a} \cdot \vec{b} &= \begin{bmatrix} a_1 \ a_2 \ \vdots \ a_n \end{bmatrix} \cdot \begin{bmatrix} b_1 \ b_2 \ \vdots \ b_n \end{bmatrix} = a_1b_1 + a_2b_2 + \dots + a_nb_n \ &= \sum^n_{i=1} a_i b_i \end{aligned} $$ Note that the vectors in these operations must have the same dimensions! Perhaps t...
# this is so clumsy in python; # this will become more concise in a bit def f(x0, x1, x2, x3, theta0, theta1, theta2, theta3): return theta0 * x0\ + theta1 * x1\ + theta2 * x2\ + theta3 * x3
examples/fundamentals/fundamentals.ipynb
ml4a/ml4a-guides
gpl-2.0
$$ y = \theta_0 x_0 + \theta_1 x_1 + \theta_2 x_2 + \theta_3 x_3 $$ This kind of looks like the dot product, doesn't it? In fact, we can re-write this entire function as a dot product. We define our feature vector $x = [x_0, x_1, x_2, x_3]$ and our parameter vector $\theta = [\theta_0, \theta_1, \theta_2, \theta_3]$, t...
def f(x, theta): return x.dot(theta)
examples/fundamentals/fundamentals.ipynb
ml4a/ml4a-guides
gpl-2.0
$$ y = \theta x $$ So that's how we incorporate multiple features in a representation. There's a whole lot more to vectors than what's presented here, but this is the ground-level knowledge you should have of them. Other aspects of vectors will be explained as they come up. Learning So machine learning algorithms learn...
A = np.array([ [6, 8, 0], [8, 2, 7], [3, 3, 9], [3, 8, 6] ])
examples/fundamentals/fundamentals.ipynb
ml4a/ml4a-guides
gpl-2.0
$$ \mathbf A = \begin{bmatrix} 6 & 8 & 0 \ 8 & 2 & 7 \ 3 & 3 & 9 \ 3 & 8 & 6 \end{bmatrix} $$ Matrices are usually represented with uppercase variables. Note that the "vectors" in the matrix must have the same dimension. The matrix's dimensions are expressed in the form $m \times n$, meaning that there are $m$ rows and...
A[1,2]
examples/fundamentals/fundamentals.ipynb
ml4a/ml4a-guides
gpl-2.0
Basic matrix operations Like vectors, matrix addition and subtraction is straightforward (again, they must be of the same dimensions):
B = np.array([ [8, 3, 7], [2, 9, 6], [2, 5, 6], [5, 0, 6] ]) A + B
examples/fundamentals/fundamentals.ipynb
ml4a/ml4a-guides
gpl-2.0
$$ \begin{aligned} \mathbf B &= \begin{bmatrix} 8 & 3 & 7 \ 2 & 9 & 6 \ 2 & 5 & 6 \ 5 & 0 & 6 \end{bmatrix} \ A + B &= \begin{bmatrix} 8+6 & 3+8 & 7+0 \ 2+8 & 9+2 & 6+7 \ 2+3 & 5+3 & 6+9 \ 5+3 & 0+8 & 6+6 \end{bmatrix} \ &= \begin{bmatrix} 14 & 11 & 7 \ 10 & 11 & 13 \ 5 & 8 & 15 \ 8 & 8 & 12 \end{bmatrix} \ \end{aligne...
# a slow pure-Python matrix-vector product, # using our previous dot product implementation def matrix_vector_product(M, v): return [np.dot(row, v) for row in M] # or, with numpy, you could use np.matmul(A,v)
examples/fundamentals/fundamentals.ipynb
ml4a/ml4a-guides
gpl-2.0
$$ \mathbf M v = \begin{bmatrix} M_{1} \cdot v \ \vdots \ M_{m} \cdot v \ \end{bmatrix} $$ We have a few options when it comes to multiplying matrices with matrices. However, before we go any further we should talk about the tranpose operation - this just involves switching the columns and rows of a matrix. The transpo...
A = np.array([ [1,2,3], [4,5,6] ]) np.transpose(A)
examples/fundamentals/fundamentals.ipynb
ml4a/ml4a-guides
gpl-2.0
$$ \begin{aligned} \mathbf A &= \begin{bmatrix} 1 & 2 & 3 \ 4 & 5 & 6 \end{bmatrix} \ \mathbf A^T &= \begin{bmatrix} 1 & 4 \ 2 & 5 \ 3 & 6 \end{bmatrix} \end{aligned} $$ For matrix-matrix products, the matrix on the lefthand must have the same number of columns as the righthand's rows. To be more concrete, we'll repres...
# a slow pure-Python matrix Hadamard product def matrix_matrix_product(A, B): _, a_cols = np.shape(A) b_rows, _ = np.shape(B) assert a_cols == b_rows result = [] # tranpose B so we can iterate over its columns for col in np.tranpose(B): # using our previous implementation result...
examples/fundamentals/fundamentals.ipynb
ml4a/ml4a-guides
gpl-2.0
$$ \mathbf AB = \begin{bmatrix} A B^T_1 \ \vdots \ A B^T_p \end{bmatrix}^T $$ Finally, like with vectors, we also have Hadamard (element-wise) products:
# a slow pure-Python matrix-matrix product # or, with numpy, you can use A * B def matrix_matrix_hadamard(A, B): result = [] for a_row, b_row in zip(A, B): result.append( zip(a_i * b_i for a_i, b_i in zip(a_row, b_row)))
examples/fundamentals/fundamentals.ipynb
ml4a/ml4a-guides
gpl-2.0
$$ \mathbf A \odot B = \begin{bmatrix} A_{1,1} B_{1,1} & \dots & A_{1,n} B_{1,n} \ \vdots & \dots & \vdots \ A_{m,1} B_{m,1} & \dots & A_{m,n} B_{m,n} \end{bmatrix} $$ Like vector Hadamard products, this requires that the two matrices share the same dimensions. Tensors We've seen vectors, which is like a list of number...
positions = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, # moving forward 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, # pausing 9, 8, 7, 6, 5, 4, 3, 2, 1, 0] # moving backwards t_0 = 0 t_n = 29 (positions[t_n] - positions[t_0])/t_n
examples/fundamentals/fundamentals.ipynb
ml4a/ml4a-guides
gpl-2.0
$$ v = \frac{p_n - p_0}{n} $$ This kind of makes it look like the cyclist didn't move at all. It would probably be more useful to identify the velocity at a given second $t$. Thus we want to come up with some function $v(t)$ which gives us the velocity at some second $t$. We can apply the same approach we just used to ...
def g(x): return x**2 def h(x): return x**3 def f(x): return g(h(x)) # derivatives def g_(x): return 2*x def h_(x): return 3*(x**2)
examples/fundamentals/fundamentals.ipynb
ml4a/ml4a-guides
gpl-2.0
$$ \begin{aligned} g(x) &= x^2 \ h(x) &= x^3 \ f(x) &= g(h(x)) \ g'(x) &= 2x \ h'(x) &= 3x^2 \end{aligned} $$ We're interested in understanding how $f(x)$ changes with respect to $x$, so we want to compute the derivative of $f(x)$. The chain rule allows us to individually differentiate the component functions of $f(x)$...
def f_(x): return g_(x) * h_(x)
examples/fundamentals/fundamentals.ipynb
ml4a/ml4a-guides
gpl-2.0
Maxwell filter data with movement compensation Demonstrate movement compensation on simulated data. The simulated data contains bilateral activation of auditory cortices, repeated over 14 different head rotations (head center held fixed). See the following for details: https://github.com/mne-tools/mne-misc-data/blob/ma...
# Authors: Eric Larson <larson.eric.d@gmail.com> # # License: BSD (3-clause) from os import path as op import mne from mne.preprocessing import maxwell_filter print(__doc__) data_path = op.join(mne.datasets.misc.data_path(verbose=True), 'movement') pos = mne.chpi.read_head_pos(op.join(data_path, 'simulated_quats.p...
0.13/_downloads/plot_movement_compensation.ipynb
mne-tools/mne-tools.github.io
bsd-3-clause
Process our simulated raw data (taking into account head movements)
# extract our resulting events events = mne.find_events(raw, stim_channel='STI 014') events[:, 2] = 1 raw.plot(events=events) topo_kwargs = dict(times=[0, 0.1, 0.2], ch_type='mag', vmin=-500, vmax=500) # 0. Take average of stationary data (bilateral auditory patterns) evoked_stat = mne.Epochs(raw_stat, events, 1, -0....
0.13/_downloads/plot_movement_compensation.ipynb
mne-tools/mne-tools.github.io
bsd-3-clause
IPython review We review some of the basics of IPython. You won't be asked about IPython on the exam, but since the exam is an IPython notebook, it's essential for you to be able to work with one. Question 1. How do you set/choose the current cell? How do you edit the current cell? How do you add a new cell be...
# code cell for experimenting
Code/notebooks/bootcamp_exam_practice_answerkey.ipynb
NYUDataBootcamp/Materials
mit
Question 3. These get progressively more difficult: What type is dollars = '$1,234.5'? Find and apply a method that eliminates the dollar sign from dollars. Find and apply a method that eliminates the comma from dollars. Eliminate both the dollar sign and comma from dollars and covert the result to a float. Combin...
dollars = '$1,234.5' type(dollars) dollars = dollars.replace('$','') dollars dollars = dollars.replace(',','') dollars dollars = float(dollars) dollars # we can glue the pieces together dollars = '$1,234.5' dollars = float(dollars.replace('$','').replace(',','')) dollars
Code/notebooks/bootcamp_exam_practice_answerkey.ipynb
NYUDataBootcamp/Materials
mit
Question 4. For this problem we set letters = 'abcd' as in problem 2. Find and apply a method that converts the lower case letter 'a' to the upper case letter 'A'. Write a loop that goes through the elements of letters and prints their upper case versions. Bonus: Write a loop that goes through the elements of let...
'a'.upper() letters = 'abcd' for letter in letters: print(letter.upper()) letters = 'abcd' for letter in letters: print(letter.upper()+letter)
Code/notebooks/bootcamp_exam_practice_answerkey.ipynb
NYUDataBootcamp/Materials
mit
Question 5. For this problem xyz is the same as defined in problem 2 Write a loop that goes through the elements of xyz and prints them. Modify the loop to print both the elements of xyz and their type. Modify the loop to print only those elements that are not strings. In each case, create a code cell that deliver...
xyz = [2, 3.0, 2/3.0] for item in xyz: print(item) for item in xyz: print(item, type(item)) for item in xyz: if type(item) != str: print(item, type(item))
Code/notebooks/bootcamp_exam_practice_answerkey.ipynb
NYUDataBootcamp/Materials
mit
Data input with Pandas We explore the public indebtedness of Argentina (country code ARG), Germany (DEU), and Greece (GRC). For each one, we provide the ratio of government debt to GDP for every second year starting in 2002. The data come from the IMF's World Economic Outlook. Question 6. Write code in the cell below...
url = 'http://pages.stern.nyu.edu/~dbackus/Data/debt.csv' debt = pd.read_csv(url) debt.tail(3) # if that failed, you can generate the same data with data = {'ARG': [137.5, 106.0, 61.8, 47.0, 39.1, 37.3, 48.6], 'DEU': [59.2, 64.6, 66.3, 64.9, 80.3, 79.0, 73.1], 'GRC': [98.1, 94.9, 102.9, 108.8, 1...
Code/notebooks/bootcamp_exam_practice_answerkey.ipynb
NYUDataBootcamp/Materials
mit
Question 7. Let's describe the object debt: What type of object is debt? What are its dimensions? What are its column labels? Row labels? What dtypes are the columns? In each case, create a code cell that delivers the answer. Please write the question number in a comment in each cell.
type(debt) debt.shape debt.columns debt.index debt.dtypes
Code/notebooks/bootcamp_exam_practice_answerkey.ipynb
NYUDataBootcamp/Materials
mit
Question 8. Do the following with debt: Set Year as the index. Change the column labels from country codes to country names. Do this using both a dictionary and a list. Print the result to verify your changes. The next three get progressively more difficult: Compute the mean (average) debt for each country. ...
debt = debt.set_index('Year') rn = {"ARG": "Argentina", "DEU": "Germany", "GRC": "Greece"} debt.rename(columns=rn) debt.columns = ['Argentina', 'Germany', 'Greece'] debt debt.mean() debt.mean(axis=1) debt.mean().mean()
Code/notebooks/bootcamp_exam_practice_answerkey.ipynb
NYUDataBootcamp/Materials
mit
Python graphics with Matplotlib We'll continue to use the data in debt. Make sure the index is the year. Question 9. Create figure and axis objects with plt.subplots(). Graph public indebtedness over time using our debt data and the axis object we just created. Change the line width to 2. Change the colors to...
fig, ax = plt.subplots() debt.plot(ax=ax, linewidth=2, color=['red', 'green', 'blue']) ax.set_ylim(0) ax.set_title('Public debt') ax.set_ylabel('Public Debt (% of GDP)') debt['Argentina'].plot(ax=ax, linewidth=4, color='red')
Code/notebooks/bootcamp_exam_practice_answerkey.ipynb
NYUDataBootcamp/Materials
mit
Optional challenging questions Good practice, but more than you'll see on the exam. Question 10. In the figure of the previous question: Add a title, 14-point font, right-justified. Put the legend in the lower left corner. Change the line style to dashed. (This will take some Googling, or a good guess.) Elimi...
plt.style.use('fivethirtyeight') fig, ax = plt.subplots() debt.plot(ax=ax, linewidth=2, linestyle='dashed', color=['red', 'green', 'blue']) ax.set_title('Public debt', fontsize=14, loc='right') ax.set_ylabel('Public Debt (% of GDP)') ax.legend(loc='lower left') fig.savefig('debt.pdf')
Code/notebooks/bootcamp_exam_practice_answerkey.ipynb
NYUDataBootcamp/Materials
mit
Question 11. We ran across this one in the OECD healthcare data. The country names had numbers appended, which served as footnotes in the original spreadsheet but looked dumb when we used them as index labels. The question is how to eliminate them. A short version of the country names is names = ['Australia 1', 'C...
names = ['Australia 1', 'Canada 2', 'Chile 3', 'United States 1'] names[-1].rsplit() names[-1].rsplit(maxsplit=1) # apologies, this is harder than we thought for n in range(len(names)): item = names[n] names[n] = item.rsplit(maxsplit=1)[0] print(names) # this one's easier names = ['Australia 1', '...
Code/notebooks/bootcamp_exam_practice_answerkey.ipynb
NYUDataBootcamp/Materials
mit
Use the (local) shape of the distribution to make smarter proposals. Hamiltonian: quantity that is conserved regardless of position in space. Metaphor: hockey puck sliding on a (non-flat) surface. Want to be able to describe the state of the puck. The state has two quantities: Current position, $q$ Momentum, $p$ Ham...
dtarget = lambda x: multivariate_normal.pdf(x, mean=(3, 10), cov=[[1, 0], [0, 1]]) x1 = np.linspace(-6, 12, 101) x2 = np.linspace(-11, 31, 101) X, Y = np.meshgrid(x1, x2) Z = np.array(map(dtarget, zip(X.flat, Y.flat))).reshape(101, 101) plt.figure(figsize=(10,7)) plt.contour(X, Y, Z) plt.xlim(0, 6) plt.ylim(7, 13) plt...
.ipynb_checkpoints/Hamiltonian MCMC (HMC)-checkpoint.ipynb
erickpeirson/statistical-computing
cc0-1.0
The surface of interest will be $U(q) = -\log{f(q)}$ $K(p) = \frac{p^T p}{2m}$, where $m$ = mass of the puck. Position over time is a function of momentum: $\frac{dq_i}{dt} = \frac{p_i}{m}$ Change in momentum over time is a function of surface gradient: $\frac{dp_i}{dt} = -\frac{\delta U}{\delta q_i}$ Leap-frog algori...
def HMC_one_step(U, current_q, Eps, L, m=1): """ One step of the Hamiltonian Monte Carlo. Parameters ---------- U : callable A function that takes a single argument, the position. q : array-like Current position. Eps : float The step size, epsilon. L : int ...
.ipynb_checkpoints/Hamiltonian MCMC (HMC)-checkpoint.ipynb
erickpeirson/statistical-computing
cc0-1.0
Tuning parameters: step size, number of steps, and "mass" HMC does not work discrete parameters. STAN is all HMC. Gelman metric still applies -- we just have a better way of proposing values.
def Gelman(chains): if len(chains.shape) == 3: N_p = chains.shape[2] else: N_p = 1 generate = lambda ptn: np.array([np.array([np.array([ptn(p, i, c) for p in xrange(N_p) for i in xrange(c...
.ipynb_checkpoints/Hamiltonian MCMC (HMC)-checkpoint.ipynb
erickpeirson/statistical-computing
cc0-1.0
Banana-shaped target distribution
dtarget = lambda x: exp( (-x[0]**2)/200. - 0.5*(x[1]+(0.05*x[0]**2) - 100.*0.05)**2) x1 = np.linspace(-20, 20, 101) x2 = np.linspace(-15, 10, 101) X, Y = np.meshgrid(x1, x2) Z = np.array(map(dtarget, zip(X.flat, Y.flat))).reshape(101, 101) plt.figure(figsize=(10,7)) plt.contour(X, Y, Z) plt.show() start = np.array([...
.ipynb_checkpoints/Hamiltonian MCMC (HMC)-checkpoint.ipynb
erickpeirson/statistical-computing
cc0-1.0
NUTS Sampler Toy implementation of No-U-Turn Sampler, described by Hoffman and Gelman (2011). Algorithm 3, page 14.
def Leapfrog(U, theta, r, Eps, m=1.): """ Slightly different update rules, since the negative log of the target PDF is not used. """ gradient = lambda U, theta: derivative(U, theta, 0.01) r += (Eps/2.)*gradient(U, theta) theta += (Eps/m)*r r += (Eps/2.)*gradient(U, theta) return cop...
.ipynb_checkpoints/Hamiltonian MCMC (HMC)-checkpoint.ipynb
erickpeirson/statistical-computing
cc0-1.0
Testing on the banana
start = np.array([[uniform.rvs(loc=-10., scale=15.), uniform.rvs(loc=0., scale=10)] for i in xrange(4)]) chains = np.array([ np.array(NUTS(dtarget, start[i, :], Eps=0.55, m=1.5, num_iters=10000)) for i in xrange(start.shape[0])]) plt.figure(figsize=(10,7)) plt.contour(X, Y, Z) f...
.ipynb_checkpoints/Hamiltonian MCMC (HMC)-checkpoint.ipynb
erickpeirson/statistical-computing
cc0-1.0
TensorFlow 1 のコードを TensorFlow 2 に移行する <table class="tfo-notebook-buttons" align="left"> <td><a target="_blank" href="https://www.tensorflow.org/guide/migrate"> <img src="https://www.tensorflow.org/images/tf_logo_32px.png">TensorFlow.org で表示</a></td> <td><a target="_blank" href="https://colab.research.google.com...
import tensorflow as tf import tensorflow.compat.v1 as v1 import tensorflow_datasets as tfds g = v1.Graph() with g.as_default(): in_a = v1.placeholder(dtype=v1.float32, shape=(2)) in_b = v1.placeholder(dtype=v1.float32, shape=(2)) def forward(x): with v1.variable_scope("matmul", reuse=v1.AUTO_REUSE): ...
site/ja/guide/migrate.ipynb
tensorflow/docs-l10n
apache-2.0
変換後 変換されたコードでは : 変数はローカル Python オブジェクトです。 forward関数は依然として計算を定義します。 Session.run呼び出しはforwardへの呼び出しに置き換えられます。 パフォーマンス向上のためにオプションでtf.functionデコレータを追加可能です。 どのグローバルコレクションも参照せず、正則化は手動で計算されます。 セッションやプレースホルダーはありません。
W = tf.Variable(tf.ones(shape=(2,2)), name="W") b = tf.Variable(tf.zeros(shape=(2)), name="b") @tf.function def forward(x): return W * x + b out_a = forward([1,0]) print(out_a) out_b = forward([0,1]) regularizer = tf.keras.regularizers.l2(0.04) reg_loss=regularizer(W)
site/ja/guide/migrate.ipynb
tensorflow/docs-l10n
apache-2.0
tf.layersベースのモデル v1.layersモジュールは、変数を定義および再利用するv1.variable_scopeに依存するレイヤー関数を含めるために使用されます。 変換前
def model(x, training, scope='model'): with v1.variable_scope(scope, reuse=v1.AUTO_REUSE): x = v1.layers.conv2d(x, 32, 3, activation=v1.nn.relu, kernel_regularizer=lambda x:0.004*tf.reduce_mean(x**2)) x = v1.layers.max_pooling2d(x, (2, 2), 1) x = v1.layers.flatten(x) x = v1.layers.dropout(x,...
site/ja/guide/migrate.ipynb
tensorflow/docs-l10n
apache-2.0
変換後 レイヤーの単純なスタックが tf.keras.Sequentialにぴったり収まります。(より複雑なモデルについてはカスタムレイヤーとモデルおよび Functional API をご覧ください。) モデルが変数と正則化損失を追跡します。 v1.layersからtf.keras.layersへの直接的なマッピングがあるため、変換は一対一対応でした。 ほとんどの引数はそのままです。しかし、以下の点は異なります。 training引数は、それが実行される時点でモデルによって各レイヤーに渡されます。 元のmodel関数への最初の引数(入力 x)はなくなりました。これはオブジェクトレイヤーがモデルの呼び出しからモデルの構築を分離...
model = tf.keras.Sequential([ tf.keras.layers.Conv2D(32, 3, activation='relu', kernel_regularizer=tf.keras.regularizers.l2(0.04), input_shape=(28, 28, 1)), tf.keras.layers.MaxPooling2D(), tf.keras.layers.Flatten(), tf.keras.layers.Dropout(0.1), t...
site/ja/guide/migrate.ipynb
tensorflow/docs-l10n
apache-2.0
変数とv1.layersの混在 既存のコードは低レベルの TensorFlow 1.x 変数と演算子に高レベルのv1.layersが混ざっていることがよくあります。 変換前
def model(x, training, scope='model'): with v1.variable_scope(scope, reuse=v1.AUTO_REUSE): W = v1.get_variable( "W", dtype=v1.float32, initializer=v1.ones(shape=x.shape), regularizer=lambda x:0.004*tf.reduce_mean(x**2), trainable=True) if training: x = x + W else: x = x...
site/ja/guide/migrate.ipynb
tensorflow/docs-l10n
apache-2.0
変換後 このコードを変換するには、前の例で示したレイヤーからレイヤーへのマッピングのパターンに従います。 一般的なパターンは次の通りです。 __init__でレイヤーパラメータを収集する。 buildで変数を構築する。 callで計算を実行し、結果を返す。 v1.variable_scopeは事実上それ自身のレイヤーです。従ってtf.keras.layers.Layerとして書き直します。詳細はガイドをご覧ください。
# Create a custom layer for part of the model class CustomLayer(tf.keras.layers.Layer): def __init__(self, *args, **kwargs): super(CustomLayer, self).__init__(*args, **kwargs) def build(self, input_shape): self.w = self.add_weight( shape=input_shape[1:], dtype=tf.float32, initialize...
site/ja/guide/migrate.ipynb
tensorflow/docs-l10n
apache-2.0
注意点: サブクラス化された Keras モデルとレイヤーは v1 グラフ(自動制御依存性なし)と eager モードの両方で実行される必要があります。 call()をtf.function()にラップして、AutoGraph と自動制御依存性を得るようにします。 training引数を受け取ってcallすることを忘れないようにしてください。 それはtf.Tensorである場合があります。 それは Python ブール型である場合があります。 self.add_weight()を使用して、コンストラクタまたはModel.buildでモデル変数を作成します。 Model.buildでは、入力形状にアクセスできるた...
datasets, info = tfds.load(name='mnist', with_info=True, as_supervised=True) mnist_train, mnist_test = datasets['train'], datasets['test']
site/ja/guide/migrate.ipynb
tensorflow/docs-l10n
apache-2.0
次に、トレーニング用のデータを準備します。 各画像をリスケールする。 例の順序をシャッフルする。 画像とラベルのバッチを集める。
BUFFER_SIZE = 10 # Use a much larger value for real code. BATCH_SIZE = 64 NUM_EPOCHS = 5 def scale(image, label): image = tf.cast(image, tf.float32) image /= 255 return image, label
site/ja/guide/migrate.ipynb
tensorflow/docs-l10n
apache-2.0
例を短く保つために、データセットをトリミングして 5 バッチのみを返すようにします。
train_data = mnist_train.map(scale).shuffle(BUFFER_SIZE).batch(BATCH_SIZE) test_data = mnist_test.map(scale).batch(BATCH_SIZE) STEPS_PER_EPOCH = 5 train_data = train_data.take(STEPS_PER_EPOCH) test_data = test_data.take(STEPS_PER_EPOCH) image_batch, label_batch = next(iter(train_data))
site/ja/guide/migrate.ipynb
tensorflow/docs-l10n
apache-2.0
Keras トレーニングループを使用する トレーニングプロセスの低レベル制御が不要な場合は、Keras 組み込みのfit、evaluate、predictメソッドの使用が推奨されます。これらのメソッドは(シーケンシャル、関数型、またはサブクラス化)実装を問わず、モデルをトレーニングするための統一インターフェースを提供します。 これらのメソッドには次のような優位点があります。 Numpy 配列、Python ジェネレータ、tf.data.Datasetsを受け取ります。 正則化と活性化損失を自動的に適用します。 マルチデバイストレーニングのためにtf.distributeをサポートします。 任意の callable は損失とメトリク...
model = tf.keras.Sequential([ tf.keras.layers.Conv2D(32, 3, activation='relu', kernel_regularizer=tf.keras.regularizers.l2(0.02), input_shape=(28, 28, 1)), tf.keras.layers.MaxPooling2D(), tf.keras.layers.Flatten(), tf.keras.layers.Dropout(0.1), t...
site/ja/guide/migrate.ipynb
tensorflow/docs-l10n
apache-2.0
ループを自分で書く Keras モデルのトレーニングステップは動作していても、そのステップの外でより制御が必要な場合は、データ イテレーション ループでtf.keras.Model.train_on_batchメソッドの使用を検討してみてください。 tf.keras.callbacks.Callbackとして、多くのものが実装可能であることに留意してください。 このメソッドには前のセクションで言及したメソッドの優位点の多くがありますが、外側のループのユーザー制御も与えます。 tf.keras.Model.test_on_batchまたはtf.keras.Model.evaluateを使用して、トレーニング中のパフォーマンスをチェック...
# Model is the full model w/o custom layers model.compile(optimizer='adam', loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=['accuracy']) for epoch in range(NUM_EPOCHS): #Reset the metric accumulators model.reset_metrics() for image_batch, label_batch in...
site/ja/guide/migrate.ipynb
tensorflow/docs-l10n
apache-2.0
<a name="custom_loop"></a> トレーニングステップをカスタマイズする より多くの柔軟性と制御を必要とする場合、独自のトレーニングループを実装することでそれが可能になります。以下の 3 つのステップを踏みます。 Python ジェネレータかtf.data.Datasetをイテレートして例のバッチを作成します。 tf.GradientTapeを使用して勾配を集めます。 tf.keras.optimizersの 1 つを使用して、モデルの変数に重み更新を適用します。 留意点: サブクラス化されたレイヤーとモデルのcallメソッドには、常にtraining引数を含めます。 training引数を確実に正しくセッ...
model = tf.keras.Sequential([ tf.keras.layers.Conv2D(32, 3, activation='relu', kernel_regularizer=tf.keras.regularizers.l2(0.02), input_shape=(28, 28, 1)), tf.keras.layers.MaxPooling2D(), tf.keras.layers.Flatten(), tf.keras.layers.Dropout(0.1), t...
site/ja/guide/migrate.ipynb
tensorflow/docs-l10n
apache-2.0
新しいスタイルのメトリクスと損失 TensorFlow 2.x では、メトリクスと損失はオブジェクトです。Eager で実行的にtf.function内で動作します。 損失オブジェクトは呼び出し可能で、(y_true, y_pred) を引数として期待します。
cce = tf.keras.losses.CategoricalCrossentropy(from_logits=True) cce([[1, 0]], [[-1.0,3.0]]).numpy()
site/ja/guide/migrate.ipynb
tensorflow/docs-l10n
apache-2.0
メトリックオブジェクトには次のメソッドがあります 。 Metric.update_state() — 新しい観測を追加する Metric.result() — 観測値が与えられたとき、メトリックの現在の結果を得る Metric.reset_states() — すべての観測をクリアする オブジェクト自体は呼び出し可能です。呼び出しはupdate_stateと同様に新しい観測の状態を更新し、メトリクスの新しい結果を返します。 メトリックの変数を手動で初期化する必要はありません。また、TensorFlow 2.x は自動制御依存性を持つため、それらについても気にする必要はありません。 次のコードは、メトリックを使用してカスタムトレー...
# Create the metrics loss_metric = tf.keras.metrics.Mean(name='train_loss') accuracy_metric = tf.keras.metrics.SparseCategoricalAccuracy(name='train_accuracy') @tf.function def train_step(inputs, labels): with tf.GradientTape() as tape: predictions = model(inputs, training=True) regularization_loss=tf.math.a...
site/ja/guide/migrate.ipynb
tensorflow/docs-l10n
apache-2.0
<a id="keras_metric_names"></a> Keras メトリック名 TensorFlow 2.x では、Keras モデルはメトリクス名の処理に関してより一貫性があります。 メトリクスリストで文字列を渡すと、まさにその文字列がメトリクスのnameとして使用されます。これらの名前は<br>model.fitによって返される履歴オブジェクトと、keras.callbacksに渡されるログに表示されます。これはメトリクスリストで渡した文字列に設定されています。
model.compile( optimizer = tf.keras.optimizers.Adam(0.001), loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics = ['acc', 'accuracy', tf.keras.metrics.SparseCategoricalAccuracy(name="my_accuracy")]) history = model.fit(train_data) history.history.keys()
site/ja/guide/migrate.ipynb
tensorflow/docs-l10n
apache-2.0
これはmetrics=["accuracy"]を渡すとdict_keys(['loss', 'acc'])になっていた、以前のバージョンとは異なります。 Keras オプティマイザ v1.train.AdamOptimizerやv1.train.GradientDescentOptimizerなどのv1.train内のオプティマイザは、tf.keras.optimizers内に同等のものを持ちます。 v1.trainをkeras.optimizersに変換する オプティマイザを変換する際の注意事項を次に示します。 オプティマイザをアップグレードすると、古いチェックポイントとの互換性がなくなる可能性があります。 epsilon の...
def wrap_frozen_graph(graph_def, inputs, outputs): def _imports_graph_def(): tf.compat.v1.import_graph_def(graph_def, name="") wrapped_import = tf.compat.v1.wrap_function(_imports_graph_def, []) import_graph = wrapped_import.graph return wrapped_import.prune( tf.nest.map_structure(import_graph.as_grap...
site/ja/guide/migrate.ipynb
tensorflow/docs-l10n
apache-2.0
たとえば、次のような凍結された Inception v1 グラフ(2016 年)があります。
path = tf.keras.utils.get_file( 'inception_v1_2016_08_28_frozen.pb', 'http://storage.googleapis.com/download.tensorflow.org/models/inception_v1_2016_08_28_frozen.pb.tar.gz', untar=True)
site/ja/guide/migrate.ipynb
tensorflow/docs-l10n
apache-2.0
tf.GraphDefを読み込みます。
graph_def = tf.compat.v1.GraphDef() loaded = graph_def.ParseFromString(open(path,'rb').read())
site/ja/guide/migrate.ipynb
tensorflow/docs-l10n
apache-2.0