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
Embedded Python in ObjectScriptFrom ObjectScript, run some Python library methods.
set datetime = ##class(%SYS.Python).Import("datetime") zw datetime zw datetime.date.today().isoformat()
datetime=3@%SYS.Python ; <module 'datetime' from '/usr/lib/python3.8/datetime.py'> ; <OREF> "2021-12-12"
MIT
src/Notebooks/ObjectScript.ipynb
gjsjohnmurray/iris-python-template
Examples of usage of Gate Angle PlaceholderThe word "Placeholder" is used in Qubiter (we are in good company, Tensorflow uses this word in the same way) to mean a variable for which we delay/postpone assigning a numerical value (evaluating it) until a later time. In the case of Qubiter, it is useful to define gates wi...
import os import sys print(os.getcwd()) os.chdir('../../') print(os.getcwd()) sys.path.insert(0,os.getcwd())
C:\Users\rrtuc\Desktop\backedup\python-projects\qubiter\qubiter\jupyter-notebooks C:\Users\rrtuc\Desktop\backedup\python-projects\qubiter
Apache-2.0
qubiter/jupyter_notebooks/examples_of_placeholder_usage.ipynb
yourball/qubiter
We begin by writing a simple circuit with 4 qubits. As usual, the following code willwrite an English and a Picture file in the `io_folder` directory. Note that someangles have been entered into the write() Python functions as legalvariable names instead of floats. In the English file, you will see those legalnames whe...
from qubiter.SEO_writer import * from qubiter.SEO_reader import * from qubiter.EchoingSEO_reader import * from qubiter.SEO_simulator import * num_bits = 4 file_prefix = 'placeholder_test' emb = CktEmbedder(num_bits, num_bits) wr = SEO_writer(file_prefix, emb) wr.write_Rx(2, rads=np.pi/7) wr.write_Rx(1, rads='#2*.5') wr...
_____no_output_____
Apache-2.0
qubiter/jupyter_notebooks/examples_of_placeholder_usage.ipynb
yourball/qubiter
The following 2 files were just written:1. ../io_folder/placeholder_test_4_eng.txt2. ../io_folder/placeholder_test_4_ZLpic.txt Simply by creating an object of the class SEO_reader with the flag `write_log` set equal to True, you can create a log file which contains * a list of distinct variable numbers * a list of dist...
rdr = SEO_reader(file_prefix, num_bits, write_log=True)
_____no_output_____
Apache-2.0
qubiter/jupyter_notebooks/examples_of_placeholder_usage.ipynb
yourball/qubiter
The following log file was just written: ../io_folder/placeholder_test_4_log.txt Next, let us create two functions that will be used for the functional placeholders
def my_fun1(x): return x*.5 def my_fun2(x, y): return x + y
_____no_output_____
Apache-2.0
qubiter/jupyter_notebooks/examples_of_placeholder_usage.ipynb
yourball/qubiter
**Partial Substitution**This creates new fileswith `1=30`, `2=60`, `'my_fun1'->my_fun1`,but `3` and `'my_fun2'` still undecided
vman = PlaceholderManager(eval_all_vars=False, var_num_to_rads={1: np.pi/6, 2: np.pi/3}, fun_name_to_fun={'my_fun1': my_fun1}) wr = SEO_writer(file_prefix + '_eval01', emb) EchoingSEO_reader(file_prefix, num_bits, wr, vars_manager=vman)
_____no_output_____
Apache-2.0
qubiter/jupyter_notebooks/examples_of_placeholder_usage.ipynb
yourball/qubiter
The following 2 files were just written:1. ../io_folder/placeholder_test_eval01_4_eng.txt2. ../io_folder/placeholder_test_eval01_4_ZLpic.txt The following code runs the simulator after substituting`1=30`, `2=60`, `3=90`, `'my_fun1'->my_fun1`, `'my_fun2'->my_fun2`
vman = PlaceholderManager( var_num_to_rads={1: np.pi/6, 2: np.pi/3, 3: np.pi/2}, fun_name_to_fun={'my_fun1': my_fun1, 'my_fun2': my_fun2} ) sim = SEO_simulator(file_prefix, num_bits, verbose=False, vars_manager=vman) StateVec.describe_st_vec_dict(sim.cur_st_vec_dict)
*********branch= pure total probability of state vector (=one if no measurements)= 1.0000000000000004 dictionary with key=qubit, value=(Prob(0), Prob(1)) {0: (1.0000000000000004, -4.440892098500626e-16), 1: (0.7500000000000002, 0.24999999999999978), 2: (0.811744900929367, 0.18825509907063298), 3: (0.6235127414399703...
Apache-2.0
qubiter/jupyter_notebooks/examples_of_placeholder_usage.ipynb
yourball/qubiter
The art of using pipelines Pipelines are a natural way to think about a machine learning system. Indeed with some practice a data scientist can visualise data "flowing" through a series of steps. The input is typically some raw data which has to be processed in some manner. The goal is to represent the data in such a ...
from pprint import pprint from river import datasets for x, y in datasets.Restaurants(): pprint(x) pprint(y) break
{'area_name': 'Tōkyō-to Nerima-ku Toyotamakita', 'date': datetime.datetime(2016, 1, 1, 0, 0), 'genre_name': 'Izakaya', 'is_holiday': True, 'latitude': 35.7356234, 'longitude': 139.6516577, 'store_id': 'air_04341b588bde96cd'} 10
BSD-3-Clause
docs/examples/the-art-of-using-pipelines.ipynb
dataJSA/river
We'll start by building and running a model using a procedural coding style. The performance of the model doesn't matter, we're simply interested in the design of the model.
from river import feature_extraction from river import linear_model from river import metrics from river import preprocessing from river import stats means = ( feature_extraction.TargetAgg(by='store_id', how=stats.RollingMean(7)), feature_extraction.TargetAgg(by='store_id', how=stats.RollingMean(14)), feat...
MAE: 8.465114
BSD-3-Clause
docs/examples/the-art-of-using-pipelines.ipynb
dataJSA/river
We're not using many features. We can print the last `x` to get an idea of the features (don't forget they've been scaled!)
pprint(x)
{'is_holiday': -0.23103573677646685, 'is_weekend': 1.6249280076334165, 'weekday': 1.0292832579142892, 'y_rollingmean_14_by_store_id': -1.4125913815779154, 'y_rollingmean_21_by_store_id': -1.3980979075298519, 'y_rollingmean_7_by_store_id': -1.3502314499809096}
BSD-3-Clause
docs/examples/the-art-of-using-pipelines.ipynb
dataJSA/river
The above chunk of code is quite explicit but it's a bit verbose. The whole point of libraries such as `river` is to make life easier for users. Moreover there's too much space for users to mess up the order in which things are done, which increases the chance of there being target leakage. We'll now rewrite our model ...
from river import compose def get_date_features(x): weekday = x['date'].weekday() return {'weekday': weekday, 'is_weekend': weekday in (5, 6)} model = compose.Pipeline( ('features', compose.TransformerUnion( ('date_features', compose.FuncTransformer(get_date_features)), ('last_7_mean', ...
MAE: 8.38533
BSD-3-Clause
docs/examples/the-art-of-using-pipelines.ipynb
dataJSA/river
We use a `Pipeline` to arrange each step in a sequential order. A `TransformerUnion` is used to merge multiple feature extractors into a single transformer. The `for` loop is now much shorter and is thus easier to grok: we get the out-of-fold prediction, we fit the model, and finally we update the metric. This way of e...
from river import evaluate model = compose.Pipeline( ('features', compose.TransformerUnion( ('date_features', compose.FuncTransformer(get_date_features)), ('last_7_mean', feature_extraction.TargetAgg(by='store_id', how=stats.RollingMean(7))), ('last_14_mean', feature_extraction.TargetAgg(by...
_____no_output_____
BSD-3-Clause
docs/examples/the-art-of-using-pipelines.ipynb
dataJSA/river
Notice that you couldn't have used the `progressive_val_score` method if you wrote the model in a procedural manner.Our code is getting shorter, but it's still a bit difficult on the eyes. Indeed there is a lot of boilerplate code associated with pipelines that can get tedious to write. However `river` has some special...
model = compose.Pipeline( compose.TransformerUnion( compose.FuncTransformer(get_date_features), feature_extraction.TargetAgg(by='store_id', how=stats.RollingMean(7)), feature_extraction.TargetAgg(by='store_id', how=stats.RollingMean(14)), feature_extraction.TargetAgg(by='store_id', h...
_____no_output_____
BSD-3-Clause
docs/examples/the-art-of-using-pipelines.ipynb
dataJSA/river
Under the hood a `Pipeline` inherits from `collections.OrderedDict`. Indeed this makes sense because if you think about it a `Pipeline` is simply a sequence of steps where each step has a name. The reason we mention this is because it means you can manipulate a `Pipeline` the same way you would manipulate an ordinary `...
for name in model.steps: print(name)
TransformerUnion Discard StandardScaler LinearRegression
BSD-3-Clause
docs/examples/the-art-of-using-pipelines.ipynb
dataJSA/river
The first step is a `FeatureUnion` and it's string representation contains the string representation of each of it's elements. Not having to write names saves up some time and space and is certainly less tedious.The next trick is that we can use mathematical operators to compose our pipeline. For example we can use the...
model = compose.Pipeline( compose.FuncTransformer(get_date_features) + \ feature_extraction.TargetAgg(by='store_id', how=stats.RollingMean(7)) + \ feature_extraction.TargetAgg(by='store_id', how=stats.RollingMean(14)) + \ feature_extraction.TargetAgg(by='store_id', how=stats.RollingMean(21)), compo...
_____no_output_____
BSD-3-Clause
docs/examples/the-art-of-using-pipelines.ipynb
dataJSA/river
Likewhise we can use the `|` operator to assemble steps into a `Pipeline`.
model = ( compose.FuncTransformer(get_date_features) + feature_extraction.TargetAgg(by='store_id', how=stats.RollingMean(7)) + feature_extraction.TargetAgg(by='store_id', how=stats.RollingMean(14)) + feature_extraction.TargetAgg(by='store_id', how=stats.RollingMean(21)) ) to_discard = ['store_id', 'dat...
_____no_output_____
BSD-3-Clause
docs/examples/the-art-of-using-pipelines.ipynb
dataJSA/river
Hopefully you'll agree that this is a powerful way to express machine learning pipelines. For some people this should be quite remeniscent of the UNIX pipe operator. One final trick we want to mention is that functions are automatically wrapped with a `FuncTransformer`, which can be quite handy.
model = get_date_features for n in [7, 14, 21]: model += feature_extraction.TargetAgg(by='store_id', how=stats.RollingMean(n)) model |= compose.Discard(*to_discard) model |= preprocessing.StandardScaler() model |= linear_model.LinearRegression() evaluate.progressive_val_score(datasets.Restaurants(), model, metri...
_____no_output_____
BSD-3-Clause
docs/examples/the-art-of-using-pipelines.ipynb
dataJSA/river
Naturally some may prefer the procedural style we first used because they find it easier to work with. It all depends on your style and you should use what you feel comfortable with. However we encourage you to use operators because we believe that this will increase the readability of your code, which is very importan...
model
_____no_output_____
BSD-3-Clause
docs/examples/the-art-of-using-pipelines.ipynb
dataJSA/river
Reflect Tables into SQLAlchemy ORM
# Python SQL toolkit and Object Relational Mapper import sqlalchemy from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import Session from sqlalchemy import create_engine, func engine = create_engine("sqlite:///Resources/hawaii.sqlite") # reflect an existing database into a new model Base = automap_ba...
_____no_output_____
MIT
climate_starter.ipynb
ahchambers/sqlalchemy-challenge
Exploratory Climate Analysis
# Design a query to retrieve the last 12 months of precipitation data and plot the results # Calculate the date 1 year ago from the last data point in the database last_year = dt.date(2017, 8, 23) - dt.timedelta(days=365) # Perform a query to retrieve the data and precipitation scores results = session.query(measurem...
_____no_output_____
MIT
climate_starter.ipynb
ahchambers/sqlalchemy-challenge
Photometric PluginFor optical photometry, we provide the **PhotometryLike** plugin that handles forward folding of a spectral model through filter curves. Let's have a look at the avaiable procedures.
import numpy as np import matplotlib.pyplot as plt %matplotlib inline from threeML import * # we will need XPSEC models for extinction from astromodels.xspec import * # The filter library takes a while to load so you must import it explicitly.. from threeML.plugins.photometry.filter_library import threeML_filter_li...
_____no_output_____
BSD-3-Clause
examples/Photometry_demo.ipynb
ke-fang/3ML
SetupWe use [speclite](http://speclite.readthedocs.io/en/latest/ ) to handle optical filters.Therefore, you can easily build your own custom filters, use the built in speclite filters, or use the 3ML filter library that we have built thanks to [Spanish Virtual Observatory](http://svo.cab.inta-csic.es/main/index.php). ...
import speclite.filters as spec_filters my_backyard_telescope_filter = spec_filters.load_filter('bessell-r') # NOTE: my_backyard_telescope_filter.name
_____no_output_____
BSD-3-Clause
examples/Photometry_demo.ipynb
ke-fang/3ML
NOTE: the filter name is 'bessell-R'. The plugin will look for the name *after* the **'-'** i.e 'R'Now let's build a 3ML plugin via **PhotometryLike**. Our data are entered as keywords with the name of the filter as the keyword and the data in an magnitude,error tuple, i.e. R=(mag,mag_err):
my_backyard_telescope = PhotometryLike('backyard_astronomy', filters=my_backyard_telescope_filter, # the filter R=(20,.1) ) # the magnitude and error my_backyard_telescope.display_filters()
Using Gaussian statistic (equivalent to chi^2) with the provided errors.
BSD-3-Clause
examples/Photometry_demo.ipynb
ke-fang/3ML
3ML filter libraryExplore the filter library. If you cannot find what you need, it is simple to add your own
threeML_filter_library.SLOAN spec_filters.plot_filters(threeML_filter_library.SLOAN.SDSS) spec_filters.plot_filters(threeML_filter_library.Herschel.SPIRE) spec_filters.plot_filters(threeML_filter_library.Keck.NIRC2)
_____no_output_____
BSD-3-Clause
examples/Photometry_demo.ipynb
ke-fang/3ML
Build your own filtersFollowing the example from speclite, we can build our own filters and add them:
fangs_g = spec_filters.FilterResponse( wavelength = [3800, 4500, 5200] * u.Angstrom, response = [0, 0.5, 0], meta=dict(group_name='fangs', band_name='g')) fangs_r = spec_filters.FilterResponse( wavelength = [4800, 5500, 6200] * u.Angstrom, response = [0, 0.5, 0], meta=dict(group_name='fangs', band_name=...
Using Gaussian statistic (equivalent to chi^2) with the provided errors.
BSD-3-Clause
examples/Photometry_demo.ipynb
ke-fang/3ML
GROND ExampleNow we will look at GROND. We get the filter from the 3ML filter library.(Just play with tab completion to see what is available!)
grond = PhotometryLike('GROND', filters=threeML_filter_library.ESO.GROND, #g=(21.5.93,.23), # we exclude these filters #r=(22.,0.12), i=(21.8,.01), z=(21.2,.01), J=(19.6,.01), ...
_____no_output_____
BSD-3-Clause
examples/Photometry_demo.ipynb
ke-fang/3ML
Model specificationHere we use XSPEC's dust extinction models for the milky way and the host
spec = Powerlaw() * XS_zdust() * XS_zdust() data_list = DataList(grond) model = Model(PointSource('grb',0,0,spectral_shape=spec)) spec.piv_1 = 1E-2 spec.index_1.fix=False spec.redshift_2 = 0.347 spec.redshift_2.fix = True spec.e_bmv_2 = 5./2.93 spec.e_bmv_2.fix = True spec.rv_2 = 2.93 spec.rv_2.fix = True spec.m...
_____no_output_____
BSD-3-Clause
examples/Photometry_demo.ipynb
ke-fang/3ML
We compute $m_{\rm AB}$ from astromodels photon fluxes. This is done by convolving the differential flux over the filter response:$ F[R,f_\lambda] \equiv \int_0^\infty \frac{dg}{d\lambda}(\lambda)R(\lambda) \omega(\lambda) d\lambda$where we have converted the astromodels functions to wavelength properly.
_ = jl.fit()
Best fit values:
BSD-3-Clause
examples/Photometry_demo.ipynb
ke-fang/3ML
We can now look at the fit in magnitude space or model space as with any plugin.
_=display_photometry_model_magnitudes(jl) _ = plot_point_source_spectra(jl.results,flux_unit='erg/(cm2 s keV)', xscale='linear', energy_unit='nm',ene_min=1E3, ene_max=1E5, num_ene=200 )
_____no_output_____
BSD-3-Clause
examples/Photometry_demo.ipynb
ke-fang/3ML
Copyright 2018 The TensorFlow Authors.
#@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under...
_____no_output_____
Apache-2.0
lite/examples/gesture_classification/ml/tensorflowjs_to_tflite_colab_notebook.ipynb
hawk-praxs/examples
Tensorflow Lite Gesture Classification Example Conversion ScriptThis guide shows how you can go about converting the model trained with TensorFlowJS to TensorFlow Lite FlatBuffers.Run all steps in-order. At the end, `model.tflite` file will be downloaded. Run in Google Colab View source on...
!pip3 install tensorflow==1.14.0 keras==2.2.4 tensorflowjs==0.6.4 --force-reinstall import traceback import logging import tensorflow.compat.v1 as tf import keras.backend as K import os from google.colab import files from keras import Model, Input from keras.applications import MobileNet from keras.engine.saving impo...
_____no_output_____
Apache-2.0
lite/examples/gesture_classification/ml/tensorflowjs_to_tflite_colab_notebook.ipynb
hawk-praxs/examples
***Cleanup any existing models if necessary***
!rm -rf *.h5 *.tflite *.json *.bin
_____no_output_____
Apache-2.0
lite/examples/gesture_classification/ml/tensorflowjs_to_tflite_colab_notebook.ipynb
hawk-praxs/examples
**Upload your Tensorflow.js Artifacts Here**i.e., The weights manifest **model.json** and the binary weights file **model-weights.bin**
files.upload()
_____no_output_____
Apache-2.0
lite/examples/gesture_classification/ml/tensorflowjs_to_tflite_colab_notebook.ipynb
hawk-praxs/examples
**Export Configuration**
#@title Export Configuration # TensorFlow.js arguments config_json = "model.json" #@param {type:"string"} weights_path_prefix = None #@param {type:"raw"} model_tflite = "model.tflite" #@param {type:"string"}
_____no_output_____
Apache-2.0
lite/examples/gesture_classification/ml/tensorflowjs_to_tflite_colab_notebook.ipynb
hawk-praxs/examples
**Model Converter**The following class converts a TensorFlow.js model to a TFLite FlatBuffer
class ModelConverter: """ Creates a ModelConverter class from a TensorFlow.js model file. Args: :param config_json_path: Full filepath of weights manifest file containing the model architecture. :param weights_path_prefix: Full filepath to the directory in which the weights binaries exist. ...
_____no_output_____
Apache-2.0
lite/examples/gesture_classification/ml/tensorflowjs_to_tflite_colab_notebook.ipynb
hawk-praxs/examples
Generate dataset
np.random.seed(12) y = np.random.randint(0,10,5000) idx= [] for i in range(10): print(i,sum(y==i)) idx.append(y==i) x = np.zeros((5000,2)) np.random.seed(12) x[idx[0],:] = np.random.multivariate_normal(mean = [5,5],cov=[[0.1,0],[0,0.1]],size=sum(idx[0])) x[idx[1],:] = np.random.multivariate_normal(mean = [-6,7]...
_____no_output_____
MIT
AAAI/Learnability/CIN/Linear/ds2/size_100/synthetic_type2_Linear_m_50.ipynb
lnpandey/DL_explore_synth_data
Introduction to Convolutional Neural Networks (CNNs) in PyTorch Representing images digitallyWhile convolutional neural networks (CNNs) see a wide variety of uses, they were originally designed for images, and CNNs are still most commonly used for vision-related tasks.For today, we'll primarily be focusing on CNNs fo...
%matplotlib inline import imageio import matplotlib.pyplot as plt # Read the image "./Figures/chapel.jpg" from the disk. # Hint: use `im = imageio.imread(<Path to the image>)`. # Print the shape of the tensor # Display the image
_____no_output_____
MIT
day2_student_notebook.ipynb
dukeplusds/mlwscv2002
We can see that the image we loaded has height and width of $620 \times 1175$, with 3 channels corresponding to RGB.We can easily slice out and view individual color channels:
# Uncomment the following command to extract the red channel of the above image. # im_red = im[:,:,0] # Display the image # Hint: To display the pixel values for a single channel, we can display the image using the gray-scale colormap # Repeat the above for the blue channel to visualize features represented in the blu...
_____no_output_____
MIT
day2_student_notebook.ipynb
dukeplusds/mlwscv2002
While we have so far considered only 3 channel RGB images, there are many settings in which we may consider a different number of channels.For example, [hyperspectral imaging](https://en.wikipedia.org/wiki/Hyperspectral_imaging) uses a wide range of the electromagnetic spectrum to characterize a scene.Such modalities m...
import numpy as np # PyTorch Imports ################################################## # # # ---- YOUR CODE HERE ---- # # # ##################################################
_____no_output_____
MIT
day2_student_notebook.ipynb
dukeplusds/mlwscv2002
Review: Fully connected layerIn a fully connected layer, the input $x \in \mathbb R^{M \times C_{in}}$ is a vector (or, rather a batch of vectors), where $M$ is the minibatch size and $C_{in}$ is the dimensionality of the input. We first matrix multiply the input $x$ by a weight matrix $W$.This weight matrix has dimen...
# Create a random flat input vector x_fc = torch.randn(100, 1024) # Create weight matrix variable W = torch.randn(1024, 10)/np.sqrt(1024) # Create bias variable b = torch.zeros(10, requires_grad=True) # Use `W` and `b` to apply a fully connected layer. # Store the output in variable `y`. # Don't forget to apply the...
_____no_output_____
MIT
day2_student_notebook.ipynb
dukeplusds/mlwscv2002
Convolutional layerIn a convolutional layer, we convolve the input $x$ with a convolutional kernel (aka filter), which we also call $W$, producing output $y$:\begin{align*}y = \text{ReLU}(W*x + b)\end{align*}In the context of CNNs, the output $y$ is often referred to as feature maps. As with a fully connected layer, t...
# Create a random 4D tensor. Use the NCHW format, where N = 100, C = 3, H = W =32 x_cnn = # Create convolutional kernel variable (C_out, C_in, H_k, W_k) W1 = # Create a bias variable of size C_out b1 = # Apply the convolutional layer with relu activation conv1 = # Print input/output shape print("Input shape: {}...
_____no_output_____
MIT
day2_student_notebook.ipynb
dukeplusds/mlwscv2002
Just like in a MLP, we can stack multiple of these convolutional layers. In the *Representing Images Digitally* section, we briefly mentioned considering images with channels more than 3.Observe that the input to the second layer (i.e. the output of the first layer) can be viewed as an "image" with $C_{out}$ channels.I...
# Create the second convolutional layer by defining a random `W2` and `b2` W2 = b2 = # Apply 2nd convolutional layer to the output of the first convolutional layer conv2 = # Print output shape print("Second convolution output shape: {}".format(conv2.shape))
_____no_output_____
MIT
day2_student_notebook.ipynb
dukeplusds/mlwscv2002
In fact, we typically perform these convolution operations many times. Popular CNN architectures for image analysis today can be 100+ layers. ReshapingYou'll commonly finding yourself needing to reshape tensors while building CNNs.The PyTorch function for doing so is `view()`. Anyone familiar with NumPy will find it v...
M = torch.zeros(4, 3) M2 = M.view(1,1,12) M3 = M.view(2,1,2,3) M4 = M.view(-1,2,3) M5 = M.view(-1)
_____no_output_____
MIT
day2_student_notebook.ipynb
dukeplusds/mlwscv2002
To get an idea of why reshaping is need in a CNN, let's look at a diagram of a simple CNN.First of all, the CNN expects a 4D input, with the dimensions corresponding to `[batch, channel, height, width]`.Your data may not come in this format, so you may have to reshape it yourself.
x_flat = torch.randn(100, 1024) # Reshape flat input image into a 4D batched image input # Hint: Use batch=100, height=width=32. x_reshaped = # Print input shape print(x_reshaped.shape)
_____no_output_____
MIT
day2_student_notebook.ipynb
dukeplusds/mlwscv2002
CNN architectures also commonly contain fully connected layers or a softmax, as we're often interested in classification.Both of these expect 2D inputs with dimensions `[batch, dim]`, so you have to "flatten" a CNN's 4D output to 2D.For example, to flatten the convolutional feature maps we created earlier:
# Flatten convolutional feature maps into a vector h_flat = conv2.view(-1, 32*32*32) # Print output shape print(h_flat.shape)
_____no_output_____
MIT
day2_student_notebook.ipynb
dukeplusds/mlwscv2002
Pooling and stridingAlmost all CNN architectures incorporate either pooling or striding. This is done for a number of reasons, including:- Dimensionality reduction: pooling and striding operations reduces computational complexity by shrinking the number of values passed to the next layer.For example, a 2x2 maxpool red...
# Recreate the values in pooling figure with shape [4,4] feature_map_fig = # Convert 2D matrix to a 4D tensor of shape [1,1,4,4]. fmap_fig = print("Feature map shape pre-pooling: {}".format(fmap_fig.shape)) # Apply max pool to fmap_fig max_pool_fig = print("\nMax pool") print("Shape: {}".format(max_pool_fig.shap...
_____no_output_____
MIT
day2_student_notebook.ipynb
dukeplusds/mlwscv2002
Now we will apply max pool and average pool to the output of the convolutional layer `conv2`.
# Taking the output we've been working with so far, first print its current size print("Shape of conv2 feature maps before pooling: {0}".format(conv2.shape)) # Apply Max pool with size = 2 and then print new shape. max_pool2 = print("Shape of conv2 feature maps after max pooling: {0}".format(max_pool2.shape)) # Aver...
_____no_output_____
MIT
day2_student_notebook.ipynb
dukeplusds/mlwscv2002
StridingOne might expect that pixels in an image have high correlation with neighboring pixels, so we can save computation by skipping positions while sliding the convolutional kernel. By default, a CNN slides across the input one pixel at a time, which we call a stride of 1.By instead striding by 2, we skip calculati...
# Since striding is part of the convolution operation, we'll start with the feature maps before the 2nd convolution print("Shape of conv1 feature maps: {0}".format(conv1.shape)) # Apply 2nd convolutional layer, with striding of 2 conv2_strided = # Print output shape print("Shape of conv2 feature maps with stride of ...
_____no_output_____
MIT
day2_student_notebook.ipynb
dukeplusds/mlwscv2002
Building a custom CNN Let's revisit MNIST digit classification, but this time, we'll use the following CNN as our classifier: $5 \times 5$ convolution -> $2 \times 2$ max pool -> $5 \times 5$ convolution -> $2 \times 2$ max pool -> fully connected to $\mathbb R^{256}$ -> fully connected to $\mathbb R^{10}$ (prediction...
import torch.nn as nn # Important: Inherit the `nn.Module` class to define a PyTorch model class CIFAR_CNN(): def __init__(self): super().__init__() # Step 1: Define the first convoluation layer (C_in=3, C_out=32, H_k=W_k=5, padding = 2) self.conv1 = # Step 2: Def...
_____no_output_____
MIT
day2_student_notebook.ipynb
dukeplusds/mlwscv2002
Notice how our `nn.Module` contains several operation chained together.The code for submodule initialization, which creates all the stateful parameters associated with each operation, is placed in the `__init__()` function, where it is run once during object instantiation.Meanwhile, the code describing the forward pass...
model = CIFAR_CNN() print(model)
_____no_output_____
MIT
day2_student_notebook.ipynb
dukeplusds/mlwscv2002
We can drop this model into our logistic regression training code, with few modifications beyond changing the model itself.A few other changes:- CNNs expect a 4-D input, so we no longer have to reshape the images before feeding them to our neural network.- Since CNNs are a little more complex than models we've worked w...
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torchvision import datasets, transforms from tqdm.notebook import tqdm, trange cifar_train = datasets.CIFAR10(root="./datasets/cifar-10/", train=True, transform=transforms.ToTensor(), download=True) cifar_test = datasets.CIFAR10...
_____no_output_____
MIT
day2_student_notebook.ipynb
dukeplusds/mlwscv2002
Let's plot the loss function
################################################## # # # ---- YOUR CODE HERE ---- # # # ##################################################
_____no_output_____
MIT
day2_student_notebook.ipynb
dukeplusds/mlwscv2002
Testing the trained model
## Testing correct = 0 total = len(cifar_test) with torch.no_grad(): # Iterate through test set minibatchs for images, labels in tqdm(test_loader): # Step 1: Forward pass to get y = # Step 2: Compute the predicted labels from `y`. predictions = ...
_____no_output_____
MIT
day2_student_notebook.ipynb
dukeplusds/mlwscv2002
If you are running this notebook on CPU, training this CNN might take a while.On the other hand, if you use a GPU, this model should train in seconds.This is why we usually prefer to use GPUs when we have them. Torchvision Datasets and transformsAs any experienced ML practioner will say, data wrangling is often half ...
from torchvision import datasets mnist_train = datasets.CIFAR10(root="./datasets", train=True, transform=transforms.ToTensor(), download=True)
_____no_output_____
MIT
day2_student_notebook.ipynb
dukeplusds/mlwscv2002
Of course, there's [many more](https://pytorch.org/vision/stable/datasets.html).Currently, datasets for image classification (e.g. MNIST, CIFAR, ImageNet), object detection (VOC, COCO, Cityscapes), and video action recognition (UCF101, Kinetics) are included.For formatting, pre-processing, and augmenting, [transforms](...
import torchvision.models as models resnet18 = models.resnet18() print(resnet18)
_____no_output_____
MIT
day2_student_notebook.ipynb
dukeplusds/mlwscv2002
gpu info
gtx950 = DeviceInfo() gtx950.sm_num = 6 gtx950.sharedmem_per_sm = 49152 gtx950.reg_per_sm = 65536 gtx950.maxthreads_per_sm = 2048
_____no_output_____
MIT
mem_mem/t2-cke.ipynb
3upperm2n/trans_kernel_model
single stream info
data_size = 23000 trace_file = './1cke/trace_' + str(data_size) + '.csv' df_trace = trace2dataframe(trace_file) # read the trace to the dataframe df_trace df_single_stream = model_param_from_trace_v1(df_trace) df_single_stream.head(20) df_s1 = reset_starting(df_single_stream) df_s1
_____no_output_____
MIT
mem_mem/t2-cke.ipynb
3upperm2n/trans_kernel_model
running 2cke case
stream_num = 2 df_cke_list = [] for x in range(stream_num): df_cke_list.append(df_s1.copy(deep=True)) df_cke_list[0] df_cke_list[1] H2D_H2D_OVLP_TH = 3.158431 for i in range(1,stream_num): # compute the time for the init data transfer stream_startTime = find_whentostart_comingStream(df_cke_list[i-1], H2D_...
_____no_output_____
MIT
mem_mem/t2-cke.ipynb
3upperm2n/trans_kernel_model
check whether there is h2d overlapping
prev_stm_h2ds_start, prev_stm_h2ds_end = find_h2ds_timing(df_cke_list[0]) print("prev stream h2ds : {} - {}".format(prev_stm_h2ds_start, prev_stm_h2ds_end)) curr_stm_h2ds_start, curr_stm_h2ds_end = find_h2ds_timing(df_cke_list[1]) print("curr stream h2ds : {} - {}".format(curr_stm_h2ds_start, curr_stm_h2ds_end)) if cu...
h2ds_ovlp_between_stream : False
MIT
mem_mem/t2-cke.ipynb
3upperm2n/trans_kernel_model
check kernel overlapping
prev_stm_kern_start, prev_stm_kern_end = find_kern_timing(df_cke_list[0]) print("prev stream kern : {} - {}".format(prev_stm_kern_start, prev_stm_kern_end)) curr_stm_kern_start, curr_stm_kern_end = find_kern_timing(df_cke_list[1]) print("curr stream kern : {} - {}".format(curr_stm_kern_start, curr_stm_kern_end)) if ...
kern_ovlp_between_stream : True
MIT
mem_mem/t2-cke.ipynb
3upperm2n/trans_kernel_model
use cke model if kern_ovlp_between_stream is true
# get the overlapping kernel info from both stream kernel_ = model_cke_from_same_kernel(gtx950, df_trace, )
_____no_output_____
MIT
mem_mem/t2-cke.ipynb
3upperm2n/trans_kernel_model
Reflect Tables into SQLAlchemy ORM
# Python SQL toolkit and Object Relational Mapper import sqlalchemy from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import Session from sqlalchemy import create_engine, func engine = create_engine("sqlite:///Resources/hawaii.sqlite") # reflect an existing database into a new model Base = automap_bas...
_____no_output_____
ADSL
sql_alchemy.ipynb
Yuva38/sqlalchemy-challenge
Exploratory Climate Analysis using pandas
# Design a query to retrieve the last 12 months of precipitation data and plot the results # Calculate the date 1 year ago from the last data point in the database # Perform a query to retrieve the data and precipitation scores # Save the query results as a Pandas DataFrame and set the index to the date column # So...
_____no_output_____
ADSL
sql_alchemy.ipynb
Yuva38/sqlalchemy-challenge
Tutorial - Time Series Forecasting - Autoregression (AR)The goal is to forecast time series with the Autoregression (AR) Approach. 1) JetRail Commuter, 2) Air Passengers, 3) Function Autoregression with Air Passengers, and 5) Function Autoregression with Wine Sales.References Jason Brownlee - https://machinelearningma...
import pandas as pd import numpy as np import matplotlib.pyplot as plt import datetime import warnings warnings.filterwarnings("ignore") # Load File url = 'https://raw.githubusercontent.com/tristanga/Machine-Learning/master/Data/JetRail%20Avg%20Hourly%20Traffic%20Data%20-%202012-2013.csv' df = pd.read_csv(url) df.inf...
_____no_output_____
MIT
Time Series Analysis/Time Series Forecasting - Autoregression (AR)/Autoregression (AR).ipynb
shreejitverma/Data-Scientist
Autoregression (AR) Approach with JetRail The autoregression (AR) method models the next step in the sequence as a linear function of the observations at prior time steps.The notation for the model involves specifying the order of the model p as a parameter to the AR function, e.g. AR(p). For example, AR(1) is a first...
#Split Train Test import math total_size=len(df) split = 10392 / 11856 train_size=math.floor(split*total_size) train=df.head(train_size) test=df.tail(len(df) -train_size) from statsmodels.tsa.ar_model import AR model = AR(train.Count) fit1 = model.fit() y_hat = test.copy() y_hat['AR'] = fit1.predict(start=len(train), e...
_____no_output_____
MIT
Time Series Analysis/Time Series Forecasting - Autoregression (AR)/Autoregression (AR).ipynb
shreejitverma/Data-Scientist
RMSE Calculation
from sklearn.metrics import mean_squared_error from math import sqrt rms = sqrt(mean_squared_error(test.Count, y_hat.AR)) print('RMSE = '+str(rms))
RMSE = 28.635096626807453
MIT
Time Series Analysis/Time Series Forecasting - Autoregression (AR)/Autoregression (AR).ipynb
shreejitverma/Data-Scientist
Autoregression (AR) Approach with Air Passagers
# Subsetting url = 'https://raw.githubusercontent.com/tristanga/Machine-Learning/master/Data/International%20Airline%20Passengers.csv' df = pd.read_csv(url, sep =";") df.info() df.Month = pd.to_datetime(df.Month,format='%Y-%m') df.index = df.Month #df.head() #Creating train and test set import math total_size=len(df) ...
RMSE = 60.13838110500644
MIT
Time Series Analysis/Time Series Forecasting - Autoregression (AR)/Autoregression (AR).ipynb
shreejitverma/Data-Scientist
Function Autoregression (AR) Approach with variables
def AR_forecasting(mydf,colval,split): #print(split) import math from statsmodels.tsa.api import Holt from sklearn.metrics import mean_squared_error from math import sqrt global y_hat, train, test total_size=len(mydf) train_size=math.floor(split*total_size) #(70% Dataset) train=mydf....
_____no_output_____
MIT
Time Series Analysis/Time Series Forecasting - Autoregression (AR)/Autoregression (AR).ipynb
shreejitverma/Data-Scientist
Testing Function Autoregression (AR) Approach with Wine Dataset
url = 'https://raw.githubusercontent.com/tristanga/Data-Cleaning/master/Converting%20Time%20Series/Wine_Sales_R_Dataset.csv' df = pd.read_csv(url) df.info() df.Date = pd.to_datetime(df.Date,format='%Y-%m-%d') df.index = df.Date AR_forecasting(df,'Sales',0.7)
_____no_output_____
MIT
Time Series Analysis/Time Series Forecasting - Autoregression (AR)/Autoregression (AR).ipynb
shreejitverma/Data-Scientist
import numpy as np # Vector 1-D array a = [1,2,3] a = a + [1] print(a) # Numpy array 1-D b = np.array([4,5,6]) b = np.append(b,[7]) A = np.array([[1,22,3],[4,5,6],[111,-11,33]]) B = np.array([[10,11,12],[13,14,15],[14,7,2.5]]) A.shape sum = np.sum(np.dot(A,B)) print(sum) sum.dtype C = np.arr...
[[[0 0 0] [0 0 0] [0 0 0]] [[0 0 0] [0 0 0] [0 0 0]] [[0 0 0] [0 0 0] [0 0 0]] [[0 0 0] [0 0 0] [0 0 0]]] Number of Dimensions 3 Size of Array 36
MIT
numpy.ipynb
OmidMustafa/XOR_python
Copyright 2019 The TensorFlow Authors.
#@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under...
_____no_output_____
Apache-2.0
site/it/tutorials/quickstart/advanced.ipynb
justaverygoodboy/docs-l10n
Introduzione a TensorFlow 2 per esperti Visualizza su TensorFlow.org Esegui in Google Colab Visualizza il sorgente su GitHub Scarica il notebook Note: La nostra comunità di Tensorflow ha tradotto questi documenti. Poichè queste traduzioni sono *best-effort*, non è garantito che rispecchino...
import tensorflow as tf from tensorflow.keras.layers import Dense, Flatten, Conv2D from tensorflow.keras import Model
_____no_output_____
Apache-2.0
site/it/tutorials/quickstart/advanced.ipynb
justaverygoodboy/docs-l10n
Carica e prepara il [dataset MNIST](http://yann.lecun.com/exdb/mnist/).
mnist = tf.keras.datasets.mnist (x_train, y_train), (x_test, y_test) = mnist.load_data() x_train, x_test = x_train / 255.0, x_test / 255.0 # Add a channels dimension x_train = x_train[..., tf.newaxis] x_test = x_test[..., tf.newaxis]
_____no_output_____
Apache-2.0
site/it/tutorials/quickstart/advanced.ipynb
justaverygoodboy/docs-l10n
Usa `tf.data` per raggruppare e mischiare il dataset:
train_ds = tf.data.Dataset.from_tensor_slices( (x_train, y_train)).shuffle(10000).batch(32) test_ds = tf.data.Dataset.from_tensor_slices((x_test, y_test)).batch(32)
_____no_output_____
Apache-2.0
site/it/tutorials/quickstart/advanced.ipynb
justaverygoodboy/docs-l10n
Costrusci il modello `tf.keras` usando l'[API Keras per creare sottoclassi di modelli](https://www.tensorflow.org/guide/kerasmodel_subclassing):
class MyModel(Model): def __init__(self): super(MyModel, self).__init__() self.conv1 = Conv2D(32, 3, activation='relu') self.flatten = Flatten() self.d1 = Dense(128, activation='relu') self.d2 = Dense(10, activation='softmax') def call(self, x): x = self.conv1(x) x = self.flatten(x) ...
_____no_output_____
Apache-2.0
site/it/tutorials/quickstart/advanced.ipynb
justaverygoodboy/docs-l10n
Scegli un metodo di ottimizzazione e una funzione obiettivo per l'addestramento:
loss_object = tf.keras.losses.SparseCategoricalCrossentropy() optimizer = tf.keras.optimizers.Adam()
_____no_output_____
Apache-2.0
site/it/tutorials/quickstart/advanced.ipynb
justaverygoodboy/docs-l10n
Seleziona delle metriche per misurare la pertita e l'accuratezza del modello. Queste metriche accumulano i valori alle varie epoche e alla fine stampano il risultato globale.
train_loss = tf.keras.metrics.Mean(name='train_loss') train_accuracy = tf.keras.metrics.SparseCategoricalAccuracy(name='train_accuracy') test_loss = tf.keras.metrics.Mean(name='test_loss') test_accuracy = tf.keras.metrics.SparseCategoricalAccuracy(name='test_accuracy')
_____no_output_____
Apache-2.0
site/it/tutorials/quickstart/advanced.ipynb
justaverygoodboy/docs-l10n
Usa `tf.GradientTape` per addestrare il modello:
@tf.function def train_step(images, labels): with tf.GradientTape() as tape: predictions = model(images) loss = loss_object(labels, predictions) gradients = tape.gradient(loss, model.trainable_variables) optimizer.apply_gradients(zip(gradients, model.trainable_variables)) train_loss(loss) train_accur...
_____no_output_____
Apache-2.0
site/it/tutorials/quickstart/advanced.ipynb
justaverygoodboy/docs-l10n
Testa il modello:
@tf.function def test_step(images, labels): predictions = model(images) t_loss = loss_object(labels, predictions) test_loss(t_loss) test_accuracy(labels, predictions) EPOCHS = 5 for epoch in range(EPOCHS): for images, labels in train_ds: train_step(images, labels) for test_images, test_labels in test...
_____no_output_____
Apache-2.0
site/it/tutorials/quickstart/advanced.ipynb
justaverygoodboy/docs-l10n
用带有三种类型噪声(度,边权重,点权重)的传销模型网络测试RoleMagnet的抗噪性
import numpy as np import networkx as nx import matplotlib.pyplot as plt
_____no_output_____
MIT
experiment_3.ipynb
Tirami-su/rolemagnet
Creating a graph模拟23人的小型传销组织,带少量噪声
%matplotlib inline plt.rcParams['figure.dpi'] = 150 plt.rcParams['figure.figsize'] = (4, 3) G = nx.DiGraph() G.add_weighted_edges_from([('11','s1',0.07),('12','s1',0.1),('13','s1',0.06),('14','s1',0.09),('15','s1',0.08), ('21','s2',0.07),('22','s2',0.1),('23','s2',0.06),('24','s2',0.09),('25...
_____no_output_____
MIT
experiment_3.ipynb
Tirami-su/rolemagnet
RoleMagnet
import rolemagnet as rm vec,role,label=rm.role_magnet(G, balance=balance)
Embedding: 100.00% - SOM shape: [11, 7] Training SOM: 145
MIT
experiment_3.ipynb
Tirami-su/rolemagnet
Visualization可视化节点的向量表示,用PCA降到二维后再次可视化
print ('三维嵌入结果') for i in range(len(G.nodes)): print (list(G.nodes)[i],'\t',vec[i]) from mpl_toolkits.mplot3d import Axes3D coord = np.transpose(vec) fig = plt.figure(figsize=(4,3)) ax = Axes3D(fig) ax.scatter(coord[0], coord[1], coord[2], c=color, s=150) plt.show() # 再次降到二维 from sklearn.decomposition import ...
三维嵌入结果 11 [-4.656918 2.50780243 -2.60384377] s1 [13.6955635 -7.36617524 0. ] 12 [-3.4945784 1.04689359 -3.71977681] 13 [-4.72707781 3.05246777 -2.23186608] 14 [-3.95635282 1.50288243 -3.34779913] 15 [-4.37087035 1.9886804 -2.97582145] 21 [-4.5643264 3.33294681 -2.60384377] s2 [ 17.36...
MIT
experiment_3.ipynb
Tirami-su/rolemagnet
Evaluation用 Adjusted Rand Index 和 V-Measure 两种指标评价聚类结果
from sklearn.metrics.cluster import adjusted_rand_score, homogeneity_completeness_v_measure true_label=[1,2,1,1,1,1, 1,2,1,1,1,1,1, 1,2,1,1,1,1,1, 3,4,5,6,6,6,6,7,7] print('Adjusted Rand Index:',adjusted_rand_score(true_label,label)) print('V-Measure:',homogeneity_completeness_v_me...
Adjusted Rand Index: 0.9892723141150981 V-Measure: (1.0, 0.9536171907216509, 0.9762579846765088) 聚类结果 21 [-0.6 -0.4] 11 12 13 14 15 21 22 24 23 25 26 31 32 33 34 35 36 45 [1.2 1.2] s1 59 [1.6 1.2] s2 s3 41 [0.6 3.2] mid 71 [ 3.6 -0.2] ...
MIT
experiment_3.ipynb
Tirami-su/rolemagnet
Euler Problem 14================The following iterative sequence is defined for the set of positive integers: n → n/2 (n is even) n → 3n + 1 (n is odd)Using the rule above and starting with 13, we generate the following sequence: 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1It can be seen that this sequence (star...
D = {1:0} maxlen = 0 start = 1 def collatz(n): if n in D: return D[n] elif (n % 2): c = 1 + collatz(3*n+1) else: c = 1 + collatz(n/2) D[n] = c return c for n in range(1,1000000): c = collatz(n) if c > maxlen: maxlen = c start = n print(start)
837799
MIT
Euler 014 - Longest Collatz Sequence.ipynb
Radcliffe/project-euler
Relatório de Análise IV Seleções e Frequências
import pandas as pd dados = pd.read_csv('dados/aluguel_residencial.csv', sep = ';') dados.head(10) # Selecione somente os imóveis classificados com tipo 'Apartamento' selecao = dados['Tipo'] == 'Apartamento' n1 = dados[selecao].shape[0] n1 # Selecione os imóveis classificados com tipos 'Casa', 'Casa de Condomínio' e 'C...
Nº de imóveis classificados com tipo 'Apartamento' -> 19532 Nº de imóveis classificados com tipos 'Casa', 'Casa de Condomínio' e 'Casa de Vila' -> 2212 Nº de imóveis com área entre 60 e 100 metros quadrados, incluindo os limites -> 8719 Nº de imóveis que tenham pelo menos 4 quartos e aluguel menor que R$ 2.000,00 -> 41...
MIT
FormacaoPythonParaDataScience/PythonPandas-TratandoAnalisandoDados/CursoPandas/SelecoesFrequencias.ipynb
anablima/TreinamentosAlura
Scrumblet(Courtesy of K Polansky)Two-step doublet score processing, mirroring the approach from Popescu et al. https://www.nature.com/articles/s41586-019-1652-y which was closely based on Pijuan-Sala et al. https://www.nature.com/articles/s41586-019-0933-9The first step starts with some sort of doublet score, e.g. Scru...
path_to_data = '/nfs/users/nfs_l/lg18/team292/lg18/gonads/data/scRNAseq/FCA/rawdata/' metadata = pd.read_csv(path_to_data + 'immune_meta.csv', index_col=0) metadata['process'].value_counts() # Select process = CD45+ metadata_enriched = metadata[metadata['process'] == 'CD45+'] metadata_enriched metadata_enriched['stage...
FCA_GND8784459
MIT
immune_CD45enriched_load_detect_doublets.ipynb
ventolab/HGDA
The BasicsAt the core of Python (and any programming language) there are some key characteristics of how a program is structured that enable the proper execution of that program. These characteristics include the structure of the code itself, the core data types from which others are built, and core operators that mod...
# The interpreter can be used as a calculator, and can also echo or concatenate strings. 3 + 3 3 * 3 3 ** 3 3 / 2 # classic division - output is a floating point number # Use quotes around strings, single or double, but be consistent to the extent possible 'dogs' "dogs" "They're going to the beach" 'He said "I like m...
Hello World!
Apache-2.0
1.2-The Basics.ipynb
unmrds/cc-python
Try It YourselfGo to the section _4.4. Numeric Types_ in the Python 3 documentation at . The table in that section describes different operators - try some!What is the difference between the different division operators (`/`, `//`, and `%`)? VariablesVariables allow us to store values for later use.
a = 5 b = 10 a + b
_____no_output_____
Apache-2.0
1.2-The Basics.ipynb
unmrds/cc-python
Variables can be reassigned:
b = 38764289.1097 a + b
_____no_output_____
Apache-2.0
1.2-The Basics.ipynb
unmrds/cc-python
The ability to reassign variable values becomes important when iterating through groups of objects for batch processing or other purposes. In the example below, the value of `b` is dynamically updated every time the `while` loop is executed:
a = 5 b = 10 while b > a: print("b="+str(b)) b = b-1
b=10 b=9 b=8 b=7 b=6
Apache-2.0
1.2-The Basics.ipynb
unmrds/cc-python
Variable data types can be inferred, so Python does not require us to declare the data type of a variable on assignment.
a = 5 type(a)
_____no_output_____
Apache-2.0
1.2-The Basics.ipynb
unmrds/cc-python
is equivalent to
a = int(5) type(a) c = 'dogs' print(type(c)) c = str('dogs') print(type(c))
<class 'str'> <class 'str'>
Apache-2.0
1.2-The Basics.ipynb
unmrds/cc-python
There are cases when we may want to declare the data type, for example to assign a different data type from the default that will be inferred. Concatenating strings provides a good example.
customer = 'Carol' pizzas = 2 print(customer + ' ordered ' + pizzas + ' pizzas.')
_____no_output_____
Apache-2.0
1.2-The Basics.ipynb
unmrds/cc-python
Above, Python has inferred the type of the variable `pizza` to be an integer. Since strings can only be concatenated with other strings, our print statement generates an error. There are two ways we can resolve the error:1. Declare the `pizzas` variable as type string (`str`) on assignment or2. Re-cast the `pizzas` var...
customer = 'Carol' pizzas = str(2) print(customer + ' ordered ' + pizzas + ' pizzas.') customer = 'Carol' pizzas = 2 print(customer + ' ordered ' + str(pizzas) + ' pizzas.')
Carol ordered 2 pizzas.
Apache-2.0
1.2-The Basics.ipynb
unmrds/cc-python
Given the following variable assignments:```x = 12y = str(14)z = donuts```Predict the output of the following:1. `y + z`2. `x + y`3. `x + int(y)`4. `str(x) + y`Check your answers in the interpreter. Variable Naming RulesVariable names are case senstive and:1. Can only consist of one "word" (no spaces).2. Must begin wit...
# Read unstructured text # One way is to open the whole file as a block file_path = "./beowulf" # We can save the path to the file as a variable file_in = open(file_path, "r") # Options are 'r', 'w', and 'a' (read, write, append) beowulf_a = file_in.read() file_in.close() print(beowulf_a) # Another way is to read the ...
Asymmetry Ellipticity AvgLength (cm) Number of images \ count 1400.000000 1400.000000 1400.000000 1400.000000 mean 0.148230 0.384384 3.426853 9.320714 std 0.071228 0.089594 2.161549 20.747693 min 0.001400 0.096700 1.196...
Apache-2.0
1.2-The Basics.ipynb
unmrds/cc-python
StructureNow that we have practiced assigning variables and reading information from files, we will have a look at concepts that are key to developing processes to use and analyze this information. BlocksThe structure of a Python program is pretty simple:Blocks of code are defined using indentation. Code that is at a ...
# Fun with types this = 12 that = 15 the_other = "27" my_stuff = [this,that,the_other,["a","b","c",4]] more_stuff = { "item1": this, "item2": that, "item3": the_other, "item4": my_stuff } this + that # this won't work ... # this + that + the_other # ... but this will ... this + that + int(the_othe...
_____no_output_____
Apache-2.0
1.2-The Basics.ipynb
unmrds/cc-python
ListsLists are a type of collection in Python. Lists allow us to store sequences of items that are typically but not always similar. All of the following lists are legal in Python:
# Separate list items with commas! number_list = [1, 2, 3, 4, 5] string_list = ['apples', 'oranges', 'pears', 'grapes', 'pineapples'] combined_list = [1, 2, 'oranges', 3.14, 'peaches', 'grapes', 99.19876] # Nested lists - lists of lists - are allowed. list_of_lists = [[1, 2, 3], ['oranges', 'grapes...
_____no_output_____
Apache-2.0
1.2-The Basics.ipynb
unmrds/cc-python
There are multiple ways to create a list:
# Create an empty list empty_list = [] # As we did above, by using square brackets around a comma-separated sequence of items new_list = [1, 2, 3] # Using the type constructor constructed_list = list('purple') # Using a list comprehension result_list = [i for i in range(1, 20)]
_____no_output_____
Apache-2.0
1.2-The Basics.ipynb
unmrds/cc-python
We can inspect our lists:
empty_list new_list result_list constructed_list
_____no_output_____
Apache-2.0
1.2-The Basics.ipynb
unmrds/cc-python