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 |
|---|---|---|---|---|---|
nanowrite blog post generscript to create blog posts templates november for nano write.Creates 30 posts. One for each day of the month.rst files + metaSave type as you type it to json file that has time stamp attached to it. rst name is nanowrimo (year) day (day) | import os
for novran in range(1,31):
print ('nanowrimo15day' + str(novran))
for worcu in range(1,31):
print(worcu)
os.system('wc -w /home/wcmckee/Downloads/writersden/posts/nanowrimo15-day' + str(worcu) + '.rst > /home/wcmckee/nano/' + str(worcu))
mylisit = list()
for worcu in range(1,31):
opfilz = open... | _____no_output_____ | MIT | nanowrimoPosts.ipynb | wcmckee/wcmckee |
Interpolating {interpolate_example}=============Interpolate one mesh\'s point/cell arrays onto another mesh\'s nodesusing a Gaussian Kernel. | # sphinx_gallery_thumbnail_number = 4
import pyvista as pv
from pyvista import examples | _____no_output_____ | MIT | locale/examples/01-filter/interpolate.ipynb | tkoyama010/pyvista-doc-translations |
Simple Surface Interpolation============================Resample the points\' arrays onto a surface | # Download sample data
surface = examples.download_saddle_surface()
points = examples.download_sparse_points()
p = pv.Plotter()
p.add_mesh(points, point_size=30.0, render_points_as_spheres=True)
p.add_mesh(surface)
p.show() | _____no_output_____ | MIT | locale/examples/01-filter/interpolate.ipynb | tkoyama010/pyvista-doc-translations |
Run the interpolation | interpolated = surface.interpolate(points, radius=12.0)
p = pv.Plotter()
p.add_mesh(points, point_size=30.0, render_points_as_spheres=True)
p.add_mesh(interpolated, scalars="val")
p.show() | _____no_output_____ | MIT | locale/examples/01-filter/interpolate.ipynb | tkoyama010/pyvista-doc-translations |
Complex Interpolation=====================In this example, we will in interpolate sparse points in 3D space into avolume. These data are from temperature probes in the subsurface and thegoal is to create an approximate 3D model of the temperature field inthe subsurface.This approach is a great for back-of-the-hand esti... | # Download the sparse data
probes = examples.download_thermal_probes() | _____no_output_____ | MIT | locale/examples/01-filter/interpolate.ipynb | tkoyama010/pyvista-doc-translations |
Create the interpolation grid around the sparse data | grid = pv.UniformGrid()
grid.origin = (329700, 4252600, -2700)
grid.spacing = (250, 250, 50)
grid.dimensions = (60, 75, 100)
dargs = dict(cmap="coolwarm", clim=[0,300], scalars="temperature (C)")
cpos = [(364280.5723737897, 4285326.164400684, 14093.431895014139),
(337748.7217949739, 4261154.45054595, -637.109254993512... | _____no_output_____ | MIT | locale/examples/01-filter/interpolate.ipynb | tkoyama010/pyvista-doc-translations |
Run an interpolation | interp = grid.interpolate(probes, radius=15000, sharpness=10, strategy='mask_points') | _____no_output_____ | MIT | locale/examples/01-filter/interpolate.ipynb | tkoyama010/pyvista-doc-translations |
Visualize the results | vol_opac = [0, 0, .2, 0.2, 0.5, 0.5]
p = pv.Plotter(shape=(1,2), window_size=[1024*3, 768*2])
p.enable_depth_peeling()
p.add_volume(interp, opacity=vol_opac, **dargs)
p.add_mesh(probes, render_points_as_spheres=True, point_size=10, **dargs)
p.subplot(0,1)
p.add_mesh(interp.contour(5), opacity=0.5, **dargs)
p.add_mesh(... | _____no_output_____ | MIT | locale/examples/01-filter/interpolate.ipynb | tkoyama010/pyvista-doc-translations |
Document embeddings in BigQueryThis notebook shows how to do use a pre-trained embedding as a vector representation of a natural language text column.Given this embedding, we can use it in machine learning models. Embedding model for documentsWe're going to use a model that has been pretrained on Google News. Here's ... | import tensorflow as tf
import tensorflow_hub as tfhub
model = tf.keras.Sequential()
model.add(tfhub.KerasLayer("https://tfhub.dev/google/tf2-preview/gnews-swivel-20dim/1",
output_shape=[20], input_shape=[], dtype=tf.string))
model.summary()
model.predict(["""
Long years ago, we made a tryst... | Model: "sequential_4"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
keras_layer_3 (KerasLayer) (None, 20) 400020
==================================... | Apache-2.0 | 02_data_representation/text_embeddings.ipynb | modoai/ml-design-patterns |
Loading model into BigQueryThe Swivel model above is already available in SavedModel format. But we need it on Google Cloud Storage before we can load it into BigQuery. | %%bash
BUCKET=ai-analytics-solutions-kfpdemo # CHANGE AS NEEDED
rm -rf tmp
mkdir tmp
FILE=swivel.tar.gz
wget --quiet -O tmp/swivel.tar.gz https://tfhub.dev/google/tf2-preview/gnews-swivel-20dim/1?tf-hub-format=compressed
cd tmp
tar xvfz swivel.tar.gz
cd ..
mv tmp swivel
gsutil -m cp -R swivel gs://${BUCKET}/swivel
... | assets/
assets/tokens.txt
saved_model.pb
variables/
variables/variables.data-00000-of-00001
variables/variables.index
Model artifacts are now at gs://ai-analytics-solutions-kfpdemo/swivel/*
| Apache-2.0 | 02_data_representation/text_embeddings.ipynb | modoai/ml-design-patterns |
Let's load the model into a BigQuery dataset named advdata (create it if necessary) | %%bigquery
CREATE OR REPLACE MODEL advdata.swivel_text_embed
OPTIONS(model_type='tensorflow', model_path='gs://ai-analytics-solutions-kfpdemo/swivel/*') | _____no_output_____ | Apache-2.0 | 02_data_representation/text_embeddings.ipynb | modoai/ml-design-patterns |
From the BigQuery web console, click on "schema" tab for the newly loaded model. We see that the input is called sentences and the output is called output_0: | %%bigquery
SELECT output_0 FROM
ML.PREDICT(MODEL advdata.swivel_text_embed,(
SELECT "Long years ago, we made a tryst with destiny; and now the time comes when we shall redeem our pledge, not wholly or in full measure, but very substantially." AS sentences)) | _____no_output_____ | Apache-2.0 | 02_data_representation/text_embeddings.ipynb | modoai/ml-design-patterns |
Create lookup tableLet's create a lookup table of embeddings. We'll use the comments field of a storm reports table from NOAA.This is an example of the Feature Store design pattern. | %%bigquery
CREATE OR REPLACE TABLE advdata.comments_embedding AS
SELECT
output_0 as comments_embedding,
comments
FROM ML.PREDICT(MODEL advdata.swivel_text_embed,(
SELECT comments, LOWER(comments) AS sentences
FROM `bigquery-public-data.noaa_preliminary_severe_storms.wind_reports`
)) | _____no_output_____ | Apache-2.0 | 02_data_representation/text_embeddings.ipynb | modoai/ml-design-patterns |
Pumpkin PricingLoad up required libraries and dataset. Convert the data to a dataframe containing a subset of the data: - Only get pumpkins priced by the bushel- Convert the date to a month- Calculate the price to be an average of high and low prices- Convert the price to reflect the pricing by bushel quantity | import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, classification_report
from sklearn.metrics import roc_curve, roc_auc_score
from sklearn.l... | _____no_output_____ | MIT | 2-Regression/3-Linear/notebook.ipynb | GDaglio/ML-For-Beginners |
A basic scatterplot reminds us that we only have month data from August through December. We probably need more data to be able to draw conclusions in a linear fashion. | new_pumpkins["Month_str"] = new_pumpkins['Month'].apply(lambda x: calendar.month_abbr[x])
plt.scatter('Month_str', 'Price', data=new_pumpkins)
plt.scatter("City", "Price", data=new_pumpkins)
new_pumpkins.iloc[:, 0:-1] = new_pumpkins.iloc[:, 0:-1].apply(LabelEncoder().fit_transform)
new_pumpkins.head(10)
print(new_pumpk... | _____no_output_____ | MIT | 2-Regression/3-Linear/notebook.ipynb | GDaglio/ML-For-Beginners |
Lecture 1-4 - Binary classification | pumpkins = pd.read_csv('../data/US-pumpkins.csv')
new_columns = ['Color','Origin','Item Size','Variety','City Name','Package']
new_pumpkins = pumpkins[new_columns]
new_pumpkins.dropna(inplace=True)
new_pumpkins = new_pumpkins.apply(LabelEncoder().fit_transform)
new_pumpkins
g = sns.PairGrid(new_pumpkins)
g.map(sns.sc... | 0.6976998904709748
| MIT | 2-Regression/3-Linear/notebook.ipynb | GDaglio/ML-For-Beginners |
prepared by Abuzer Yakaryilmaz (QLatvia) updated by Melis Pahalı | December 5, 2019 updated by Özlem Salehi | September 17, 2020 This cell contains some macros. If there is a problem with displaying mathematical form... | from qiskit import QuantumCircuit,QuantumRegister,ClassicalRegister,execute,Aer
from random import randrange
from math import sin,cos,pi
# We start with 3 quantum registers
# qreg[2]: Asja's first qubit - qubit to be teleported
# qreg[1]: Asja's second qubit
# qreg[0]: Balvis' qubit
qreg=QuantumRegister(3)
creg=Class... | _____no_output_____ | Apache-2.0 | bronze/B54_Quantum_Teleportation_Solutions.ipynb | ozlemsalehi/bronze-boun |
Task 5 Implement the protocol above by including the post-processing part done by Balvis, i.e., the measurement results by Asja are sent to Balvis and then he may apply $ X $ or $ Z $ gates depending on the measurement results.We use the classically controlled quantum operators. Since we do not make measurement on $ q... | from qiskit import QuantumCircuit,QuantumRegister,ClassicalRegister,execute,Aer
from random import randrange
from math import sin,cos,pi
# We start with 3 quantum registers
# qreg[2]: Asja's first qubit - qubit to be teleported
# qreg[1]: Asja's second qubit
# qreg[0]: Balvis' qubit
qreg=QuantumRegister(3)
c1=Classic... | _____no_output_____ | Apache-2.0 | bronze/B54_Quantum_Teleportation_Solutions.ipynb | ozlemsalehi/bronze-boun |
DLISIO in a Nutshell Importing | %matplotlib inline
import os
import pandas as pd
import dlisio
import matplotlib.pyplot as plt
import numpy as np
import numpy.lib.recfunctions as rfn
import hvplot.pandas
import holoviews as hv
from holoviews import opts, streams
from holoviews.plotting.links import DataLink
hv.extension('bokeh', logo=None) | _____no_output_____ | MIT | DLISIO_Simple_Reading.ipynb | dcslagel/DLISIO_Notebooks |
You can work with a single file using the cell below - or by adding an additional for loop to the code below, you can work through a list of files. Another option is to use os.walk to get all .dlis files in a parent folder. Example: for (root, dirs, files) in os.walk(folderpath): for f in files: ... | filepath = r"" | _____no_output_____ | MIT | DLISIO_Simple_Reading.ipynb | dcslagel/DLISIO_Notebooks |
Query for specific curve Very quickly you can use regex to find certain curves in a file (helpful if you are scanning a lot of files for certain curves) | with dlisio.dlis.load(filepath) as file:
for d in file:
depth_channels = d.find('CHANNEL','DEPT')
for channel in depth_channels:
print(channel.name)
print(channel.curves()) | _____no_output_____ | MIT | DLISIO_Simple_Reading.ipynb | dcslagel/DLISIO_Notebooks |
Examining internal files and frames Keep in mind that dlis files can contain multiple files and multiple frames. You can quickly get a numpy array of the curves in each frame below. | with dlisio.dlis.load(filepath) as file:
print(file.describe())
with dlisio.dlis.load(filepath) as file:
for d in file:
for fram in d.frames:
print(d.channels)
print(fram.curves()) | _____no_output_____ | MIT | DLISIO_Simple_Reading.ipynb | dcslagel/DLISIO_Notebooks |
Metadata including Origin information (well name and header) | with dlisio.dlis.load(filepath) as file:
for d in file:
print(d.describe())
for fram in d.frames:
print(fram.describe())
for channel in d.channels:
print(channel.describe())
with dlisio.dlis.load(filepath) as file:
for d in file:
for origin in d.or... | _____no_output_____ | MIT | DLISIO_Simple_Reading.ipynb | dcslagel/DLISIO_Notebooks |
Reading a full dlis file But most likely we want a single data frame of every curve, no matter which frame it came from. So we write a bit more code to look through each frame, then look at each channel and get the curve name and unit information along with it. We will also save the information about which internal ... | curves_L = []
curves_name = []
longs = []
unit = []
files_L = []
files_num = []
frames = []
frames_num = []
with dlisio.dlis.load(filepath) as file:
for d in file:
files_L.append(d)
frame_count = 0
for fram in d.frames:
if frame_count == 0:
frames.append(fram)
... | _____no_output_____ | MIT | DLISIO_Simple_Reading.ipynb | dcslagel/DLISIO_Notebooks |
Creating a Pandas dataframe for the entire .dlis file We have to be careful creating a dataframe for the whole .dlis file as often there are some curves that represent mulitple values (numpy array of list values). So, you can use something like:df = pd.DataFrame(data=curves_L, index=curves_name).T to view the full dl... | def df_column_uniquify(df):
df_columns = df.columns
new_columns = []
for item in df_columns:
counter = 0
newitem = item
while newitem in new_columns:
counter += 1
newitem = "{}_{}".format(item, counter)
new_columns.append(newitem)
df.columns = new_... | _____no_output_____ | MIT | DLISIO_Simple_Reading.ipynb | dcslagel/DLISIO_Notebooks |
Then we can set the index and start making some plots. | curve_df = df_column_uniquify(curve_df)
curve_df['DEPTH_Calc_ft'] = curve_df.loc[:,'TDEP'] * 0.0083333 #0.1 inch/12 inches per foot
curve_df['DEPTH_ft'] = curve_df['DEPTH_Calc_ft']
curve_df = curve_df.set_index("DEPTH_Calc_ft")
curve_df.index.names = [None]
curve_df = curve_df.replace(-999.25,np.nan)
min_val = curve_df... | _____no_output_____ | MIT | DLISIO_Simple_Reading.ipynb | dcslagel/DLISIO_Notebooks |
Example 5: Quantum-to-quantum transfer learning. This is an example of a continuous variable (CV) quantum network for state classification, developed according to the *quantum-to-quantum transfer learning* scheme presented in [1]. Introduction In this proof-of-principle demonstration we consider two distinct toy data... | # Plotting
%matplotlib inline
import matplotlib.pyplot as plt
# TensorFlow
import tensorflow as tf
# Strawberryfields (simulation of CV quantum circuits)
import strawberryfields as sf
from strawberryfields.ops import Dgate, Kgate, Sgate, Rgate, Vgate, Fock, Ket
# Other modules
import numpy as np
import time
# Syste... | _____no_output_____ | Apache-2.0 | q2q_transfer_learning.ipynb | Jerry2001Qu/quantum-transfer-learning |
Setting of the main parameters of the network model and of the training process. | # Hilbert space cutoff
cutoff = 15
# Normalization cutoff (must be equal or smaller than cutoff dimension)
target_cutoff = 15
# Normalization weight
norm_weight = 0
# Batch size
batch_size = 8
# Number of batches (i.e. number training iterations)
num_batches = 500
# Number of state generation layers
g_depth = 1
#... | _____no_output_____ | Apache-2.0 | q2q_transfer_learning.ipynb | Jerry2001Qu/quantum-transfer-learning |
Variational circuits for state generation and classificaiton Input states: _Dataset B_The dataset is introduced by defining the corresponding random variational circuit that generates input Gaussian and non-Gaussian states. | # Placeholders for class labels
batch_labels = tf.placeholder(dtype=tf.int64, shape = [batch_size])
batch_labels_fl = tf.to_float(batch_labels)
# State generation parameters
# Squeezing gate
sq_gen = tf.placeholder(dtype = tf.float32, shape = [batch_size,g_depth])
# Rotation gates
r1_gen = tf.placeholder(dtyp... | _____no_output_____ | Apache-2.0 | q2q_transfer_learning.ipynb | Jerry2001Qu/quantum-transfer-learning |
Loading of pre-trained block (_Circuit A_)We assume that _Circuit A_ has been already pre-trained (e.g. by running a dedicated Python script) and that the associated optimal weights have been saved to a NumPy file. Here we first load the such parameters and then we define _Circuit A_ as a constant pre-processing block... | # Loading of pre-trained weights
trained_params_npy = np.load('pre_trained/circuit_A.npy')
if trained_params_npy.shape[1] < pre_depth:
print("Error: circuit q_depth > trained q_depth.")
raise SystemExit(0)
# Convert numpy arrays to TF tensors
trained_params = tf.constant(tra... | _____no_output_____ | Apache-2.0 | q2q_transfer_learning.ipynb | Jerry2001Qu/quantum-transfer-learning |
Addition of trainable layers (_Circuit B_)As discussed in the introduction, _Circuit B_ can is obtained by adding some additional layers that we are going to train on _Dataset B_. | # Trainable variables
with tf.name_scope('variables'):
# Squeeze gate
sq_var = tf.Variable(tf.random_normal(shape=[q_depth], stddev=active_sd))
# Displacement gate
d_var = tf.Variable(tf.random_normal(shape=[q_depth], stddev=active_sd))
# Rotation gates
r1_var = tf.Variable(tf.random_... | _____no_output_____ | Apache-2.0 | q2q_transfer_learning.ipynb | Jerry2001Qu/quantum-transfer-learning |
Symbolic evaluation of the full networkWe first instantiate a _StrawberryFields_ quantum simulator, taylored for simulating a single-mode quantum optical system. Then we synbolically evaluate a batch of output states. | prog = sf.Program(1)
eng = sf.Engine('tf', backend_options={'cutoff_dim': cutoff, 'batch_size': batch_size})
# Circuit B
with prog.context as q:
# State generation network
for k in range(g_depth):
layer_gen(k, q[0])
# Pre-trained network (Circuit A)
for k in... | _____no_output_____ | Apache-2.0 | q2q_transfer_learning.ipynb | Jerry2001Qu/quantum-transfer-learning |
Loss function, accuracy and optimizer.As usual in machine learning, we need to define a loss function that we are going to minimize during the training phase.As discussed in the introduction, we assume that only the vacuum state probability `p_0` is measured. Ideally, `p_0` should be large for non-Gaussian states (_la... | # Batch vacuum probabilities
p0 = out_state.fock_prob([0])
# Complementary probabilities
q0 = 1.0 - p0
# Cross entropy loss function
eps = 0.0000001
main_loss = tf.reduce_mean(-batch_labels_fl * tf.log(p0 + eps) - (1.0 - batch_labels_fl) * tf.log(q0 + eps))
# Decision function
predictions = tf.sign(p0 - 0.5) * 0.5 ... | _____no_output_____ | Apache-2.0 | q2q_transfer_learning.ipynb | Jerry2001Qu/quantum-transfer-learning |
Training and testing Up to now we just defined the analytic graph of the quantum network without numerically evaluating it. Now, after initializing a _TensorFlow_ session, we can finally run the actual training and testing phases. | # Function generating a dictionary of random parameters for a batch of states.
def random_dict():
param_dict = { # Labels (0 = Gaussian, 1 = non-Gaussian)
batch_labels: rng_data.randint(2, size=batch_size),
# Squeezing and rotation parameters
sq... | Train batch: 100, Running loss: 0.6885, Running acc 0.3700, Norm loss 0.0460, Batch time 0.0494
Train batch: 200, Running loss: 0.6673, Running acc 0.3750, Norm loss 0.0599, Batch time 0.0498
Train batch: 300, Running loss: 0.6575, Running acc 0.3825, Norm loss 0.0495, Batch time 0.0502
Train batch: 400, Running loss: ... | Apache-2.0 | q2q_transfer_learning.ipynb | Jerry2001Qu/quantum-transfer-learning |
Borehole lithology logs viewerInteractive view of borehole data used for [exploratory lithology analysis](https://github.com/csiro-hydrogeology/pyela)Powered by [Voila](https://github.com/QuantStack/voila), [ipysheet](https://github.com/QuantStack/ipysheet) and [ipyleaflet](https://github.com/jupyter-widgets/ipyleafle... | import os
import sys
import pandas as pd
import numpy as np
# from bqplot import Axis, Figure, Lines, LinearScale
# from bqplot.interacts import IndexSelector
# from ipyleaflet import basemaps, FullScreenControl, LayerGroup, Map, MeasureControl, Polyline, Marker, MarkerCluster, CircleMarker, WidgetControl
# from ipywid... | _____no_output_____ | BSD-3-Clause | app.ipynb | csiro-hydrogeology/lithology-viewer |
Note: it may take a minute or two for the display to first appear....Select a marker: | plot_map(geoloc, click_handler_ipysheet)
# plot_map(geoloc, click_handler_rawprint) | _____no_output_____ | BSD-3-Clause | app.ipynb | csiro-hydrogeology/lithology-viewer |
Descriptive lithology: | out
## Appendix A : qgrid, but at best ended up with "Model not available". May not work yet with Jupyter lab 1.0.x
# import qgrid
# d = data_for_hydroid(10062775)
# d
# import ipywidgets as widgets
# def build_qgrid():
# qgrid.set_grid_option('maxVisibleRows', 10)
# col_opts = {
# 'editable': Fals... | _____no_output_____ | BSD-3-Clause | app.ipynb | csiro-hydrogeology/lithology-viewer |
Series Inelastic Cantilever This notebook verifies the `elle.beam2dseries` element against an analysis run with the FEDEASLab `Inel2dFrm_wOneComp` element. | import anon
import anon as ana
import elle.beam2d
import elle.solvers
import elle.sections
import anon.ops as anp | _____no_output_____ | Apache-2.0 | src/archive/main.ipynb | claudioperez/elle-0004 |
Model Definition | from elle.beam2dseries import no_3, no_4, no_5, no_6
from elle.sections import aisc
L = 72.0
E = 29e3
fy = 60.0
Hi = 1.0e-6
Hk = 1e-9 #1.0e-9
sect = aisc.load('W14x426','A, I, Zx')
Np = fy*sect['A']
Mp = fy*sect['Zx']
Hi = Hi * 6.* E*sect['I']/L * anp.ones((2,1))
Hk = Hk * 6.* E*sect['I']/L * anp.ones((2,1))
xyz = an... | _____no_output_____ | Apache-2.0 | src/archive/main.ipynb | claudioperez/elle-0004 |
Loading | # Np = 0.85*Np
q_ref = anp.array([[ 0.0*Np, 0.0, 0.000*Mp],
[-0.4*Np, 0.0, 0.000*Mp],
[-0.4*Np, 0.0, 0.400*Mp],
[-0.4*Np, 0.0, 0.700*Mp],
[-0.32*Np, 0.0, 0.600*Mp],
[-0.2*Np, 0.0, 0.400*Mp],
[-0.1*Np, ... | _____no_output_____ | Apache-2.0 | src/archive/main.ipynb | claudioperez/elle-0004 |
Model Initialization | u, q = [], []
u0, p0 = anp.zeros((6,1)), anp.zeros((6,1))
# vi = U_to_V(U[0])
BeamResponse(u0,p0)
pi, ui, state = BeamModel(p0, u0)
u.append(ui)
q.append(state[0])
# [print(s) for s in state]
# print(ui) | _____no_output_____ | Apache-2.0 | src/archive/main.ipynb | claudioperez/elle-0004 |
Analysis Procedure | for i in range(len(load_history)):
pi = ag(ui, pi).T @ load_history[i][:, None]
pi, ui, state = BeamModel(pi, ui, state)
u.append(ui)
q.append(state[0]) | /mnt/c/Users/claud/git/elle/elle-solvers/elle/solvers/inv_solve.py:113: UserWarning: Failed to converge on function <function transform.<locals>.geom.<locals>.f at 0x7f5af443a8b0> inversion.
warnings.warn(f"Failed to converge on function {f} inversion.")
/mnt/c/Users/claud/git/elle/elle-solvers/elle/solvers/inv_solve... | Apache-2.0 | src/archive/main.ipynb | claudioperez/elle-0004 |
Post Processing and Validation | import matplotlib.pyplot as plt
# plt.style.use('trois-pas');
# %config InlineBackend.figure_format = 'svg'
fig, ax = plt.subplots()
ax.plot([ ui[1] for ui in u ],[ qi[2] for qi in q ], '.');
# ax.plot([ ui[1] for ui in u ],
# [ pi['Elem'][0]['q'][1] for pi in data['Post'] ], '.', label='FEDEASLab');
# plt.le... | _____no_output_____ | Apache-2.0 | src/archive/main.ipynb | claudioperez/elle-0004 |
ClassificationThis notebook aims at giving an overview of the classification metrics thatcan be used to evaluate the predictive model generalization performance. We canrecall that in a classification setting, the vector `target` is categoricalrather than continuous.We will load the blood transfusion dataset. | import pandas as pd
blood_transfusion = pd.read_csv("../datasets/blood_transfusion.csv")
data = blood_transfusion.drop(columns="Class")
target = blood_transfusion["Class"] | _____no_output_____ | CC-BY-4.0 | notebooks/metrics_classification.ipynb | lesteve/scikit-learn-mooc |
NoteIf you want a deeper overview regarding this dataset, you can refer to theAppendix - Datasets description section at the end of this MOOC. Let's start by checking the classes present in the target vector `target`. | import matplotlib.pyplot as plt
target.value_counts().plot.barh()
plt.xlabel("Number of samples")
_ = plt.title("Number of samples per classes present\n in the target") | _____no_output_____ | CC-BY-4.0 | notebooks/metrics_classification.ipynb | lesteve/scikit-learn-mooc |
We can see that the vector `target` contains two classes corresponding towhether a subject gave blood. We will use a logistic regression classifier topredict this outcome.To focus on the metrics presentation, we will only use a single split insteadof cross-validation. | from sklearn.model_selection import train_test_split
data_train, data_test, target_train, target_test = train_test_split(
data, target, shuffle=True, random_state=0, test_size=0.5) | _____no_output_____ | CC-BY-4.0 | notebooks/metrics_classification.ipynb | lesteve/scikit-learn-mooc |
We will use a logistic regression classifier as a base model. We will trainthe model on the train set, and later use the test set to compute thedifferent classification metric. | from sklearn.linear_model import LogisticRegression
classifier = LogisticRegression()
classifier.fit(data_train, target_train) | _____no_output_____ | CC-BY-4.0 | notebooks/metrics_classification.ipynb | lesteve/scikit-learn-mooc |
Classifier predictionsBefore we go into details regarding the metrics, we will recall what typeof predictions a classifier can provide.For this reason, we will create a synthetic sample for a new potential donor:he/she donated blood twice in the past (1000 c.c. each time). The last timewas 6 months ago, and the first ... | new_donor = [[6, 2, 1000, 20]] | _____no_output_____ | CC-BY-4.0 | notebooks/metrics_classification.ipynb | lesteve/scikit-learn-mooc |
We can get the class predicted by the classifier by calling the method`predict`. | classifier.predict(new_donor) | _____no_output_____ | CC-BY-4.0 | notebooks/metrics_classification.ipynb | lesteve/scikit-learn-mooc |
With this information, our classifier predicts that this synthetic subjectis more likely to not donate blood again.However, we cannot check whether the prediction is correct (we do not knowthe true target value). That's the purpose of the testing set. First, wepredict whether a subject will give blood with the help of ... | target_predicted = classifier.predict(data_test)
target_predicted[:5] | _____no_output_____ | CC-BY-4.0 | notebooks/metrics_classification.ipynb | lesteve/scikit-learn-mooc |
Accuracy as a baselineNow that we have these predictions, we can compare them with the truepredictions (sometimes called ground-truth) which we did not use until now. | target_test == target_predicted | _____no_output_____ | CC-BY-4.0 | notebooks/metrics_classification.ipynb | lesteve/scikit-learn-mooc |
In the comparison above, a `True` value means that the value predicted by ourclassifier is identical to the real value, while a `False` means that ourclassifier made a mistake. One way of getting an overall rate representingthe generalization performance of our classifier would be to compute how manytimes our classifie... | import numpy as np
np.mean(target_test == target_predicted) | _____no_output_____ | CC-BY-4.0 | notebooks/metrics_classification.ipynb | lesteve/scikit-learn-mooc |
This measure is called the accuracy. Here, our classifier is 78%accurate at classifying if a subject will give blood. `scikit-learn` providesa function that computes this metric in the module `sklearn.metrics`. | from sklearn.metrics import accuracy_score
accuracy = accuracy_score(target_test, target_predicted)
print(f"Accuracy: {accuracy:.3f}") | _____no_output_____ | CC-BY-4.0 | notebooks/metrics_classification.ipynb | lesteve/scikit-learn-mooc |
`LogisticRegression` also has a method named `score` (part of the standardscikit-learn API), which computes the accuracy score. | classifier.score(data_test, target_test) | _____no_output_____ | CC-BY-4.0 | notebooks/metrics_classification.ipynb | lesteve/scikit-learn-mooc |
Confusion matrix and derived metricsThe comparison that we did above and the accuracy that we calculated did nottake into account the type of error our classifier was making. Accuracyis an aggregate of the errors made by the classifier. We may be interestedin finer granularity - to know independently what the error is... | from sklearn.metrics import ConfusionMatrixDisplay
_ = ConfusionMatrixDisplay.from_estimator(classifier, data_test, target_test) | _____no_output_____ | CC-BY-4.0 | notebooks/metrics_classification.ipynb | lesteve/scikit-learn-mooc |
The in-diagonal numbers are related to predictions that were correctwhile off-diagonal numbers are related to incorrect predictions(misclassifications). We now know the four types of correct and erroneouspredictions:* the top left corner are true positives (TP) and corresponds to people who gave blood and were predict... | from sklearn.metrics import precision_score, recall_score
precision = precision_score(target_test, target_predicted, pos_label="donated")
recall = recall_score(target_test, target_predicted, pos_label="donated")
print(f"Precision score: {precision:.3f}")
print(f"Recall score: {recall:.3f}") | _____no_output_____ | CC-BY-4.0 | notebooks/metrics_classification.ipynb | lesteve/scikit-learn-mooc |
These results are in line with what was seen in the confusion matrix. Lookingat the left column, more than half of the "donated" predictions were correct,leading to a precision above 0.5. However, our classifier mislabeled a lot ofpeople who gave blood as "not donated", leading to a very low recall ofaround 0.1. The is... | target_train.value_counts(normalize=True).plot.barh()
plt.xlabel("Class frequency")
_ = plt.title("Class frequency in the training set") | _____no_output_____ | CC-BY-4.0 | notebooks/metrics_classification.ipynb | lesteve/scikit-learn-mooc |
We observe that the positive class, `'donated'`, comprises only 24% of thesamples. The good accuracy of our classifier is then linked to its ability tocorrectly predict the negative class `'not donated'` which may or may not berelevant, depending on the application. We can illustrate the issue using adummy classifier a... | from sklearn.dummy import DummyClassifier
dummy_classifier = DummyClassifier(strategy="most_frequent")
dummy_classifier.fit(data_train, target_train)
print(f"Accuracy of the dummy classifier: "
f"{dummy_classifier.score(data_test, target_test):.3f}") | _____no_output_____ | CC-BY-4.0 | notebooks/metrics_classification.ipynb | lesteve/scikit-learn-mooc |
With the dummy classifier, which always predicts the negative class `'notdonated'`, we obtain an accuracy score of 76%. Therefore, it means that thisclassifier, without learning anything from the data `data`, is capable ofpredicting as accurately as our logistic regression model.The problem illustrated above is also kn... | from sklearn.metrics import balanced_accuracy_score
balanced_accuracy = balanced_accuracy_score(target_test, target_predicted)
print(f"Balanced accuracy: {balanced_accuracy:.3f}") | _____no_output_____ | CC-BY-4.0 | notebooks/metrics_classification.ipynb | lesteve/scikit-learn-mooc |
The balanced accuracy is equivalent to accuracy in the context of balancedclasses. It is defined as the average recall obtained on each class. Evaluation and different probability thresholdsAll statistics that we presented up to now rely on `classifier.predict` whichoutputs the most likely label. We haven't made use of... | target_proba_predicted = pd.DataFrame(classifier.predict_proba(data_test),
columns=classifier.classes_)
target_proba_predicted[:5]
target_predicted = classifier.predict(data_test)
target_predicted[:5] | _____no_output_____ | CC-BY-4.0 | notebooks/metrics_classification.ipynb | lesteve/scikit-learn-mooc |
Since probabilities sum to 1 we can get the class with the highestprobability without using the threshold 0.5. | equivalence_pred_proba = (
target_proba_predicted.idxmax(axis=1).to_numpy() == target_predicted)
np.all(equivalence_pred_proba) | _____no_output_____ | CC-BY-4.0 | notebooks/metrics_classification.ipynb | lesteve/scikit-learn-mooc |
The default decision threshold (0.5) might not be the best threshold thatleads to optimal generalization performance of our classifier. In this case, onecan vary the decision threshold, and therefore the underlying prediction, andcompute the same statistics presented earlier. Usually, the two metricsrecall and precisio... | from sklearn.metrics import PrecisionRecallDisplay
disp = PrecisionRecallDisplay.from_estimator(
classifier, data_test, target_test, pos_label='donated',
marker="+"
)
_ = disp.ax_.set_title("Precision-recall curve") | _____no_output_____ | CC-BY-4.0 | notebooks/metrics_classification.ipynb | lesteve/scikit-learn-mooc |
TipScikit-learn will return a display containing all plotting element. Notably,displays will expose a matplotlib axis, named ax_, that can be used to addnew element on the axis.You can refer to the documentation to have more information regarding thevisualizations in scikit-learnOn this curve, each blue cross correspon... | from sklearn.metrics import RocCurveDisplay
disp = RocCurveDisplay.from_estimator(
classifier, data_test, target_test, pos_label='donated',
marker="+")
disp = RocCurveDisplay.from_estimator(
dummy_classifier, data_test, target_test, pos_label='donated',
color="tab:orange", linestyle="--", ax=disp.ax_)
... | _____no_output_____ | CC-BY-4.0 | notebooks/metrics_classification.ipynb | lesteve/scikit-learn-mooc |
Para entrar no modo apresentação, execute a seguinte célula e pressione `-` | %reload_ext slide | _____no_output_____ | MIT | resultados/4.Proxy.ipynb | jacsonrbinf/minicurso-mineracao-interativa |
ProxyEste notebook apresenta os seguintes tópicos:- [Introdução](Introdu%C3%A7%C3%A3o)- [Servidor de proxy](Servidor-de-proxy) IntroduçãoExiste muita informação disponível em repositórios software.A seguir temos uma *screenshot* do repositório `gems-uff/sapos`. Nessa imagem, vemos a organização e nome do repositório ... | SITE = "http://localhost:5000/" # Se não usar o proxy, alterar para https://github.com/
import requests
response = requests.get(SITE + "gems-uff/sapos")
response.headers['server'], response.status_code | _____no_output_____ | MIT | resultados/4.Proxy.ipynb | jacsonrbinf/minicurso-mineracao-interativa |
Implement function ToLowerCase() that has a string parameter str, and returns the same string in lowercase.Example 1:```javascriptInput: "Hello"Output: "hello"```Example 2:```javascriptInput: "here"Output: "here"```Example 3:```javascriptInput: "LOVELY"Output: "lovely"``` | class Solution(object):
def toLowerCase(self, str):
"""
type: str, str
rtype: str
"""
return str.lower()
if __name__ == '__main__':
sol = Solution()
print(sol.toLowerCase("Hello"))
print(sol.toLowerCase("here"))
print(sol.toLowerCase("LOVELY"))
# Time: O(n)
... | _____no_output_____ | Apache-2.0 | 709.ToLowerCase.ipynb | charlesxu90/leetcode_py |
BRAIN IMAGINGDATA STRUCTURE The dataset for this tutorial is structured according to the [Brain Imaging Data Structure (BIDS)](http://bids.neuroimaging.io/). BIDS is a simple and intuitive way to organize and describe your neuroimaging and behavioral data. Neuroimaging experiments result in complicated data that can be... | %%bash
cd /data
datalad install -r ///workshops/nih-2017/ds000114 | _____no_output_____ | BSD-3-Clause | notebooks/introduction_dataset.ipynb | siyunb/Nipype_tutorial |
In order to download data, you can use ``datalad get foldername`` command, to download all files in the folder ``foldername``. For this tutorial we only want to download part of the dataset, i.e. the anatomical and the functional `fingerfootlips` images: | %%bash
cd /data/ds000114
datalad get -J 4 derivatives/fmriprep/sub-*/anat/*preproc.nii.gz \
sub-01/ses-test/anat \
sub-*/ses-test/func/*fingerfootlips* | _____no_output_____ | BSD-3-Clause | notebooks/introduction_dataset.ipynb | siyunb/Nipype_tutorial |
So let's have a look at the tutorial dataset. | !tree -L 4 /data/ds000114/ | _____no_output_____ | BSD-3-Clause | notebooks/introduction_dataset.ipynb | siyunb/Nipype_tutorial |
As you can, for every subject we have one anatomical T1w image, five functional images, and one diffusion weighted image.**Note**: If you used `datalad` or `git annex` to get the dataset, you can see symlinks for the image files. Behavioral TaskSubject from the ds000114 dataset did five behavioral tasks. In our datase... | %%bash
cd /data/ds000114
datalad get sub-01/ses-test/func/sub-01_ses-test_task-linebisection_events.tsv
!cat /data/ds000114/sub-01/ses-test/func/sub-01_ses-test_task-linebisection_events.tsv | _____no_output_____ | BSD-3-Clause | notebooks/introduction_dataset.ipynb | siyunb/Nipype_tutorial |
STAT 453: Deep Learning (Spring 2021) Instructor: Sebastian Raschka (sraschka@wisc.edu) Course website: http://pages.stat.wisc.edu/~sraschka/teaching/stat453-ss2021/ GitHub repository: https://github.com/rasbt/stat453-deep-learning-ss21--- | %load_ext watermark
%watermark -a 'Sebastian Raschka' -v -p torch | Author: Sebastian Raschka
Python implementation: CPython
Python version : 3.9.2
IPython version : 7.21.0
torch: 1.9.0a0+d819a21
| MIT | L14/2-resnet-example.ipynb | sum-coderepo/stat453-deep-learning-ss21 |
- Runs on CPU or GPU (if available) A Convolutional ResNet and Residual Blocks Please note that this example does not implement a really deep ResNet as described in literature but rather illustrates how the residual blocks described in He et al. [1] can be implemented in PyTorch.- [1] He, Kaiming, et al. "Deep residua... | import time
import numpy as np
import torch
from torch.utils.data import DataLoader
from torchvision import datasets
from torchvision import transforms | _____no_output_____ | MIT | L14/2-resnet-example.ipynb | sum-coderepo/stat453-deep-learning-ss21 |
Settings and Dataset | ##########################
### SETTINGS
##########################
# Device
device = torch.device("cuda:1" if torch.cuda.is_available() else "cpu")
# Hyperparameters
random_seed = 123
learning_rate = 0.01
num_epochs = 10
batch_size = 128
# Architecture
num_classes = 10
##########################
### MNIST DATASET
... | Image batch dimensions: torch.Size([128, 1, 28, 28])
Image label dimensions: torch.Size([128])
| MIT | L14/2-resnet-example.ipynb | sum-coderepo/stat453-deep-learning-ss21 |
ResNet with identity blocks The following code implements the residual blocks with skip connections such that the input passed via the shortcut matches the dimensions of the main path's output, which allows the network to learn identity functions. Such a residual block is illustrated below::
def __init__(self, num_classes):
super(ConvNet, self).__init__()
#########################
### 1st residual block
#########################
self.block_1 = torc... | _____no_output_____ | MIT | L14/2-resnet-example.ipynb | sum-coderepo/stat453-deep-learning-ss21 |
Training | def compute_accuracy(model, data_loader):
correct_pred, num_examples = 0, 0
for i, (features, targets) in enumerate(data_loader):
features = features.to(device)
targets = targets.to(device)
logits = model(features)
_, predicted_labels = torch.max(logits, 1)
nu... | Test accuracy: 92.16%
| MIT | L14/2-resnet-example.ipynb | sum-coderepo/stat453-deep-learning-ss21 |
ResNet with convolutional blocks for resizing The following code implements the residual blocks with skip connections such that the input passed via the shortcut matches is resized to dimensions of the main path's output. Such a residual block is illustrated below: | class ResidualBlock(torch.nn.Module):
""" Helper Class"""
def __init__(self, channels):
super(ResidualBlock, self).__init__()
self.block = torch.nn.Sequential(
torch.nn.Conv2d(in_channels=channels[0],
out_channels=channels[1],
... | _____no_output_____ | MIT | L14/2-resnet-example.ipynb | sum-coderepo/stat453-deep-learning-ss21 |
Training | for epoch in range(num_epochs):
model = model.train()
for batch_idx, (features, targets) in enumerate(train_loader):
features = features.to(device)
targets = targets.to(device)
### FORWARD AND BACK PROP
logits = model(features)
cost = torch.nn.functi... | Test accuracy: 98.13%
| MIT | L14/2-resnet-example.ipynb | sum-coderepo/stat453-deep-learning-ss21 |
Hidden Markov Model What is a Hidden Markov Model?A Hidden Markov Model (HMM) is a statistical Markov model in with the system being modeled is assumed to be a Markov process with **hidden** states.An HMM allows us to talk about both observed events (like words that we see in the input) and hidden events (like Part-Of... | # Inorder to get the notebooks running in current directory
import os, sys, inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0, parentdir)
import hmm | _____no_output_____ | MIT | notebooks/HiddenMarkovModel.ipynb | kad99kev/HiddenMarkovModel |
Let us take a simple example with two hidden states and two observable states.The **Hidden states** will be **Rainy** and **Sunny**.The **Observable states** will be **Sad** and **Happy**.The transition and emission matrices are given below.The initial probabilities are obtained by computing the stationary distribution... | # Hidden
hidden_states = ["Rainy", "Sunny"]
transition_matrix = [[0.5, 0.5], [0.3, 0.7]]
# Observable
observable_states = ["Sad", "Happy"]
emission_matrix = [[0.8, 0.2], [0.4, 0.6]]
# Inputs
input_seq = [0, 0, 1]
model = hmm.HiddenMarkovModel(
observable_states, hidden_states, transition_matrix, emission_matrix
)
... | **************************************************
Observable States: ['Sad', 'Happy']
Emission Matrix:
Sad Happy
Rainy 0.8 0.2
Sunny 0.4 0.6
Hidden States: ['Rainy', 'Sunny']
Transition Matrix:
Rainy Sunny
Rainy 0.5 0.5
Sunny 0.3 0.7
Initial Probabilities: [0.375 0.625]
| MIT | notebooks/HiddenMarkovModel.ipynb | kad99kev/HiddenMarkovModel |
Here the blue lines indicate the hidden transitions.Here the red lines indicate the emission transitions. Problem 1:Computing Likelihood: Given an HMM $\lambda$ = (A, B) and an observation sequence O, determine the likelihood P(O | $\lambda$) How It Is Calculated?For our example, for the given **observed** sequence - ... | alpha, a_probs = model.forward(input_seq)
hmm.print_forward_result(alpha, a_probs) | **************************************************
Alpha:
[[0.3 0.18 0.0258]
[0.25 0.13 0.1086]]
Probability of sequence: 0.13440000000000002
| MIT | notebooks/HiddenMarkovModel.ipynb | kad99kev/HiddenMarkovModel |
Backward AlgorithmThe Backward Algorithm is the time-reversed version of the Forward Algorithm. | beta, b_probs = model.backward(input_seq)
hmm.print_backward_result(beta, b_probs) | **************************************************
Beta:
[[0.256 0.4 1. ]
[0.2304 0.48 1. ]]
Probability of sequence: 0.13440000000000002
| MIT | notebooks/HiddenMarkovModel.ipynb | kad99kev/HiddenMarkovModel |
Problem 2: Given an observation sequence O and an HMM λ = (A,B), discover the best hidden state sequence Q. Viterbi AlgorithmThe Viterbi Algorithm increments over each time step, finding the maximum probability of any path that gets to state i at time t, that also has the correct observations for the sequence up to ti... | path, delta, phi = model.viterbi(input_seq)
hmm.print_viterbi_result(input_seq, observable_states, hidden_states, path, delta, phi) | **************************************************
Starting Forward Walk
State=0 : Sequence=1 | phi[0, 1]=0.0
State=1 : Sequence=1 | phi[1, 1]=1.0
State=0 : Sequence=2 | phi[0, 2]=0.0
State=1 : Sequence=2 | phi[1, 2]=0.0
**************************************************
Start Backtrace
Path[1]=0
Path[0]=0
************... | MIT | notebooks/HiddenMarkovModel.ipynb | kad99kev/HiddenMarkovModel |
Deep Reinforcement Learning in Action by Alex Zai and Brandon Brown Chapter 3 Listing 3.1 | from Gridworld import Gridworld
game = Gridworld(size=4, mode='static')
import sys
game.display()
game.makeMove('d')
game.makeMove('d')
game.makeMove('d')
game.display()
game.reward()
game.board.render_np()
game.board.render_np().shape | _____no_output_____ | MIT | Errata/Chapter 3.ipynb | karshtharyani/DeepReinforcementLearningInAction |
Listing 3.2 | import numpy as np
import torch
from Gridworld import Gridworld
import random
from matplotlib import pylab as plt
l1 = 64
l2 = 150
l3 = 100
l4 = 4
model = torch.nn.Sequential(
torch.nn.Linear(l1, l2),
torch.nn.ReLU(),
torch.nn.Linear(l2, l3),
torch.nn.ReLU(),
torch.nn.Linear(l3,l4)
)
loss_fn = t... | _____no_output_____ | MIT | Errata/Chapter 3.ipynb | karshtharyani/DeepReinforcementLearningInAction |
Listing 3.3 | epochs = 1000
losses = []
for i in range(epochs):
game = Gridworld(size=4, mode='static')
state_ = game.board.render_np().reshape(1,64) + np.random.rand(1,64)/10.0
state1 = torch.from_numpy(state_).float()
status = 1
while(status == 1):
qval = model(state1)
qval_ = qval.data.numpy()
... | _____no_output_____ | MIT | Errata/Chapter 3.ipynb | karshtharyani/DeepReinforcementLearningInAction |
Listing 3.4 | def test_model(model, mode='static', display=True):
i = 0
test_game = Gridworld(mode=mode)
state_ = test_game.board.render_np().reshape(1,64) + np.random.rand(1,64)/10.0
state = torch.from_numpy(state_).float()
if display:
print("Initial State:")
print(test_game.display())
status... | Initial State:
[['+' '-' ' ' 'P']
[' ' 'W' ' ' ' ']
[' ' ' ' ' ' ' ']
[' ' ' ' ' ' ' ']]
Move #: 0; Taking action: l
[['+' '-' 'P' ' ']
[' ' 'W' ' ' ' ']
[' ' ' ' ' ' ' ']
[' ' ' ' ' ' ' ']]
Move #: 1; Taking action: d
[['+' '-' ' ' ' ']
[' ' 'W' 'P' ' ']
[' ' ' ' ' ' ' ']
[' ' ' ' ' ' ' ']]
Move #: 2; Taking ... | MIT | Errata/Chapter 3.ipynb | karshtharyani/DeepReinforcementLearningInAction |
Listing 3.5 | from collections import deque
epochs = 5000
losses = []
mem_size = 1000
batch_size = 200
replay = deque(maxlen=mem_size)
max_moves = 50
h = 0
for i in range(epochs):
game = Gridworld(size=4, mode='random')
state1_ = game.board.render_np().reshape(1,64) + np.random.rand(1,64)/100.0
state1 = torch.from_numpy(... | Initial State:
[['P' ' ' ' ' ' ']
[' ' ' ' ' ' ' ']
[' ' ' ' ' ' 'W']
['-' '+' ' ' ' ']]
Move #: 0; Taking action: r
[[' ' 'P' ' ' ' ']
[' ' ' ' ' ' ' ']
[' ' ' ' ' ' 'W']
['-' '+' ' ' ' ']]
Move #: 1; Taking action: d
[[' ' ' ' ' ' ' ']
[' ' 'P' ' ' ' ']
[' ' ' ' ' ' 'W']
['-' '+' ' ' ' ']]
Move #: 2; Taking ... | MIT | Errata/Chapter 3.ipynb | karshtharyani/DeepReinforcementLearningInAction |
Listing 3.6 | max_games = 1000
wins = 0
for i in range(max_games):
win = test_model(model, mode='random', display=False)
if win:
wins += 1
win_perc = float(wins) / float(max_games)
print("Games played: {0}, # of wins: {1}".format(max_games,wins))
print("Win percentage: {}".format(100.0*win_perc)) | Games played: 1000, # of wins: 908
Win percentage: 90.8
| MIT | Errata/Chapter 3.ipynb | karshtharyani/DeepReinforcementLearningInAction |
Listing 3.7 | import copy
model = torch.nn.Sequential(
torch.nn.Linear(l1, l2),
torch.nn.ReLU(),
torch.nn.Linear(l2, l3),
torch.nn.ReLU(),
torch.nn.Linear(l3,l4)
)
model2 = model2 = copy.deepcopy(model)
model2.load_state_dict(model.state_dict())
sync_freq = 50
loss_fn = torch.nn.MSELoss()
learning_rate = 1e-... | _____no_output_____ | MIT | Errata/Chapter 3.ipynb | karshtharyani/DeepReinforcementLearningInAction |
Listing 3.8 | from IPython.display import clear_output
from collections import deque
epochs = 5000
losses = []
mem_size = 1000
batch_size = 200
replay = deque(maxlen=mem_size)
max_moves = 50
h = 0
sync_freq = 500
j=0
for i in range(epochs):
game = Gridworld(size=4, mode='random')
state1_ = game.board.render_np().reshape(1,64... | Initial State:
[[' ' ' ' ' ' ' ']
[' ' ' ' ' ' 'W']
['+' ' ' ' ' ' ']
['-' 'P' ' ' ' ']]
Move #: 0; Taking action: u
[[' ' ' ' ' ' ' ']
[' ' ' ' ' ' 'W']
['+' 'P' ' ' ' ']
['-' ' ' ' ' ' ']]
Move #: 1; Taking action: l
[[' ' ' ' ' ' ' ']
[' ' ' ' ' ' 'W']
['+' ' ' ' ' ' ']
['-' ' ' ' ' ' ']]
Game won! Reward: ... | MIT | Errata/Chapter 3.ipynb | karshtharyani/DeepReinforcementLearningInAction |
0. General note * This notebook produces figures and calculations presented in [Ye et al. 2017, JGR](https://agupubs.onlinelibrary.wiley.com/doi/abs/10.1002/2016JB013811).* This notebook demonstrates how to correct pressure scales for the existing phase boundary data. 1. Global setup | import matplotlib.pyplot as plt
import numpy as np
from uncertainties import unumpy as unp
import pytheos as eos | _____no_output_____ | Apache-2.0 | Mantle_Boundaries.ipynb | SHDShim/cider2018_tutorial |
2. Pressure calculations for PPv * Data from Tateno2009T (K) | Au-Tsuchiya | Pt-Holmes | MgO-Speziale------|-------------|-----------|--------------3500 | 120.4 | 137.7 | 135.62000 | 110.5 | 126.8 | 115.8* Dorogokupets2007T (K) | Au | Pt | MgO ------|-------------|-----------|--... | t_ppv = np.asarray([3500., 2000.])
Au_T = eos.gold.Tsuchiya2003()
Au_D = eos.gold.Dorogokupets2007()
v = np.asarray([51.58,51.7])
p_Au_T_ppv = Au_T.cal_p(v, t_ppv)
p_Au_D_ppv = Au_D.cal_p(v, t_ppv)
print(p_Au_T_ppv, p_Au_D_ppv)
print('slopes: ', (p_Au_T_ppv[0]-p_Au_T_ppv[1])/(t_ppv[0]-t_ppv[1]),\
(p_Au_D_ppv[0]-... | [135.56997269894586+/-0.9530902142955003
115.8281642808288+/-0.49022460541552476] [129.57114762303976+/-0.0071388388100554765
113.23868528253495+/-0.006849434801332905]
slopes: 0.01316+/-0.00032 0.01088831+/-0.00000020
| Apache-2.0 | Mantle_Boundaries.ipynb | SHDShim/cider2018_tutorial |
3. Post-spinel Fei2004Scales| PT | PT ------|------------|------------MgO-S | 23.6, 1573 | 22.8, 2173MgO-D | 23.1, 1573 | 22.0, 2173Ye2014Scales | PT | PT-------|------------|------------Pt-F | 25.2, 1550 | 23.2, 2380Pt-D | 24.6, 1550 | 22.5, 2380 Au-F | 28.3, 1650 | 27.1, 2150Au-D | 27.0, 165... | MgO_S = eos.periclase.Speziale2001()
MgO_D = eos.periclase.Dorogokupets2007()
v = np.asarray([68.75, 70.3])
t_MgO = np.asarray([1573.,2173.])
p_MgO_S = MgO_S.cal_p(v, t_MgO)
p_MgO_D = MgO_D.cal_p(v, t_MgO)
print(p_MgO_S, p_MgO_D)
print('slopes: ', (p_MgO_S[0]-p_MgO_S[1])/(t_MgO[0]-t_MgO[1]), (p_MgO_D[0]-p_MgO_D[1])/(t... | _____no_output_____ | Apache-2.0 | Mantle_Boundaries.ipynb | SHDShim/cider2018_tutorial |
Generators 生成器 > Here we'll take a deeper dive into Python generators, including *generator expressions* and *generator functions*.本章我们深入讨论Python的生成器,包括*生成器表达式*和*生成器函数* Generator Expressions 生成器表达式 > The difference between list comprehensions and generator expressions is sometimes confusing; here we'll quickly outlin... | [n ** 2 for n in range(12)] | _____no_output_____ | CC0-1.0 | 12-Generators.ipynb | MoRa-0/wwtop |
> While this is a representative generator expression:下面这个却是一个生成器表达式: | (n ** 2 for n in range(12)) | _____no_output_____ | CC0-1.0 | 12-Generators.ipynb | MoRa-0/wwtop |
> Notice that printing the generator expression does not print the contents; one way to print the contents of a generator expression is to pass it to the ``list`` constructor:你会注意到直接打印生成器表达式并不会输出生成器的内容;可以使用`list`将生成器转换为一个列表然后输出: | G = (n ** 2 for n in range(12))
list(G) | _____no_output_____ | CC0-1.0 | 12-Generators.ipynb | MoRa-0/wwtop |
A list is a collection of values, while a generator is a recipe for producing values 列表是一个集合,而生成器只是产生集合值的配方> When you create a list, you are actually building a collection of values, and there is some memory cost associated with that.When you create a generator, you are not building a collection of values, but a recip... | L = [n ** 2 for n in range(12)]
for val in L:
print(val, end=' ')
G = (n ** 2 for n in range(12))
for val in G:
print(val, end=' ') | 0 1 4 9 16 25 36 49 64 81 100 121 | CC0-1.0 | 12-Generators.ipynb | MoRa-0/wwtop |
> The difference is that a generator expression does not actually compute the values until they are needed.This not only leads to memory efficiency, but to computational efficiency as well!This also means that while the size of a list is limited by available memory, the size of a generator expression is unlimited!区别在于生... | from itertools import count
count()
for i in count():
print(i, end=' ')
if i >= 10: break | 0 1 2 3 4 5 6 7 8 9 10 | CC0-1.0 | 12-Generators.ipynb | MoRa-0/wwtop |
> The ``count`` iterator will go on happily counting forever until you tell it to stop; this makes it convenient to create generators that will also go on forever:`count`函数会永远的迭代下去除非你停止了它的运行;这也可以用来创建永远运行的生成器: | factors = [2, 3, 5, 7]
G = (i for i in count() if all(i % n > 0 for n in factors))
for val in G:
print(val, end=' ')
if val > 40: break | 1 11 13 17 19 23 29 31 37 41 | CC0-1.0 | 12-Generators.ipynb | MoRa-0/wwtop |
> You might see what we're getting at here: if we were to expand the list of factors appropriately, what we would have the beginnings of is a prime number generator, using the Sieve of Eratosthenes algorithm. We'll explore this more momentarily.上面的例子你应该已经看出来了:如果我们使用Sieve of Eratosthenes算法,将factors列表进行合适的扩展的话,那么我们将会得到一个... | L = [n ** 2 for n in range(12)]
for val in L:
print(val, end=' ')
print()
for val in L:
print(val, end=' ') | 0 1 4 9 16 25 36 49 64 81 100 121
0 1 4 9 16 25 36 49 64 81 100 121 | CC0-1.0 | 12-Generators.ipynb | MoRa-0/wwtop |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.