markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
we dont need to start slicng at 0
print (data[5:10,7:15])
01-analysing-data.ipynb
drwalshaw/sc-python
mit
we dont even need to inc upper and lower limits
smallchunk=data[:3,36:] print(smallchunk)
01-analysing-data.ipynb
drwalshaw/sc-python
mit
arithmetic on arrays
doublesmallchunk=smallchunk*2.0 print(doublesmallchunk) triplesmallchunk=smallchunk+doublesmallchunk print(triplesmallchunk) print(numpy.mean(data)) print (numpy.max(data)) print (numpy.min(data))
01-analysing-data.ipynb
drwalshaw/sc-python
mit
get a set of data for the first station this is shorthand for "all the columns"
station_0=data[0,:] print(numpy.max(station_0))
01-analysing-data.ipynb
drwalshaw/sc-python
mit
we dont need to create @temporary@ array slices we can refer to what we call array axes
print(numpy.mean(data, axis=0)) print(numpy.mean(data, axis=1))
01-analysing-data.ipynb
drwalshaw/sc-python
mit
axis = 0 gets mean down eaach column axis=1 gets the mean across each row so the mean temp for each station for all periods see above do some simple vissualisations
import matplotlib.pyplot %matplotlib inline image=matplotlib.pyplot.imshow(data)
01-analysing-data.ipynb
drwalshaw/sc-python
mit
lets look at the average tempp over time
avg_temperature=numpy.mean(data,axis=0) avg_plot=matplotlib.pyplot.plot(avg_temperature) import numpy import matplotlib.pyplot %matplotlib inline data=numpy.loadtxt(fname='data/weather-01.csv',delimiter=',')
01-analysing-data.ipynb
drwalshaw/sc-python
mit
create a wide figure to hold sub plots
fig=matplotlib.pyplot.figure (figsize=(10.0,3.0))
01-analysing-data.ipynb
drwalshaw/sc-python
mit
create placeholders for plots
fig=matplotlib.pyplot.figure (figsize=(10.0,3.0)) subplot1=fig.add_subplot (1,3,1) subplot2=fig.add_subplot (1,3,2) subplot3=fig.add_subplot (1,3,3) subplot1.set_ylabel('average') subplot1.plot(numpy.mean(data, axis=0)) subplot2.set_ylabel('minimum') subplot2.plot(numpy.min(data, axis=0)) subplot3.set_ylabel('maximu...
01-analysing-data.ipynb
drwalshaw/sc-python
mit
this is fine for small numbers of datasets, what if wwe have hundreds or thousands? we need more automaation loops
word='notebook' print (word[4])
01-analysing-data.ipynb
drwalshaw/sc-python
mit
see aabove note diff between squaare and normaal brackets
for char in word: # colon before word or indentation v imporetaant #indent is 4 spaces for char in word: print (char)
01-analysing-data.ipynb
drwalshaw/sc-python
mit
reading filenames get a list of all the filenames from disk
import glob
01-analysing-data.ipynb
drwalshaw/sc-python
mit
global..something~
print(glob.glob('data/weather*.csv'))
01-analysing-data.ipynb
drwalshaw/sc-python
mit
putting it all together
filenames=sorted(glob.glob('data/weather*.csv')) filenames=filenames[0:3] for f in filenames: print (f) data=numpy.loadtxt(fname=f, delimiter=',') #next bits need indenting fig=matplotlib.pyplot.figure (figsize=(10.0,3.0)) subplot1=fig.add_subplot (1,3,1) subplot2=fig.add_subplot (1,3,2) ...
01-analysing-data.ipynb
drwalshaw/sc-python
mit
didnt print "done" due to break in indentation sequence
num=-3 if num>0: print (num, "is positive") elif num ==0: print (num, "is zero") else: print (num, "is negative")
01-analysing-data.ipynb
drwalshaw/sc-python
mit
elif eqauls else if, always good to finish a chain with an else
filenames=sorted(glob.glob('data/weather*.csv')) filenames=sorted(glob.glob('data/weather*.csv')) filenames=filenames[0:3] for f in filenames: print (f) data=numpy.loadtxt(fname=f, delimiter=',') == 0 if numpy.max (data, axis=0)[0] ==0 and numpy.max (data, axis=0)[20] ==20: print ('suspicious lo...
01-analysing-data.ipynb
drwalshaw/sc-python
mit
something went wrong with the above
def fahr_to_kelvin(temp): return((temp-32)*(5/9)+ 273.15) print ('freezing point of water:', fahr_to_kelvin(32)) print ('boiling point of water:', fahr_to_kelvin(212))
01-analysing-data.ipynb
drwalshaw/sc-python
mit
using functions
def analyse (filename): data=numpy.loadtxt(fname=filename,)......
01-analysing-data.ipynb
drwalshaw/sc-python
mit
unfinsinshed
def detect_problems (filename): data=numpy.loadtxt(fname=filename, delimiter=',') if numpy.max (data, axis=0)[0] ==0 and numpy.max (data, axis=0)[20] ==20: print ('suspicious looking maxima') elif numpy.sum(numpy.min(data, axis=0)) ==0: print ('minimum adds to zero') else: p...
01-analysing-data.ipynb
drwalshaw/sc-python
mit
Tensorflow TensorFlow provides multiple APIs. The lowest level API--TensorFlow Core-- provides you with complete programming control. We recommend TensorFlow Core for machine learning researchers and others who require fine levels of control over their models Hello World We can think of TensorFlow Core programs as cons...
# note that this is simply telling tensorflow to # create a constant operation, nothing gets # executed until we start a session and run it hello = tf.constant('Hello, TensorFlow!') hello # start the session and run the graph with tf.Session() as sess: print(sess.run(hello))
deep_learning/softmax_tensorflow.ipynb
ethen8181/machine-learning
mit
We can think of tensorflow as a system to define our computation, and using the operation that we've defined it will construct a computation graph (where each operation becomes a node in the graph). The computation graph that we've defined will not be run unless we give it some context and explicitly tell it to do so. ...
a = tf.constant(2.0, tf.float32) b = tf.constant(3.0) # also tf.float32 implicitly c = a + b with tf.Session() as sess: print('mutiply: ', sess.run(a * b)) print('add: ', sess.run(c)) # note that we can define the add operation outside print('add: ', sess.run(a + b)) # or inside the .run()
deep_learning/softmax_tensorflow.ipynb
ethen8181/machine-learning
mit
The example above is not especially interesting because it always produces a constant result. A graph can be parameterized to accept external inputs, known as placeholders. Think of it as the input data we would give to machine learning algorithm at some point. We can do the same operation as above by first defining a ...
a = tf.placeholder(tf.float32) b = tf.placeholder(tf.float32) # define some operations add = a + b mul = a * b with tf.Session() as sess: print('mutiply: ', sess.run(mul, feed_dict = {a: 2, b: 3})) print('add: ', sess.run(add, feed_dict = {a: 2, b: 3}))
deep_learning/softmax_tensorflow.ipynb
ethen8181/machine-learning
mit
Some matrix operations are the same compared to numpy. e.g.
c = np.array([[3.,4], [5.,6], [6.,7]]) print(c) print(np.mean(c, axis = 1)) print(np.argmax(c, axis = 1)) with tf.Session() as sess: result = sess.run(tf.reduce_mean(c, axis = 1)) print(result) print(sess.run(tf.argmax(c, axis = 1)))
deep_learning/softmax_tensorflow.ipynb
ethen8181/machine-learning
mit
The functionality of numpy.mean and tensorflow.reduce_mean are the same. When axis argument parameter is 1, it computes mean across (3,4) and (5,6) and (6,7), so 1 defines across which axis the mean is computed (axis = 1, means the operation is along the column, so it will compute the mean for each row). When it is 0, ...
# Parameters learning_rate = 0.01 # learning rate for the optimizer (gradient descent) n_epochs = 1000 # number of iterations to train the model display_epoch = 100 # display the cost for every display_step iteration # make up some trainig data X_train = np.asarray([3.3, 4.4, 5.5, 6.71, 6.93, 4.168, 9.779, 6.182, 7...
deep_learning/softmax_tensorflow.ipynb
ethen8181/machine-learning
mit
MNIST Using Softmax MNIST is a simple computer vision dataset. It consists of images of handwritten digits like these: <img src='images/mnist.png'> Each image is 28 pixels by 28 pixels, which is essentially a $28 \times 28$ array of numbers. To use it in a context of a machine learning problem, we can flatten this arra...
n_class = 10 n_features = 784 # mnist is a 28 * 28 image # load the dataset and some preprocessing step that can be skipped (X_train, y_train), (X_test, y_test) = mnist.load_data() X_train = X_train.reshape(60000, n_features) X_test = X_test.reshape(10000, n_features) X_train = X_train.astype('float32') X_test = X_tes...
deep_learning/softmax_tensorflow.ipynb
ethen8181/machine-learning
mit
In the following code chunk, we define the overall computational graph/structure for the softmax classifier using the cross entropy cost function as the objective. Recall that the formula for this function can be denoted as: $$L = -\sum_i y'_i \log(y_i)$$ Where y is our predicted probability distribution, and y′ is the...
# define some global variables learning_rate = 0.1 n_iterations = 400 # define the input and output # here None means that a dimension can be of any length, # which is what we want, since the number of observations # we have can vary; # note that the shape argument to placeholder is optional, # but it allows Tensor...
deep_learning/softmax_tensorflow.ipynb
ethen8181/machine-learning
mit
```python to define the softmax classifier and cross entropy cost we can do the following matrix multiplication using the .matmul command and add the softmax output output = tf.nn.softmax(tf.matmul(X, W) + b) cost function: cross entropy, the reduce mean is simply the average of the cost function across all observation...
# but for numerical stability reason, the tensorflow documentation # suggests using the following function output = tf.matmul(X, W) + b cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels = y, logits = output))
deep_learning/softmax_tensorflow.ipynb
ethen8181/machine-learning
mit
Now that we defined the structure of our model, we'll: Define a optimization algorithm the train it. In this case, we ask TensorFlow to minimize our defined cross_entropy cost using the gradient descent algorithm with a learning rate of 0.5. There are also other off the shelf optimizers that we can use that are faster...
train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(cross_entropy) init = tf.global_variables_initializer() # here we're return the predicted class of each observation using argmax # and see if the ouput (prediction) is equal to the target variable (y) # since equal is a boolean type tensor, we cast...
deep_learning/softmax_tensorflow.ipynb
ethen8181/machine-learning
mit
Now it's time to run it. During each step of the loop, we get a "batch" of one hundred random data points (defined by batch_size) from our training set. We run train_step feeding in the batches data to replace the placeholders. Using small batches of random data is called stochastic training -- in this case, stochastic...
with tf.Session() as sess: # initialize the variable, train the "batch" gradient descent # for a specified number of iterations and evaluate on accuracy score # remember the key to the feed_dict dictionary must match the variable we use # as the placeholder for the data in the beginning sess.run(in...
deep_learning/softmax_tensorflow.ipynb
ethen8181/machine-learning
mit
Access the Database with the sqlite3 Package We can use the sqlite3 package from the Python standard library to connect to the sqlite database:
import sqlite3 conn = sqlite3.connect('data/iris/database.sqlite') cursor = conn.cursor() type(cursor)
Week-8-NLP-Databases/Working with Databases.ipynb
kkhenriquez/python-for-data-science
mit
A sqlite3.Cursor object is our interface to the database, mostly throught the execute method that allows to run any SQL query on our database. First of all we can get a list of all the tables saved into the database, this is done by reading the column name from the sqlite_master metadata table with: SELECT name FROM sq...
for row in cursor.execute("SELECT name FROM sqlite_master"): print(row)
Week-8-NLP-Databases/Working with Databases.ipynb
kkhenriquez/python-for-data-science
mit
a shortcut to directly execute the query and gather the results is the fetchall method:
cursor.execute("SELECT name FROM sqlite_master").fetchall()
Week-8-NLP-Databases/Working with Databases.ipynb
kkhenriquez/python-for-data-science
mit
Notice: this way of finding the available tables in a database is specific to sqlite, other databases like MySQL or PostgreSQL have different syntax. Then we can execute standard SQL query on the database, SQL is a language designed to interact with data stored in a relational database. It has a standard specification,...
sample_data = cursor.execute("SELECT * FROM Iris LIMIT 20").fetchall() print(type(sample_data)) sample_data [row[0] for row in cursor.description]
Week-8-NLP-Databases/Working with Databases.ipynb
kkhenriquez/python-for-data-science
mit
It is evident that the interface provided by sqlite3 is low-level, for data exploration purposes we would like to directly import data into a more user friendly library like pandas. Import data from a database to pandas
import pandas as pd iris_data = pd.read_sql_query("SELECT * FROM Iris", conn) iris_data.head() iris_data.dtypes
Week-8-NLP-Databases/Working with Databases.ipynb
kkhenriquez/python-for-data-science
mit
pandas.read_sql_query takes a SQL query and a connection object and imports the data into a DataFrame, also keeping the same data types of the database columns. pandas provides a lot of the same functionality of SQL with a more user-friendly interface. However, sqlite3 is extremely useful for downselecting data before ...
iris_setosa_data = pd.read_sql_query("SELECT * FROM Iris WHERE Species == 'Iris-setosa'", conn) iris_setosa_data print(iris_setosa_data.shape) print(iris_data.shape)
Week-8-NLP-Databases/Working with Databases.ipynb
kkhenriquez/python-for-data-science
mit
GPFlow first approximation
## Import modules import numpy as np import scipy.spatial.distance as sp from matplotlib import pyplot as plt plt.style.use('ggplot')
notebooks/Sandboxes/TensorFlow/GPFlow_examples.ipynb
molgor/spystats
bsd-2-clause
Simulating Data Simulate random uniform 4-d vector. Give N of this.
## Parameter definitions N = 1000 phi = 0.05 sigma2 = 1.0 beta_0 = 10.0 beta_1 = 1.5 beta_2 = -1.0 # AL NAGAT nugget = 0.03 X = np.random.rand(N,4)
notebooks/Sandboxes/TensorFlow/GPFlow_examples.ipynb
molgor/spystats
bsd-2-clause
Calculate distance X can be interpreted as covariate matrix in which the first two columns are the longitud and latitude. GPFlow requires that all the covariates (including spatio-temporal coordinates) are in X.
points = X[:,0:2] dist_points = sp.pdist(points) ## Reshape the vector to square matrix distance_matrix = sp.squareform(dist_points) correlation_matrix = np.exp(- distance_matrix / phi) covariance_matrix = correlation_matrix * sigma2 plt.imshow(covariance_matrix)
notebooks/Sandboxes/TensorFlow/GPFlow_examples.ipynb
molgor/spystats
bsd-2-clause
Simulate the Gaussian Process $S$ Remmember that for a stationary Gaussian Process, the value at Z is independent of the betas (Covariate weights). Mean 0's $\Sigma$ Correlation matrix $$S = MVN(0,\Sigma) + \epsilon$$ $ \epsilon \sim N(0,\sigma^{2}) $ S is a realization of a spatial process.
S = np.random.multivariate_normal(np.zeros(N), correlation_matrix) +\ np.random.normal(size = N) * nugget S.shape # We convert to Matrix [1 column] S = S.reshape(N,1) ## Plot x, y using as color the Gaussian process plt.scatter(X[:, 0], X[:, 1], c = S) plt.colorbar()
notebooks/Sandboxes/TensorFlow/GPFlow_examples.ipynb
molgor/spystats
bsd-2-clause
Simulate the Response Variable $y$ $$y_1(x_1,x_2) = S(x_1,x_2) $$ $$y_2(x_1,x_2) = \beta_0 + x_3\beta_1 + x_4\beta_2 + S(x_1,x_2)$$
# remmember index 0 is 1 mu = beta_0 + beta_1 * X[:, 2] + beta_2 * X[:, 3] mu = mu.reshape(N,1) Y1 = S Y2 = mu + S plt.scatter(X[:, 0], X[:, 1], c = Y2) plt.colorbar() S.shape
notebooks/Sandboxes/TensorFlow/GPFlow_examples.ipynb
molgor/spystats
bsd-2-clause
GP Model ! This model is without covariates
# Import GPFlow import GPflow as gf # Defining the model Matern function with \kappa = 0.5 k = gf.kernels.Matern12(2, lengthscales=1, active_dims = [0,1] ) type(k)
notebooks/Sandboxes/TensorFlow/GPFlow_examples.ipynb
molgor/spystats
bsd-2-clause
Model for $y_1$
m = gf.gpr.GPR(points, Y1, k) ## First guess init_nugget = 0.001 m.likelihood.variance = init_nugget print(m)
notebooks/Sandboxes/TensorFlow/GPFlow_examples.ipynb
molgor/spystats
bsd-2-clause
Like in tensorflow, m is a graph and has at least three nodes: lengthscale, kern variance and likelihood variance
# Estimation using symbolic gradient descent m.optimize() print(m)
notebooks/Sandboxes/TensorFlow/GPFlow_examples.ipynb
molgor/spystats
bsd-2-clause
compare with original parameters (made from the simulation)
print(phi,sigma2,nugget) print points.shape print Y1.shape
notebooks/Sandboxes/TensorFlow/GPFlow_examples.ipynb
molgor/spystats
bsd-2-clause
it was close enough GAUSSIAN PROCESS WITH LINEAR TREND Defining the model
k = gf.kernels.Matern12(2, lengthscales=1, active_dims = [0,1] ) gf.mean_functions.Linear() meanf = gf.mean_functions.Linear(np.ones((4,1)), np.ones(1)) m = gf.gpr.GPR(X, Y2, k, meanf) m.likelihood.variance = init_nugget print(m) # Estimation m.optimize() print(m)
notebooks/Sandboxes/TensorFlow/GPFlow_examples.ipynb
molgor/spystats
bsd-2-clause
Original parameters phi = 0.05 ---> lengthscale sigma2 = 1.0 ---> variance transform nugget = 0.03 ---> likelihood variance beta_0 = 10.0 ---> mean_function b beta_1 = 1.5 ---> mean_fucntionA [2] beta_2 = -1.0 ---> mean_functionA [3] mean_functionA[0] and mean_functionA[1] are the betas for for x and y (coordinates r...
# Defining the model k = gf.kernels.Matern12(2, lengthscales=1, active_dims = [0,1])
notebooks/Sandboxes/TensorFlow/GPFlow_examples.ipynb
molgor/spystats
bsd-2-clause
Custom made mean function (Erick Chacón )
from GPflow.mean_functions import MeanFunction, Param import tensorflow as tf class LinearG(MeanFunction): """ y_i = A x_i + b """ def __init__(self, A=None, b=None): """ A is a matrix which maps each element of X to Y, b is an additive constant. If X has N rows and D col...
notebooks/Sandboxes/TensorFlow/GPFlow_examples.ipynb
molgor/spystats
bsd-2-clause
Now we can use the special mean function without the coordinates (covariates).
meanf = LinearG(np.ones((2,1)), np.ones(1)) X.shape Y2.shape m = gf.gpr.GPR(X, Y2, k, meanf)a m.likelihood.variance = 0.1 print(m)
notebooks/Sandboxes/TensorFlow/GPFlow_examples.ipynb
molgor/spystats
bsd-2-clause
Only 2 parameters now!
# Estimation m.optimize() print(m)
notebooks/Sandboxes/TensorFlow/GPFlow_examples.ipynb
molgor/spystats
bsd-2-clause
Original parameters phi = 0.05 ---> lengthscale sigma2 = 1.0 ---> variance transform nugget = 0.03 ---> likelihood variance beta_0 = 10.0 ---> mean_function b beta_1 = 1.5 ---> mean_fucntionA [2] beta_2 = -1.0 ---> mean_functionA [3]
predicted_x = np.linspace(0.0,1.0,100) from external_plugins.spystats.models import makeDuples predsX = makeDuples(predicted_x) pX = np.array(predsX) tt = np.ones((10000,2)) *0.5 ## Concatenate with horizontal stack SuperX = np.hstack((pX,tt)) SuperX.shape mean, variance = m.predict_y(SuperX) minmean = min(mean) ...
notebooks/Sandboxes/TensorFlow/GPFlow_examples.ipynb
molgor/spystats
bsd-2-clause
Create topographic ERF maps in delayed SSP mode This script shows how to apply SSP projectors delayed, that is, at the evoked stage. This is particularly useful to support decisions related to the trade-off between denoising and preserving signal. In this example we demonstrate how to use topographic maps for delayed S...
# Authors: Denis Engemann <denis.engemann@gmail.com> # Christian Brodbeck <christianbrodbeck@nyu.edu> # Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # # License: BSD (3-clause) import numpy as np import mne from mne import io from mne.datasets import sample print(__doc__) data_path ...
0.14/_downloads/plot_evoked_topomap_delayed_ssp.ipynb
mne-tools/mne-tools.github.io
bsd-3-clause
Set parameters
raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif' event_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw-eve.fif' ecg_fname = data_path + '/MEG/sample/sample_audvis_ecg_proj.fif' event_id, tmin, tmax = 1, -0.2, 0.5 # Setup for reading the raw data raw = io.Raw(raw_fname) events = mne.re...
0.14/_downloads/plot_evoked_topomap_delayed_ssp.ipynb
mne-tools/mne-tools.github.io
bsd-3-clause
Interactively select / deselect the SSP projection vectors
# 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') # Hint: the same works for evoked.plot and evoked.plot_topo
0.14/_downloads/plot_evoked_topomap_delayed_ssp.ipynb
mne-tools/mne-tools.github.io
bsd-3-clause
Using the optimal control module to find the pulse This feature integrated into the sub-class OptPulseProcessor which use methods in the optimal control module to find the optimal pulse sequence for the desired gates. It can find the optimal pulse either for the whole unitary evolution or for each gate. Here we choose ...
setting_args = {"SNOT": {"num_tslots": 5, "evo_time": 1}, "CNOT": {"num_tslots": 12, "evo_time": 5}} processor = OptPulseProcessor(N=3) processor.add_control(sigmaz(), cyclic_permutation=True) processor.add_control(sigmax(), cyclic_permutation=True) processor.add_control(tensor([sigmax(), sigmax(), iden...
examples/qip-processor-DJ-algorithm.ipynb
ajgpitch/qutip-notebooks
lgpl-3.0
To quickly visualize the pulse, Processor has a method called plot_pulses. In the figure bellow, each colour represents the pulse sequence of one control Hamiltonian in the system as a function of time. In each time interval, the pulse remains constant.
processor.plot_pulses(title="Control pulse of OptPulseProcessor", figsize=(8, 4), dpi=100);
examples/qip-processor-DJ-algorithm.ipynb
ajgpitch/qutip-notebooks
lgpl-3.0
To simulate the evolution, we only need to call the method run_state which calls one of the open system solvers in QuTiP and calculate the time evolution. Without decoherence
psi0 = tensor([basis(2, 0), basis(2, 0), basis(2, 1)]) result = processor.run_state(init_state=psi0) print("Probability of measuring state 00:") print(np.real((basis00.dag() * ptrace(result.states[-1], [0,1]) * basis00)[0,0]))
examples/qip-processor-DJ-algorithm.ipynb
ajgpitch/qutip-notebooks
lgpl-3.0
With decoherence
processor.t1 = 100 processor.t2 = 30 psi0 = tensor([basis(2, 0), basis(2, 0), basis(2, 1)]) result = processor.run_state(init_state=psi0) print("Probability of measuring state 00:") print(np.real((basis00.dag() * ptrace(result.states[-1], [0,1]) * basis00)[0,0]))
examples/qip-processor-DJ-algorithm.ipynb
ajgpitch/qutip-notebooks
lgpl-3.0
We can see that under noisy evolution their is a none zero probability of measuring state 00. Generating pulse based on quantum computing model Below, we simulate the same quantum circuit using one sub-class LinearSpinChain. It will find the pulse based on the Hamiltonian available on a quantum computer of the linear s...
processor2 = LinearSpinChain(3) processor2.load_circuit(qc); processor2.plot_pulses(title="Control pulse of Spin chain");
examples/qip-processor-DJ-algorithm.ipynb
ajgpitch/qutip-notebooks
lgpl-3.0
The first three pulse periods (from $t=0$ to $t\approx5$) are for the three Hadamard gates, they are followed by two long periods for the CNOT gates and then again two Hadamard. Different colours represent different kinds of interaction, as shown in the legend. Without decoherence
psi0 = tensor([basis(2, 0), basis(2, 0), basis(2, 1)]) result = processor2.run_state(init_state=psi0) print("Probability of measuring state 00:") print(np.real((basis00.dag() * ptrace(result.states[-1], [0,1]) * basis00)[0,0]))
examples/qip-processor-DJ-algorithm.ipynb
ajgpitch/qutip-notebooks
lgpl-3.0
With decoherence
processor2.t1 = 100 processor2.t2 = 30 psi0 = tensor([basis(2, 0), basis(2, 0), basis(2, 1)]) result = processor2.run_state(init_state=psi0) print("Probability of measuring state 00:") print(np.real((basis00.dag() * ptrace(result.states[-1], [0,1]) * basis00)[0,0])) from qutip.ipynbtools import version_table version_t...
examples/qip-processor-DJ-algorithm.ipynb
ajgpitch/qutip-notebooks
lgpl-3.0
移動モデル ロボットを100台出してみます。 どのロボットも1前進という命令を出しましたが、バラバラしていることがわかります。
actual_landmarks = Landmarks([[1.0,0.0]]) robots = [] for i in range(100): robots.append(Robot(0,0,0)) for robot in robots: robot.move(1.0, 0) draw(0)
monte_calro_localization/notebook_demo.ipynb
Kuwamai/probrobo_note
mit
観測モデル 同様にロボットを100台出して、1先に見える星を観測させます。 カラフルなドットがロボットから見える星の位置です。
actual_landmarks = Landmarks([[1.0,0.0]]) robots = [] for i in range(100): robots.append(Robot(0,0,0)) for robot in robots: robot.observation(actual_landmarks) draw(1)
monte_calro_localization/notebook_demo.ipynb
Kuwamai/probrobo_note
mit
尤度計算 今回は尤度計算に正規分布を使っています。 ロボットの観測データ$d, \varphi$と、パーティクルの観測データ$d', \varphi'$の差が大きいほど小さな値になります。 $$ p(z|x_t) \propto \frac {\exp (- \frac {1}{2\sigma_d}(d-d')^2)}{\sigma_d \sqrt{2 \pi}} \frac {\exp (- \frac {1}{2\sigma_\varphi}(\varphi-\varphi')^2)}{\sigma_\varphi \sqrt{2 \pi}} $$ 下のグラフは$d$と$\varphi$についてそれぞれ別々に描画した正規分布...
rd = 1 rf = 0 sigma_rd = 1.0 * 0.2 sigma_rf = math.pi * 3 / 180 pd = np.arange(-3, 3, 0.01) pf = np.arange(-3, 3, 0.01) d = np.exp(-(rd - pd) ** 2 / (2 * (sigma_rd ** 2))) / (sigma_rd * np.sqrt(2 * np.pi)) f = np.exp(-(rf - pf) ** 2 / (2 * (sigma_rf ** 2))) / (sigma_rf * np.sqrt(2 * np.pi)) fig = plt.figure(figsize=...
monte_calro_localization/notebook_demo.ipynb
Kuwamai/probrobo_note
mit
The features? - TV: advertising dollars spent on TV (for a single product, in a given market) - Radio: advertising dollars spent on Radio (for a single product, in a given market) - Newspaper: advertising dollars spent on Newspaper (for a single product, in a given market) What is the response? - Sales: sales of a s...
# print the size of the DataFrame object, i.e., the size of the dataset data.shape
Data Science UA - September 2017/Lecture 05 - Modeling Techniques and Regression/Linear_Regression.ipynb
iRipVanWinkle/ml
mit
There are 200 observations, corresponding to 200 markets. We can try to discover if there is any relationship between the money spend on a specific type of ad, in a given market, and the sales in that market by plotting the sales figures against each category of advertising expenditure.
fig, axs = plt.subplots(1, 3, sharey=True) data.plot(kind='scatter', x='TV', y='Sales', ax=axs[0], figsize=(16, 8)) data.plot(kind='scatter', x='Radio', y='Sales', ax=axs[1]) data.plot(kind='scatter', x='Newspaper', y='Sales', ax=axs[2])
Data Science UA - September 2017/Lecture 05 - Modeling Techniques and Regression/Linear_Regression.ipynb
iRipVanWinkle/ml
mit
Questions How can the company selling the product decide on how to spend its advertising money in the future? We first need to answer the following question: "Based on this data, does there apear to be a relationship between ads and sales?" If yes, 1. Which ad types contribute to sales? 2. How strong is the relationsh...
import statsmodels.formula.api as sf #create a model with Sales as dependent variable and TV as explanatory variable model = sf.ols('Sales ~ TV', data) #fit the model to the data fitted_model = model.fit() # print the coefficients print(fitted_model.params)
Data Science UA - September 2017/Lecture 05 - Modeling Techniques and Regression/Linear_Regression.ipynb
iRipVanWinkle/ml
mit
Interpreting Model Coefficients Q: How do we interpret the coefficient ($\beta_1$) of the explanatory variable "TV"? A: A unit (a thousand dollars) increase in TV ad spending is associated with a 0.047537 unit (a thousand widgets) increase in Sales, i.e., an additional $1000 spent on TV ads is associated with an increa...
7.032594 + 0.047537*50
Data Science UA - September 2017/Lecture 05 - Modeling Techniques and Regression/Linear_Regression.ipynb
iRipVanWinkle/ml
mit
The predicted Sales in that market are of 9.409444 * 1000 =~ 9409 widgets Using Statsmodels:
# create a DataFrame to use with the Statsmodels formula interface New_TV_spending = pd.DataFrame({'TV': [50]}) #check the newly created DataFrame New_TV_spending.head() # use the model created above to predict the sales to be generated by the new TV ad money sales = fitted_model.predict(New_TV_spending) print(sales)
Data Science UA - September 2017/Lecture 05 - Modeling Techniques and Regression/Linear_Regression.ipynb
iRipVanWinkle/ml
mit
Plotting the Least Squares Line Let's make predictions for the smallest and largest observed values of money spent on TV ads, and then use the predicted values to plot the least squares line:
# create a DataFrame with the minimum and maximum values of TV ad money New_TV_money = pd.DataFrame({'TV': [data.TV.min(), data.TV.max()]}) print(New_TV_money.head()) # make predictions for those x values and store them sales_predictions = fitted_model.predict(New_TV_money) print(sales_predictions) # plot the observe...
Data Science UA - September 2017/Lecture 05 - Modeling Techniques and Regression/Linear_Regression.ipynb
iRipVanWinkle/ml
mit
Confidence in Linear Regression Models Q: Is linear regression a high bias/low variance model, or a low variance/high bias model? A: High bias/low variance. Under repeated sampling, the line will stay roughly in the same place (low variance), but the average of those models won't do a great job capturing the true relat...
# print the confidence intervals for the model coefficients print(fitted_model.conf_int())
Data Science UA - September 2017/Lecture 05 - Modeling Techniques and Regression/Linear_Regression.ipynb
iRipVanWinkle/ml
mit
Since we only have a single sample of data, and not the entire population the "true" value of the regression coefficient is either within this interval or it isn't, but there is no way to actually know. We estimate the regression coefficient using the data we have, and then we characterize the uncertainty about that e...
# print the p-values for the model coefficients fitted_model.pvalues
Data Science UA - September 2017/Lecture 05 - Modeling Techniques and Regression/Linear_Regression.ipynb
iRipVanWinkle/ml
mit
If the 95% confidence interval includes zero, the p-value for that coefficient will be greater than 0.05. If the 95% confidence interval does not include zero, the p-value will be less than 0.05. Thus, a p-value less than 0.05 is one way to decide whether there is likely a relationship between the feature and the respo...
# print the R-squared value for the model fitted_model.rsquared
Data Science UA - September 2017/Lecture 05 - Modeling Techniques and Regression/Linear_Regression.ipynb
iRipVanWinkle/ml
mit
Is that a "good" R-squared value? One cannot generally assess that. What a "good" R-squared value is depends on the domain and therefore R-squared is most useful as a tool for comparing different models. Multiple Linear Regression Simple linear regression can be extended to include multiple explanatory variables: $y = ...
# create a model with all three features multi_model = sf.ols(formula='Sales ~ TV + Radio + Newspaper', data=data) fitted_multi_model = multi_model.fit() # print the coefficients print(fitted_multi_model.params)
Data Science UA - September 2017/Lecture 05 - Modeling Techniques and Regression/Linear_Regression.ipynb
iRipVanWinkle/ml
mit
How do we interpret the coefficients? For a given amount of Radio and Newspaper ad spending, an increase of a unit ($1000 dollars) in TV ad spending is associated with an increase in Sales of 45.765 widgets. Other information is available in the model summary output:
# print a summary of the fitted model fitted_multi_model.summary()
Data Science UA - September 2017/Lecture 05 - Modeling Techniques and Regression/Linear_Regression.ipynb
iRipVanWinkle/ml
mit
TV and Radio have significant p-values, whereas Newspaper does not. Thus we reject the null hypothesis for TV and Radio (that there is no association between those features and Sales), and fail to reject the null hypothesis for Newspaper. TV and Radio ad spending are both positively associated with Sales, whereas Newsp...
# only include TV and Radio in the model model1 = sf.ols(formula='Sales ~ TV + Radio', data=data).fit() print(model1.rsquared) # add Newspaper to the model (which we believe has no association with Sales) model2 = sf.ols(formula='Sales ~ TV + Radio + Newspaper', data=data).fit() print(model2.rsquared)
Data Science UA - September 2017/Lecture 05 - Modeling Techniques and Regression/Linear_Regression.ipynb
iRipVanWinkle/ml
mit
R-squared will always increase as you add more features to the model, even if they are unrelated to the response. Thus, selecting the model with the highest R-squared is not a reliable approach for choosing the best linear model. There is alternative to R-squared called adjusted R-squared that penalizes model complexit...
# create a DataFrame feature_cols = ['TV', 'Radio', 'Newspaper'] X = data[feature_cols] y = data.Sales from sklearn.linear_model import LinearRegression lm = LinearRegression() lm.fit(X, y) # print intercept and coefficients print(lm.intercept_) print(lm.coef_) # pair the feature names with the coefficients print(z...
Data Science UA - September 2017/Lecture 05 - Modeling Techniques and Regression/Linear_Regression.ipynb
iRipVanWinkle/ml
mit
Handling Categorical Predictors with Two Categories What if one of the predictors was categorical? Let's create a new feature called Size, and randomly assign observations to be small or large:
import numpy as np # create a Series of booleans in which roughly half are True #generate len(data) numbers between 0 and 1 numbers = np.random.rand(len(data)) #create and index of 0s and 1s by based on whether the corresponding random number #is greater than 0.5. index_for_large = (numbers > 0.5) #create a new da...
Data Science UA - September 2017/Lecture 05 - Modeling Techniques and Regression/Linear_Regression.ipynb
iRipVanWinkle/ml
mit
When using scikit-learn, we need to represent all data numerically. For example, if the feature we want to represent has only two categories, we create a dummy variable that represents the categories as a binary value:
# create a new Series called IsLarge data['IsLarge'] = data.Size.map({'small':0, 'large':1}) data.head()
Data Science UA - September 2017/Lecture 05 - Modeling Techniques and Regression/Linear_Regression.ipynb
iRipVanWinkle/ml
mit
The multiple linear regression including the IsLarge predictor:
# create X and y feature_cols = ['TV', 'Radio', 'Newspaper', 'IsLarge'] X = data[feature_cols] y = data.Sales # instantiate, fit lm = LinearRegression() lm.fit(X, y) # print coefficients list(zip(feature_cols, lm.coef_))
Data Science UA - September 2017/Lecture 05 - Modeling Techniques and Regression/Linear_Regression.ipynb
iRipVanWinkle/ml
mit
How do we interpret the coefficient of IsLarge? For a given amount of TV/Radio/Newspaper ad spending, a large market is associated with an average increase in Sales of 51.55 widgets (as compared to sales in a Small market). If we reverse the 0/1 encoding and created the feature 'IsSmall', the coefficient would be the s...
# set a seed for reproducibility np.random.seed(123456) # assign roughly one third of observations to each group nums = np.random.rand(len(data)) mask_suburban = (nums > 0.33) & (nums < 0.66) mask_urban = nums > 0.66 data['Area'] = 'rural' data.loc[mask_suburban, 'Area'] = 'suburban' data.loc[mask_urban, 'Area'] = 'ur...
Data Science UA - September 2017/Lecture 05 - Modeling Techniques and Regression/Linear_Regression.ipynb
iRipVanWinkle/ml
mit
We have to represent Area numerically, but an encoding such as 0=rural, 1=suburban, 2=urban would not work because that would imply that there is an ordered relationship between suburban and urban. Instead, we can create another dummy variable.
# create three dummy variables using get_dummies, then exclude the first dummy column area_dummies = pd.get_dummies(data.Area, prefix='Area').iloc[:, 1:] # concatenate the dummy variable columns onto the original DataFrame (axis=0 means rows, axis=1 means columns) data = pd.concat([data, area_dummies], axis=1) data.he...
Data Science UA - September 2017/Lecture 05 - Modeling Techniques and Regression/Linear_Regression.ipynb
iRipVanWinkle/ml
mit
rural is coded as Area_suburban=0 and Area_urban=0 suburban is coded as Area_suburban=1 and Area_urban=0 urban is coded as Area_suburban=0 and Area_urban=1 Only two dummies are needed to captures all of the information about the Area feature.(In general, for a categorical feature with k levels, we create k-1 dummy var...
# read data into a DataFrame #data = pd.read_csv('http://www-bcf.usc.edu/~gareth/ISL/Advertising.csv', index_col=0) # create X and y feature_cols = ['TV', 'Radio', 'Newspaper', 'IsLarge', 'Area_suburban', 'Area_urban'] X = data[feature_cols] y = data.Sales # instantiate, fit lm = LinearRegression() lm.fit(X, y) # pr...
Data Science UA - September 2017/Lecture 05 - Modeling Techniques and Regression/Linear_Regression.ipynb
iRipVanWinkle/ml
mit
Hat potential The following potential is often used in Physics and other fields to describe symmetry breaking and is often known as the "hat potential": $$ V(x) = -a x^2 + b x^4 $$ Write a function hat(x,a,b) that returns the value of this function:
def hat(x,a,b): return -a*x**2+b*x**4 assert hat(0.0, 1.0, 1.0)==0.0 assert hat(0.0, 1.0, 1.0)==0.0 assert hat(1.0, 10.0, 1.0)==-9.0
assignments/assignment11/OptimizationEx01.ipynb
brettavedisian/phys202-2015-work
mit
Plot this function over the range $x\in\left[-3,3\right]$ with $b=1.0$ and $a=5.0$:
a = 5.0 b = 1.0 x=np.linspace(-3,3,100) plt.figure(figsize=(9,6)) plt.xlabel('Range'), plt.ylabel('V(x)'), plt.title('Hat Potential') plt.plot(x, hat(x,a,b)) plt.box(False) plt.grid(True) plt.tick_params(axis='x', top='off', direction='out') plt.tick_params(axis='y', right='off', direction='out'); assert True # leave...
assignments/assignment11/OptimizationEx01.ipynb
brettavedisian/phys202-2015-work
mit
Write code that finds the two local minima of this function for $b=1.0$ and $a=5.0$. Use scipy.optimize.minimize to find the minima. You will have to think carefully about how to get this function to find both minima. Print the x values of the minima. Plot the function as a blue line. On the same axes, show the minima...
res1 = opt.minimize_scalar(hat, bounds=(-3,0), args=(a,b), method='bounded') res2 = opt.minimize_scalar(hat, bounds=(0,3), args=(a,b), method='bounded') print('Local minima: %f, %f' % (res1.x, res2.x)) plt.figure(figsize=(9,6)) plt.xlabel('Range'), plt.ylabel('V(x)') plt.plot(x, hat(x,a,b), label="Potential") plt.scatt...
assignments/assignment11/OptimizationEx01.ipynb
brettavedisian/phys202-2015-work
mit
MDR: and needs by GPU-fan code, too...
import utils_MDR from utils_MDR import *
deeplearning1/nbs/lesson5.ipynb
Mdround/fastai-deeplearning1
apache-2.0
Setup data We're going to look at the IMDB dataset, which contains movie reviews from IMDB, along with their sentiment. Keras comes with some helpers for this dataset.
from keras.datasets import imdb idx = imdb.get_word_index()
deeplearning1/nbs/lesson5.ipynb
Mdround/fastai-deeplearning1
apache-2.0
This is the word list:
idx_arr = sorted(idx, key=idx.get) idx_arr[:10]
deeplearning1/nbs/lesson5.ipynb
Mdround/fastai-deeplearning1
apache-2.0
...and this is the mapping from id to word
## idx2word = {v: k for k, v in idx.iteritems()} ## Py 2.7 idx2word = {v: k for k, v in idx.items()} ## Py 3.x
deeplearning1/nbs/lesson5.ipynb
Mdround/fastai-deeplearning1
apache-2.0
We download the reviews using code copied from keras.datasets:
path = get_file('imdb_full.pkl', origin='https://s3.amazonaws.com/text-datasets/imdb_full.pkl', md5_hash='d091312047c43cf9e4e38fef92437263') f = open(path, 'rb') (x_train, labels_train), (x_test, labels_test) = pickle.load(f) len(x_train)
deeplearning1/nbs/lesson5.ipynb
Mdround/fastai-deeplearning1
apache-2.0
Here's the 1st review. As you see, the words have been replaced by ids. The ids can be looked up in idx2word.
', '.join(map(str, x_train[0]))
deeplearning1/nbs/lesson5.ipynb
Mdround/fastai-deeplearning1
apache-2.0
The first word of the first review is 23022. Let's see what that is.
idx2word[23022]
deeplearning1/nbs/lesson5.ipynb
Mdround/fastai-deeplearning1
apache-2.0
Here's the whole review, mapped from ids to words.
' '.join([idx2word[o] for o in x_train[0]])
deeplearning1/nbs/lesson5.ipynb
Mdround/fastai-deeplearning1
apache-2.0
The labels are 1 for positive, 0 for negative.
labels_train[:10]
deeplearning1/nbs/lesson5.ipynb
Mdround/fastai-deeplearning1
apache-2.0
Reduce vocab size by setting rare words to max index.
vocab_size = 5000 trn = [np.array([i if i<vocab_size-1 else vocab_size-1 for i in s]) for s in x_train] test = [np.array([i if i<vocab_size-1 else vocab_size-1 for i in s]) for s in x_test]
deeplearning1/nbs/lesson5.ipynb
Mdround/fastai-deeplearning1
apache-2.0
Look at distribution of lengths of sentences.
## create an array of 'len'...gths # lens = np.array(map(len, trn)) ## only works in Py2.x, not 3.x ... ## 'map in Python 3 return an iterator, while map in Python 2 returns a list' ## (https://stackoverflow.com/questions/35691489/error-in-python-3-5-cant-add-map-results-together) # This is a quick fix - not re...
deeplearning1/nbs/lesson5.ipynb
Mdround/fastai-deeplearning1
apache-2.0
Pad (with zero) or truncate each sentence to make consistent length.
seq_len = 500 trn = sequence.pad_sequences(trn, maxlen=seq_len, value=0) test = sequence.pad_sequences(test, maxlen=seq_len, value=0)
deeplearning1/nbs/lesson5.ipynb
Mdround/fastai-deeplearning1
apache-2.0
This results in nice rectangular matrices that can be passed to ML algorithms. Reviews shorter than 500 words are pre-padded with zeros, those greater are truncated.
trn.shape
deeplearning1/nbs/lesson5.ipynb
Mdround/fastai-deeplearning1
apache-2.0
Create simple models Single hidden layer NN The simplest model that tends to give reasonable results is a single hidden layer net. So let's try that. Note that we can't expect to get any useful results by feeding word ids directly into a neural net - so instead we use an embedding to replace them with a vector of 32 (i...
model = Sequential([ Embedding(vocab_size, 32, input_length=seq_len), Flatten(), Dense(100, activation='relu'), Dropout(0.7), Dense(1, activation='sigmoid')]) model.compile(loss='binary_crossentropy', optimizer=Adam(), metrics=['accuracy']) model.summary() set_gpu_fan_speed(90) model.fit(trn, labe...
deeplearning1/nbs/lesson5.ipynb
Mdround/fastai-deeplearning1
apache-2.0
The stanford paper that this dataset is from cites a state of the art accuracy (without unlabelled data) of 0.883. So we're short of that, but on the right track. Single conv layer with max pooling A CNN is likely to work better, since it's designed to take advantage of ordered data. We'll need to use a 1D CNN, since a...
conv1 = Sequential([ Embedding(vocab_size, 32, input_length=seq_len, dropout=0.2), Dropout(0.2), Convolution1D(64, 5, border_mode='same', activation='relu'), Dropout(0.2), MaxPooling1D(), Flatten(), Dense(100, activation='relu'), Dropout(0.7), Dense(1, activation='sigmoid')]) conv1....
deeplearning1/nbs/lesson5.ipynb
Mdround/fastai-deeplearning1
apache-2.0