markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
Correlation plots
from scipy.signal import correlate def autocorr(x): xunbiased = x-np.mean(x) xnorm = np.sum(xunbiased**2) acor = np.correlate(xunbiased, xunbiased, "same")/xnorm #result = correlate(x, x, mode='full') #result /= result[result.argmax()] acor = acor[len(acor)/2:] return acor#result[result.size...
2015_Fall/MATH-578B/Homework2/Homework2.ipynb
saketkc/hatex
mit
Result The autocorrelation seems to be high even for large values of $N_{step}$ for both the temperature values. I expected higher $T$ to yield lower autocorrelations. Problem 1 Let the state space be $S = {\phi, \alpha, \beta, \alpha+\beta, pol, \dagger}$ Definitions: 1. $\tau_a = { n \geq 0: X_n=a}$ $N = \sum_{k=0...
k_a=0.2 k_b=0.2 k_p=0.5 P = np.matrix([[1-k_a-k_b, k_a ,k_b, 0, 0, 0], [k_a, 1-k_a-k_b, 0, k_b, 0, 0], [k_b, 0, 1-k_a-k_b, k_a, 0, 0], [0, k_b, k_a, 1-k_a-k_b-k_p, k_p, 0], [0, 0, 0, 0, 0, 1], [0, 0, 0, 1, 0, 0]]) Q=P[1:5,1:5] iq = np.eye(4)-Q...
2015_Fall/MATH-578B/Homework2/Homework2.ipynb
saketkc/hatex
mit
$\alpha$
print('Simulation: {}\t Calculation: {}'.format(h('alpha')[1],u[0]))
2015_Fall/MATH-578B/Homework2/Homework2.ipynb
saketkc/hatex
mit
$\beta$
print('Simulation: {}\t Calculation: {}'.format(h('beta')[1],u[1]))
2015_Fall/MATH-578B/Homework2/Homework2.ipynb
saketkc/hatex
mit
$\alpha+\beta$
print('Simulation: {}\t Calculation: {}'.format(h('ab')[1],u[2]))
2015_Fall/MATH-578B/Homework2/Homework2.ipynb
saketkc/hatex
mit
pol
print('Simulation: {}\t Calculation: {}'.format(h('pol')[1],u[3]))
2015_Fall/MATH-578B/Homework2/Homework2.ipynb
saketkc/hatex
mit
We can compute a derivative symbolically, but it is of course horrendous (see below). Think of how much worse it would be if we chose a function with products, more dimensions, or iterated more than 20 times.
from sympy import diff, Symbol, sin from __future__ import print_function x = Symbol('x') dexp = diff(func(x), x) print(dexp)
SymbolicVsAD.ipynb
BYUFLOWLab/MDOnotebooks
mit
We can now evaluate the expression.
xpt = 0.1 dfdx = dexp.subs(x, xpt) print('dfdx =', dfdx)
SymbolicVsAD.ipynb
BYUFLOWLab/MDOnotebooks
mit
Let's compare with automatic differentiation using operator overloading:
from algopy import UTPM, sin x_algopy = UTPM.init_jacobian(xpt) y_algopy = func(x_algopy) dfdx = UTPM.extract_jacobian(y_algopy) print('dfdx =', dfdx)
SymbolicVsAD.ipynb
BYUFLOWLab/MDOnotebooks
mit
Let's also compare to AD using a source code transformation method (I used Tapenade in Fortran)
def funcad(x): xd = 1.0 yd = xd y = x for i in range(30): yd = (xd + yd)*cos(x + y) y = sin(x + y) return yd dfdx = funcad(xpt) print('dfdx =', dfdx)
SymbolicVsAD.ipynb
BYUFLOWLab/MDOnotebooks
mit
Algoritmo de Regresion Lineal en TensorFlow
import tensorflow as tf import numpy as np import matplotlib.pyplot as plt learning_rate = 0.01 training_epochs = 100 x_train = np.linspace(-1,1,101) y_train = 2 * x_train + np.random.randn(*x_train.shape) * 0.33 X = tf.placeholder("float") Y = tf.placeholder("float") def model(X,w): return tf.multiply(X,w) w ...
TensorFlow/02_Linear_Regression.ipynb
josdaza/deep-toolbox
mit
Regresion Lineal en Polinomios de grado N
import tensorflow as tf import numpy as np import matplotlib.pyplot as plt learning_rate = 0.01 training_epochs = 40 trX = np.linspace(-1, 1, 101) num_coeffs = 6 trY_coeffs = [1, 2, 3, 4, 5, 6] trY = 0 #Construir datos polinomiales pseudo-aleatorios para probar el algoritmo for i in range(num_coeffs): trY += trY...
TensorFlow/02_Linear_Regression.ipynb
josdaza/deep-toolbox
mit
Regularizacion Para manejar un poco mejor el impacto que tienen los outliers sobre nuestro modelo (y asi evitar que el modelo produzca curvas demasiado complicadas, y el overfitting) existe el termino Regularizacion que se define como: $$ Cost(X,Y) = Loss(X,Y) + \lambda |x| $$ en donde |x| es la norma del vector (la ...
import tensorflow as tf import numpy as np import matplotlib.pyplot as plt def split_dataset(x_dataset, y_dataset, ratio): arr = np.arange(x_dataset.size) np.random.shuffle(arr) num_train = int(ratio* x_dataset.size) x_train = x_dataset[arr[0:num_train]] y_train = y_dataset[arr[0:num_train]] x_...
TensorFlow/02_Linear_Regression.ipynb
josdaza/deep-toolbox
mit
時間太長!
def zebra_puzzle(): return [locals() for (紅, 綠, 白, 黃, 藍) in 所有順序 if 在右邊(綠, 白) #6 for (英國人, 西班牙人, 烏克蘭人, 日本人, 挪威人) in 所有順序 if 英國人 is 紅 #2 if 挪威人 is 第一間 #10 if 隔壁(挪威人, 藍) #15 for (咖啡...
Tutorial 3.ipynb
tjwei/PythonTutorial
mit
Outline Preliminaries: Setup & introduction Beam dynamics Tutorial N1. Linear optics.. Web version. Linear optics. DBA. Tutorial N2. Tracking.. Web version. Linear optics of the European XFEL Injector Tracking. First and second order. Tutorial N3. Space Charge.. Web version. Tracking with SC effects. Tutorial...
import IPython print('IPython:', IPython.__version__) import numpy print('numpy:', numpy.__version__) import scipy print('scipy:', scipy.__version__) import matplotlib print('matplotlib:', matplotlib.__version__) import ocelot print('ocelot:', ocelot.__version__)
1_introduction.ipynb
sergey-tomin/workshop
mit
<a id="tutorial1"></a> Tutorial N1. Double Bend Achromat. We designed a simple lattice to demonstrate the basic concepts and syntax of the optics functions calculation. Also, we chose DBA to demonstrate the periodic solution for the optical functions calculation.
from __future__ import print_function # the output of plotting commands is displayed inline within frontends, # directly below the code cell that produced it %matplotlib inline # import from Ocelot main modules and functions from ocelot import * # import from Ocelot graphical modules from ocelot.gui.accelerator imp...
1_introduction.ipynb
sergey-tomin/workshop
mit
Creating lattice Ocelot has following elements: Drift, Quadrupole, Sextupole, Octupole, Bend, SBend, RBend, Edge, Multipole, Hcor, Vcor, Solenoid, Cavity, Monitor, Marker, Undulator.
# defining of the drifts D1 = Drift(l=2.) D2 = Drift(l=0.6) D3 = Drift(l=0.3) D4 = Drift(l=0.7) D5 = Drift(l=0.9) D6 = Drift(l=0.2) # defining of the quads Q1 = Quadrupole(l=0.4, k1=-1.3) Q2 = Quadrupole(l=0.8, k1=1.4) Q3 = Quadrupole(l=0.4, k1=-1.7) Q4 = Quadrupole(l=0.5, k1=1.3) # defining of the bending magnet B =...
1_introduction.ipynb
sergey-tomin/workshop
mit
hint: to see a simple description of the function put cursor inside () and press Shift-Tab or you can type sign ? before function. To extend dialog window press +* * The cell is a list of the simple objects which contain a physical information of lattice elements such as length, strength, voltage and so on. In order to...
lat = MagneticLattice(cell) # to see total lenth of the lattice print("length of the cell: ", lat.totalLen, "m")
1_introduction.ipynb
sergey-tomin/workshop
mit
Optical function calculation Uses: * twiss() function and, * Twiss() object contains twiss parameters and other information at one certain position (s) of lattice To calculate twiss parameters you have to run twiss(lattice, tws0=None, nPoints=None) function. If you want to get a periodic solution leave tws0 by default...
tws=twiss(lat) # to see twiss paraments at the begining of the cell, uncomment next line # print(tws[0]) # to see twiss paraments at the end of the cell, uncomment next line print(tws[-1]) len(tws) # plot optical functions. plot_opt_func(lat, tws, top_plot = ["Dx", "Dy"], legend=False, font_size=10) plt.show() # y...
1_introduction.ipynb
sergey-tomin/workshop
mit
<h3>How many facilities have accurate records online?</h3> Those that have no offline records.
df[(df['offline'].isnull())].count()[0]
notebooks/analysis/.ipynb_checkpoints/facilities_analysis-checkpoint.ipynb
TheOregonian/long-term-care-db
mit
<h3>How many facilities have inaccurate records online?<h/3> Those that have offline records.
df[(df['offline'].notnull())].count()[0]
notebooks/analysis/.ipynb_checkpoints/facilities_analysis-checkpoint.ipynb
TheOregonian/long-term-care-db
mit
<h3>How many facilities had more than double the number of complaints shown online?</h3>
df[(df['offline']>df['online']) & (df['online'].notnull())].count()[0]
notebooks/analysis/.ipynb_checkpoints/facilities_analysis-checkpoint.ipynb
TheOregonian/long-term-care-db
mit
<h3>How many facilities show zero complaints online but have complaints offline?</h3>
df[(df['online'].isnull()) & (df['offline'].notnull())].count()[0]
notebooks/analysis/.ipynb_checkpoints/facilities_analysis-checkpoint.ipynb
TheOregonian/long-term-care-db
mit
<h3>How many facilities have complaints and are accurate online?</h3>
df[(df['online'].notnull()) & (df['offline'].isnull())].count()[0]
notebooks/analysis/.ipynb_checkpoints/facilities_analysis-checkpoint.ipynb
TheOregonian/long-term-care-db
mit
<h3>How many facilities have complaints?</h3>
df[(df['online'].notnull()) | df['offline'].notnull()].count()[0]
notebooks/analysis/.ipynb_checkpoints/facilities_analysis-checkpoint.ipynb
TheOregonian/long-term-care-db
mit
<h3>What percent of facilities have accurate records online?</h3>
df[(df['offline'].isnull())].count()[0]/df.count()[0]*100
notebooks/analysis/.ipynb_checkpoints/facilities_analysis-checkpoint.ipynb
TheOregonian/long-term-care-db
mit
<h3>What is the total capacity of all facilities with inaccurate records?</h3>
df[df['offline'].notnull()].sum()['fac_capacity'] df[df['fac_capacity'].isnull()] #df#['fac_capacity'].sum()
notebooks/analysis/.ipynb_checkpoints/facilities_analysis-checkpoint.ipynb
TheOregonian/long-term-care-db
mit
Artifact Correction with SSP
import numpy as np import mne from mne.datasets import sample from mne.preprocessing import compute_proj_ecg, compute_proj_eog # getting some data ready data_path = sample.data_path() raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif' raw = mne.io.read_raw_fif(raw_fname, preload=True) raw.set_eeg_...
0.14/_downloads/plot_artifacts_correction_ssp.ipynb
mne-tools/mne-tools.github.io
bsd-3-clause
Compute SSP projections
projs, events = compute_proj_ecg(raw, n_grad=1, n_mag=1, average=True) print(projs) ecg_projs = projs[-2:] mne.viz.plot_projs_topomap(ecg_projs) # Now for EOG projs, events = compute_proj_eog(raw, n_grad=1, n_mag=1, average=True) print(projs) eog_projs = projs[-2:] mne.viz.plot_projs_topomap(eog_projs)
0.14/_downloads/plot_artifacts_correction_ssp.ipynb
mne-tools/mne-tools.github.io
bsd-3-clause
Apply SSP projections MNE is handling projections at the level of the info, so to register them populate the list that you find in the 'proj' field
raw.info['projs'] += eog_projs + ecg_projs
0.14/_downloads/plot_artifacts_correction_ssp.ipynb
mne-tools/mne-tools.github.io
bsd-3-clause
Yes this was it. Now MNE will apply the projs on demand at any later stage, so watch out for proj parmeters in functions or to it explicitly with the .apply_proj method Demonstrate SSP cleaning on some evoked data
events = mne.find_events(raw, stim_channel='STI 014') reject = dict(grad=4000e-13, mag=4e-12, eog=150e-6) # this can be highly data dependent event_id = {'auditory/left': 1} epochs_no_proj = mne.Epochs(raw, events, event_id, tmin=-0.2, tmax=0.5, proj=False, baseline=(None, 0), reject=reject...
0.14/_downloads/plot_artifacts_correction_ssp.ipynb
mne-tools/mne-tools.github.io
bsd-3-clause
Looks cool right? It is however often not clear how many components you should take and unfortunately this can have bad consequences as can be seen interactively using the delayed SSP mode:
evoked = mne.Epochs(raw, events, event_id, tmin=-0.2, tmax=0.5, proj='delayed', baseline=(None, 0), reject=reject).average() # set time instants in seconds (from 50 to 150ms in a step of 10ms) times = np.arange(0.05, 0.15, 0.01) evoked.plot_topomap(times, proj='interactive')
0.14/_downloads/plot_artifacts_correction_ssp.ipynb
mne-tools/mne-tools.github.io
bsd-3-clause
Show a bunch of 4s
fig, ax = plt.subplots(nrows=5, ncols=5, sharex=True, sharey=True,) ax = ax.flatten() for i in range(25): img = X_train[y_train == 4][i].reshape(28, 28) ax[i].imshow(img, cmap='Greys', interpolation='nearest') ax[0].set_xticks([]) ax[0].set_yticks([]) plt.tight_layout() plt.show()
python-ml-book/ch12/ch12.ipynb
krosaen/ml-study
mit
Classifying with tree based models Let's see how well some other models do before we get to the neural net.
from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import RandomForestClassifier tree10 = DecisionTreeClassifier(criterion='entropy', max_depth=10, random_state=0) tree100 = DecisionTreeClassifier(criterion='entropy', max_depth=100, random_state=0) rf10 = RandomForestClassifier(criterion='entropy',...
python-ml-book/ch12/ch12.ipynb
krosaen/ml-study
mit
degree centrality for a node v is the fraction of nodes it is connected to
# the type of degree centrality is a dictionary type(nx.degree_centrality(graph)) # get all the values of the dictionary, this returns a list of centrality scores # turn the list into a numpy array # take the mean of the numpy array np.array(nx.degree_centrality(graph).values()).mean()
to_do/vax_temp/test.ipynb
gloriakang/vax-sentiment
mit
closeness centrality of a node u is the reciprocal of the sum of the shortest path distances from u to all n-1 other nodes. Since the sum of distances depends on the number of nodes in the graph, closeness is normalized by the sum of minimum possible distances n-1. Notice that higher values of closeness indicate higher...
nx.closeness_centrality(graph)
to_do/vax_temp/test.ipynb
gloriakang/vax-sentiment
mit
betweenness centrality of a node v is the sum of the fraction of all-pairs shortest paths that pass through v
nx.betweenness_centrality(graph) np.array(nx.betweenness_centrality(graph).values()).mean()
to_do/vax_temp/test.ipynb
gloriakang/vax-sentiment
mit
degree assortativity coefficient Assortativity measures the similarity of connections in the graph with respect to the node degree.
nx.degree_assortativity_coefficient(graph)
to_do/vax_temp/test.ipynb
gloriakang/vax-sentiment
mit
Now we can load up two GeoDataFrames containing (multi)polygon geometries...
%matplotlib inline from shapely.geometry import Point from geopandas import datasets, GeoDataFrame, read_file from geopandas.tools import overlay # NYC Boros zippath = datasets.get_path('nybb') polydf = read_file(zippath) # Generate some circles b = [int(x) for x in polydf.total_bounds] N = 10 polydf2 = GeoDataFrame(...
examples/overlays.ipynb
ozak/geopandas
bsd-3-clause
The first dataframe contains multipolygons of the NYC boros
polydf.plot()
examples/overlays.ipynb
ozak/geopandas
bsd-3-clause
And the second GeoDataFrame is a sequentially generated set of circles in the same geographic space. We'll plot these with a different color palette.
polydf2.plot(cmap='tab20b')
examples/overlays.ipynb
ozak/geopandas
bsd-3-clause
The geopandas.tools.overlay function takes three arguments: df1 df2 how Where how can be one of: ['intersection', 'union', 'identity', 'symmetric_difference', 'difference'] So let's identify the areas (and attributes) where both dataframes intersect using the overlay tool.
from geopandas.tools import overlay newdf = overlay(polydf, polydf2, how="intersection") newdf.plot(cmap='tab20b')
examples/overlays.ipynb
ozak/geopandas
bsd-3-clause
And take a look at the attributes; we see that the attributes from both of the original GeoDataFrames are retained.
polydf.head() polydf2.head() newdf.head()
examples/overlays.ipynb
ozak/geopandas
bsd-3-clause
Now let's look at the other how operations:
newdf = overlay(polydf, polydf2, how="union") newdf.plot(cmap='tab20b') newdf = overlay(polydf, polydf2, how="identity") newdf.plot(cmap='tab20b') newdf = overlay(polydf, polydf2, how="symmetric_difference") newdf.plot(cmap='tab20b') newdf = overlay(polydf, polydf2, how="difference") newdf.plot(cmap='tab20b')
examples/overlays.ipynb
ozak/geopandas
bsd-3-clause
Prepare Dataset
with open('data_w1w4.csv', 'r') as f: reader = csv.reader(f) data = list(reader) matrix = obtain_data_matrix(data) samples = len(matrix) print("Number of samples: " + str(samples)) Y = matrix[:,[8]] X = matrix[:,[9]] S = matrix[:,[11]]
Linear Regression.ipynb
tlkh/Generating-Inference-from-3D-Printing-Jobs
mit
Use the model (LinearRegression)
# Create linear regression object regr = linear_model.LinearRegression() # Train the model using the training sets regr.fit(X, Y) # Make predictions using the testing set Y_pred = regr.predict(X)
Linear Regression.ipynb
tlkh/Generating-Inference-from-3D-Printing-Jobs
mit
Plot the data
fig = plt.figure(1, figsize=(10, 4)) plt.scatter([X], [Y], color='blue', edgecolor='k') plt.plot(X, Y_pred, color='red', linewidth=1) plt.xticks(()) plt.yticks(()) print('Coefficients: ', regr.coef_) plt.show() # The mean squared error print("Mean squared error: %.2f" % mean_squared_error(Y, Y_pred)) # Explai...
Linear Regression.ipynb
tlkh/Generating-Inference-from-3D-Printing-Jobs
mit
Bootstrap to find parameter confidence intervals
from sklearn.utils import resample bootstrap_resamples = 5000 intercepts = [] coefs = [] for k in range(bootstrap_resamples): #resample population with replacement samples_resampled = resample(X,Y,replace=True,n_samples=len(X)) ## Fit model to resampled data # Create linear regression object r...
Linear Regression.ipynb
tlkh/Generating-Inference-from-3D-Printing-Jobs
mit
Calculate confidence interval
alpha = 0.95 p_lower = ((1-alpha)/2.0) * 100 p_upper = (alpha + ((1-alpha)/2.0)) * 100 coefs_lower = np.percentile(coefs,p_lower) coefs_upper = np.percentile(coefs,p_upper) intercepts_lower = np.percentile(intercepts,p_lower) intercepts_upper = np.percentile(intercepts,p_upper) print('Coefs %.0f%% CI = %.5f - %.5f' % (...
Linear Regression.ipynb
tlkh/Generating-Inference-from-3D-Printing-Jobs
mit
Visualize frequency distributions of bootstrapped parameters
plt.hist(coefs) plt.xlabel('Coefficient X0') plt.title('Frquency Distribution of Coefficient X0') plt.show() plt.hist(intercepts) plt.xlabel('Intercept') plt.title('Frquency Distribution of Intercepts') plt.show()
Linear Regression.ipynb
tlkh/Generating-Inference-from-3D-Printing-Jobs
mit
Vertex AI: Vertex AI Migration: AutoML Image Classification <table align="left"> <td> <a href="https://colab.research.google.com/github/GoogleCloudPlatform/ai-platform-samples/blob/master/vertex-ai-samples/tree/master/notebooks/official/migration/UJ1%20Vertex%20SDK%20AutoML%20Image%20Classification.ipynb"> ...
import os # Google Cloud Notebook if os.path.exists("/opt/deeplearning/metadata/env_version"): USER_FLAG = "--user" else: USER_FLAG = "" ! pip3 install --upgrade google-cloud-aiplatform $USER_FLAG
notebooks/official/migration/UJ1 Vertex SDK AutoML Image Classification.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Install the latest GA version of google-cloud-storage library as well.
! pip3 install -U google-cloud-storage $USER_FLAG if os.getenv("IS_TESTING"): ! pip3 install --upgrade tensorflow $USER_FLAG
notebooks/official/migration/UJ1 Vertex SDK AutoML Image Classification.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Location of Cloud Storage training data. Now set the variable IMPORT_FILE to the location of the CSV index file in Cloud Storage.
IMPORT_FILE = ( "gs://cloud-samples-data/vision/automl_classification/flowers/all_data_v2.csv" )
notebooks/official/migration/UJ1 Vertex SDK AutoML Image Classification.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Create a dataset datasets.create-dataset-api Create the Dataset Next, create the Dataset resource using the create method for the ImageDataset class, which takes the following parameters: display_name: The human readable name for the Dataset resource. gcs_source: A list of one or more dataset index files to import the...
dataset = aip.ImageDataset.create( display_name="Flowers" + "_" + TIMESTAMP, gcs_source=[IMPORT_FILE], import_schema_uri=aip.schema.dataset.ioformat.image.single_label_classification, ) print(dataset.resource_name)
notebooks/official/migration/UJ1 Vertex SDK AutoML Image Classification.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Example Output: INFO:google.cloud.aiplatform.datasets.dataset:Creating ImageDataset INFO:google.cloud.aiplatform.datasets.dataset:Create ImageDataset backing LRO: projects/759209241365/locations/us-central1/datasets/2940964905882222592/operations/1941426647739662336 INFO:google.cloud.aiplatform.datasets.dataset:ImageDa...
dag = aip.AutoMLImageTrainingJob( display_name="flowers_" + TIMESTAMP, prediction_type="classification", multi_label=False, model_type="CLOUD", base_model=None, ) print(dag)
notebooks/official/migration/UJ1 Vertex SDK AutoML Image Classification.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Example output: &lt;google.cloud.aiplatform.training_jobs.AutoMLImageTrainingJob object at 0x7f806a6116d0&gt; Run the training pipeline Next, you run the DAG to start the training job by invoking the method run, with the following parameters: dataset: The Dataset resource to train the model. model_display_name: The h...
model = dag.run( dataset=dataset, model_display_name="flowers_" + TIMESTAMP, training_fraction_split=0.8, validation_fraction_split=0.1, test_fraction_split=0.1, budget_milli_node_hours=8000, disable_early_stopping=False, )
notebooks/official/migration/UJ1 Vertex SDK AutoML Image Classification.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Example output: INFO:google.cloud.aiplatform.training_jobs:View Training: https://console.cloud.google.com/ai/platform/locations/us-central1/training/2109316300865011712?project=759209241365 INFO:google.cloud.aiplatform.training_jobs:AutoMLImageTrainingJob projects/759209241365/locations/us-central1/trainingPipelines/2...
# Get model resource ID models = aip.Model.list(filter="display_name=flowers_" + TIMESTAMP) # Get a reference to the Model Service client client_options = {"api_endpoint": f"{REGION}-aiplatform.googleapis.com"} model_service_client = aip.gapic.ModelServiceClient(client_options=client_options) model_evaluations = mode...
notebooks/official/migration/UJ1 Vertex SDK AutoML Image Classification.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Example output: name: "projects/759209241365/locations/us-central1/models/623915674158235648/evaluations/4280507618583117824" metrics_schema_uri: "gs://google-cloud-aiplatform/schema/modelevaluation/classification_metrics_1.0.0.yaml" metrics { struct_value { fields { key: "auPrc" value { numbe...
test_items = !gsutil cat $IMPORT_FILE | head -n2 if len(str(test_items[0]).split(",")) == 3: _, test_item_1, test_label_1 = str(test_items[0]).split(",") _, test_item_2, test_label_2 = str(test_items[1]).split(",") else: test_item_1, test_label_1 = str(test_items[0]).split(",") test_item_2, test_label_2...
notebooks/official/migration/UJ1 Vertex SDK AutoML Image Classification.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Example output: INFO:google.cloud.aiplatform.jobs:Creating BatchPredictionJob &lt;google.cloud.aiplatform.jobs.BatchPredictionJob object at 0x7f806a6112d0&gt; is waiting for upstream dependencies to complete. INFO:google.cloud.aiplatform.jobs:BatchPredictionJob created. Resource name: projects/759209241365/locations/us...
batch_predict_job.wait()
notebooks/official/migration/UJ1 Vertex SDK AutoML Image Classification.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Example Output: INFO:google.cloud.aiplatform.jobs:BatchPredictionJob created. Resource name: projects/759209241365/locations/us-central1/batchPredictionJobs/181835033978339328 INFO:google.cloud.aiplatform.jobs:To use this BatchPredictionJob in another session: INFO:google.cloud.aiplatform.jobs:bpj = aiplatform.BatchPre...
import json import tensorflow as tf bp_iter_outputs = batch_predict_job.iter_outputs() prediction_results = list() for blob in bp_iter_outputs: if blob.name.split("/")[-1].startswith("prediction"): prediction_results.append(blob.name) tags = list() for prediction_result in prediction_results: gfile_...
notebooks/official/migration/UJ1 Vertex SDK AutoML Image Classification.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Example Output: {'instance': {'content': 'gs://andy-1234-221921aip-20210802180634/100080576_f52e8ee070_n.jpg', 'mimeType': 'image/jpeg'}, 'prediction': {'ids': ['3195476558944927744', '1636105187967893504', '7400712711002128384', '2789026692574740480', '5501319568158621696'], 'displayNames': ['daisy', 'dandelion', 'ros...
endpoint = model.deploy()
notebooks/official/migration/UJ1 Vertex SDK AutoML Image Classification.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Example output: INFO:google.cloud.aiplatform.models:Creating Endpoint INFO:google.cloud.aiplatform.models:Create Endpoint backing LRO: projects/759209241365/locations/us-central1/endpoints/4867177336350441472/operations/4087251132693348352 INFO:google.cloud.aiplatform.models:Endpoint created. Resource name: projects/75...
test_item = !gsutil cat $IMPORT_FILE | head -n1 if len(str(test_item[0]).split(",")) == 3: _, test_item, test_label = str(test_item[0]).split(",") else: test_item, test_label = str(test_item[0]).split(",") print(test_item, test_label)
notebooks/official/migration/UJ1 Vertex SDK AutoML Image Classification.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Make the prediction Now that your Model resource is deployed to an Endpoint resource, you can do online predictions by sending prediction requests to the Endpoint resource. Request Since in this example your test item is in a Cloud Storage bucket, you open and read the contents of the image using tf.io.gfile.Gfile(). T...
import base64 import tensorflow as tf with tf.io.gfile.GFile(test_item, "rb") as f: content = f.read() # The format of each instance should conform to the deployed model's prediction input schema. instances = [{"content": base64.b64encode(content).decode("utf-8")}] prediction = endpoint.predict(instances=instan...
notebooks/official/migration/UJ1 Vertex SDK AutoML Image Classification.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Example output: Prediction(predictions=[{'ids': ['3195476558944927744', '5501319568158621696', '1636105187967893504', '2789026692574740480', '7400712711002128384'], 'displayNames': ['daisy', 'tulips', 'dandelion', 'sunflowers', 'roses'], 'confidences': [0.999987364, 2.69604527e-07, 8.2222e-06, 5.32310196e-07, 3.6782335...
endpoint.undeploy_all()
notebooks/official/migration/UJ1 Vertex SDK AutoML Image Classification.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Sunspots Data
print(sm.datasets.sunspots.NOTE) dta = sm.datasets.sunspots.load_pandas().data dta.index = pd.Index(pd.date_range("1700", end="2009", freq="A-DEC")) del dta["YEAR"] dta.plot(figsize=(12,4)); fig = plt.figure(figsize=(12,8)) ax1 = fig.add_subplot(211) fig = sm.graphics.tsa.plot_acf(dta.values.squeeze(), lags=40, ax=...
v0.12.1/examples/notebooks/generated/statespace_arma_0.ipynb
statsmodels/statsmodels.github.io
bsd-3-clause
Does our model obey the theory?
sm.stats.durbin_watson(arma_mod30.resid) fig = plt.figure(figsize=(12,4)) ax = fig.add_subplot(111) ax = plt.plot(arma_mod30.resid) resid = arma_mod30.resid stats.normaltest(resid) fig = plt.figure(figsize=(12,4)) ax = fig.add_subplot(111) fig = qqplot(resid, line='q', ax=ax, fit=True) fig = plt.figure(figsize=(12...
v0.12.1/examples/notebooks/generated/statespace_arma_0.ipynb
statsmodels/statsmodels.github.io
bsd-3-clause
This indicates a lack of fit. In-sample dynamic prediction. How good does our model do?
predict_sunspots = arma_mod30.predict(start='1990', end='2012', dynamic=True) fig, ax = plt.subplots(figsize=(12, 8)) dta.loc['1950':].plot(ax=ax) predict_sunspots.plot(ax=ax, style='r'); def mean_forecast_err(y, yhat): return y.sub(yhat).mean() mean_forecast_err(dta.SUNACTIVITY, predict_sunspots)
v0.12.1/examples/notebooks/generated/statespace_arma_0.ipynb
statsmodels/statsmodels.github.io
bsd-3-clause
Explore the Data The dataset is broken into batches to prevent your machine from running out of memory. The CIFAR-10 dataset consists of 5 batches, named data_batch_1, data_batch_2, etc.. Each batch contains the labels and images that are one of the following: * airplane * automobile * bird * cat * deer * dog * frog *...
%matplotlib inline %config InlineBackend.figure_format = 'retina' import helper import numpy as np # Explore the dataset batch_id = 1 sample_id = 2 helper.display_stats(cifar10_dataset_folder_path, batch_id, sample_id)
image-classification/dlnd_image_classification.ipynb
yuanotes/deep-learning
mit
Implement Preprocess Functions Normalize In the cell below, implement the normalize function to take in image data, x, and return it as a normalized Numpy array. The values should be in the range of 0 to 1, inclusive. The return object should be the same shape as x.
def normalize(x): """ Normalize a list of sample image data in the range of 0 to 1 : x: List of image data. The image shape is (32, 32, 3) : return: Numpy array of normalize data """ # TODO: Implement Function return x / 255.0 """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE...
image-classification/dlnd_image_classification.ipynb
yuanotes/deep-learning
mit
One-hot encode Just like the previous code cell, you'll be implementing a function for preprocessing. This time, you'll implement the one_hot_encode function. The input, x, are a list of labels. Implement the function to return the list of labels as One-Hot encoded Numpy array. The possible values for labels are 0 t...
def one_hot_encode(x): """ One hot encode a list of sample labels. Return a one-hot encoded vector for each label. : x: List of sample Labels : return: Numpy array of one-hot encoded labels """ x = np.asarray(x) result = np.zeros((x.shape[0], 10)) result[np.arange(x.shape[0]), x] = 1 ...
image-classification/dlnd_image_classification.ipynb
yuanotes/deep-learning
mit
Build the network For the neural network, you'll build each layer into a function. Most of the code you've seen has been outside of functions. To test your code more thoroughly, we require that you put each layer in a function. This allows us to give you better feedback and test for simple mistakes using our unittest...
import tensorflow as tf def neural_net_image_input(image_shape): """ Return a Tensor for a batch of image input : image_shape: Shape of the images : return: Tensor for image input. """ # TODO: Implement Function return tf.placeholder(tf.float32, shape=(None, ) + image_shape, name="x") def...
image-classification/dlnd_image_classification.ipynb
yuanotes/deep-learning
mit
Convolution and Max Pooling Layer Convolution layers have a lot of success with images. For this code cell, you should implement the function conv2d_maxpool to apply convolution then max pooling: * Create the weight and bias using conv_ksize, conv_num_outputs and the shape of x_tensor. * Apply a convolution to x_tensor...
def conv2d_maxpool(x_tensor, conv_num_outputs, conv_ksize, conv_strides, pool_ksize, pool_strides): """ Apply convolution then max pooling to x_tensor :param x_tensor: TensorFlow Tensor :param conv_num_outputs: Number of outputs for the convolutional layer :param conv_ksize: kernal size 2-D Tuple fo...
image-classification/dlnd_image_classification.ipynb
yuanotes/deep-learning
mit
Flatten Layer Implement the flatten function to change the dimension of x_tensor from a 4-D tensor to a 2-D tensor. The output should be the shape (Batch Size, Flattened Image Size). Shortcut option: you can use classes from the TensorFlow Layers or TensorFlow Layers (contrib) packages for this layer. For more of a ch...
from tensorflow.contrib.layers.python import layers def flatten(x_tensor): """ Flatten x_tensor to (Batch Size, Flattened Image Size) : x_tensor: A tensor of size (Batch Size, ...), where ... are the image dimensions. : return: A tensor of size (Batch Size, Flattened Image Size). """ return lay...
image-classification/dlnd_image_classification.ipynb
yuanotes/deep-learning
mit
Fully-Connected Layer Implement the fully_conn function to apply a fully connected layer to x_tensor with the shape (Batch Size, num_outputs). Shortcut option: you can use classes from the TensorFlow Layers or TensorFlow Layers (contrib) packages for this layer. For more of a challenge, only use other TensorFlow packag...
from tensorflow.contrib.layers.python import layers def fully_conn(x_tensor, num_outputs): """ Apply a fully connected layer to x_tensor using weight and bias : x_tensor: A 2-D tensor where the first dimension is batch size. : num_outputs: The number of output that the new tensor should be. : retur...
image-classification/dlnd_image_classification.ipynb
yuanotes/deep-learning
mit
Output Layer Implement the output function to apply a fully connected layer to x_tensor with the shape (Batch Size, num_outputs). Shortcut option: you can use classes from the TensorFlow Layers or TensorFlow Layers (contrib) packages for this layer. For more of a challenge, only use other TensorFlow packages. Note: Act...
def output(x_tensor, num_outputs): """ Apply a output layer to x_tensor using weight and bias : x_tensor: A 2-D tensor where the first dimension is batch size. : num_outputs: The number of output that the new tensor should be. : return: A 2-D tensor where the second dimension is num_outputs. """...
image-classification/dlnd_image_classification.ipynb
yuanotes/deep-learning
mit
Create Convolutional Model Implement the function conv_net to create a convolutional neural network model. The function takes in a batch of images, x, and outputs logits. Use the layers you created above to create this model: Apply 1, 2, or 3 Convolution and Max Pool layers Apply a Flatten Layer Apply 1, 2, or 3 Full...
def conv_net(x, keep_prob): """ Create a convolutional neural network model : x: Placeholder tensor that holds image data. : keep_prob: Placeholder tensor that hold dropout keep probability. : return: Tensor that represents logits """ # TODO: Apply 1, 2, or 3 Convolution and Max Pool layers ...
image-classification/dlnd_image_classification.ipynb
yuanotes/deep-learning
mit
Train the Neural Network Single Optimization Implement the function train_neural_network to do a single optimization. The optimization should use optimizer to optimize in session with a feed_dict of the following: * x for image input * y for labels * keep_prob for keep probability for dropout This function will be cal...
def train_neural_network(session, optimizer, keep_probability, feature_batch, label_batch): """ Optimize the session on a batch of images and labels : session: Current TensorFlow session : optimizer: TensorFlow optimizer function : keep_probability: keep probability : feature_batch: Batch of Num...
image-classification/dlnd_image_classification.ipynb
yuanotes/deep-learning
mit
Show Stats Implement the function print_stats to print loss and validation accuracy. Use the global variables valid_features and valid_labels to calculate validation accuracy. Use a keep probability of 1.0 to calculate the loss and validation accuracy.
def print_stats(session, feature_batch, label_batch, cost, accuracy): """ Print information about loss and validation accuracy : session: Current TensorFlow session : feature_batch: Batch of Numpy image data : label_batch: Batch of Numpy label data : cost: TensorFlow cost function : accuracy...
image-classification/dlnd_image_classification.ipynb
yuanotes/deep-learning
mit
Hyperparameters Tune the following parameters: * Set epochs to the number of iterations until the network stops learning or start overfitting * Set batch_size to the highest number that your machine has memory for. Most people set them to common sizes of memory: * 64 * 128 * 256 * ... * Set keep_probability to the...
# TODO: Tune Parameters epochs = 10 batch_size = 256 keep_probability = 0.5
image-classification/dlnd_image_classification.ipynb
yuanotes/deep-learning
mit
Checkpoint The model has been saved to disk. Test Model Test your model against the test dataset. This will be your final accuracy. You should have an accuracy greater than 50%. If you don't, keep tweaking the model architecture and parameters.
""" DON'T MODIFY ANYTHING IN THIS CELL """ %matplotlib inline %config InlineBackend.figure_format = 'retina' import tensorflow as tf import pickle import helper import random # Set batch size if not already set try: if batch_size: pass except NameError: batch_size = 64 save_model_path = './image_clas...
image-classification/dlnd_image_classification.ipynb
yuanotes/deep-learning
mit
Matrix Factorization without Side Information (BPMF) As a first example we can run SMURFF without side information. The method used here is BPMF. Input matrix for Y is a sparse scipy matrix (either coo_matrix, csr_matrix or csc_matrix). The test matrix Ytest also needs to ne sparse matrix of the same size as Y. Here we...
trainSession = smurff.BPMFSession( Ytrain = ic50_train, Ytest = ic50_test, num_latent = 16, burnin = 20, nsamples = 80, verbose = 0,) predictions = trainSession.r...
docs/notebooks/different_methods.ipynb
ExaScience/smurff
mit
Matrix Factorization with Side Information (Macau) If we want to use the compound features we can use the Macau algorithm. The parameter side_info = [ecfp, None] sets the side information for rows and columns, respectively. In this example we only use side information for the compounds (rows of the matrix). Since the e...
predictions = smurff.MacauSession( Ytrain = ic50_train, Ytest = ic50_test, side_info = [ecfp, None], direct = False, # use CG solver instead of Cholesky decomposition num_latent = 16, ...
docs/notebooks/different_methods.ipynb
ExaScience/smurff
mit
Macau univariate sampler SMURFF also includes an option to use a very fast univariate sampler, i.e., instead of sampling blocks of variables jointly it samples each individually. An example:
predictions = smurff.MacauSession( Ytrain = ic50_train, Ytest = ic50_test, side_info = [ecfp, None], direct = True, univariate = True, num_latent = 32, ...
docs/notebooks/different_methods.ipynb
ExaScience/smurff
mit
CSV to List
# The rb flag opens file for reading with open('data/fileops/vehicles.csv', 'rb') as csv_file: rdr = csv.reader(csv_file, delimiter=',', quotechar='"') for row in rdr: print '\t'.join(row)
.ipynb_checkpoints/python-data-files-checkpoint.ipynb
Startupsci/data-science-notebooks
mit
Dictionary to CSV
# Dictionary data structures can be used to represent rows game1_scores = {'Game':'Quarter', 'Team A': 45, 'Team B': 90} game2_scores = {'Game':'Semi', 'Team A': 80, 'Team B': 32} game3_scores = {'Game':'Final', 'Team A': 70, 'Team B': 68} headers = ['Game', 'Team A', 'Team B'] # Create CSV from dictionaries with ope...
.ipynb_checkpoints/python-data-files-checkpoint.ipynb
Startupsci/data-science-notebooks
mit
CSV to Dictionary
# Read CSV into dictionary data structure with open('data/fileops/game-scores.csv', 'rb') as df: dict_rdr = csv.DictReader(df) for row in dict_rdr: print('\t'.join([row['Game'], row['Team A'], row['Team B']])) print('\t'.join(row.keys()))
.ipynb_checkpoints/python-data-files-checkpoint.ipynb
Startupsci/data-science-notebooks
mit
Pandas for CSV file operations Pandas goal is to become the most powerful and flexible open source data analysis / manipulation tool available in any language. Pandas includes file operations capabilities for CSV, among other formats. CSV operations in Pandas are much faster than in native Python. DataFrame to CSV
import pandas as pd # Create a DataFrame df = pd.DataFrame({ 'Name' : ['Josh', 'Eli', 'Ram', 'Bil'], 'Sales' : [34.32, 12.1, 4.77, 31.63], 'Region' : ['North', 'South', 'West', 'East'], 'Product' : ['PC', 'Phone', 'SW', 'Cloud']}) df # DataFrame to CSV df.to_csv('data/fileops/sales.csv...
.ipynb_checkpoints/python-data-files-checkpoint.ipynb
Startupsci/data-science-notebooks
mit
CSV to DataFrame
# CSV to DataFrame df2 = pd.read_csv('data/fileops/sales.csv') df2
.ipynb_checkpoints/python-data-files-checkpoint.ipynb
Startupsci/data-science-notebooks
mit
DataFrame to Excel
# DataFrame to XLSX Excel file df.to_excel('data/fileops/sales.xlsx', index=False) print(check_output(["ls", "data/fileops"]).decode("utf8"))
.ipynb_checkpoints/python-data-files-checkpoint.ipynb
Startupsci/data-science-notebooks
mit
Excel to DataFrame
# Excel to DataFrame df3 = pd.read_excel('data/fileops/sales.xlsx') df3
.ipynb_checkpoints/python-data-files-checkpoint.ipynb
Startupsci/data-science-notebooks
mit
<a id=weo></a> WEO data on government debt We use the IMF's data on government debt again, specifically its World Economic Outlook database, commonly referred to as the WEO. We focus on government debt expressed as a percentage of GDP, variable code GGXWDG_NGDP. The central question here is how the debt of Argenti...
url1 = "http://www.imf.org/external/pubs/ft/weo/2016/02/weodata/" url2 = "WEOOct2016all.xls" url = url1 + url2 weo = pd.read_csv(url, sep='\t', usecols=[1,2] + list(range(19,46)), thousands=',', na_values=['n/a', '--']) print('Variable dtypes:\n', weo.dtypes.he...
Code/notebooks/bootcamp_pandas-summarize.ipynb
NYUDataBootcamp/Materials
mit
Clean and shape Second step: select the variable we want and generate the two dataframes.
# select debt variable variables = ['GGXWDG_NGDP'] db = weo[weo['WEO Subject Code'].isin(variables)] # drop variable code column (they're all the same) db = db.drop('WEO Subject Code', axis=1) # set index to country code db = db.set_index('ISO') # name columns db.columns.name = 'Year' # transpose dbt = db.T #...
Code/notebooks/bootcamp_pandas-summarize.ipynb
NYUDataBootcamp/Materials
mit
Example. Let's try a simple graph of the dataframe dbt. The goal is to put Argentina in perspective by plotting it along with many other countries.
fig, ax = plt.subplots() dbt.plot(ax=ax, legend=False, color='blue', alpha=0.3, ylim=(0,150) ) ax.set_ylabel('Percent of GDP') ax.set_xlabel('') ax.set_title('Government debt', fontsize=14, loc='left') dbt['ARG'].plot(ax=ax, color='black', linewidth=1.5)
Code/notebooks/bootcamp_pandas-summarize.ipynb
NYUDataBootcamp/Materials
mit
Exercise. What do you take away from this graph? What would you change to make it look better? To make it mnore informative? To put Argentina's debt in context? Exercise. Do the same graph with Greece (GRC) as the country of interest. How does it differ? Why do you think that is? <a id=describe></a> Describi...
dbt.shape # count non-missing values dbt.count(axis=1).plot()
Code/notebooks/bootcamp_pandas-summarize.ipynb
NYUDataBootcamp/Materials
mit
Describing series Let's take the data for 2001 -- the year of Argentina's default -- and see what how Argentina compares. Was its debt high compare to other countries? which leads to more questions. How would we compare? Compare Argentina to the mean or median? Something else? Let's see how that works.
# 2001 data db01 = db['2001'] db01['ARG'] db01.mean() db01.median() db01.describe() db01.quantile(q=[0.25, 0.5, 0.75])
Code/notebooks/bootcamp_pandas-summarize.ipynb
NYUDataBootcamp/Materials
mit
Comment. If we add enough quantiles, we might as well plot the whole distribution. The easiest way to do this is with a histogram.
fig, ax = plt.subplots() db01.hist(bins=15, ax=ax, alpha=0.35) ax.set_xlabel('Government Debt (Percent of GDP)') ax.set_ylabel('Number of Countries') ymin, ymax = ax.get_ylim() ax.vlines(db01['ARG'], ymin, ymax, color='blue', lw=2)
Code/notebooks/bootcamp_pandas-summarize.ipynb
NYUDataBootcamp/Materials
mit
Comment Compared to the whole sample of countries in 2001, it doesn't seem that Argentina had particularly high debt. Describing dataframes We can compute the same statistics for dataframes. Here we hve a choice: we can compute (say) the mean down rows (axis=0) or across columns (axis=1). If we use the dataframe dbt...
# here we compute the mean across countries at every date dbt.mean(axis=1).head() # or we could do the median dbt.median(axis=1).head() # or a bunch of stats at once # NB: db not dbt (there's no axix argument here) db.describe() # the other way dbt.describe()
Code/notebooks/bootcamp_pandas-summarize.ipynb
NYUDataBootcamp/Materials
mit
Example. Let's add the mean to our graph. We make it a dashed line with linestyle='dashed'.
fig, ax = plt.subplots() dbt.plot(ax=ax, legend=False, color='blue', alpha=0.2, ylim=(0,200) ) dbt['ARG'].plot(ax=ax, color='black', linewidth=1.5) ax.set_ylabel('Percent of GDP') ax.set_xlabel('') ax.set_title('Government debt', fontsize=14, loc='left') dbt.mean(axis=1).plot(ax=ax, color='b...
Code/notebooks/bootcamp_pandas-summarize.ipynb
NYUDataBootcamp/Materials
mit
Question. Do you think this looks better when the mean varies with time, or when we use a constant mean? Let's try it and see.
dbar = dbt.mean().mean() dbar fig, ax = plt.subplots() dbt.plot(ax=ax, legend=False, color='blue', alpha=0.3, ylim=(0,150) ) dbt['ARG'].plot(ax=ax, color='black', linewidth=1.5) ax.set_ylabel('Percent of GDP') ax.set_xlabel('') ax.set_title('Government debt', fontsize=14, loc='left') xmin,...
Code/notebooks/bootcamp_pandas-summarize.ipynb
NYUDataBootcamp/Materials
mit
Exercise. Which do we like better? Exercise. Replace the (constant) mean with the (constant) median? Which do you prefer? <a id=value-counts></a> Describing categorical data A categorical variable is one that takes on a small number of values. States take on one of fifty values. University students are either grad...
url = 'http://pages.stern.nyu.edu/~dbackus/Data/mlcombined.csv' ml = pd.read_csv(url, index_col=0,encoding = "ISO-8859-1") print('Dimensions:', ml.shape) # fix up the dates ml["timestamp"] = pd.to_datetime(ml["timestamp"], unit="s") ml.head(10) # which movies have the most ratings? ml['title'].value_counts().head(1...
Code/notebooks/bootcamp_pandas-summarize.ipynb
NYUDataBootcamp/Materials
mit