markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
As you can infer, we can find the path to the terminal state starting from any given state using this policy.
All maze problems can be solved by formulating it as a MDP.
POMDP
Two state POMDP
Let's consider a problem where we have two doors, one to our left and one to our right.
One of these doors opens to a room with ... | t_prob = [[[0.5, 0.5],
[0.5, 0.5]],
[[0.5, 0.5],
[0.5, 0.5]],
[[1.0, 0.0],
[0.0, 1.0]]] | mdp_apps.ipynb | Chipe1/aima-python | mit |
Followed by the observation model. | e_prob = [[[0.5, 0.5],
[0.5, 0.5]],
[[0.5, 0.5],
[0.5, 0.5]],
[[0.85, 0.15],
[0.15, 0.85]]] | mdp_apps.ipynb | Chipe1/aima-python | mit |
And the reward model. | rewards = [[-100, 10],
[10, -100],
[-1, -1]] | mdp_apps.ipynb | Chipe1/aima-python | mit |
Let's now define our states, observations and actions.
<br>
We will use gamma = 0.95 for this example.
<br> | # 0: open-left, 1: open-right, 2: listen
actions = ('0', '1', '2')
# 0: left, 1: right
states = ('0', '1')
gamma = 0.95 | mdp_apps.ipynb | Chipe1/aima-python | mit |
We have all the required variables to instantiate an object of the POMDP class. | pomdp = POMDP(actions, t_prob, e_prob, rewards, states, gamma) | mdp_apps.ipynb | Chipe1/aima-python | mit |
We can now find the utility function by running pomdp_value_iteration on our pomdp object. | utility = pomdp_value_iteration(pomdp, epsilon=3)
utility
import matplotlib.pyplot as plt
%matplotlib inline
def plot_utility(utility):
open_left = utility['0'][0]
open_right = utility['1'][0]
listen_left = utility['2'][0]
listen_right = utility['2'][-1]
left = (open_left[0] - listen_left[0]) / (o... | mdp_apps.ipynb | Chipe1/aima-python | mit |
TensorFlow Lite Metadata Writer API
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://www.tensorflow.org/lite/models/convert/metadata_writer_tutorial"><img src="https://www.tensorflow.org/images/tf_logo_32px.png" />View on TensorFlow.org</a>
</td>
<td>
<a target="_bla... | !pip install tflite-support-nightly | site/en-snapshot/lite/models/convert/metadata_writer_tutorial.ipynb | tensorflow/docs-l10n | apache-2.0 |
Create Model Metadata for Task Library and Codegen
<a name=image_classifiers></a>
Image classifiers
See the image classifier model compatibility requirements for more details about the supported model format.
Step 1: Import the required packages. | from tflite_support.metadata_writers import image_classifier
from tflite_support.metadata_writers import writer_utils | site/en-snapshot/lite/models/convert/metadata_writer_tutorial.ipynb | tensorflow/docs-l10n | apache-2.0 |
Step 2: Download the example image classifier, mobilenet_v2_1.0_224.tflite, and the label file. | !curl -L https://github.com/tensorflow/tflite-support/raw/master/tensorflow_lite_support/metadata/python/tests/testdata/image_classifier/mobilenet_v2_1.0_224.tflite -o mobilenet_v2_1.0_224.tflite
!curl -L https://github.com/tensorflow/tflite-support/raw/master/tensorflow_lite_support/metadata/python/tests/testdata/imag... | site/en-snapshot/lite/models/convert/metadata_writer_tutorial.ipynb | tensorflow/docs-l10n | apache-2.0 |
Step 3: Create metadata writer and populate. | ImageClassifierWriter = image_classifier.MetadataWriter
_MODEL_PATH = "mobilenet_v2_1.0_224.tflite"
# Task Library expects label files that are in the same format as the one below.
_LABEL_FILE = "mobilenet_labels.txt"
_SAVE_TO_PATH = "mobilenet_v2_1.0_224_metadata.tflite"
# Normalization parameters is required when rep... | site/en-snapshot/lite/models/convert/metadata_writer_tutorial.ipynb | tensorflow/docs-l10n | apache-2.0 |
<a name=object_detectors></a>
Object detectors
See the object detector model compatibility requirements for more details about the supported model format.
Step 1: Import the required packages. | from tflite_support.metadata_writers import object_detector
from tflite_support.metadata_writers import writer_utils | site/en-snapshot/lite/models/convert/metadata_writer_tutorial.ipynb | tensorflow/docs-l10n | apache-2.0 |
Step 2: Download the example object detector, ssd_mobilenet_v1.tflite, and the label file. | !curl -L https://github.com/tensorflow/tflite-support/raw/master/tensorflow_lite_support/metadata/python/tests/testdata/object_detector/ssd_mobilenet_v1.tflite -o ssd_mobilenet_v1.tflite
!curl -L https://github.com/tensorflow/tflite-support/raw/master/tensorflow_lite_support/metadata/python/tests/testdata/object_detect... | site/en-snapshot/lite/models/convert/metadata_writer_tutorial.ipynb | tensorflow/docs-l10n | apache-2.0 |
Step 3: Create metadata writer and populate. | ObjectDetectorWriter = object_detector.MetadataWriter
_MODEL_PATH = "ssd_mobilenet_v1.tflite"
# Task Library expects label files that are in the same format as the one below.
_LABEL_FILE = "ssd_mobilenet_labels.txt"
_SAVE_TO_PATH = "ssd_mobilenet_v1_metadata.tflite"
# Normalization parameters is required when reprocess... | site/en-snapshot/lite/models/convert/metadata_writer_tutorial.ipynb | tensorflow/docs-l10n | apache-2.0 |
<a name=image_segmenters></a>
Image segmenters
See the image segmenter model compatibility requirements for more details about the supported model format.
Step 1: Import the required packages. | from tflite_support.metadata_writers import image_segmenter
from tflite_support.metadata_writers import writer_utils | site/en-snapshot/lite/models/convert/metadata_writer_tutorial.ipynb | tensorflow/docs-l10n | apache-2.0 |
Step 2: Download the example image segmenter, deeplabv3.tflite, and the label file. | !curl -L https://github.com/tensorflow/tflite-support/raw/master/tensorflow_lite_support/metadata/python/tests/testdata/image_segmenter/deeplabv3.tflite -o deeplabv3.tflite
!curl -L https://github.com/tensorflow/tflite-support/raw/master/tensorflow_lite_support/metadata/python/tests/testdata/image_segmenter/labelmap.tx... | site/en-snapshot/lite/models/convert/metadata_writer_tutorial.ipynb | tensorflow/docs-l10n | apache-2.0 |
Step 3: Create metadata writer and populate. | ImageSegmenterWriter = image_segmenter.MetadataWriter
_MODEL_PATH = "deeplabv3.tflite"
# Task Library expects label files that are in the same format as the one below.
_LABEL_FILE = "deeplabv3_labels.txt"
_SAVE_TO_PATH = "deeplabv3_metadata.tflite"
# Normalization parameters is required when reprocessing the image. It ... | site/en-snapshot/lite/models/convert/metadata_writer_tutorial.ipynb | tensorflow/docs-l10n | apache-2.0 |
<a name=nl_classifiers></a>
Natural language classifiers
See the natural language classifier model compatibility requirements for more details about the supported model format.
Step 1: Import the required packages. | from tflite_support.metadata_writers import nl_classifier
from tflite_support.metadata_writers import metadata_info
from tflite_support.metadata_writers import writer_utils | site/en-snapshot/lite/models/convert/metadata_writer_tutorial.ipynb | tensorflow/docs-l10n | apache-2.0 |
Step 2: Download the example natural language classifier, movie_review.tflite, the label file, and the vocab file. | !curl -L https://github.com/tensorflow/tflite-support/raw/master/tensorflow_lite_support/metadata/python/tests/testdata/nl_classifier/movie_review.tflite -o movie_review.tflite
!curl -L https://github.com/tensorflow/tflite-support/raw/master/tensorflow_lite_support/metadata/python/tests/testdata/nl_classifier/labels.tx... | site/en-snapshot/lite/models/convert/metadata_writer_tutorial.ipynb | tensorflow/docs-l10n | apache-2.0 |
Step 3: Create metadata writer and populate. | NLClassifierWriter = nl_classifier.MetadataWriter
_MODEL_PATH = "movie_review.tflite"
# Task Library expects label files and vocab files that are in the same formats
# as the ones below.
_LABEL_FILE = "movie_review_labels.txt"
_VOCAB_FILE = "movie_review_vocab.txt"
# NLClassifier supports tokenize input string using th... | site/en-snapshot/lite/models/convert/metadata_writer_tutorial.ipynb | tensorflow/docs-l10n | apache-2.0 |
<a name=audio_classifiers></a>
Audio classifiers
See the audio classifier model compatibility requirements for more details about the supported model format.
Step 1: Import the required packages. | from tflite_support.metadata_writers import audio_classifier
from tflite_support.metadata_writers import metadata_info
from tflite_support.metadata_writers import writer_utils | site/en-snapshot/lite/models/convert/metadata_writer_tutorial.ipynb | tensorflow/docs-l10n | apache-2.0 |
Step 2: Download the example audio classifier, yamnet.tflite, and the label file. | !curl -L https://github.com/tensorflow/tflite-support/raw/master/tensorflow_lite_support/metadata/python/tests/testdata/audio_classifier/yamnet_wavin_quantized_mel_relu6.tflite -o yamnet.tflite
!curl -L https://github.com/tensorflow/tflite-support/raw/master/tensorflow_lite_support/metadata/python/tests/testdata/audio_... | site/en-snapshot/lite/models/convert/metadata_writer_tutorial.ipynb | tensorflow/docs-l10n | apache-2.0 |
Step 3: Create metadata writer and populate. | AudioClassifierWriter = audio_classifier.MetadataWriter
_MODEL_PATH = "yamnet.tflite"
# Task Library expects label files that are in the same format as the one below.
_LABEL_FILE = "yamnet_labels.txt"
# Expected sampling rate of the input audio buffer.
_SAMPLE_RATE = 16000
# Expected number of channels of the input aud... | site/en-snapshot/lite/models/convert/metadata_writer_tutorial.ipynb | tensorflow/docs-l10n | apache-2.0 |
Create Model Metadata with semantic information
You can fill in more descriptive information about the model and each tensor through the Metadata Writer API to help improve model understanding. It can be done through the 'create_from_metadata_info' method in each metadata writer. In general, you can fill in data throug... | from tflite_support.metadata_writers import image_classifier
from tflite_support.metadata_writers import metadata_info
from tflite_support.metadata_writers import writer_utils
from tflite_support import metadata_schema_py_generated as _metadata_fb | site/en-snapshot/lite/models/convert/metadata_writer_tutorial.ipynb | tensorflow/docs-l10n | apache-2.0 |
Step 3: Create model and tensor information. | model_buffer = writer_utils.load_file("mobilenet_v2_1.0_224.tflite")
# Create general model information.
general_md = metadata_info.GeneralMd(
name="ImageClassifier",
version="v1",
description=("Identify the most prominent object in the image from a "
"known set of categories."),
autho... | site/en-snapshot/lite/models/convert/metadata_writer_tutorial.ipynb | tensorflow/docs-l10n | apache-2.0 |
Step 4: Create metadata writer and populate. | ImageClassifierWriter = image_classifier.MetadataWriter
# Create the metadata writer.
writer = ImageClassifierWriter.create_from_metadata_info(
model_buffer, general_md, input_md, output_md)
# Verify the metadata generated by metadata writer.
print(writer.get_metadata_json())
# Populate the metadata into the mode... | site/en-snapshot/lite/models/convert/metadata_writer_tutorial.ipynb | tensorflow/docs-l10n | apache-2.0 |
Read the metadata populated to your model.
You can display the metadata and associated files in a TFLite model through the following code: | from tflite_support import metadata
displayer = metadata.MetadataDisplayer.with_model_file("mobilenet_v2_1.0_224_metadata.tflite")
print("Metadata populated:")
print(displayer.get_metadata_json())
print("Associated file(s) populated:")
for file_name in displayer.get_packed_associated_file_list():
print("file name: ... | site/en-snapshot/lite/models/convert/metadata_writer_tutorial.ipynb | tensorflow/docs-l10n | apache-2.0 |
Run a query | %%bigquery --project $PROJECT
SELECT
start_station_name
, AVG(duration) as duration
, COUNT(duration) as num_trips
FROM `bigquery-public-data`.london_bicycles.cycle_hire
GROUP BY start_station_name
ORDER BY num_trips DESC
LIMIT 5 | 05_devel/magics.ipynb | GoogleCloudPlatform/bigquery-oreilly-book | apache-2.0 |
Run a parameterized query | PARAMS = {"num_stations": 3}
%%bigquery --project $PROJECT --params $PARAMS
SELECT
start_station_name
, AVG(duration) as duration
, COUNT(duration) as num_trips
FROM `bigquery-public-data`.london_bicycles.cycle_hire
GROUP BY start_station_name
ORDER BY num_trips DESC
LIMIT @num_stations | 05_devel/magics.ipynb | GoogleCloudPlatform/bigquery-oreilly-book | apache-2.0 |
Into a dataframe | %%bigquery df --project $PROJECT
SELECT
start_station_name
, AVG(duration) as duration
, COUNT(duration) as num_trips
FROM `bigquery-public-data`.london_bicycles.cycle_hire
GROUP BY start_station_name
ORDER BY num_trips DESC
df.describe()
df.plot.scatter('duration', 'num_trips'); | 05_devel/magics.ipynb | GoogleCloudPlatform/bigquery-oreilly-book | apache-2.0 |
"This grouped variable is now a GroupBy object. It has not actually computed anything yet except for some intermediate data about the group key df['key1']. The idea is that this object has all of the information needed to then apply some operation to each of the groups." - Python for Data Analysis
View a grouping
Use l... | list(df['preTestScore'].groupby(df['regiment'])) | python/pandas_apply_operations_to_groups.ipynb | tpin3694/tpin3694.github.io | mit |
Descriptive statistics by group | df['preTestScore'].groupby(df['regiment']).describe() | python/pandas_apply_operations_to_groups.ipynb | tpin3694/tpin3694.github.io | mit |
Mean of each regiment's preTestScore | groupby_regiment.mean() | python/pandas_apply_operations_to_groups.ipynb | tpin3694/tpin3694.github.io | mit |
Mean preTestScores grouped by regiment and company | df['preTestScore'].groupby([df['regiment'], df['company']]).mean() | python/pandas_apply_operations_to_groups.ipynb | tpin3694/tpin3694.github.io | mit |
Mean preTestScores grouped by regiment and company without heirarchical indexing | df['preTestScore'].groupby([df['regiment'], df['company']]).mean().unstack() | python/pandas_apply_operations_to_groups.ipynb | tpin3694/tpin3694.github.io | mit |
Group the entire dataframe by regiment and company | df.groupby(['regiment', 'company']).mean() | python/pandas_apply_operations_to_groups.ipynb | tpin3694/tpin3694.github.io | mit |
Number of observations in each regiment and company | df.groupby(['regiment', 'company']).size() | python/pandas_apply_operations_to_groups.ipynb | tpin3694/tpin3694.github.io | mit |
Iterate an operations over groups | # Group the dataframe by regiment, and for each regiment,
for name, group in df.groupby('regiment'):
# print the name of the regiment
print(name)
# print the data of that regiment
print(group) | python/pandas_apply_operations_to_groups.ipynb | tpin3694/tpin3694.github.io | mit |
Group by columns
Specifically in this case: group by the data types of the columns (i.e. axis=1) and then use list() to view what that grouping looks like | list(df.groupby(df.dtypes, axis=1)) | python/pandas_apply_operations_to_groups.ipynb | tpin3694/tpin3694.github.io | mit |
In the dataframe "df", group by "regiments, take the mean values of the other variables for those groups, then display them with the prefix_mean | df.groupby('regiment').mean().add_prefix('mean_') | python/pandas_apply_operations_to_groups.ipynb | tpin3694/tpin3694.github.io | mit |
Create a function to get the stats of a group | def get_stats(group):
return {'min': group.min(), 'max': group.max(), 'count': group.count(), 'mean': group.mean()} | python/pandas_apply_operations_to_groups.ipynb | tpin3694/tpin3694.github.io | mit |
Create bins and bin up postTestScore by those pins | bins = [0, 25, 50, 75, 100]
group_names = ['Low', 'Okay', 'Good', 'Great']
df['categories'] = pd.cut(df['postTestScore'], bins, labels=group_names) | python/pandas_apply_operations_to_groups.ipynb | tpin3694/tpin3694.github.io | mit |
Apply the get_stats() function to each postTestScore bin | df['postTestScore'].groupby(df['categories']).apply(get_stats).unstack() | python/pandas_apply_operations_to_groups.ipynb | tpin3694/tpin3694.github.io | mit |
De um modo similar ao que fizemos antes, vamos contar todas as ocorrencias em todas as sessões do nome de cada cidade | %matplotlib inline
import pylab
import matplotlib
import pandas
import numpy
dateparse = lambda x: pandas.datetime.strptime(x, '%Y-%m-%d')
sessoes = pandas.read_csv('sessoes_democratica_org.csv',index_col=0,parse_dates=['data'], date_parser=dateparse)
from functools import reduce
# retira falsas ocorrencias de 'gua... | notebooks/Deputado-Histogramado-4.ipynb | fsilva/deputado-histogramado | gpl-3.0 |
Agora representamos o mapa, e depois desenhamos circulos para cada cidade, de cor e tamanho variável consoante o número de menções.
Para representar os distritos Portugueses necessitamos de um dataset com os 'shapefiles' destes: obtem-o em http://www.gadm.org/country
Alternativamente o script tambem executa sem a linha... | from mpl_toolkits.basemap import Basemap
pylab.figure(figsize=(20,10))
#map = Basemap(projection='merc',lat_0=40,lon_0=0,resolution='l',llcrnrlon=-10.5, llcrnrlat=36,urcrnrlon=-5.5, urcrnrlat=43) # PT continental
map = Basemap(projection='merc',lat_0=40,lon_0=0,resolution='l',llcrnrlon=-32, llcrnrlat=31,urcrnrlon=-5.5,... | notebooks/Deputado-Histogramado-4.ipynb | fsilva/deputado-histogramado | gpl-3.0 |
In the above example, the compiler did nothing because the default compiler (when MainEngine is called without a specific engine_list parameter) translates the individual gates to the gate set supported by the backend. In our case, the backend is a CommandPrinter which supports any type of gate.
We can check what happe... | from projectq.backends import Simulator
from projectq.setups.default import get_engine_list
# Use the default compiler engines with a CommandPrinter in the end:
engines2 = get_engine_list() + [CommandPrinter()]
eng2 = projectq.MainEngine(backend=Simulator(), engine_list=engines2)
my_quantum_program(eng2) | examples/compiler_tutorial.ipynb | ProjectQ-Framework/ProjectQ | apache-2.0 |
As one can see, in this case the compiler had to do a little work because the Simulator does not support a QFT gate. Therefore, it automatically replaces the QFT gate by a sequence of lower-level gates.
Using a provided setup and specifying a particular gate set
ProjectQ's compiler is fully modular, so one can easily b... | import projectq
from projectq.setups import restrictedgateset
from projectq.ops import All, H, Measure, Rx, Ry, Rz, Toffoli
engine_list3 = restrictedgateset.get_engine_list(one_qubit_gates="any",
two_qubit_gates=(CNOT,),
oth... | examples/compiler_tutorial.ipynb | ProjectQ-Framework/ProjectQ | apache-2.0 |
Please have a look at the documention of the restrictedgateset for details. The above compiler compiles the circuit to gates consisting of any single qubit gate, the CNOT and Toffoli gate. The gate specifications can either be a gate class, e.g., Rz or a specific instance Rz(math.pi). A smaller but still universal gate... | engine_list4 = restrictedgateset.get_engine_list(one_qubit_gates=(Rz, Ry),
two_qubit_gates=(CNOT,),
other_gates=())
eng4 = projectq.MainEngine(backend=CommandPrinter(accept_input=False),
engine_lis... | examples/compiler_tutorial.ipynb | ProjectQ-Framework/ProjectQ | apache-2.0 |
As mentioned in the documention of this setup, one cannot (yet) choose an arbitrary gate set but there is a limited choice. If it doesn't work for a specified gate set, the compiler will either raises a NoGateDecompositionError or a RuntimeError: maximum recursion depth exceeded... which means that for this particular ... | import projectq
from projectq.backends import CommandPrinter
from projectq.cengines import AutoReplacer, DecompositionRuleSet, InstructionFilter
from projectq.ops import All, ClassicalInstructionGate, Measure, Toffoli, X
import projectq.setups.decompositions
# Write a function which, given a Command object, returns wh... | examples/compiler_tutorial.ipynb | ProjectQ-Framework/ProjectQ | apache-2.0 |
We fail here because the description column is a string.
Lets try again without the description. | # features
feature_names_integers = ['Barcode','UnitRRP']
# Extra features from panda (without description)
training_data_integers = df_training[feature_names_integers].values
training_data_integers[:3]
# train model again
model_dtc.fit(training_data_integers, target)
# Extract test data and test the model
test_data... | Session4/code/01 Loading EPOS Category Data for modelling.ipynb | catalystcomputing/DSIoT-Python-sessions | apache-2.0 |
Lets try a different Classifier
Linear classifiers (SVM, logistic regression, a.o.) with SGD training. | from sklearn.linear_model import SGDClassifier
# Create classifier class
model_sgd = SGDClassifier()
# train model again
model_sgd.fit(training_data_integers, target)
predicted_sgd = model_sgd.predict(test_data_integers)
print(metrics.classification_report(expected, predicted_sgd, target_names=target_categories)... | Session4/code/01 Loading EPOS Category Data for modelling.ipynb | catalystcomputing/DSIoT-Python-sessions | apache-2.0 |
The search for good, evil, and the gender divide
We took a look at how Marvel and DC are divided along the lines of gender and good vs. evil. | #Clean up and shape the Marvel dataframe
#Set Alignment to Index
marvel_men = marvel[['ALIGN','SEX']]
marvel_men=marvel_men.set_index('ALIGN')
#Create separate Male and Female columns
gender = ['Male','Female']
oldmarvel = marvel_men.copy()
vnames=[]
for x in gender:
newname = x
vnames.append(newname)
ma... | MBA_S16/Berry-Domenico-Comics.ipynb | NYUDataBootcamp/Projects | mit |
We can see that the Marvel and DC universes are each dominated by men. What may be surprising, however, is that in both franchises, bad men dominate the universe. On the female side, there are more good females than bad females. Perhaps comic book authors have found have
Proportionally, DC has more equal representatio... | #Clean up and shape the Marvel dataframe
#Set Alignment to Index
marvel_gsm = marvel[['ALIGN','GSM']]
marvel_gsm=marvel_gsm.set_index('ALIGN')
#Create separate GSM columns
gsm = ['Hetero', 'Bisexual','Transvestites',
'Homosexual','Pansexual',
'Transgender','Genderfluid']
oldmarvel2 = marvel_gsm.copy()
on... | MBA_S16/Berry-Domenico-Comics.ipynb | NYUDataBootcamp/Projects | mit |
Our findings here are pretty encouraging! Non-heterosexual characters have not been disproportionately vilified in either Marvel or DC.
Sexual Orientation in Comics Over the Years
We'll take a look at how many characters of each orientation were introduced in both Marvel and DC each year, and any trends that surfaces. | # We create a copy of the original dataframes to look at gender
GenderM = marvel.copy()
GenderDC = dc.copy()
# Clean up and shape the Marvel dataframe
# First, we'll drop those decimals from the years
GenderM["Year"] = GenderM["Year"].astype(str)
GenderM["Year"] = GenderM["Year"].str.replace(".0","")
GenderM["Year"] ... | MBA_S16/Berry-Domenico-Comics.ipynb | NYUDataBootcamp/Projects | mit |
A brief comparison of the two plots reveals that Marvel has introduced more variation in sexual identity over the years than DC. To get a better idea, though, we'll want to look at them side by side.
Comparing Representation in Marvel vs. DC | # Now we can compare the two franchises in combined plots
ax = OrientationM["Homosexual"].plot()
OrientationDC["Homosexual"].plot(ax=ax)
# Pretty powerful data, but we can make it look better
# By adding a title, axis labels, legend; changing the colors, and enlarging, we enhance the "Pow!" factor
ax = OrientationM["H... | MBA_S16/Berry-Domenico-Comics.ipynb | NYUDataBootcamp/Projects | mit |
This shows us that Marvel introduced more homosexual characters as early as the 1940s, but DC has been more representative in recent years. | # We can go on to do this for any orientation
ax = OrientationM["Bisexual"].plot(label="Marvel", color="green", linewidth=2.0)
OrientationDC["Bisexual"].plot(ax=ax, label="DC", figsize=(12,6), color="purple", linewidth=2.0)
ax.set_title("Bisexual Comic Characters", fontsize=16, fontweight="bold")
ax.set_xlabel("Year", ... | MBA_S16/Berry-Domenico-Comics.ipynb | NYUDataBootcamp/Projects | mit |
When it comes to bisexual characters, it is harder to find a trend. The two franchises seem to have ebbed and flowed in representation for this group. | # We could also use a stacked bar chart to look at the array of introductions per year
OrientationM.plot.bar(stacked=True, figsize=(16,8), title="Marvel Yearly Character Introductions", fontsize=12)
# Or the same thing for DC...
OrientationDC.plot.bar(stacked=True, figsize=(16,8), title="DC Yearly Character Introducti... | MBA_S16/Berry-Domenico-Comics.ipynb | NYUDataBootcamp/Projects | mit |
GlobalMaxPooling2D
[pooling.GlobalMaxPooling2D.0] input 6x6x3, data_format='channels_last' | data_in_shape = (6, 6, 3)
L = GlobalMaxPooling2D(data_format='channels_last')
layer_0 = Input(shape=data_in_shape)
layer_1 = L(layer_0)
model = Model(inputs=layer_0, outputs=layer_1)
# set weights to random (use seed for reproducibility)
np.random.seed(270)
data_in = 2 * np.random.random(data_in_shape) - 1
result = m... | notebooks/layers/pooling/GlobalMaxPooling2D.ipynb | qinwf-nuan/keras-js | mit |
[pooling.GlobalMaxPooling2D.1] input 3x6x6, data_format='channels_first' | data_in_shape = (3, 6, 6)
L = GlobalMaxPooling2D(data_format='channels_first')
layer_0 = Input(shape=data_in_shape)
layer_1 = L(layer_0)
model = Model(inputs=layer_0, outputs=layer_1)
# set weights to random (use seed for reproducibility)
np.random.seed(271)
data_in = 2 * np.random.random(data_in_shape) - 1
result = ... | notebooks/layers/pooling/GlobalMaxPooling2D.ipynb | qinwf-nuan/keras-js | mit |
[pooling.GlobalMaxPooling2D.2] input 5x3x2, data_format='channels_last' | data_in_shape = (5, 3, 2)
L = GlobalMaxPooling2D(data_format='channels_last')
layer_0 = Input(shape=data_in_shape)
layer_1 = L(layer_0)
model = Model(inputs=layer_0, outputs=layer_1)
# set weights to random (use seed for reproducibility)
np.random.seed(272)
data_in = 2 * np.random.random(data_in_shape) - 1
result = m... | notebooks/layers/pooling/GlobalMaxPooling2D.ipynb | qinwf-nuan/keras-js | mit |
23. 系统A:当负荷增加250MW时,频率下降0.1HZ。系统B:当负荷增加400MW时,频率下降0.1HZ。系统A运行于49.85HZ,系统B运行于50HZ,如用联络线将两系统相连,求联络线上的功率。 | Ka=2500
Kb=4000
fa=49.85
fb=50
df2=fb-fa
dPl=df2*Ka
dfab=-1*dPl/(Ka+Kb)#B下降的频率
Pab=dfab*Kb
trans_power(Ka,Kb,dPl,0) | power_system/调频计算.ipynb | chengts95/homeworkOfPowerSystem | gpl-2.0 |
24. A、B两系统经联络线相连,已知:$K_{GA}=270MW/Hz$ ,$K_{LA}=21MW/Hz$ ,$K_{GB}=480MW/Hz$ ,$K_{LB}=21MW/Hz$ ,$P_{AB}=300MW$ ,系统B负荷增加150MW。1)两系统所有发电机均仅参加一次调频,求系统频率、联络线功率变化量,A、B两系统发电机和负荷功率变化量;2)除一次调频外,A系统设调频厂进行二次调频,联络线最大允许输送功率为400MW,求系统频率的变化量。 | Ka=291
Kb=501
Plb=150
df=-1*Plb/(Ka+Kb)
trans_power(Ka,Kb,0,Plb)
df
100/Ka | power_system/调频计算.ipynb | chengts95/homeworkOfPowerSystem | gpl-2.0 |
Create Cloud Storage bucket for storing Vertex Pipeline artifacts | BUCKET_NAME = f"gs://{PROJECT_ID}-bucket"
print(BUCKET_NAME)
!gsutil ls -al $BUCKET_NAME
USER = "dougkelly" # <---CHANGE THIS
PIPELINE_ROOT = "{}/pipeline_root/{}".format(BUCKET_NAME, USER)
PIPELINE_ROOT | self-paced-labs/vertex-ai/vertex-pipelines/kfp/lab_exercise.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Create BigQuery dataset | !bq --location=US mk -d \
$PROJECT_ID:$BQ_DATASET_NAME | self-paced-labs/vertex-ai/vertex-pipelines/kfp/lab_exercise.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Exploratory Data Analysis in BigQuery | %%bigquery data
SELECT
CAST(EXTRACT(DAYOFWEEK FROM trip_start_timestamp) AS string) AS trip_dayofweek,
FORMAT_DATE('%A',cast(trip_start_timestamp as date)) AS trip_dayname,
COUNT(*) as trip_count,
FROM `bigquery-public-data.chicago_taxi_trips.taxi_trips`
WHERE
EXTRACT(YEAR FROM trip_start_timestamp) ... | self-paced-labs/vertex-ai/vertex-pipelines/kfp/lab_exercise.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Create BigQuery dataset for ML classification task | SAMPLE_SIZE = 100000
YEAR = 2020
sql_script = '''
CREATE OR REPLACE TABLE `@PROJECT_ID.@DATASET.@TABLE`
AS (
WITH
taxitrips AS (
SELECT
trip_start_timestamp,
trip_seconds,
trip_miles,
payment_type,
pickup_longitude,
pickup_latitude,
dropoff_longi... | self-paced-labs/vertex-ai/vertex-pipelines/kfp/lab_exercise.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Verify data split proportions | %%bigquery
SELECT data_split, COUNT(*)
FROM dougkelly-vertex-demos.chicago_taxi.chicago_taxi_tips_raw
GROUP BY data_split | self-paced-labs/vertex-ai/vertex-pipelines/kfp/lab_exercise.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Create
Import libraries | import json
import logging
from typing import NamedTuple
import kfp
# from google.cloud import aiplatform
from google_cloud_pipeline_components import aiplatform as gcc_aip
from kfp.v2 import dsl
from kfp.v2.dsl import (ClassificationMetrics, Input, Metrics, Model, Output,
component)
from kfp.v... | self-paced-labs/vertex-ai/vertex-pipelines/kfp/lab_exercise.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Create and run an AutoML Tabular classification pipeline using Kubeflow Pipelines SDK
Create a custom KFP evaluation component | @component(
base_image="gcr.io/deeplearning-platform-release/tf2-cpu.2-3:latest",
output_component_file="components/tables_eval_component.yaml", # Optional: you can use this to load the component later
packages_to_install=["google-cloud-aiplatform==1.0.0"],
)
def classif_model_eval_metrics(
project: str... | self-paced-labs/vertex-ai/vertex-pipelines/kfp/lab_exercise.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Define the pipeline | @kfp.dsl.pipeline(name="automl-tab-chicago-taxi-tips-train", pipeline_root=PIPELINE_ROOT)
def pipeline(
bq_source: str = "bq://dougkelly-vertex-demos:chicago_taxi.chicago_taxi_tips_raw",
display_name: str = DISPLAY_NAME,
project: str = PROJECT_ID,
gcp_region: str = REGION,
api_endpoint: str = "us-ce... | self-paced-labs/vertex-ai/vertex-pipelines/kfp/lab_exercise.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Compile and run the pipeline | from kfp.v2 import compiler # noqa: F811
compiler.Compiler().compile(
pipeline_func=pipeline, package_path="automl-tab-chicago-taxi-tips-train_pipeline.json"
) | self-paced-labs/vertex-ai/vertex-pipelines/kfp/lab_exercise.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Run the pipeline | from kfp.v2.google.client import AIPlatformClient # noqa: F811
api_client = AIPlatformClient(project_id=PROJECT_ID, region=REGION)
response = api_client.create_run_from_job_spec(
"automl-tab-chicago-taxi-tips-train_pipeline.json",
pipeline_root=PIPELINE_ROOT,
parameter_values={"project": PROJECT_ID, "dis... | self-paced-labs/vertex-ai/vertex-pipelines/kfp/lab_exercise.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Query your deployed model to retrieve online predictions and explanations | from google.cloud import aiplatform
import matplotlib.pyplot as plt
import pandas as pd
endpoint = aiplatform.Endpoint(
endpoint_name="2677161280053182464",
project=PROJECT_ID,
location=REGION)
%%bigquery test_df
SELECT
CAST(trip_month AS STRING) AS trip_month,
CAST(trip_day AS STRING) AS trip_day,
... | self-paced-labs/vertex-ai/vertex-pipelines/kfp/lab_exercise.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Some OpenCV functions (beyond those introduced in the lesson) that might be useful for this project are:
cv2.inRange() for color selection
cv2.fillPoly() for regions selection
cv2.line() to draw lines on an image given endpoints
cv2.addWeighted() to coadd / overlay two images
cv2.cvtColor() to grayscale or change color... | import math
def grayscale(img):
"""Applies the Grayscale transform
This will return an image with only one color channel
but NOTE: to see the returned image as grayscale
you should call plt.imshow(gray, cmap='gray')"""
return cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
# Or use BGR2GRAY if you read a... | find_lane_lines/CarND_LaneLines_P1/P1.ipynb | gon1213/SDC | gpl-3.0 |
Test on Images
Now you should build your pipeline to work on the images in the directory "test_images"
You should make sure your pipeline works well on these images before you try the videos. | import os
os.listdir("test_images/") | find_lane_lines/CarND_LaneLines_P1/P1.ipynb | gon1213/SDC | gpl-3.0 |
run your solution on all test_images and make copies into the test_images directory). | # TODO: Build your pipeline that will draw lane lines on the test_images
# then save them to the test_images directory.
| find_lane_lines/CarND_LaneLines_P1/P1.ipynb | gon1213/SDC | gpl-3.0 |
Test on Videos
You know what's cooler than drawing lanes over images? Drawing lanes over video!
We can test our solution on two provided videos:
solidWhiteRight.mp4
solidYellowLeft.mp4 | # Import everything needed to edit/save/watch video clips
from moviepy.editor import VideoFileClip
from IPython.display import HTML
def process_image(image):
# NOTE: The output you return should be a color image (3 channel) for processing video below
# TODO: put your pipeline here,
# you should return the ... | find_lane_lines/CarND_LaneLines_P1/P1.ipynb | gon1213/SDC | gpl-3.0 |
Let's try the one with the solid white lane on the right first ... | white_output = 'white.mp4'
clip1 = VideoFileClip("solidWhiteRight.mp4")
white_clip = clip1.fl_image(process_image) #NOTE: this function expects color images!!
%time white_clip.write_videofile(white_output, audio=False) | find_lane_lines/CarND_LaneLines_P1/P1.ipynb | gon1213/SDC | gpl-3.0 |
Play the video inline, or if you prefer find the video in your filesystem (should be in the same directory) and play it in your video player of choice. | HTML("""
<video width="960" height="540" controls>
<source src="{0}">
</video>
""".format(white_output)) | find_lane_lines/CarND_LaneLines_P1/P1.ipynb | gon1213/SDC | gpl-3.0 |
At this point, if you were successful you probably have the Hough line segments drawn onto the road, but what about identifying the full extent of the lane and marking it clearly as in the example video (P1_example.mp4)? Think about defining a line to run the full length of the visible lane based on the line segments ... | yellow_output = 'yellow.mp4'
clip2 = VideoFileClip('solidYellowLeft.mp4')
yellow_clip = clip2.fl_image(process_image)
%time yellow_clip.write_videofile(yellow_output, audio=False)
HTML("""
<video width="960" height="540" controls>
<source src="{0}">
</video>
""".format(yellow_output)) | find_lane_lines/CarND_LaneLines_P1/P1.ipynb | gon1213/SDC | gpl-3.0 |
Reflections
Congratulations on finding the lane lines! As the final step in this project, we would like you to share your thoughts on your lane finding pipeline... specifically, how could you imagine making your algorithm better / more robust? Where will your current algorithm be likely to fail?
Please add your thoug... | challenge_output = 'extra.mp4'
clip2 = VideoFileClip('challenge.mp4')
challenge_clip = clip2.fl_image(process_image)
%time challenge_clip.write_videofile(challenge_output, audio=False)
HTML("""
<video width="960" height="540" controls>
<source src="{0}">
</video>
""".format(challenge_output)) | find_lane_lines/CarND_LaneLines_P1/P1.ipynb | gon1213/SDC | gpl-3.0 |
Fourier Transform Examples
Fourier transforms are most often used to decompose a signal as a function of time into the frequency components that comprise it, e.g. transforming between time and frequency domains. It's also possible to post-process a filtered signal using Fourier transforms.
FFTs decompose a single signa... | # Create signal
frq1 = 50 # Frequency 1(hz)
amp1 = 5 # Amplitude 1
frq2 = 250 # Frequency 2(hz)
amp2 = 3 # Amplitude 2
sr = 2000 # Sample rate
dur = 0.4 # Duration (s) (increasing/decreasing this cha... | 08 - Signal Processing - Scipy.ipynb | blakeflei/IntroScientificPythonWithJupyter | bsd-3-clause |
The amplitudes don't seem quite right - longer duration increases the signal to noise and gives a better result: | # Create signal
sr = 2000 # Sample rate
dur = 10 # Increased duration (s) (increasing/decreasing this changes S/N)
X = np.linspace(0, dur-1/sr, int(dur*sr)) # Time
Y_s = amp1*np.sin(X*2*np.pi*frq1 - np.pi/4) + amp2*np.sin(X*2*np.pi*frq2 + np.pi/2)
Y_sn = Y_s + 40*np.random.rand(len(X))
# Determi... | 08 - Signal Processing - Scipy.ipynb | blakeflei/IntroScientificPythonWithJupyter | bsd-3-clause |
Phase Example
Phase is shift of a periodic signal 'left' or 'right'. it is the $\phi_x$ in the following equation:
$$ Y = \frac{1}{2} a_0 \sum_{n=1}^{\infty} a_n cos (n x + \phi_x) $$ | # We can use the previous signal to get the phase:
# Set a tolerance limit - phase is sensitive to floating point errors
# (see Gotchas and Optimization for more info):
FT_trun = FT
tol = 1*10**-6 # Truncate signal below tolerance level
FT_trun[np.abs(FT_trun)<tol] = 0
# Use the angle function (arc tangent of imagin... | 08 - Signal Processing - Scipy.ipynb | blakeflei/IntroScientificPythonWithJupyter | bsd-3-clause |
This shows the phase for every single frequency, but we really only care about the nonzero frequencies with minimum amplitude: | nonzero_freqs = freqs[SSFT_amp > 1][1:]
print('Notable frequencies are: {}'.format(nonzero_freqs))
inds = [list(freqs).index(x) for x in nonzero_freqs] # Return index of nonzero frequencies
print('Phase shifts for notable frequencies are: {}'.format(phase_rad[inds])) | 08 - Signal Processing - Scipy.ipynb | blakeflei/IntroScientificPythonWithJupyter | bsd-3-clause |
This is better visualized without noise: | # Determine Single Sided FT Spectrum
Y_s_fft = np.fft.fft(Y_s)
# Update ft output
FT = np.roll(Y_s_fft, len(X)//2)
# Set a tolerance limit - phase is sensitive to floating point errors
# (see Gotchas and Optimization for more info):
FT_trun = FT
tol = 1*10**-6 # Truncate signal below tolerance level
FT_trun[np.abs... | 08 - Signal Processing - Scipy.ipynb | blakeflei/IntroScientificPythonWithJupyter | bsd-3-clause |
Notch Filter
Plot our original, non-noisy two-component signal:
Perform the Fourier transform, and set the 200 Hz signal to zero: | # Fourier transform
Yfft = np.fft.fft(Y_s);
freqs = sr*np.arange(0,len(Yfft)/2)/len(Y_sn) # Frequencies of the FT
ind250Hz = np.where(freqs==250)[0][0] # Index to get just 250 Hz Signal
Y_filt = Yfft[:] # The original, non-absolute, full spectrum is important
full_w = 200 # Width of spectrum to set to zero
# S... | 08 - Signal Processing - Scipy.ipynb | blakeflei/IntroScientificPythonWithJupyter | bsd-3-clause |
Inverse Fourier transform back, and plot the original filtered signal: | # Inverse FFT the original, non-absolute, full spectrum
Y2 = np.fft.ifft(Y_filt)
Y2 = np.real(Y2) # Use the real values to plot the filtered signal
# Plot
plt.plot(X[:100],Y_s[:100], label='Original')
plt.plot(X[:100],Y2[:100], label='Filtered')
plt.title('Two Signals')
plt.xlabel('Time (s)')
plt.ylabel('Signal Amplu... | 08 - Signal Processing - Scipy.ipynb | blakeflei/IntroScientificPythonWithJupyter | bsd-3-clause |
While the Fourier amplitudes properly represent the amplitude of frequency components, the power spectral density (square of the discrete fourier transform) can be estimated using a periodogram: | # Determine approx power spectral density
f, Pxx_den = signal.periodogram(Y_s, sr)
# Plot
plt.plot(f, Pxx_den)
plt.xlabel('frequency [Hz]')
plt.ylabel('PSD')
plt.show() | 08 - Signal Processing - Scipy.ipynb | blakeflei/IntroScientificPythonWithJupyter | bsd-3-clause |
Correlation
Correlations are a measure of the product of two signals as a function of the x-axis shift between them. They are often used to determine similarity between the two signals, e.g. is there some structure or repeating feature that is present in both signals? | # Create a signal
npts = 200
heartbeat = np.array([0,1,0,0,4,8,2,-4,0,4,0,1,2,1,0,0,0,0])/8
xvals = np.linspace(0,len(heartbeat),npts)
heartbeat = np.interp(xvals,np.arange(0,len(heartbeat)),heartbeat) # Use interpolation to spread the signal out
# Repeat the signal ten times, add some noise:
hrtbt = np.tile(heartbea... | 08 - Signal Processing - Scipy.ipynb | blakeflei/IntroScientificPythonWithJupyter | bsd-3-clause |
The center of the repeating (heartbeat) signal is marked as a centroid: | # Find center of each repeating signal
cent_x = np.arange(1,11)*200 - 100
cent_y = np.ones(10)*max(hrtbt)
# Plot
plt.plot(hrtbt[:], label='heartbeat')
plt.plot(cent_x[:],cent_y[:],'r^', label='Centroid')
plt.title('Heartbeat Electrocardiogram')
plt.xlabel('Time')
plt.ylabel('Volts')
plt.legend(loc='best')
plt.show() | 08 - Signal Processing - Scipy.ipynb | blakeflei/IntroScientificPythonWithJupyter | bsd-3-clause |
Correlate the single signal with the repeating, noisy one: | # Correlate
corr = signal.correlate(hrtbt_noise, heartbeat, mode='same')
# Plot
plt.plot(corr/max(corr), label='Corelogram')
plt.plot(cent_x,cent_y,'r^', label='Centroid')
plt.title('Correlogram')
plt.xlabel('Delay')
plt.ylabel('Normalized Volts $^2$')
plt.legend(loc='best')
plt.show() | 08 - Signal Processing - Scipy.ipynb | blakeflei/IntroScientificPythonWithJupyter | bsd-3-clause |
The correlogram recovered the repeating signal central points. This is because at these points, the signal has the greatest similarity with the rectangular pulse. In other words, we're recovering the areas that share the greatest amount of similarity with our rectangular pulse.
Convolution
Convolution is a process in w... | # Signal and PSF
orig_sig = signal.sawtooth(2*np.pi*np.linspace(0,3,300))/2+0.5
psf = signal.gaussian(101, std=15)
# Convolve
convolved = signal.convolve(orig_sig, psf)
# Plot
G = gridspec.GridSpec(3, 1)
axis1 = plt.subplot(G[0, 0])
axis1.plot(orig_sig)
axis1.set_xlim(0, le... | 08 - Signal Processing - Scipy.ipynb | blakeflei/IntroScientificPythonWithJupyter | bsd-3-clause |
Deconvolution
Deconvolution can be thought of as removing the filter or instrument response. This is pretty common when reconstructing real signals if the response is known.
In the microscope example, this would be deconvolving image with a known response of the instrument to a point source. If it is known how much the... | # Deconvolve
recovered, remainder = signal.deconvolve(convolved, psf)
# Plot
G = gridspec.GridSpec(3, 1)
axis1 = plt.subplot(G[0, 0])
axis1.plot(convolved)
axis1.set_xlim(0, len(convolved))
axis1.set_title('Convolved Signal')
axis2 = plt.subplot(G[1, 0])
axis2.plot(psf)
axis2.set_xlim(0,... | 08 - Signal Processing - Scipy.ipynb | blakeflei/IntroScientificPythonWithJupyter | bsd-3-clause |
Filtering
Filters recieve a signal input and selectively reduce the amplitude of certain frequencies. Working with digital signals, they can broadly be divided into infinitie impulse response (IIR) and finite impulse response (FIR).
IIR filters that receive an impulse response (signal of value 1 followed by many zeros)... | frq1 = 250 # Frequency 1(hz)
amp1 = 3 # Amplitude 1
sr = 2000 # Sample rate
dur = 1 # Duration (s) (increasing/decreasing this changes S/N)
# Create timesteps, signal and noise
X = np.linspace(0, dur-1/sr, int(dur*sr)) # Time
Y = amp1*n... | 08 - Signal Processing - Scipy.ipynb | blakeflei/IntroScientificPythonWithJupyter | bsd-3-clause |
Infinite Impulse Response (IIR) filters
Digital filters inherently account for digital signal limitations, i.e. the sampling frequency. The Nyquist theorem asserts that we can't measure frequencies that are higher than 1/2 the sampling frequency, and the digital filter operates on this principle.
Next, we create the di... | f_order = 10.0 # Filter order
f_pass = 'low' # Filter is low pass
f_freq = 210.0 # Frequency to pass
f_cutoff = f_freq/(sr/2) # Convert frequency into
# Create the filter
b, a = signal.iirfilter(f_order, f_cutoff, btype=f_pass, ftype='butter')
# Test the filter
w, h = signal.freqz(... | 08 - Signal Processing - Scipy.ipynb | blakeflei/IntroScientificPythonWithJupyter | bsd-3-clause |
Applying the filter to our signal filters all higher frequencies: | # Apply filter to signal
sig_filtered = signal.filtfilt(b, a, Y_noise)
# Determine approx PSD
f, Pxx_den_f = signal.periodogram(sig_filtered, sr)
# Plot
G = gridspec.GridSpec(2, 1)
axis1 = plt.subplot(G[0, 0])
axis1.plot(f, Pxx_den)
axis1.set_title('Approx PSD of Original Signal')
axis2 = plt.subplot(G[1, 0])
ax... | 08 - Signal Processing - Scipy.ipynb | blakeflei/IntroScientificPythonWithJupyter | bsd-3-clause |
Finite Impulse Response Filters
A finite impulse response (FIR) filter can be designed where a linear phase response is specified within specified regions (up to the Nyquist or 1/2 of the sampling frequency). Only feedforward coefficients (b) are used. | # Create FIR filter
taps = 150 # Analogus to IIR order - indication
# of memory, calculation, and
# 'filtering'
freqs = [0, 150, 300, 500, sr/2.] # FIR frequencies
ny_fract = np.array(freqs)/(sr/2) # Conver... | 08 - Signal Processing - Scipy.ipynb | blakeflei/IntroScientificPythonWithJupyter | bsd-3-clause |
And the effect of the FIR digital filter: | # Apply FIR filter
sig_filtered = signal.filtfilt(b, 1, Y_noise)
# Determine approx PSD
f, Pxx_den_f = signal.periodogram(sig_filtered, sr)
# Plot
G = gridspec.GridSpec(2, 1)
axis1 = plt.subplot(G[0, 0])
axis1.plot(f, Pxx_den)
axis1.set_title('Approx PSD of Original Signal')
axis2 = plt.sub... | 08 - Signal Processing - Scipy.ipynb | blakeflei/IntroScientificPythonWithJupyter | bsd-3-clause |
Now construct the class containing the initial conditions of the problem | LM0 = LakeModel(lamb,alpha,b,d)
x0 = LM0.find_steady_state()# initial conditions
print "Initial Steady State: ", x0 | solutions/lakemodel_solutions.ipynb | gxxjjj/QuantEcon.py | bsd-3-clause |
New legislation changes $\lambda$ to $0.2$ | LM1 = LakeModel(0.2,alpha,b,d)
xbar = LM1.find_steady_state() # new steady state
X_path = np.vstack(LM1.simulate_stock_path(x0*N0,T)) # simulate stocks
x_path = np.vstack(LM1.simulate_rate_path(x0,T)) # simulate rates
print "New Steady State: ", xbar | solutions/lakemodel_solutions.ipynb | gxxjjj/QuantEcon.py | bsd-3-clause |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.