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
ADMM Optimizer Introduction The ADMM Optimizer can solve classes of mixed-binary constrained optimization problems, hereafter (MBCO), which often appear in logistic, finance, and operation research. In particular, the ADMM Optimizer here designed can tackle the following optimization problem $(P)$:$$\min_{x \in \math...
import time from typing import List, Optional, Any import numpy as np import matplotlib.pyplot as plt from docplex.mp.model import Model from qiskit import BasicAer from qiskit.aqua.algorithms import QAOA, NumPyMinimumEigensolver from qiskit.optimization.algorithms import CobylaOptimizer, MinimumEigenOptimizer from ...
_____no_output_____
Apache-2.0
tutorials/optimization/5_admm_optimizer.ipynb
prasad-kumkar/qiskit-tutorials
We first initialize all the algorithms we plan to use later in this tutorial.To solve the QUBO problems we can choose between - `MinimumEigenOptimizer` using different `MinimumEigensolver`, such as `VQE`, `QAOA` or `NumpyMinimumEigensolver` (classical)- `GroverOptimizer`- `CplexOptimizer` (classical, if CPLEX is instal...
# define COBYLA optimizer to handle convex continuous problems. cobyla = CobylaOptimizer() # define QAOA via the minimum eigen optimizer qaoa = MinimumEigenOptimizer(QAOA(quantum_instance=BasicAer.get_backend('statevector_simulator'))) # exact QUBO solver as classical benchmark exact = MinimumEigenOptimizer(NumPyMini...
_____no_output_____
Apache-2.0
tutorials/optimization/5_admm_optimizer.ipynb
prasad-kumkar/qiskit-tutorials
ExampleWe test 3-ADMM-H algorithm on a simple Mixed-Binary Quadratic Problem with equality and inequality constraints (Example 6 reported in [1]). We first construct a docplex problem and then load it into a `QuadraticProgram`.
# construct model using docplex mdl = Model('ex6') v = mdl.binary_var(name='v') w = mdl.binary_var(name='w') t = mdl.binary_var(name='t') u = mdl.continuous_var(name='u') mdl.minimize(v + w + t + 5 * (u-2)**2) mdl.add_constraint(v + 2 * w + t + u <= 3, "cons1") mdl.add_constraint(v + w + t >= 1, "cons2") mdl.add_cons...
\ This file has been generated by DOcplex \ ENCODING=ISO-8859-1 \Problem name: ex6 Minimize obj: v + w + t - 20 u + [ 10 u^2 ]/2 + 20 Subject To cons1: v + 2 w + t + u <= 3 cons2: v + w + t >= 1 cons3: v + w = 1 Bounds 0 <= v <= 1 0 <= w <= 1 0 <= t <= 1 Binaries v w t End
Apache-2.0
tutorials/optimization/5_admm_optimizer.ipynb
prasad-kumkar/qiskit-tutorials
Classical Solution3-ADMM-H needs a QUBO optimizer to solve the QUBO subproblem, and a continuous optimizer to solve the continuous convex constrained subproblem. We first solve the problem classically: we use the `MinimumEigenOptimizer` with the `NumPyMinimumEigenSolver` as a classical and exact QUBO solver and we use...
admm_params = ADMMParameters( rho_initial=1001, beta=1000, factor_c=900, max_iter=100, three_block=True, tol=1.e-6 )
_____no_output_____
Apache-2.0
tutorials/optimization/5_admm_optimizer.ipynb
prasad-kumkar/qiskit-tutorials
Calling 3-ADMM-H algorithmTo invoke the 3-ADMM-H algorithm, an instance of the `ADMMOptimizer` class needs to be created. This takes ADMM-specific parameters and the subproblem optimizers separately into the constructor. The solution returned is an instance of `OptimizationResult` class.
# define QUBO optimizer qubo_optimizer = exact # qubo_optimizer = cplex # uncomment to use CPLEX instead # define classical optimizer convex_optimizer = cobyla # convex_optimizer = cplex # uncomment to use CPLEX instead # initialize ADMM with classical QUBO and convex optimizer admm = ADMMOptimizer(params=admm_para...
_____no_output_____
Apache-2.0
tutorials/optimization/5_admm_optimizer.ipynb
prasad-kumkar/qiskit-tutorials
Classical Solver ResultThe 3-ADMM-H solution can be then printed and visualized. The `x` attribute of the solution contains respectively, thevalues of the binary decision variables and the values of the continuous decision variables. The `fval` is the objectivevalue of the solution.
print("x={}".format(result.x)) print("fval={:.2f}".format(result.fval))
x=[0.0, 1.0, 0.0, 1.0000000000000002] fval=6.00
Apache-2.0
tutorials/optimization/5_admm_optimizer.ipynb
prasad-kumkar/qiskit-tutorials
Solution statistics can be accessed in the `state` field and visualized. We here display the convergence of 3-ADMM-H, in terms of primal residuals.
plt.plot(result.state.residuals) plt.xlabel("Iterations") plt.ylabel("Residuals") plt.show()
_____no_output_____
Apache-2.0
tutorials/optimization/5_admm_optimizer.ipynb
prasad-kumkar/qiskit-tutorials
Quantum SolutionWe now solve the same optimization problem with QAOA as QUBO optimizer, running on simulated quantum device. First, one need to select the classical optimizer of the eigensolver QAOA. Then, the simulation backened is set. Finally, the eigensolver is wrapped into the `MinimumEigenOptimizer` class. A new...
# define QUBO optimizer qubo_optimizer = qaoa # define classical optimizer convex_optimizer = cobyla # convex_optimizer = cplex # uncomment to use CPLEX instead # initialize ADMM with quantum QUBO optimizer and classical convex optimizer admm_q = ADMMOptimizer(params=admm_params, qubo_optimi...
_____no_output_____
Apache-2.0
tutorials/optimization/5_admm_optimizer.ipynb
prasad-kumkar/qiskit-tutorials
Quantum Solver ResultsHere we present the results obtained from the quantum solver. As in the example above `x` stands for the solution, the `fval` is for objective value.
print("x={}".format(result_q.x)) print("fval={:.2f}".format(result_q.fval)) plt.clf() plt.plot(result_q.state.residuals) plt.xlabel("Iterations") plt.ylabel("Residuals") plt.show() import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
_____no_output_____
Apache-2.0
tutorials/optimization/5_admm_optimizer.ipynb
prasad-kumkar/qiskit-tutorials
CMAES parallel run for 50 trials hard barrier
folder = 'result_cmaes_50tr_30n' config = pickle.load(open(folder + "/config.p", "rb")) exps = pickle.load(open(folder + "/exps.p", "rb")) res = pickle.load(open(list(glob.glob(folder + '/final_res*.p'))[0], 'rb')) plot_results(res, config['opt'])
_____no_output_____
MIT
notebooks/Plot_results-parallel_run-cmaes.ipynb
hannanabdul55/seldonian-fairness
CMAES run for 50 trials with stratification
folder = 'result_cmaes_50tr_30n_stratify' config = pickle.load(open(folder + "/config.p", "rb")) exps = pickle.load(open(folder + "/exps.p", "rb")) res = pickle.load(open(list(glob.glob(folder + '/final_res*.p'))[0], 'rb')) plot_results(res, config['opt'])
_____no_output_____
MIT
notebooks/Plot_results-parallel_run-cmaes.ipynb
hannanabdul55/seldonian-fairness
4 Setting the initial SoC Setting the initial SoC for your pack is performed with an argument passed to the solve algorithm. Currently the same value is applied to each battery but in future it will be possible to vary the SoC across the pack.
import liionpack as lp import pybamm import numpy as np import matplotlib.pyplot as plt
c:\users\tom\code\pybamm\pybamm\expression_tree\functions.py:204: RuntimeWarning: invalid value encountered in sign return self.function(*evaluated_children)
MIT
examples/notebooks/04 Initial SoC.ipynb
brosaplanella/liionpack
Lets set up the most simple pack possible with 1 battery and very low busbar resistance to compare to a pure PyBaMM simulation
Rsmall = 1e-6 netlist = lp.setup_circuit(Np=1, Ns=1, Rb=Rsmall, Rc=Rsmall, Ri=5e-2, V=4.0, I=1.0) # Heat transfer coefficients htc = np.ones(1) * 10 # PyBaMM parameters chemistry = pybamm.parameter_sets.Chen2020 parameter_values = pybamm.ParameterValues(chemistry=chemistry) # Cycling experiment experiment = pybamm.Expe...
c:\users\tom\code\pybamm\pybamm\expression_tree\functions.py:204: RuntimeWarning: invalid value encountered in sign return self.function(*evaluated_children) Solving Pack: 100%|███████████████████████████████████████████████████████████████| 1200/1200 [00:06<00:00, 191.77it/s]
MIT
examples/notebooks/04 Initial SoC.ipynb
brosaplanella/liionpack
Let's compare to the PyBaMM simulation
parameter_values = pybamm.ParameterValues(chemistry=chemistry) parameter_values.update({"Total heat transfer coefficient [W.m-2.K-1]": 10.0}) sim = lp.create_simulation(parameter_values, experiment, make_inputs=False) sol = sim.solve(initial_soc=SoC) def compare(sol, output): # Get pack level results time = sol...
_____no_output_____
MIT
examples/notebooks/04 Initial SoC.ipynb
brosaplanella/liionpack
Now lets start the simulation from a different state of charge
SoC = 0.25 # Solve pack output = lp.solve(netlist=netlist, parameter_values=parameter_values, experiment=experiment, htc=htc, initial_soc=SoC) compare(sol, output)
_____no_output_____
MIT
examples/notebooks/04 Initial SoC.ipynb
brosaplanella/liionpack
Here we are still comparing to the PyBaMM simulation at 0.5 SoC and we can see that liionpack started at a lower voltage corresponding to a lower SoC.
parameter_values = pybamm.ParameterValues(chemistry=chemistry) parameter_values.update({"Total heat transfer coefficient [W.m-2.K-1]": 10.0}) sim = lp.create_simulation(parameter_values, experiment, make_inputs=False) sol = sim.solve(initial_soc=SoC)
_____no_output_____
MIT
examples/notebooks/04 Initial SoC.ipynb
brosaplanella/liionpack
Now we can re-run the PyBaMM simulation and compare again
compare(sol, output) lp.draw_circuit(netlist)
_____no_output_____
MIT
examples/notebooks/04 Initial SoC.ipynb
brosaplanella/liionpack
Découverte du format CSV - *Comma-Separated values* **Plan du document**- Le format **CSV**- Représenter des données CSV avec Python - Première solution: un tableau de tuples - **Deuxième solution**: un tableau de *tuples nommés* (dictionnaires) - l'*unpacking*, - l'opération *zip* - syntaxe...
donnees_CSV = """nom,prenom,date_naissance Durand,Jean-Pierre,23/05/1985 Dupont,Christophe,15/12/1967 Terta,Henry,12/06/1978""" etape1 = donnees_CSV.split('\n') etape1 etape2 = [obj.split(',') for obj in etape1] etape2 # une liste de liste etape3 = [tuple(obj) for obj in etape2] etape3 # une liste de tuple fin = etape3...
_____no_output_____
CC0-1.0
01_donnees_en_tables/correction/03_1_format_csv_correction.ipynb
efloti/cours-nsi-premiere
À faire toi-mêmeOn peut parvenir à `fin` à partir de `donnees_CSV` en **une seule fois** par *composition* ... essais!
# deux_en_un = [ obj.split(',') for obj in donnees_CSV.split('\n') ] # trois_en_un = [ tuple( obj.split(',') ) for obj in donnees_CSV.split('\n') ] # tu peux essayer de faire deux_en_un, puis trois_en_un avant. quatre_en_un = [ tuple( obj.split(',') ) for obj in donnees_CSV.split('\n') ][1:] # pour tester assert quatre...
_____no_output_____
CC0-1.0
01_donnees_en_tables/correction/03_1_format_csv_correction.ipynb
efloti/cours-nsi-premiere
___ L'inconvénient de cette représentation c'est qu'elle «oublie» les descripteurs.Pourquoi ne pas les conserver comme à l'étape3? Pour éviter d'avoir un tableau *hétérogène*: le premier élément ne serait pas un «objet». De tels tableaux sont plus difficile à manipuler. Deuxième solution: un tableau de *tuples nommés*...
donnees_CSV = """nom,prenom,date_naissance Durand,Jean-Pierre,23/05/1985 Dupont,Christophe,15/12/1967 Terta,Henry,12/06/1978"""
_____no_output_____
CC0-1.0
01_donnees_en_tables/correction/03_1_format_csv_correction.ipynb
efloti/cours-nsi-premiere
Les étapes qui suivent servent à séparer les descripteurs et les objets:
tmp = donnees_CSV.split('\n') tmp descripteurs_str = tmp[0] descripteurs = tuple(descripteurs_str.split(',')) print(f"le tuple des descripteurs: {descripteurs}") donnees_str = tmp[1:] donnees_str objets = [tuple(obj.split(',')) for obj in donnees_str] print(f"la liste des objets (des personnes ici):\n {objets}")
la liste des objets (des personnes ici): [('Durand', 'Jean-Pierre', '23/05/1985'), ('Dupont', 'Christophe', '15/12/1967'), ('Terta', 'Henry', '12/06/1978')]
CC0-1.0
01_donnees_en_tables/correction/03_1_format_csv_correction.ipynb
efloti/cours-nsi-premiere
À faire toi-mêmePeux-tu compléter les parties manquantes pour obtenir le même résultat plus rapidement?
descripteurs = tuple( donnees_CSV.split('\n')[0].split(',') ) objets = [ tuple( ligne.split(',') ) for ligne in donnees_CSV.split('\n')[1:] ] print(f"- les descripteurs:\n\t {descripteurs}\n- les objets:\n\t {objets}")
- les descripteurs: ('nom', 'prenom', 'date_naissance') - les objets: [('Durand', 'Jean-Pierre', '23/05/1985'), ('Dupont', 'Christophe', '15/12/1967'), ('Terta', 'Henry', '12/06/1978')]
CC0-1.0
01_donnees_en_tables/correction/03_1_format_csv_correction.ipynb
efloti/cours-nsi-premiere
______ À faire toi-même - *découverte de l'**unpacking** (déballage)*Peux-tu réaliser le traitement précédent en **vraiment** une seule ligne? Pour cela observe les trois exemples qui suivent:
# exemple1 d'unpacking tete, *queue = [1, 2, 3, 4] print(f"La tête: {tete} et la queue: {queue}") # exemple2 d'unpacking un, deux, *reste = [1, 2, 3, 4] print(f"un: {un}\ndeux: {deux}\nreste: {reste}") # exemple3 d'unpacking tete, *corps, pied = [1,2,3,4] print(f"tete: {tete}\ncorps: {corps}\npied: {pied}") # À toi de ...
les descripteurs: ('nom', 'prenom', 'date_naissance') les objets: [('Durand', 'Jean-Pierre', '23/05/1985'), ('Dupont', 'Christophe', '15/12/1967'), ('Terta', 'Henry', '12/06/1978')]
CC0-1.0
01_donnees_en_tables/correction/03_1_format_csv_correction.ipynb
efloti/cours-nsi-premiere
____ Arrivé à ce stade nous voudrions combiner:- `('descr1', 'descr2', ...)` et `('v1', 'v2', ...)` en ...- `{'descr1': 'v1', 'descr2': 'v2', ..}` (n-uplet nommé) Appareiller deux séquences - `zip` On a souvent besoin de grouper par paires deux séquences de même longueur `len`.*Ex*: je **dispose** de `['a', 'b', 'c']...
def appareiller(t1, t2): assert len(t1) == len(t2) t = [] for i in range(len(t1)): couple = (t1[i], t2[i]) t.append( couple ) return t # autre solution avec la syntaxe en compréhension def appareiller2(t1, t2): assert len(t1) == len(t2) return [ (t1[i], t2[i]) fo...
_____no_output_____
CC0-1.0
01_donnees_en_tables/correction/03_1_format_csv_correction.ipynb
efloti/cours-nsi-premiere
___ Un cas d'utilisation fréquent de l'apparaillement est la lecture dans une boucle des paires
# tester moi tab1 = ['a', 'b', 'c'] tab2 = [3, 2, 1] for a, b in appareiller(tab1, tab2): print(f'a vaut "{a}" et b vaut "{b}"')
a vaut "a" et b vaut "3" a vaut "b" et b vaut "2" a vaut "c" et b vaut "1"
CC0-1.0
01_donnees_en_tables/correction/03_1_format_csv_correction.ipynb
efloti/cours-nsi-premiere
en fait, Python dispose d'une fonction prédéfinie `zip(seq1, seq2, ...)` qui fait la même chose avec des «séquences» (`list` est un cas particulier de séquence).*note*: `zip`?? penser à la «fermeture-éclair» d'un blouson ...
z = zip(tab1, tab2) print(z) print(list(z))
_____no_output_____
CC0-1.0
01_donnees_en_tables/correction/03_1_format_csv_correction.ipynb
efloti/cours-nsi-premiere
*note*: elle renvoie un objet spécial de type `zip` car on l'utilise souvent dans une boucle directement c'est-à-dire sans mémoriser le zip (un peu comme avec `range`)
# tester moi tab1 = ['a', 'b', 'c'] tab2 = [3, 2, 1] for a, b in zip(tab1, tab): print(f'a vaut "{a}" et b vaut "{b}"')
a vaut "a" et b vaut "3" a vaut "b" et b vaut "2"
CC0-1.0
01_donnees_en_tables/correction/03_1_format_csv_correction.ipynb
efloti/cours-nsi-premiere
Découverte: la syntaxe en compréhension est aussi valable pour les `dict` Voici un exemple simple:
modele_tuple_nomme = {desc: None for desc in descripteurs} modele_tuple_nomme
_____no_output_____
CC0-1.0
01_donnees_en_tables/correction/03_1_format_csv_correction.ipynb
efloti/cours-nsi-premiere
Bien Noter que la partie avant `for` est de la forme `: `.On utilise généralement cela avec `zip`:
cles = ("cle1", "cle2", "cle3") valeurs = ("ah", "oh", "hein") {c: v for c, v in zip(cles, valeurs)} # zip fonctionne aussi avec des tuples de même longueur!
_____no_output_____
CC0-1.0
01_donnees_en_tables/correction/03_1_format_csv_correction.ipynb
efloti/cours-nsi-premiere
Voici encore un exemple bien utile pour réaliser un tableau à partir de données CSV.
cles = ("cle1", "cle2", "cle3") objets = [("ah", "oh", "hein"), ('riri', 'fifi', 'loulou')] # on veut un tableau de tuples nommés [ {desc: val for desc, val in zip(cles, objet)} for objet in objets ]
_____no_output_____
CC0-1.0
01_donnees_en_tables/correction/03_1_format_csv_correction.ipynb
efloti/cours-nsi-premiere
Synthèse: retour au problème des données au format CSV En combinant tout ce que tu as appris et les exemples précédents, tu devrais être capable d'obtenir notre liste de n-uplets nommés en quelques lignes ... Non?*rappel*: au départ, on **dispose de**```pythondonnees_CSV = """nom,prenom,date_naissanceDurand,Jean-Pierr...
descripteurs, *objets = [tuple(ligne.split(',')) for ligne in donnees_CSV.split('\n')] objets = [ # sur plusieurs ligne pour plus de clarté. { desc: val for desc, val in zip(descripteurs, obj) } for obj in objets ] objets
_____no_output_____
CC0-1.0
01_donnees_en_tables/correction/03_1_format_csv_correction.ipynb
efloti/cours-nsi-premiere
À faire toi-même La syntaxe en compréhension des listes et des dictionnaires est utile et puissante mais nécessite pas mal d'investissement pour être bien maîtrisée.Pour cette raison, reprend le problème en écrivant une fonction `csv_vers_objets(csv_str)` qui prend en argument la chaîne au format csv et renvoie le tab...
def csv_vers_objets(csv_str): descripteurs, *objets = [tuple(ligne.split(',')) for ligne in csv_str.split('\n')] objets = [ # sur plusieurs ligne pour plus de clarté. { desc: val for desc, val in zip(descripteurs, obj) } for obj in objets ] return objets csv_vers_ob...
_____no_output_____
CC0-1.0
01_donnees_en_tables/correction/03_1_format_csv_correction.ipynb
efloti/cours-nsi-premiere
TF neural net with normalized ISO spectra
# TensorFlow and tf.keras import tensorflow as tf from tensorflow import keras # Helper libraries import glob import matplotlib.pyplot as plt import numpy as np import pandas as pd from concurrent.futures import ProcessPoolExecutor from IPython.core.debugger import set_trace as st from sklearn.model_selection import t...
1.10.0
BSD-3-Clause
ipy_notebooks/old/current_neural_net-normalized-culled.ipynb
mattjshannon/swsnet
Dataset: ISO-SWS (normalized, culled)
# Needed directories base_dir = '../data/isosws_atlas/' # Pickles containing our spectra in the form of pandas dataframes: spec_dir = base_dir + 'spectra_normalized/' spec_files = np.sort(glob.glob(spec_dir + '*.pkl')) # Metadata pickle (pd.dataframe). Note each entry contains a pointer to the corresponding spectrum ...
_____no_output_____
BSD-3-Clause
ipy_notebooks/old/current_neural_net-normalized-culled.ipynb
mattjshannon/swsnet
Labels ('group'):1. Naked stars2. Stars with dust3. Warm, dusty objects4. Cool, dusty objects5. Very red objects6. Continuum-free objects but having emission lines7. Flux-free and/or fatally flawed spectra Subset 1: all data included
features, labels = helpers.load_data(base_dir=base_dir, metadata=metadata, only_ok_data=False, clean=False, verbose=False) print(features.shape) print(labels.shape)
(1235, 359) (1235,)
BSD-3-Clause
ipy_notebooks/old/current_neural_net-normalized-culled.ipynb
mattjshannon/swsnet
Subset 2: exclude group 7
features_clean, labels_clean = \ helpers.load_data(base_dir=base_dir, metadata=metadata, only_ok_data=False, clean=True, verbose=False) print(features_clean.shape) print(labels_clean.shape)
(1058, 359) (1058,)
BSD-3-Clause
ipy_notebooks/old/current_neural_net-normalized-culled.ipynb
mattjshannon/swsnet
Subset 3: exclude group 7, uncertain data
features_certain, labels_certain = \ helpers.load_data(base_dir=base_dir, metadata=metadata, only_ok_data=True, clean=False, verbose=False) print(features_certain.shape) print(labels_certain.shape)
(851, 359) (851,)
BSD-3-Clause
ipy_notebooks/old/current_neural_net-normalized-culled.ipynb
mattjshannon/swsnet
Testing l2norms
def neural(features, labels, test_size=0.3, l2norm=0.01): X_train, X_test, y_train, y_test = \ train_test_split(features, labels, test_size=test_size, random_state = 42) # Sequential model, 7 classes of output. model = keras.Sequential() model.add(keras.layers.Dense(64, activation='relu', kern...
L2 norm, accuracy: 0.001 0.88671875 L2 norm, accuracy: 0.0001 0.859375 L2 norm, accuracy: 1e-05 0.86328125 L2 norm, accuracy: 1e-06 0.859375
BSD-3-Clause
ipy_notebooks/old/current_neural_net-normalized-culled.ipynb
mattjshannon/swsnet
*** Testing training size vs. accuracy Model:
def run_NN(input_tuple): """Run a Keras NN for the purpose of examining the effect of training set size. Args: features (ndarray): Array containing the spectra (fluxes). labels (ndarray): Array containing the group labels for the spectra. test_size (float): Fraction of test size rel...
_____no_output_____
BSD-3-Clause
ipy_notebooks/old/current_neural_net-normalized-culled.ipynb
mattjshannon/swsnet
Search space (training size):
# Values of test_size to probe. search_space = np.arange(0.14, 0.60, 0.02) print('Size of test set considered: ', search_space) # Number of iterations for each test_size value. n_iterations = 20 # Create a vector to iterate over. rx = np.array([search_space] * n_iterations).T search_space_full = rx.flatten() print('...
Took 344.395 seconds Took 307.249 seconds Took 264.682 seconds
BSD-3-Clause
ipy_notebooks/old/current_neural_net-normalized-culled.ipynb
mattjshannon/swsnet
Full set:
plot_results(run_matrix)
_____no_output_____
BSD-3-Clause
ipy_notebooks/old/current_neural_net-normalized-culled.ipynb
mattjshannon/swsnet
Clean set:
plot_results(run_matrix_clean)
_____no_output_____
BSD-3-Clause
ipy_notebooks/old/current_neural_net-normalized-culled.ipynb
mattjshannon/swsnet
Certain set:
plot_results(run_matrix_certain)
_____no_output_____
BSD-3-Clause
ipy_notebooks/old/current_neural_net-normalized-culled.ipynb
mattjshannon/swsnet
*** Based on the above, probably need to do more data preprocessing:- e.g., remove untrustworthy data
# save_path = '../models/nn_sorted_normalized_culled.h5' # model.save(save_path)
_____no_output_____
BSD-3-Clause
ipy_notebooks/old/current_neural_net-normalized-culled.ipynb
mattjshannon/swsnet
Filename: MNIST_data.ipynbFrom this bookAbbreviation: MNIST = Modified (handwritten digits data set from the U.S.) National Institute of Standards and TechnologyPurpose: Explore the MNIST digits data to get familiar with the content and quality of the data.
import mnist_loader import pandas as pd import numpy as np import matplotlib.pyplot as plt # training_data, validation_data, test_data = mnist_loader.load_data_wrapper() #training_data, validation_data, test_data = mnist_loader.load_data() training, validation, test = mnist_loader.load_data() struct = [{'name': 'train...
_____no_output_____
MIT
MNIST_data.ipynb
hotpocket/DigitRecognizer
Training, validation, and test data structures are 2 element tuples having the following structure:* [[p,i,x,e,l,s, , i,n, i,m,a,g,e, ,1], [...]]* [num_represented_by_image1, ...]
fig, axes = plt.subplots(1, 3) train = pd.Series(training_data[1]) train.hist(ax=axes[0]) axes[0].set_title("Training Data") #display(train.describe()) validate = pd.Series(validation_data[1]) validate.hist(ax=axes[1]) axes[1].set_title("Validation Data") #display(validate.describe()) test = pd.Series(test_data[1]) ...
_____no_output_____
MIT
MNIST_data.ipynb
hotpocket/DigitRecognizer
Training Data
pixels = pd.DataFrame(training_data[0]) display("Images: {} Pixels-per-image: {}".format(*pixels.shape)) pixels.head() #pixels.T.describe() # takes FOREVER ... print('\033[1m'+"validation_data:"+'\033[0m') display(validation_data) print('{1:32s}{0}'.format(type(validation_data),'\033[1m'+"validation_data type:"+'...
_____no_output_____
MIT
MNIST_data.ipynb
hotpocket/DigitRecognizer
`asyncio` BeispielAb IPython≥7.0 könnt ihr `asyncio` direkt in Jupyter Notebooks verwenden; seht auch [IPython 7.0, Async REPL](https://blog.jupyter.org/ipython-7-0-async-repl-a35ce050f7f7). Wenn ihr die Fehlermeldung `RuntimeError: This event loop is already running` erhaltet, hilft euch vielleicht [nest-asyncio] wei...
import nest_asyncio nest_asyncio.apply()
_____no_output_____
BSD-3-Clause
docs/refactoring/performance/asyncio-example.ipynb
veit/jupyter-tutorial-de
Einfaches *Hello world*-Beispiel
import asyncio async def hello(): print('Hello') await asyncio.sleep(1) print('world') await hello()
Hello world
BSD-3-Clause
docs/refactoring/performance/asyncio-example.ipynb
veit/jupyter-tutorial-de
Ein bisschen näher an einem realen Beispiel
import asyncio import random async def produce(queue, n): for x in range(1, n + 1): # produce an item print('producing {}/{}'.format(x, n)) # simulate i/o operation using sleep await asyncio.sleep(random.random()) item = str(x) # put the item in the queue aw...
producing 1/10 producing 2/10 consuming 1 producing 3/10 consuming 2 producing 4/10 consuming 3 producing 5/10 consuming 4 producing 6/10 consuming 5 producing 7/10 consuming 6 producing 8/10 consuming 7 producing 9/10 consuming 8 producing 10/10 consuming 9 consuming 10
BSD-3-Clause
docs/refactoring/performance/asyncio-example.ipynb
veit/jupyter-tutorial-de
Ausnahmebehandlung> **Siehe auch:** [set_exception_handler](https://docs.python.org/3/library/asyncio-eventloop.htmlasyncio.loop.set_exception_handler)
def main(): loop = asyncio.get_event_loop() # May want to catch other signals too signals = (signal.SIGHUP, signal.SIGTERM, signal.SIGINT) for s in signals: loop.add_signal_handler( s, lambda s=s: asyncio.create_task(shutdown(loop, signal=s))) loop.set_exception_handler(handle_ex...
_____no_output_____
BSD-3-Clause
docs/refactoring/performance/asyncio-example.ipynb
veit/jupyter-tutorial-de
Testen mit `pytest` Beispiel:
import pytest @pytest.mark.asyncio async def test_consume(mock_get, mock_queue, message, create_mock_coro): mock_get.side_effect = [message, Exception("break while loop")] with pytest.raises(Exception, match="break while loop"): await consume(mock_queue)
_____no_output_____
BSD-3-Clause
docs/refactoring/performance/asyncio-example.ipynb
veit/jupyter-tutorial-de
Bibliotheken von Drittanbietern* [pytest-asyncio](https://github.com/pytest-dev/pytest-asyncio) hat hilfreiche Dinge wie Test-Fixtures für `event_loop`, `unused_tcp_port`, und `unused_tcp_port_factory`; und die Möglichkeit zum Erstellen eurer eigenen [asynchronen Fixtures](https://github.com/pytest-dev/pytest-asyncio/...
from aiodebug import log_slow_callbacks def main(): loop = asyncio.get_event_loop() log_slow_callbacks.enable(0.05)
_____no_output_____
BSD-3-Clause
docs/refactoring/performance/asyncio-example.ipynb
veit/jupyter-tutorial-de
Logging[aiologger](https://github.com/b2wdigital/aiologger) ermöglicht eine nicht-blockierendes Logging. Asynchrone Widgets> **Seht auch:** [Asynchronous Widgets](https://ipywidgets.readthedocs.io/en/stable/examples/Widget%20Asynchronous.html)
def wait_for_change(widget, value): future = asyncio.Future() def getvalue(change): # make the new value available future.set_result(change.new) widget.unobserve(getvalue, value) widget.observe(getvalue, value) return future from ipywidgets import IntSlider slider = IntSlider() ...
_____no_output_____
BSD-3-Clause
docs/refactoring/performance/asyncio-example.ipynb
veit/jupyter-tutorial-de
B - A Closer Look at Word EmbeddingsWe have very briefly covered how word embeddings (also known as word vectors) are used in the tutorials. In this appendix we'll have a closer look at these embeddings and find some (hopefully) interesting results.Embeddings transform a one-hot encoded vector (a vector that is 0 in e...
import torchtext.vocab glove = torchtext.vocab.GloVe(name = '6B', dim = 100) print(f'There are {len(glove.itos)} words in the vocabulary')
There are 400000 words in the vocabulary
MIT
B - A Closer Look at Word Embeddings.ipynb
Andrews2017/pytorch-sentiment-analysis
As shown above, there are 400,000 unique words in the GloVe vocabulary. These are the most common words found in the corpus the vectors were trained on. **In these set of GloVe vectors, every single word is lower-case only.**`glove.vectors` is the actual tensor containing the values of the embeddings.
glove.vectors.shape
_____no_output_____
MIT
B - A Closer Look at Word Embeddings.ipynb
Andrews2017/pytorch-sentiment-analysis
We can see what word is associated with each row by checking the `itos` (int to string) list. Below implies that row 0 is the vector associated with the word 'the', row 1 for ',' (comma), row 2 for '.' (period), etc.
glove.itos[:10]
_____no_output_____
MIT
B - A Closer Look at Word Embeddings.ipynb
Andrews2017/pytorch-sentiment-analysis
We can also use the `stoi` (string to int) dictionary, in which we input a word and receive the associated integer/index. If you try get the index of a word that is not in the vocabulary, you receive an error.
glove.stoi['the']
_____no_output_____
MIT
B - A Closer Look at Word Embeddings.ipynb
Andrews2017/pytorch-sentiment-analysis
We can get the vector of a word by first getting the integer associated with it and then indexing into the word embedding tensor with that index.
glove.vectors[glove.stoi['the']].shape
_____no_output_____
MIT
B - A Closer Look at Word Embeddings.ipynb
Andrews2017/pytorch-sentiment-analysis
We'll be doing this a lot, so we'll create a function that takes in word embeddings and a word then returns the associated vector. It'll also throw an error if the word doesn't exist in the vocabulary.
def get_vector(embeddings, word): assert word in embeddings.stoi, f'*{word}* is not in the vocab!' return embeddings.vectors[embeddings.stoi[word]]
_____no_output_____
MIT
B - A Closer Look at Word Embeddings.ipynb
Andrews2017/pytorch-sentiment-analysis
As before, we use a word to get the associated vector.
get_vector(glove, 'the').shape
_____no_output_____
MIT
B - A Closer Look at Word Embeddings.ipynb
Andrews2017/pytorch-sentiment-analysis
Similar ContextsNow to start looking at the context of different words. If we want to find the words similar to a certain input word, we first find the vector of this input word, then we scan through our vocabulary calculating the distance between the vector of each word and our input word vector. We then sort these f...
import torch def closest_words(embeddings, vector, n = 10): distances = [(word, torch.dist(vector, get_vector(embeddings, word)).item()) for word in embeddings.itos] return sorted(distances, key = lambda w: w[1])[:n]
_____no_output_____
MIT
B - A Closer Look at Word Embeddings.ipynb
Andrews2017/pytorch-sentiment-analysis
Let's try it out with 'korea'. The closest word is the word 'korea' itself (not very interesting), however all of the words are related in some way. Pyongyang is the capital of North Korea, DPRK is the official name of North Korea, etc.Interestingly, we also get 'Japan' and 'China', implies that Korea, Japan and China...
word_vector = get_vector(glove, 'korea') closest_words(glove, word_vector)
_____no_output_____
MIT
B - A Closer Look at Word Embeddings.ipynb
Andrews2017/pytorch-sentiment-analysis
Looking at another country, India, we also get nearby countries: Thailand, Malaysia and Sri Lanka (as two separate words). Australia is relatively close to India (geographically), but Thailand and Malaysia are closer. So why is Australia closer to India in vector space? This is most probably due to India and Australia ...
word_vector = get_vector(glove, 'india') closest_words(glove, word_vector)
_____no_output_____
MIT
B - A Closer Look at Word Embeddings.ipynb
Andrews2017/pytorch-sentiment-analysis
We'll also create another function that will nicely print out the tuples returned by our `closest_words` function.
def print_tuples(tuples): for w, d in tuples: print(f'({d:02.04f}) {w}')
_____no_output_____
MIT
B - A Closer Look at Word Embeddings.ipynb
Andrews2017/pytorch-sentiment-analysis
A final word to look at, 'sports'. As we can see, the closest words are most of the sports themselves.
word_vector = get_vector(glove, 'sports') print_tuples(closest_words(glove, word_vector))
(0.0000) sports (3.5875) sport (4.4590) soccer (4.6508) basketball (4.6561) baseball (4.8028) sporting (4.8763) football (4.9624) professional (4.9824) entertainment (5.0975) media
MIT
B - A Closer Look at Word Embeddings.ipynb
Andrews2017/pytorch-sentiment-analysis
AnalogiesAnother property of word embeddings is that they can be operated on just as any standard vector and give interesting results.We'll show an example of this first, and then explain it:
def analogy(embeddings, word1, word2, word3, n=5): #get vectors for each word word1_vector = get_vector(embeddings, word1) word2_vector = get_vector(embeddings, word2) word3_vector = get_vector(embeddings, word3) #calculate analogy vector analogy_vector = word2_vector - word1_vector + ...
man is to king as woman is to... (4.0811) queen (4.6429) monarch (4.9055) throne (4.9216) elizabeth (4.9811) prince
MIT
B - A Closer Look at Word Embeddings.ipynb
Andrews2017/pytorch-sentiment-analysis
This is the canonical example which shows off this property of word embeddings. So why does it work? Why does the vector of 'woman' added to the vector of 'king' minus the vector of 'man' give us 'queen'?If we think about it, the vector calculated from 'king' minus 'man' gives us a "royalty vector". This is the vector ...
print_tuples(analogy(glove, 'man', 'actor', 'woman'))
man is to actor as woman is to... (2.8133) actress (5.0039) comedian (5.1399) actresses (5.2773) starred (5.3085) screenwriter
MIT
B - A Closer Look at Word Embeddings.ipynb
Andrews2017/pytorch-sentiment-analysis
For a "baby animal vector":
print_tuples(analogy(glove, 'cat', 'kitten', 'dog'))
cat is to kitten as dog is to... (3.8146) puppy (4.2944) rottweiler (4.5888) puppies (4.6086) pooch (4.6520) pug
MIT
B - A Closer Look at Word Embeddings.ipynb
Andrews2017/pytorch-sentiment-analysis
A "capital city vector":
print_tuples(analogy(glove, 'france', 'paris', 'england'))
france is to paris as england is to... (4.1426) london (4.4938) melbourne (4.7087) sydney (4.7630) perth (4.7952) birmingham
MIT
B - A Closer Look at Word Embeddings.ipynb
Andrews2017/pytorch-sentiment-analysis
A "musician's genre vector":
print_tuples(analogy(glove, 'elvis', 'rock', 'eminem'))
elvis is to rock as eminem is to... (5.6597) rap (6.2057) rappers (6.2161) rapper (6.2444) punk (6.2690) hop
MIT
B - A Closer Look at Word Embeddings.ipynb
Andrews2017/pytorch-sentiment-analysis
And an "ingredient vector":
print_tuples(analogy(glove, 'beer', 'barley', 'wine'))
beer is to barley as wine is to... (5.6021) grape (5.6760) beans (5.8174) grapes (5.9035) lentils (5.9454) figs
MIT
B - A Closer Look at Word Embeddings.ipynb
Andrews2017/pytorch-sentiment-analysis
Correcting Spelling MistakesAnother interesting property of word embeddings is that they can actually be used to correct spelling mistakes! We'll put their findings into code and briefly explain them, but to read more about this, check out the [original thread](http://forums.fast.ai/t/nlp-any-libraries-dictionaries-ou...
glove = torchtext.vocab.GloVe(name = '840B', dim = 300)
_____no_output_____
MIT
B - A Closer Look at Word Embeddings.ipynb
Andrews2017/pytorch-sentiment-analysis
Checking the vocabulary size of these embeddings, we can see we now have over 2 million unique words in our vocabulary!
glove.vectors.shape
_____no_output_____
MIT
B - A Closer Look at Word Embeddings.ipynb
Andrews2017/pytorch-sentiment-analysis
As the vectors were trained with a much larger vocabulary on a larger corpus of text, the words that appear are a little different. Notice how the words 'north', 'south', 'pyongyang' and 'dprk' no longer appear in the most closest words to 'korea'.
word_vector = get_vector(glove, 'korea') print_tuples(closest_words(glove, word_vector))
(0.0000) korea (3.9857) taiwan (4.4022) korean (4.9016) asia (4.9593) japan (5.0721) seoul (5.4058) thailand (5.6025) singapore (5.7010) russia (5.7240) hong
MIT
B - A Closer Look at Word Embeddings.ipynb
Andrews2017/pytorch-sentiment-analysis
Our first step to correcting spelling mistakes is looking at the vector for a misspelling of the word 'reliable'.
word_vector = get_vector(glove, 'relieable') print_tuples(closest_words(glove, word_vector))
(0.0000) relieable (5.0366) relyable (5.2610) realible (5.4719) realiable (5.5402) relable (5.5917) relaible (5.6412) reliabe (5.8802) relaiable (5.9593) stabel (5.9981) consitant
MIT
B - A Closer Look at Word Embeddings.ipynb
Andrews2017/pytorch-sentiment-analysis
Notice how the correct spelling, "reliable", does not appear in the top 10 closest words. Surely the misspellings of a word should appear next to the correct spelling of the word as they appear in the same context, right? The hypothesis is that misspellings of words are all equally shifted away from their correct spell...
reliable_vector = get_vector(glove, 'reliable') reliable_misspellings = ['relieable', 'relyable', 'realible', 'realiable', 'relable', 'relaible', 'reliabe', 'relaiable'] diff_reliable = [(reliable_vector - get_vector(glove, s)).unsqueeze(0) for s in reliable_misspellings]
_____no_output_____
MIT
B - A Closer Look at Word Embeddings.ipynb
Andrews2017/pytorch-sentiment-analysis
We take the average of these 8 'difference from reliable' vectors to get our "misspelling vector".
misspelling_vector = torch.cat(diff_reliable, dim = 0).mean(dim = 0)
_____no_output_____
MIT
B - A Closer Look at Word Embeddings.ipynb
Andrews2017/pytorch-sentiment-analysis
We can now correct other spelling mistakes using this "misspelling vector" by finding the closest words to the sum of the vector of a misspelled word and the "misspelling vector".For a misspelling of "because":
word_vector = get_vector(glove, 'becuase') print_tuples(closest_words(glove, word_vector + misspelling_vector))
(6.1090) because (6.4250) even (6.4358) fact (6.4914) sure (6.5094) though (6.5601) obviously (6.5682) reason (6.5856) if (6.6099) but (6.6415) why
MIT
B - A Closer Look at Word Embeddings.ipynb
Andrews2017/pytorch-sentiment-analysis
For a misspelling of "definitely":
word_vector = get_vector(glove, 'defintiely') print_tuples(closest_words(glove, word_vector + misspelling_vector))
(5.4070) definitely (5.5643) certainly (5.7192) sure (5.8152) well (5.8588) always (5.8812) also (5.9557) simply (5.9667) consider (5.9821) probably (5.9948) definately
MIT
B - A Closer Look at Word Embeddings.ipynb
Andrews2017/pytorch-sentiment-analysis
For a misspelling of "consistent":
word_vector = get_vector(glove, 'consistant') print_tuples(closest_words(glove, word_vector + misspelling_vector))
(5.9641) consistent (6.3674) reliable (7.0195) consistant (7.0299) consistently (7.1605) accurate (7.2737) fairly (7.3037) good (7.3520) reasonable (7.3801) dependable (7.4027) ensure
MIT
B - A Closer Look at Word Embeddings.ipynb
Andrews2017/pytorch-sentiment-analysis
For a misspelling of "package":
word_vector = get_vector(glove, 'pakage') print_tuples(closest_words(glove, word_vector + misspelling_vector))
(6.6117) package (6.9315) packages (7.0195) pakage (7.0911) comes (7.1241) provide (7.1469) offer (7.1861) reliable (7.2431) well (7.2434) choice (7.2453) offering
MIT
B - A Closer Look at Word Embeddings.ipynb
Andrews2017/pytorch-sentiment-analysis
This notebook explores the calendar of Munich listings to answer the question: What is the most expensive and the cheapest time to visit Munich?
import pandas as pd import numpy as np from matplotlib import pyplot as plt import seaborn as sns sns.set() LOCATION = 'munich' df_list = pd.read_csv(LOCATION + '/listings.csv.gz') df_reviews = pd.read_csv(LOCATION + '/reviews.csv.gz') df_cal = pd.read_csv(LOCATION + '/calendar.csv.gz') pd.options.display.max_rows=10 ...
_____no_output_____
MIT
2. Best Time To Visit Munich.ipynb
rmnng/dsblogpost
___ Calendar First look into to data and types for each column:
df_cal df_cal.dtypes
_____no_output_____
MIT
2. Best Time To Visit Munich.ipynb
rmnng/dsblogpost
___ Some data types are wrong. In order to be able to work with the data, we need to change some datatypes. First convert **date** to *datetime* type:
df_cal['date'] = pd.to_datetime(df_cal['date'])
_____no_output_____
MIT
2. Best Time To Visit Munich.ipynb
rmnng/dsblogpost
**Price** needs to converted to *float* in order to be able to work with it.
df_cal['price']=df_cal['price'].replace(to_replace='[\$,]', value='', regex=True).astype(float) df_cal['adjusted_price']=df_cal['adjusted_price'].replace(to_replace='[\$,]', value='', regex=True).astype(float)
_____no_output_____
MIT
2. Best Time To Visit Munich.ipynb
rmnng/dsblogpost
This is how it looks now:
df_cal.head()
_____no_output_____
MIT
2. Best Time To Visit Munich.ipynb
rmnng/dsblogpost
And this are the corrected data types:
df_cal.dtypes
_____no_output_____
MIT
2. Best Time To Visit Munich.ipynb
rmnng/dsblogpost
___ First question to be answered is, what is the price distribution over the year: Let's calculate the mean price over all listings for each day of the year: First check if we have *NULL* values in the data frame.
df_cal.isnull().sum()
_____no_output_____
MIT
2. Best Time To Visit Munich.ipynb
rmnng/dsblogpost
*NULL* values have impact to the average (even if very small due to the small number of missing values), let's drop all rows with *NULL* **price**.
df_cal.dropna(subset=['price'], inplace=True)
_____no_output_____
MIT
2. Best Time To Visit Munich.ipynb
rmnng/dsblogpost
Now let's group all listings by **date** and calculate the average **price** of all listings for each day:
mean_price = df_cal[['date', 'price']].groupby(by='date').mean().reset_index() mean_price
_____no_output_____
MIT
2. Best Time To Visit Munich.ipynb
rmnng/dsblogpost
And plot the result:
## use the plot method and scale the size based on ploted values scale_from = mean_price['price'][1:-2].min()*0.95 scale_to = mean_price['price'][1:-2].max()*1.02 mean_price.set_index('date')[1:-2].plot(kind='line', y='price', figsize=(20,10), grid=True).set_ylim(scale_from, scale_to);
_____no_output_____
MIT
2. Best Time To Visit Munich.ipynb
rmnng/dsblogpost
HERE WE ARE! There are two interesting observations: 1. There is a peak in the second half of September: **"Welcome to the Octoberfest!**" 2. The price apparently depends on the day of week. Let's have a closer look at it. ___ Second question: What is the price distribution within a week? To be able to have a close ...
df_cal['day_of_week'] = df_cal['date'].dt.dayofweek
_____no_output_____
MIT
2. Best Time To Visit Munich.ipynb
rmnng/dsblogpost
Let's group the prices for each day of week and get the average price:
mean_price_dow = df_cal[['day_of_week', 'price']].groupby(by='day_of_week').mean().reset_index() mean_price_dow
_____no_output_____
MIT
2. Best Time To Visit Munich.ipynb
rmnng/dsblogpost
It's difficult to interpret index-based day of week. Let's convert it to strings from Monday to Sunday:
def convert_day_of_week(day_idx): ''' This function convert index based day of week to string 0 - Monday 6 - Sunday if the day_idx oís out of this range, this index will be returned ''' if(day_idx>6 or day_idx<0): return day_idx lst = ['Monday', 'Tuesday', 'Wed...
_____no_output_____
MIT
2. Best Time To Visit Munich.ipynb
rmnng/dsblogpost
Now we can plot the result:
scale_from = mean_price_dow['price'].min()*0.95 scale_to = mean_price_dow['price'].max()*1.02 sns.set(rc={'figure.figsize':(15,5)}) fig = sns.barplot(data=mean_price_dow, x='day_of_week', y='price', color='#0080bb'); fig.set_ylim(scale_from, scale_to); fig.set_title('Prices for day of the week'); fig.set_xlabel('Day o...
_____no_output_____
MIT
2. Best Time To Visit Munich.ipynb
rmnng/dsblogpost
Matplotlib 快速入门 Matplotlib 是什么- 官方文档: https://matplotlib.org> Matplotlib is a Python 2D plotting library which produces publication-quality figures in a variety of hardcopy formats and interactive environments across platforms. Matplotlib can be used in Python scripts, the Python and IPython shell (à la MATLAB or Math...
import matplotlib.pyplot as plt plt.plot([1,2,3,2]) plt.ylabel('some numbers') plt.show()
_____no_output_____
Apache-2.0
doc/matplotlib/quickstart.ipynb
huifer/python_doc
End-To-End Example: Bad Password Checker- Read in list of bad passwords from file `bad-passwords.txt`- Main program loop which: - inputs a password - checks whether the password is "good" or "bad" by checking against the list - repeats this until you enter no password.
# read passwords into list #todo: #input: none, output: list of bad passwords # for each line in bad-passwords.txt # add to list def read_passwords(): bad_password_list = [] filename = "ETEE-bad-passwords.txt" with open(filename) as f: for line in f: bad_password_list.append(line.strip(...
This program will check for quality passwords against a list of known bad passwords. Enter a password or ENTER to quit: 123456 123456 is a bad password. It is on the list. Enter a password or ENTER to quit: fjdskafjoda;shv fjdskafjoda;shv seems like an ok password. It is not on the list. Enter a password or ENTER to qu...
MIT
content/lessons/09/End-To-End-Example/ETEE-Bad-Password-Checker.ipynb
MahopacHS/spring2019-mollea1213
Copyright 2019 The TensorFlow Authors.
#@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under...
_____no_output_____
Apache-2.0
site/en/tutorials/generative/dcgan.ipynb
PhilipMay/docs
Deep Convolutional Generative Adversarial Network View on TensorFlow.org Run in Google Colab View source on GitHub Download notebook This tutorial demonstrates how to generate images of handwritten digits using a [Deep Convolutional Generative Adversarial Network](h...
from __future__ import absolute_import, division, print_function, unicode_literals try: # %tensorflow_version only exists in Colab. %tensorflow_version 2.x except Exception: pass import tensorflow as tf tf.__version__ # To generate GIFs !pip install imageio import glob import imageio import matplotlib.pyplot as ...
_____no_output_____
Apache-2.0
site/en/tutorials/generative/dcgan.ipynb
PhilipMay/docs