markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
Review
CSPs are a special kind of search problems. Here we don't treat the space as a black box but the state has a particular form and we use that to our advantage to tweak our algorithms to be more suited to the problems. A CSP State is defined by a set of variables which can take values from corresponding domains. T... | %psource CSP | .ipynb_checkpoints/csp-checkpoint.ipynb | nikodtbVf/aima-si | mit |
The _ init _ method parameters specify the CSP. Variable can be passed as a list of strings or integers. Domains are passed as dict where key specify the variables and value specify the domains. The variables are passed as an empty list. Variables are extracted from the keys of the domain dictionary. Neighbor is a di... | s = UniversalDict(['R','G','B'])
s[5] | .ipynb_checkpoints/csp-checkpoint.ipynb | nikodtbVf/aima-si | mit |
For our CSP we also need to define a constraint function f(A, a, B, b). In this what we need is that the neighbors must not have the same color. This is defined in the function different_values_constraint of the module. | %psource different_values_constraint | .ipynb_checkpoints/csp-checkpoint.ipynb | nikodtbVf/aima-si | mit |
The CSP class takes neighbors in the form of a Dict. The module specifies a simple helper function named parse_neighbors which allows to take input in the form of strings and return a Dict of the form compatible with the CSP Class. | %pdoc parse_neighbors | .ipynb_checkpoints/csp-checkpoint.ipynb | nikodtbVf/aima-si | mit |
The MapColoringCSP function creates and returns a CSP with the above constraint function and states. The variables our the keys of the neighbors dict and the constraint is the one specified by the different_values_constratint function. australia, usa and france are three CSPs that have been created using MapColoringCSP... | %psource MapColoringCSP
australia, usa, france | .ipynb_checkpoints/csp-checkpoint.ipynb | nikodtbVf/aima-si | mit |
NQueens
The N-queens puzzle is the problem of placing N chess queens on a N×N chessboard so that no two queens threaten each other. Here N is a natural number. Like the graph coloring, problem NQueens is also implemented in the csp module. The NQueensCSP class inherits from the CSP class. It makes some modifications in... | %psource queen_constraint | .ipynb_checkpoints/csp-checkpoint.ipynb | nikodtbVf/aima-si | mit |
The NQueensCSP method implements methods that support solving the problem via min_conflicts which is one of the techniques for solving CSPs. Because min_conflicts hill climbs the number of conflicts to solve the CSP assign and unassign are modified to record conflicts. More details about the structures rows, downs, ups... | %psource NQueensCSP | .ipynb_checkpoints/csp-checkpoint.ipynb | nikodtbVf/aima-si | mit |
The _ init _ method takes only one parameter n the size of the problem. To create an instance we just pass the required n into the constructor. | eight_queens = NQueensCSP(8) | .ipynb_checkpoints/csp-checkpoint.ipynb | nikodtbVf/aima-si | mit |
Helper Functions
We will now implement few helper functions that will help us visualize the Coloring Problem. We will make some modifications to the existing Classes and Functions for additional book keeping. To begin with we modify the assign and unassign methods in the CSP to add a copy of the assignment to the assin... | import copy
class InstruCSP(CSP):
def __init__(self, variables, domains, neighbors, constraints):
super().__init__(variables, domains, neighbors, constraints)
self.assingment_history = []
def assign(self, var, val, assignment):
super().assign(var,val, assignment)
se... | .ipynb_checkpoints/csp-checkpoint.ipynb | nikodtbVf/aima-si | mit |
Next, we define make_instru which takes an instance of CSP and returns a InstruCSP instance. | def make_instru(csp):
return InstruCSP(csp.variables, csp.domains, csp.neighbors,
csp.constraints) | .ipynb_checkpoints/csp-checkpoint.ipynb | nikodtbVf/aima-si | mit |
We will now use a graph defined as a dictonary for plotting purposes in our Graph Coloring Problem. The keys are the nodes and their corresponding values are the nodes are they are connected to. | neighbors = {
0: [6, 11, 15, 18, 4, 11, 6, 15, 18, 4],
1: [12, 12, 14, 14],
2: [17, 6, 11, 6, 11, 10, 17, 14, 10, 14],
3: [20, 8, 19, 12, 20, 19, 8, 12],
4: [11, 0, 18, 5, 18, 5, 11, 0],
5: [4, 4],
6: [8, 15, 0, 11, 2, 14, 8, 11, 15, 2, 0, 14],
7: [13, 16, 13, 16],
8: [19, 15... | .ipynb_checkpoints/csp-checkpoint.ipynb | nikodtbVf/aima-si | mit |
Backtracking Search
For solving a CSP the main issue with Naive search algorithms is that they can continue expanding obviously wrong paths. In backtracking search, we check constraints as we go. Backtracking is just the above idea combined with the fact that we are dealing with one variable at a time. Backtracking Sea... | result = backtracking_search(coloring_problem1)
result # A dictonary of assingments. | .ipynb_checkpoints/csp-checkpoint.ipynb | nikodtbVf/aima-si | mit |
Let us also check the number of assingments made. | coloring_problem1.nassigns | .ipynb_checkpoints/csp-checkpoint.ipynb | nikodtbVf/aima-si | mit |
Now let us check the total number of assingments and unassingments which is the lentgh ofour assingment history. | len(coloring_problem1.assingment_history) | .ipynb_checkpoints/csp-checkpoint.ipynb | nikodtbVf/aima-si | mit |
Now let us explore the optional keyword arguments that the backtracking_search function takes. These optional arguments help speed up the assignment further. Along with these, we will also point out to methods in the CSP class that help make this work.
The first of these is select_unassigned_variable. It takes in a fu... | %psource mrv
%psource num_legal_values
%psource CSP.nconflicts | .ipynb_checkpoints/csp-checkpoint.ipynb | nikodtbVf/aima-si | mit |
Another ordering related parameter order_domain_values governs the value ordering. Here we select the Least Constraining Value which is implemented by the function lcv. The idea is to select the value which rules out the fewest values in the remaining variables. The intuition behind selecting the lcv is that it leaves ... | %psource lcv | .ipynb_checkpoints/csp-checkpoint.ipynb | nikodtbVf/aima-si | mit |
Finally, the third parameter inference can make use of one of the two techniques called Arc Consistency or Forward Checking. The details of these methods can be found in the Section 6.3.2 of the book. In short the idea of inference is to detect the possible failure before it occurs and to look ahead to not make mistake... | solve_simple = copy.deepcopy(usa)
solve_parameters = copy.deepcopy(usa)
backtracking_search(solve_simple)
backtracking_search(solve_parameters, order_domain_values=lcv, select_unassigned_variable=mrv, inference=mac )
solve_simple.nassigns
solve_parameters.nassigns | .ipynb_checkpoints/csp-checkpoint.ipynb | nikodtbVf/aima-si | mit |
Graph Coloring Visualization
Next, we define some functions to create the visualisation from the assingment_history of coloring_problem1. The reader need not concern himself with the code that immediately follows as it is the usage of Matplotib with IPython Widgets. If you are interested in reading more about these vis... | %matplotlib inline
import networkx as nx
import matplotlib.pyplot as plt
import matplotlib
import time | .ipynb_checkpoints/csp-checkpoint.ipynb | nikodtbVf/aima-si | mit |
The ipython widgets we will be using require the plots in the form of a step function such that there is a graph corresponding to each value. We define the make_update_step_function which return such a function. It takes in as inputs the neighbors/graph along with an instance of the InstruCSP. This will be more clear w... | def make_update_step_function(graph, instru_csp):
def draw_graph(graph):
# create networkx graph
G=nx.Graph(graph)
# draw graph
pos = nx.spring_layout(G,k=0.15)
return (G, pos)
G, pos = draw_graph(graph)
def update_step(iteration):
# here iterat... | .ipynb_checkpoints/csp-checkpoint.ipynb | nikodtbVf/aima-si | mit |
Finally let us plot our problem. We first use the function above to obtain a step function. | step_func = make_update_step_function(neighbors, coloring_problem1) | .ipynb_checkpoints/csp-checkpoint.ipynb | nikodtbVf/aima-si | mit |
Next we set the canvas size. | matplotlib.rcParams['figure.figsize'] = (18.0, 18.0) | .ipynb_checkpoints/csp-checkpoint.ipynb | nikodtbVf/aima-si | mit |
Finally our plot using ipywidget slider and matplotib. You can move the slider to experiment and see the coloring change. It is also possible to move the slider using arrow keys or to jump to the value by directly editing the number with a double click. The Visualize Button will automatically animate the slider for you... | import ipywidgets as widgets
from IPython.display import display
iteration_slider = widgets.IntSlider(min=0, max=len(coloring_problem1.assingment_history)-1, step=1, value=0)
w=widgets.interactive(step_func,iteration=iteration_slider)
display(w)
visualize_callback = make_visualize(iteration_slider)
visualize_button ... | .ipynb_checkpoints/csp-checkpoint.ipynb | nikodtbVf/aima-si | mit |
NQueens Visualization
Just like the Graph Coloring Problem we will start with defining a few helper functions to help us visualize the assignments as they evolve over time. The make_plot_board_step_function behaves similar to the make_update_step_function introduced earlier. It initializes a chess board in the form of ... | def label_queen_conflicts(assingment,grid):
''' Mark grid with queens that are under conflict. '''
for col, row in assingment.items(): # check each queen for conflict
row_conflicts = {temp_col:temp_row for temp_col,temp_row in assingment.items()
if temp_row == row and temp_col ... | .ipynb_checkpoints/csp-checkpoint.ipynb | nikodtbVf/aima-si | mit |
Now let us visualize a solution obtained via backtracking. We use of the previosuly defined make_instru function for keeping a history of steps. | twelve_queens_csp = NQueensCSP(12)
backtracking_instru_queen = make_instru(twelve_queens_csp)
result = backtracking_search(backtracking_instru_queen)
backtrack_queen_step = make_plot_board_step_function(backtracking_instru_queen) # Step Function for Widgets | .ipynb_checkpoints/csp-checkpoint.ipynb | nikodtbVf/aima-si | mit |
Now finally we set some matplotlib parameters to adjust how our plot will look. The font is necessary because the Black Queen Unicode character is not a part of all fonts. You can move the slider to experiment and observe the how queens are assigned. It is also possible to move the slider using arrow keys or to jump to... | matplotlib.rcParams['figure.figsize'] = (8.0, 8.0)
matplotlib.rcParams['font.family'].append(u'Dejavu Sans')
iteration_slider = widgets.IntSlider(min=0, max=len(backtracking_instru_queen.assingment_history)-1, step=0, value=0)
w=widgets.interactive(backtrack_queen_step,iteration=iteration_slider)
display(w)
visualize... | .ipynb_checkpoints/csp-checkpoint.ipynb | nikodtbVf/aima-si | mit |
The visualization has same features as the above. But here it also highlights the conflicts by labeling the conflicted queens with a red background. | iteration_slider = widgets.IntSlider(min=0, max=len(conflicts_instru_queen.assingment_history)-1, step=0, value=0)
w=widgets.interactive(conflicts_step,iteration=iteration_slider)
display(w)
visualize_callback = make_visualize(iteration_slider)
visualize_button = widgets.ToggleButton(desctiption = "Visualize", value ... | .ipynb_checkpoints/csp-checkpoint.ipynb | nikodtbVf/aima-si | mit |
Configuring MNE python
This tutorial gives a short introduction to MNE configurations. | import os.path as op
import mne
from mne.datasets.sample import data_path
fname = op.join(data_path(), 'MEG', 'sample', 'sample_audvis_raw.fif')
raw = mne.io.read_raw_fif(fname).crop(0, 10)
original_level = mne.get_config('MNE_LOGGING_LEVEL', 'INFO') | 0.18/_downloads/8a8a7b741ef485e4d3d3772b252fcb81/plot_configuration.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
MNE-python stores configurations to a folder called .mne in the user's
home directory, or to AppData directory on Windows. The path to the config
file can be found out by calling :func:mne.get_config_path. | print(mne.get_config_path()) | 0.18/_downloads/8a8a7b741ef485e4d3d3772b252fcb81/plot_configuration.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
These configurations include information like sample data paths and plotter
window sizes. Files inside this folder should never be modified manually.
Let's see what the configurations contain. | print(mne.get_config()) | 0.18/_downloads/8a8a7b741ef485e4d3d3772b252fcb81/plot_configuration.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
We see fields like "MNE_DATASETS_SAMPLE_PATH". As the name suggests, this is
the path the sample data is downloaded to. All the fields in the
configuration file can be modified by calling :func:mne.set_config.
Logging
Configurations also include the default logging level for the functions. This
field is called "MNE_LOG... | mne.set_config('MNE_LOGGING_LEVEL', 'INFO')
print(mne.get_config(key='MNE_LOGGING_LEVEL')) | 0.18/_downloads/8a8a7b741ef485e4d3d3772b252fcb81/plot_configuration.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
The default value is now set to INFO. This level will now be used by default
every time we call a function in MNE. We can set the global logging level for
only this session by calling :func:mne.set_log_level function. | mne.set_log_level('WARNING')
print(mne.get_config(key='MNE_LOGGING_LEVEL')) | 0.18/_downloads/8a8a7b741ef485e4d3d3772b252fcb81/plot_configuration.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Notice how the value in the config file was not changed. Logging level of
WARNING only applies for this session. Let's see what logging level of
WARNING prints for :func:mne.compute_raw_covariance. | cov_raw = mne.compute_raw_covariance(raw) | 0.18/_downloads/8a8a7b741ef485e4d3d3772b252fcb81/plot_configuration.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Nothing. This means that no warnings were emitted during the computation. If
you look at the documentation of :func:mne.compute_raw_covariance, you
notice the verbose keyword. Setting this parameter does not touch the
configurations, but sets the logging level for just this one function call.
Let's see what happens wit... | cov = mne.compute_raw_covariance(raw, verbose=True) | 0.18/_downloads/8a8a7b741ef485e4d3d3772b252fcb81/plot_configuration.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
As you see there is some info about what the function is doing. The logging
level can be set to 'DEBUG', 'INFO', 'WARNING', 'ERROR' or 'CRITICAL'. It can
also be set to an integer or a boolean value. The correspondence to string
values can be seen in the table below. verbose=None uses the default
value from the configu... | mne.set_config('MNE_LOGGING_LEVEL', original_level)
print('Config value restored to: %s' % mne.get_config(key='MNE_LOGGING_LEVEL')) | 0.18/_downloads/8a8a7b741ef485e4d3d3772b252fcb81/plot_configuration.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Running TFLite models
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://colab.research.google.com/github/tensorflow/examples/blob/master/courses/udacity_intro_to_tensorflow_lite/tflite_c01_linear_regression.ipynb">
<img src="https://www.tensorflow.org/images/colab_logo_32... | import tensorflow as tf
import pathlib
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input | courses/udacity_intro_to_tensorflow_lite/tflite_c01_linear_regression.ipynb | tensorflow/examples | apache-2.0 |
Create a basic model of the form y = mx + c | # Create a simple Keras model.
x = [-1, 0, 1, 2, 3, 4]
y = [-3, -1, 1, 3, 5, 7]
model = tf.keras.models.Sequential([
tf.keras.layers.Dense(units=1, input_shape=[1])
])
model.compile(optimizer='sgd', loss='mean_squared_error')
model.fit(x, y, epochs=200, verbose=1) | courses/udacity_intro_to_tensorflow_lite/tflite_c01_linear_regression.ipynb | tensorflow/examples | apache-2.0 |
Generate a SavedModel | export_dir = 'saved_model/1'
tf.saved_model.save(model, export_dir) | courses/udacity_intro_to_tensorflow_lite/tflite_c01_linear_regression.ipynb | tensorflow/examples | apache-2.0 |
Convert the SavedModel to TFLite | # Convert the model.
converter = tf.lite.TFLiteConverter.from_saved_model(export_dir)
tflite_model = converter.convert()
tflite_model_file = pathlib.Path('model.tflite')
tflite_model_file.write_bytes(tflite_model) | courses/udacity_intro_to_tensorflow_lite/tflite_c01_linear_regression.ipynb | tensorflow/examples | apache-2.0 |
Initialize the TFLite interpreter to try it out | # Load TFLite model and allocate tensors.
interpreter = tf.lite.Interpreter(model_content=tflite_model)
interpreter.allocate_tensors()
# Get input and output tensors.
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
# Test the TensorFlow Lite model on random input data... | courses/udacity_intro_to_tensorflow_lite/tflite_c01_linear_regression.ipynb | tensorflow/examples | apache-2.0 |
Visualize the model | plt.plot(inputs, outputs, 'r')
plt.show() | courses/udacity_intro_to_tensorflow_lite/tflite_c01_linear_regression.ipynb | tensorflow/examples | apache-2.0 |
Download the TFLite model file | try:
from google.colab import files
files.download(tflite_model_file)
except:
pass | courses/udacity_intro_to_tensorflow_lite/tflite_c01_linear_regression.ipynb | tensorflow/examples | apache-2.0 |
Part 3.a
The first machine learning algorithm for classifying spam emails is the Naive Bayes model. First we trained the model using the MATRIX.TRAIN data file. | df_train = rm.read_data('spam_data/MATRIX.TRAIN')
nb_model = nb_train.train(df_train) | src/homework2/q3/homework2_3.ipynb | stallmanifold/cs229-machine-learning-stanford-fall-2016 | apache-2.0 |
Next we ran the model against the testing data. | df_test = rm.read_data('spam_data/MATRIX.TEST')
nb_predictions = nb_test.test(nb_model, df_test) | src/homework2/q3/homework2_3.ipynb | stallmanifold/cs229-machine-learning-stanford-fall-2016 | apache-2.0 |
The following is the testing error. | y = df_test.iloc[:,0]
nb_error = nb_test.compute_error(y, nb_predictions)
print('NB Test error: {}'.format(nb_error)) | src/homework2/q3/homework2_3.ipynb | stallmanifold/cs229-machine-learning-stanford-fall-2016 | apache-2.0 |
Part 3.b.
The five most indicative words of a spam message are the following. | words = nb_test.k_most_indicative_words(5, nb_model.to_dataframe().iloc[:,1:])
print('The {} most spam-worthy words are: {}'.format(len(words), words)) | src/homework2/q3/homework2_3.ipynb | stallmanifold/cs229-machine-learning-stanford-fall-2016 | apache-2.0 |
Part 3.c.
To test the convergence properties of the Naive Bayes classifier on the email data set, it needs to be run on different training set sizes. Here we use six different sized training sets to see how the error rate progresses. | training_set_files = {
50 : 'spam_data/MATRIX.TRAIN.50',
100 : 'spam_data/MATRIX.TRAIN.100',
200 : 'spam_data/MATRIX.TRAIN.200',
400 : 'spam_data/MATRIX.TRAIN.400',
800 : 'spam_data/MATRIX.TRAIN.800',
1400 : 'spam_data/MATRIX.TRAIN.1400'
} | src/homework2/q3/homework2_3.ipynb | stallmanifold/cs229-machine-learning-stanford-fall-2016 | apache-2.0 |
Estimate the models and compute the errors. | nb_models = {}
for size, filename in training_set_files.items():
df_next = rm.read_data(filename)
m = nb_train.train(df_next)
nb_models[size] = m
nb_errors = {}
for size, model in nb_models.items():
guessed_y = nb_test.test(model, df_test)
err = nb_test.compute_error(y, guessed_y)
nb_errors[siz... | src/homework2/q3/homework2_3.ipynb | stallmanifold/cs229-machine-learning-stanford-fall-2016 | apache-2.0 |
The resulting errors are | print('Naive Bayes')
for size, error in nb_errors.items():
print('size: {}; error: {}'.format(size, error)) | src/homework2/q3/homework2_3.ipynb | stallmanifold/cs229-machine-learning-stanford-fall-2016 | apache-2.0 |
As the training set size increases, the error rate for the Naive Bayes classifier decreases. It converges above a training set size of about 1000 emails.
Part 3.d.
The second model used to classify the emails is a support vector machine. As in part (a), we train the SVM model using the MATRIX.TRAIN data. | tau = 8
max_iters = 40
svm_model = svm_train.train(df_train, tau, max_iters) | src/homework2/q3/homework2_3.ipynb | stallmanifold/cs229-machine-learning-stanford-fall-2016 | apache-2.0 |
Next, we run the trained SVM model against the testing data. | svm_predictions = svm_test.test(svm_model, df_test)
print(svm_predictions.shape) | src/homework2/q3/homework2_3.ipynb | stallmanifold/cs229-machine-learning-stanford-fall-2016 | apache-2.0 |
The testing error is: | ytest = 2 * df_test.iloc[:,0].as_matrix() - 1
svm_error = svm_test.compute_error(ytest, svm_predictions)
print('SVM Test Error: {}'.format(svm_error)) | src/homework2/q3/homework2_3.ipynb | stallmanifold/cs229-machine-learning-stanford-fall-2016 | apache-2.0 |
For the varying sized training sets, we estimate an SVM model. | svm_models = {}
for size, filename in training_set_files.items():
df_next = rm.read_data(filename)
m = svm_train.train(df_next, tau, max_iters)
svm_models[size] = m | src/homework2/q3/homework2_3.ipynb | stallmanifold/cs229-machine-learning-stanford-fall-2016 | apache-2.0 |
And we compute the errors for each model. | svm_errors = {}
for size, model in svm_models.items():
guessed_y = svm_test.test(model, df_test)
err = svm_test.compute_error(ytest, guessed_y)
svm_errors[size] = err | src/homework2/q3/homework2_3.ipynb | stallmanifold/cs229-machine-learning-stanford-fall-2016 | apache-2.0 |
The resulting errors are | print('Support Vector Machine')
for size, error in svm_errors.items():
print('size: {}; error: {}'.format(size, error)) | src/homework2/q3/homework2_3.ipynb | stallmanifold/cs229-machine-learning-stanford-fall-2016 | apache-2.0 |
Modifying the isotopic yields of a specific stellar model | # Select an isotope and a stellar model (the model needs to be in the yields table).
iso = "Si-28"
M = 15.0
Z = 0.02
# Run SYGMA with no yields modification.
s1 = sygma.sygma(iniZ=Z)
# Run SYGMA where the yield is multiplied by 2.
factor = 2.0
yield_modifier = [ [iso, M, Z, "multiply", factor] ]
s2 = sygma.sygma(iniZ... | DOC/Capabilities/Modifying_yields.ipynb | NuGrid/NuPyCEE | bsd-3-clause |
Modifying the isotopic yields of several stellar models | # Select an isotope
iso = "Si-28"
# Define the list of multiplication factor for each stellar model
factor_list = [2, 4, 8, 16]
M_list = [12.0, 15.0, 20.0, 25.0]
Z = 0.02
# Fill the yield_modifier array
yield_modifier = []
for M, factor in zip(M_list, factor_list):
yield_modifier.append([iso, M, Z, "multiply", fa... | DOC/Capabilities/Modifying_yields.ipynb | NuGrid/NuPyCEE | bsd-3-clause |
Example with OMEGA | # Import the NuPyCEE galactic chemical evolution code
from NuPyCEE import omega
# Print the list of available M and Z in the yields table
print("M:",s1.M_table)
print("Z:",s1.Z_table)
# Boost the Mg-24 yields of all massive stars by a factor of 2
iso = "Mg-24"
yield_modifier = []
for M in [12.0, 15.0, 20.0, 25.0]:
... | DOC/Capabilities/Modifying_yields.ipynb | NuGrid/NuPyCEE | bsd-3-clause |
Unobserved Components
The unobserved components model available in Statsmodels can be written as:
$$
y_t = \underbrace{\mu_{t}}{\text{trend}} + \underbrace{\gamma{t}}{\text{seasonal}} + \underbrace{c{t}}{\text{cycle}} + \sum{j=1}^k \underbrace{\beta_j x_{jt}}{\text{explanatory}} + \underbrace{\varepsilon_t}{\text{irreg... | # Datasets
from pandas.io.data import DataReader
# Get the raw data
start = '1948-01'
end = '2008-01'
us_gnp = DataReader('GNPC96', 'fred', start=start, end=end)
us_gnp_deflator = DataReader('GNPDEF', 'fred', start=start, end=end)
us_monetary_base = DataReader('AMBSL', 'fred', start=start, end=end).resample('QS')
rece... | examples/notebooks/statespace_structural_harvey_jaeger.ipynb | YihaoLu/statsmodels | bsd-3-clause |
To get a sense of these three variables over the timeframe, we can plot them: | # Plot the data
ax = dta.plot(figsize=(13,3))
ylim = ax.get_ylim()
ax.xaxis.grid()
ax.fill_between(dates, ylim[0]+1e-5, ylim[1]-1e-5, recessions, facecolor='k', alpha=0.1); | examples/notebooks/statespace_structural_harvey_jaeger.ipynb | YihaoLu/statsmodels | bsd-3-clause |
Model
Since the data is already seasonally adjusted and there are no obvious explanatory variables, the generic model considered is:
$$
y_t = \underbrace{\mu_{t}}{\text{trend}} + \underbrace{c{t}}{\text{cycle}} + \underbrace{\varepsilon_t}{\text{irregular}}
$$
The irregular will be assumed to be white noise, and the cy... | # Model specifications
# Unrestricted model, using string specification
unrestricted_model = {
'level': 'local linear trend', 'cycle': True, 'damped_cycle': True, 'stochastic_cycle': True
}
# Unrestricted model, setting components directly
# This is an equivalent, but less convenient, way to specify a
# local lin... | examples/notebooks/statespace_structural_harvey_jaeger.ipynb | YihaoLu/statsmodels | bsd-3-clause |
We now fit the following models:
Output, unrestricted model
Prices, unrestricted model
Prices, restricted model
Money, unrestricted model
Money, restricted model | # Output
output_mod = sm.tsa.UnobservedComponents(dta['US GNP'], **unrestricted_model)
output_res = output_mod.fit(method='powell', disp=False)
# Prices
prices_mod = sm.tsa.UnobservedComponents(dta['US Prices'], **unrestricted_model)
prices_res = prices_mod.fit(method='powell', disp=False)
prices_restricted_mod = sm.... | examples/notebooks/statespace_structural_harvey_jaeger.ipynb | YihaoLu/statsmodels | bsd-3-clause |
Once we have fit these models, there are a variety of ways to display the information. Looking at the model of US GNP, we can summarize the fit of the model using the summary method on the fit object. | print(output_res.summary()) | examples/notebooks/statespace_structural_harvey_jaeger.ipynb | YihaoLu/statsmodels | bsd-3-clause |
For unobserved components models, and in particular when exploring stylized facts in line with point (2) from the introduction, it is often more instructive to plot the estimated unobserved components (e.g. the level, trend, and cycle) themselves to see if they provide a meaningful description of the data.
The plot_com... | fig = output_res.plot_components(legend_loc='lower right', figsize=(15, 9)); | examples/notebooks/statespace_structural_harvey_jaeger.ipynb | YihaoLu/statsmodels | bsd-3-clause |
Finally, Harvey and Jaeger summarize the models in another way to highlight the relative importances of the trend and cyclical components; below we replicate their Table I. The values we find are broadly consistent with, but different in the particulars from, the values from their table. | # Create Table I
table_i = np.zeros((5,6))
start = dta.index[0]
end = dta.index[-1]
time_range = '%d:%d-%d:%d' % (start.year, start.quarter, end.year, end.quarter)
models = [
('US GNP', time_range, 'None'),
('US Prices', time_range, 'None'),
('US Prices', time_range, r'$\sigma_\eta^2 = 0$'),
('US monet... | examples/notebooks/statespace_structural_harvey_jaeger.ipynb | YihaoLu/statsmodels | bsd-3-clause |
Load Iris Dataset | # Load data
iris = datasets.load_iris()
X = iris.data
y = iris.target | machine-learning/hyperparameter_tuning_using_grid_search.ipynb | tpin3694/tpin3694.github.io | mit |
Create Logistic Regression | # Create logistic regression
logistic = linear_model.LogisticRegression() | machine-learning/hyperparameter_tuning_using_grid_search.ipynb | tpin3694/tpin3694.github.io | mit |
Create Hyperparameter Search Space | # Create regularization penalty space
penalty = ['l1', 'l2']
# Create regularization hyperparameter space
C = np.logspace(0, 4, 10)
# Create hyperparameter options
hyperparameters = dict(C=C, penalty=penalty) | machine-learning/hyperparameter_tuning_using_grid_search.ipynb | tpin3694/tpin3694.github.io | mit |
Create Grid Search | # Create grid search using 5-fold cross validation
clf = GridSearchCV(logistic, hyperparameters, cv=5, verbose=0) | machine-learning/hyperparameter_tuning_using_grid_search.ipynb | tpin3694/tpin3694.github.io | mit |
Conduct Grid Search | # Fit grid search
best_model = clf.fit(X, y) | machine-learning/hyperparameter_tuning_using_grid_search.ipynb | tpin3694/tpin3694.github.io | mit |
View Hyperparameter Values Of Best Model | # View best hyperparameters
print('Best Penalty:', best_model.best_estimator_.get_params()['penalty'])
print('Best C:', best_model.best_estimator_.get_params()['C']) | machine-learning/hyperparameter_tuning_using_grid_search.ipynb | tpin3694/tpin3694.github.io | mit |
Predict Using Best Model | # Predict target vector
best_model.predict(X) | machine-learning/hyperparameter_tuning_using_grid_search.ipynb | tpin3694/tpin3694.github.io | mit |
Python for Probability, Statistics, and Machine Learning | from __future__ import division
%pylab inline | chapters/statistics/notebooks/Bootstrap.ipynb | unpingco/Python-for-Probability-Statistics-and-Machine-Learning | mit |
As we have seen, outside of some toy problems, it can be very difficult or
impossible to determine the probability density distribution of the estimator
of some quantity. The idea behind the bootstrap is that we can use computation
to approximate these functions which would otherwise be impossible to solve
for anal... | import numpy as np
_=np.random.seed(123456)
import numpy as np
from scipy import stats
rv = stats.beta(3,2)
xsamples = rv.rvs(50) | chapters/statistics/notebooks/Bootstrap.ipynb | unpingco/Python-for-Probability-Statistics-and-Machine-Learning | mit |
Because this is simulation data, we already know that the
mean is $\mu_1 = 3/5$ and the standard deviation of the sample mean
for $n=50$ is $\bar{\sigma} =1/\sqrt {1250}$, which we will verify
this later. | %matplotlib inline
from matplotlib.pylab import subplots
fig,ax = subplots()
fig.set_size_inches(8,4)
_=ax.hist(xsamples,normed=True,color='gray')
ax2 = ax.twinx()
_=ax2.plot(np.linspace(0,1,100),rv.pdf(np.linspace(0,1,100)),lw=3,color='k')
_=ax.set_xlabel('$x$',fontsize=28)
_=ax2.set_ylabel(' $y$',fontsize=28,rotati... | chapters/statistics/notebooks/Bootstrap.ipynb | unpingco/Python-for-Probability-Statistics-and-Machine-Learning | mit |
<!-- dom:FIGURE: [fig-statistics/Bootstrap_001.png, width=500 frac=0.85] The $\beta(3,2)$ distribution and the histogram that approximates it. <div id="fig:Bootstrap_001"></div> -->
<!-- begin figure -->
<div id="fig:Bootstrap_001"></div>
<p>The $\beta(3,2)$ distribution and the histogram that approximates it.</p>
<im... | yboot = np.random.choice(xsamples,(100,50))
yboot_mn = yboot.mean() | chapters/statistics/notebooks/Bootstrap.ipynb | unpingco/Python-for-Probability-Statistics-and-Machine-Learning | mit |
and the bootstrap estimate is therefore, | np.std(yboot.mean(axis=1)) # approx sqrt(1/1250) | chapters/statistics/notebooks/Bootstrap.ipynb | unpingco/Python-for-Probability-Statistics-and-Machine-Learning | mit |
Figure shows the distribution of computed
sample means from the bootstrap samples. As promised, the next block
shows how to use sympy.stats to compute the $\beta(3,2)$ parameters we quoted
earlier. | fig,ax = subplots()
fig.set_size_inches(8,4)
_=ax.hist(yboot.mean(axis=1),normed=True,color='gray')
_=ax.set_title('Bootstrap std of sample mean %3.3f vs actual %3.3f'%
(np.std(yboot.mean(axis=1)),np.sqrt(1/1250.)))
fig.tight_layout()
#fig.savefig('fig-statistics/Bootstrap_002.png') | chapters/statistics/notebooks/Bootstrap.ipynb | unpingco/Python-for-Probability-Statistics-and-Machine-Learning | mit |
<!-- dom:FIGURE: [fig-statistics/Bootstrap_002.png, width=500 frac=0.85] For each bootstrap draw, we compute the sample mean. This is the histogram of those sample means that will be used to compute the bootstrap estimate of the standard deviation. <div id="fig:Bootstrap_002"></div> -->
<!-- begin figure -->
<div id="f... | import sympy as S
import sympy.stats
for i in range(50): # 50 samples
# load sympy.stats Beta random variables
# into global namespace using exec
execstring = "x%d = S.stats.Beta('x'+str(%d),3,2)"%(i,i)
exec(execstring)
# populate xlist with the sympy.stats random variables
# from above
xlist = [eval(... | chapters/statistics/notebooks/Bootstrap.ipynb | unpingco/Python-for-Probability-Statistics-and-Machine-Learning | mit |
Programming Tip.
Using the exec function enables the creation of a sequence of Sympy
random variables. Sympy has the var function which can automatically
create a sequence of Sympy symbols, but there is no corresponding
function in the statistics module to do this for random variables.
<!-- @@@CODE src-statistics/Boots... | import numpy as np
np.random.seed(123)
from scipy import stats
import numpy as np
p= 0.25 # true head-up probability
x = stats.bernoulli(p).rvs(10)
print x | chapters/statistics/notebooks/Bootstrap.ipynb | unpingco/Python-for-Probability-Statistics-and-Machine-Learning | mit |
The maximum likelihood estimator of $p$ is $\hat{p}=\sum X_i/n$, | phat = x.mean()
print phat | chapters/statistics/notebooks/Bootstrap.ipynb | unpingco/Python-for-Probability-Statistics-and-Machine-Learning | mit |
Then, plugging this into the delta method approximant above, | print (1-2*phat)**2*(phat)**2/10. | chapters/statistics/notebooks/Bootstrap.ipynb | unpingco/Python-for-Probability-Statistics-and-Machine-Learning | mit |
Now, let's try this using the bootstrap estimate of the variance | phat_b=np.random.choice(x,(50,10)).mean(1)
print np.var(phat_b*(1-phat_b)) | chapters/statistics/notebooks/Bootstrap.ipynb | unpingco/Python-for-Probability-Statistics-and-Machine-Learning | mit |
This shows that the delta method's estimated variance
is different from the bootstrap method, but which one is better?
For this situation we can solve for this directly using Sympy | import sympy as S
from sympy.stats import E, Bernoulli
xdata =[Bernoulli(i,p) for i in S.symbols('x:10')]
ph = sum(xdata)/float(len(xdata))
g = ph*(1-ph) | chapters/statistics/notebooks/Bootstrap.ipynb | unpingco/Python-for-Probability-Statistics-and-Machine-Learning | mit |
Programming Tip.
The argument in the S.symbols('x:10') function returns a sequence of Sympy
symbols named x1,x2 and so on. This is shorthand for creating and naming each
symbol sequentially.
Note that g is the $g(\hat{p})=\hat{p}(1- \hat{p})$
whose variance we are trying to estimate. Then,
we can plug in for the estim... | print E(g**2) - E(g)**2 | chapters/statistics/notebooks/Bootstrap.ipynb | unpingco/Python-for-Probability-Statistics-and-Machine-Learning | mit |
This case is generally representative --- the delta method tends
to underestimate the variance and the bootstrap estimate is better here.
Parametric Bootstrap
In the previous example, we used the $\lbrace x_1, x_2, \ldots, x_n \rbrace $
samples themselves as the basis for $\hat{F}$ by weighting each with $1/n$. An
alte... | rv = stats.norm(0,2)
xsamples = rv.rvs(45)
# estimate mean and var from xsamples
mn_ = np.mean(xsamples)
std_ = np.std(xsamples)
# bootstrap from assumed normal distribution with
# mn_,std_ as parameters
rvb = stats.norm(mn_,std_) #plug-in distribution
yboot = rvb.rvs(1000) | chapters/statistics/notebooks/Bootstrap.ipynb | unpingco/Python-for-Probability-Statistics-and-Machine-Learning | mit |
<!-- @@@CODE src-statistics/Bootstrap.py from-to:^# In\[7\]:@^yboot -->
Recall the sample variance estimator is the following:
$$
S^2 = \frac{1}{n-1} \sum (X_i-\bar{X})^2
$$
Assuming that the samples are normally distributed, this
means that $(n-1)S^2/\sigma^2$ has a chi-squared distribution with
$n-1$ degrees of free... | # MLE-Plugin Variance of the sample mean
print 2*(std_**2)**2/9. # MLE plugin
# Bootstrap variance of the sample mean
print yboot.var()
# True variance of sample mean
print 2*(2**2)**2/9. | chapters/statistics/notebooks/Bootstrap.ipynb | unpingco/Python-for-Probability-Statistics-and-Machine-Learning | mit |
Para exemplificar o caso unidimensional, vamos pegar uma imagem bidimensional (cameraman) e escolher apenas uma linha da imagem para ser nossa função unidimensional. | f1 = mpimg.imread('../data/cameraman.tif')[10,:]
plt.plot(f1)
F1 = fft(f1)
g1 = ifft(F1)
print ('comparando g1 e f1:', abs(g1-f1).max()) | 2S2018/10 A transformada discreta de Fourier - DFT.ipynb | robertoalotufo/ia898 | mit |
2. Exemplo bidimensional | f2 = mpimg.imread('../data/cameraman.tif')
F2 = fft2(f2)
g2 = ifft2(F2)
print ('comparando g2 e f2:', abs(g2-f2).max())
plt.figure(1, figsize=(8,8))
plt.subplot(1,2,1)
plt.imshow(f2, cmap='gray')
plt.subplot(1,2,2)
plt.imshow(ia.dftview(F2), cmap='gray') | 2S2018/10 A transformada discreta de Fourier - DFT.ipynb | robertoalotufo/ia898 | mit |
In this notebook we will use the Monte Carlo method to find the area under a curve, so first let's define a function
$$f(x) = x^2-4x+5$$ | f = lambda x:x**2-4*x+5
x = range(0, 11, 1)
y = [f(v) for v in x]
plt.plot(y) | Monte Carlos Experiments/Monte Carlo Integration.ipynb | victorgcapone/data-science-portifolio | gpl-3.0 |
Now, we know the probability of a random point being below the curve is equal to
$$P_{curve}=\dfrac{A_{curve}}{A_{rectanle}}$$
Where $A_{rectangle}$ is the area of the plot in the given interval, so let's try to integrate it from 0 to 10 | #Will use 3000 points
number_points=3000
#We want to see the points
points=[]
below=0
for p in range(0, number_points):
x,y=(random.uniform(0,10), random.uniform(0, 70))
# If the function for x is greater then the random y, then the point is under the curve
if f(x) >= y:
below +=1
points.append(... | Monte Carlos Experiments/Monte Carlo Integration.ipynb | victorgcapone/data-science-portifolio | gpl-3.0 |
Knowing the ratio of points under the curve, we can now calculate the integral as
$$P_{curve}A_{rectangle} = A_{cruve}$$
If we take the integral
$$\int_0^{10}x^2-4x+5$$
We have $$\dfrac{x^3}{3}-2x^2+5x\big\lvert_0^{10} = \dfrac{10^3}{3}-200+50 = 333.33 - 200 + 50 = 183.33$$
Which is close to the real area, now, let's ... | def monte_carlo_integration(f, number_points, xlims, ylims):
below=0
for p in range(0, number_points):
x,y=(random.uniform(*xlims), random.uniform(*ylims))
# If the function for x is greater then the random y, then the point is under the curve
if y <= f(x):
below +=1
rati... | Monte Carlos Experiments/Monte Carlo Integration.ipynb | victorgcapone/data-science-portifolio | gpl-3.0 |
As we can see the more points we sample, the more accurate our approximation is to the real values, now what about if we have segments of our curve under the $x$ axis? Let's look at this example
$$g(x) = x^2-4x-8$$ | g = lambda x:x**2-4*x-8
x = range(0, 11, 1)
y = [g(v) for v in x]
plt.plot(y)
#Will use 3000 points
number_points=3000
#We want to see the points
points=[]
below=0
for p in range(0, number_points):
x,y=(random.uniform(0,10), random.uniform(-20, 60))
# If the function for x is greater then the random y, then th... | Monte Carlos Experiments/Monte Carlo Integration.ipynb | victorgcapone/data-science-portifolio | gpl-3.0 |
We can see the area is around 184.0, so let's take the true integral to see if we are close to the real value
We have $$\int_0^{10}x^2-4x+5 = \dfrac{x^3}{3}-2x^2-8x\big\lvert_0^{10} = \dfrac{10^3}{3}-200-80 = 333.33 - 200 - 80 = 53.33$$
So, we are off by a lot, that's because we are adding the area under the $x$ axis i... | #Let's adjust our function to deal with points under the x axis
def monte_carlo_integration(f, number_points, xlims, ylims):
below=0
for p in range(0, number_points):
x,y=(random.uniform(*xlims), random.uniform(*ylims))
# If the function for x is greater then the random y, then the point is unde... | Monte Carlos Experiments/Monte Carlo Integration.ipynb | victorgcapone/data-science-portifolio | gpl-3.0 |
We need to import here the data, modify them if needed and proceed | umat_name = 'MIMTN' #This is the 5 character code for the Mori-Tanaka homogenization for composites with a matrix and ellipsoidal reinforcments
nstatev = 0
nphases = 2 #The number of phases
num_file = 0 #The num of the file that contains the subphases
int1 = 50
int2 = 50
n_matrix = 0
props = np.array([nphases, num_fi... | Examples/MMSP/parametric_analysis/fibre_angle.ipynb | chemiskyy/simmit | gpl-3.0 |
Now let's study the evolution of the concentration | param_list[0].value = 0.0
param_list[1].value = 100
c = np.arange(0.,1.01,0.01)
E_L = np.zeros(len(c))
E_T = np.zeros(len(c))
umat_name = 'MIMTN' #This is the 5 character code for the Mori-Tanaka homogenization for composites with a matrix and ellipsoidal reinforcments
for i, x in enumerate (c):
param_list[3].v... | Examples/MMSP/parametric_analysis/fibre_angle.ipynb | chemiskyy/simmit | gpl-3.0 |
量子畳み込みニューラルネットワーク
<table class="tfo-notebook-buttons" align="left">
<td><a target="_blank" href="https://www.tensorflow.org/quantum/tutorials/qcnn"><img src="https://www.tensorflow.org/images/tf_logo_32px.png"> TensorFlow.orgで表示</a></td>
<td><a target="_blank" href="https://colab.research.google.com/github/tensorfl... | !pip install tensorflow==2.7.0 | site/ja/quantum/tutorials/qcnn.ipynb | tensorflow/docs-l10n | apache-2.0 |
TensorFlow Quantum をインストールします。 | !pip install tensorflow-quantum
# Update package resources to account for version changes.
import importlib, pkg_resources
importlib.reload(pkg_resources) | site/ja/quantum/tutorials/qcnn.ipynb | tensorflow/docs-l10n | apache-2.0 |
次に、TensorFlow とモジュールの依存関係をインポートします。 | import tensorflow as tf
import tensorflow_quantum as tfq
import cirq
import sympy
import numpy as np
# visualization tools
%matplotlib inline
import matplotlib.pyplot as plt
from cirq.contrib.svg import SVGCircuit | site/ja/quantum/tutorials/qcnn.ipynb | tensorflow/docs-l10n | apache-2.0 |
1. QCNN を構築する
1.1 TensorFlow グラフで回路を組み立てる
TensorFlow Quantum(TFQ)には、グラフ内で回路を構築するために設計されたレイヤークラスがあります。たとえば tfq.layers.AddCircuit レイヤーがあり、tf.keras.Layer を継承しています。このレイヤーは、次の図で示すように、回路の入力バッチの前後いずれかに追加できます。
<img src="./images/qcnn_1.png" width="700">
次のスニペットには、このレイヤーが使用されています。 | qubit = cirq.GridQubit(0, 0)
# Define some circuits.
circuit1 = cirq.Circuit(cirq.X(qubit))
circuit2 = cirq.Circuit(cirq.H(qubit))
# Convert to a tensor.
input_circuit_tensor = tfq.convert_to_tensor([circuit1, circuit2])
# Define a circuit that we want to append
y_circuit = cirq.Circuit(cirq.Y(qubit))
# Instantiate... | site/ja/quantum/tutorials/qcnn.ipynb | tensorflow/docs-l10n | apache-2.0 |
入力テンソルを調べます。 | print(tfq.from_tensor(input_circuit_tensor)) | site/ja/quantum/tutorials/qcnn.ipynb | tensorflow/docs-l10n | apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.