markdown stringlengths 0 1.02M | code stringlengths 0 832k | output stringlengths 0 1.02M | license stringlengths 3 36 | path stringlengths 6 265 | repo_name stringlengths 6 127 |
|---|---|---|---|---|---|
To determine which clustering result better matches the original labels of the samples, we can use ```adjusted_rand_score``` which is an *external cluster validation index* which results in a score between -1 and 1, where 1 means two clusterings are identical of how they grouped the samples in a dataset (regardless of ... | from sklearn.metrics import adjusted_rand_score
ward_ar_score = adjusted_rand_score(iris.target, ward_pred) | _____no_output_____ | MIT | Clustering/Hierarchical Clustering Lab.ipynb | sjmiller8182/ML_Class |
**Exercise**:* Calculate the Adjusted Rand score of the clusters resulting from complete linkage and average linkage | # TODO: Calculated the adjusted Rand score for the complete linkage clustering labels
complete_ar_score = adjusted_rand_score(iris.target, complete_pred)
# TODO: Calculated the adjusted Rand score for the average linkage clustering labels
avg_ar_score = adjusted_rand_score(iris.target, avg_pred) | _____no_output_____ | MIT | Clustering/Hierarchical Clustering Lab.ipynb | sjmiller8182/ML_Class |
Which algorithm results in the higher Adjusted Rand Score? | print( "Scores: \nWard:", ward_ar_score,"\nComplete: ", complete_ar_score, "\nAverage: ", avg_ar_score) | Scores:
Ward: 0.731198556771
Complete: 0.642251251836
Average: 0.759198707107
| MIT | Clustering/Hierarchical Clustering Lab.ipynb | sjmiller8182/ML_Class |
3. The Effect of Normalization on ClusteringCan we improve on this clustering result?Let's take another look at the dataset | iris.data[:15] | _____no_output_____ | MIT | Clustering/Hierarchical Clustering Lab.ipynb | sjmiller8182/ML_Class |
Looking at this, we can see that the forth column has smaller values than the rest of the columns, and so its variance counts for less in the clustering process (since clustering is based on distance). Let us [normalize](https://en.wikipedia.org/wiki/Feature_scaling) the dataset so that each dimension lies between 0 an... | from sklearn import preprocessing
normalized_X = preprocessing.normalize(iris.data)
normalized_X[:10] | _____no_output_____ | MIT | Clustering/Hierarchical Clustering Lab.ipynb | sjmiller8182/ML_Class |
Now all the columns are in the range between 0 and 1. Would clustering the dataset after this transformation lead to a better clustering? (one that better matches the original labels of the samples) | ward = AgglomerativeClustering(n_clusters=3)
ward_pred = ward.fit_predict(normalized_X)
complete = AgglomerativeClustering(n_clusters=3, linkage="complete")
complete_pred = complete.fit_predict(normalized_X)
avg = AgglomerativeClustering(n_clusters=3, linkage="average")
avg_pred = avg.fit_predict(normalized_X)
ward... | Scores:
Ward: 0.885697031028
Complete: 0.644447235392
Average: 0.558371443754
| MIT | Clustering/Hierarchical Clustering Lab.ipynb | sjmiller8182/ML_Class |
4. Dendrogram visualization with scipyLet's visualize the highest scoring clustering result. To do that, we'll need to use Scipy's [```linkage```](https://docs.scipy.org/doc/scipy/reference/generated/scipy.cluster.hierarchy.linkage.html) function to perform the clusteirng again so we can obtain the linkage matrix it w... | # Import scipy's linkage function to conduct the clustering
from scipy.cluster.hierarchy import linkage
# Specify the linkage type. Scipy accepts 'ward', 'complete', 'average', as well as other values
# Pick the one that resulted in the highest Adjusted Rand Score
linkage_type = 'ward'
linkage_matrix = linkage(normal... | _____no_output_____ | MIT | Clustering/Hierarchical Clustering Lab.ipynb | sjmiller8182/ML_Class |
Plot using scipy's [dendrogram](https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.cluster.hierarchy.dendrogram.html) function | from scipy.cluster.hierarchy import dendrogram
import matplotlib.pyplot as plt
plt.figure(figsize=(22,18))
# plot using 'dendrogram()'
dendrogram(linkage_matrix)
plt.show() | _____no_output_____ | MIT | Clustering/Hierarchical Clustering Lab.ipynb | sjmiller8182/ML_Class |
5. Visualization with Seaborn's ```clustermap``` The [seaborn](http://seaborn.pydata.org/index.html) plotting library for python can plot a [clustermap](http://seaborn.pydata.org/generated/seaborn.clustermap.html), which is a detailed dendrogram which also visualizes the dataset in more detail. It conducts the cluster... | import seaborn as sns
sns.clustermap(normalized_X, figsize=(12,18), method=linkage_type, cmap='viridis')
# Expand figsize to a value like (18, 50) if you want the sample labels to be readable
# Draw back is that you'll need more scrolling to observe the dendrogram
plt.show() | C:\Program Files\Anaconda3\lib\site-packages\matplotlib\cbook.py:136: MatplotlibDeprecationWarning: The axisbg attribute was deprecated in version 2.0. Use facecolor instead.
warnings.warn(message, mplDeprecation, stacklevel=1)
| MIT | Clustering/Hierarchical Clustering Lab.ipynb | sjmiller8182/ML_Class |
**Exercise 01: Identifying Disease Reasons for Absence** | # define function, which checks if the provided integer value
# is contained in the ICD or not
def in_icd(val):
return "Yes" if val >= 1 and val <= 21 else "No"
# add Disease column
preprocessed_data["Disease"] = preprocessed_data["Reason for absence"]\
.apply(in_icd)
# plot value counts
plt.figure(figsize=(... | _____no_output_____ | MIT | Exercise01/Exercise01.ipynb | Develop-Packt/Exploring-Absenteeism-at-Work |
Weighted median In the video we have discussed that for MAPE metric the best constant prediction is [weighted median](https://en.wikipedia.org/wiki/Weighted_median) with weights$$w_i = \frac{\sum_{j=1}^N \frac{1}{x_j}}{x_i}$$for each object $x_i$.This notebook exlpains how to compute weighted median. Let's generate so... | N = 5
x = np.random.randint(low=1, high=100, size=N)
x | _____no_output_____ | MIT | How to Win a Data Science Competition Learn from Top Kagglers/Reading materials/Metrics_video3_weighted_median.ipynb | ghali007/Advanced-Machine-Learning-Specialization |
1) Compute *normalized* weights: | inv_x = 1.0/x
inv_x
w = inv_x/sum(inv_x)
w | _____no_output_____ | MIT | How to Win a Data Science Competition Learn from Top Kagglers/Reading materials/Metrics_video3_weighted_median.ipynb | ghali007/Advanced-Machine-Learning-Specialization |
2) Now sort the normalized weights. We will use `argsort` (and not just `sort`) since we will need indices later. | idxs = np.argsort(w)
sorted_w = w[idxs]
sorted_w | _____no_output_____ | MIT | How to Win a Data Science Competition Learn from Top Kagglers/Reading materials/Metrics_video3_weighted_median.ipynb | ghali007/Advanced-Machine-Learning-Specialization |
3) Compute [cumulitive sum](https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.cumsum.html) of sorted weights | sorted_w_cumsum = np.cumsum(sorted_w)
plt.plot(sorted_w_cumsum); plt.show()
print ('sorted_w_cumsum: ', sorted_w_cumsum) | _____no_output_____ | MIT | How to Win a Data Science Competition Learn from Top Kagglers/Reading materials/Metrics_video3_weighted_median.ipynb | ghali007/Advanced-Machine-Learning-Specialization |
4) Now find the index when cumsum hits 0.5: | idx = np.where(sorted_w_cumsum>0.5)[0][0]
idx | _____no_output_____ | MIT | How to Win a Data Science Competition Learn from Top Kagglers/Reading materials/Metrics_video3_weighted_median.ipynb | ghali007/Advanced-Machine-Learning-Specialization |
5) Finally, your answer is sample at that position: | pos = idxs[idx]
x[pos]
print('Data: ', x)
print('Sorted data: ', np.sort(x))
print('Weighted median: %d, Median: %d' %(x[pos], np.median(x))) | Data: [37 52 21 25 46]
Sorted data: [21 25 37 46 52]
Weighted median: 25, Median: 37
| MIT | How to Win a Data Science Competition Learn from Top Kagglers/Reading materials/Metrics_video3_weighted_median.ipynb | ghali007/Advanced-Machine-Learning-Specialization |
Asterisk- 오픈소스코드에 많이 활용됨- '*'을 의미- *: 가변인자 활용- \**: 키워드인자 활용(Pandas, Matplotlib)- unpacking에 활용 | #가변인자 활용
def asterisk_test(a, *args):
print(a, args)
print(type(args))
asterisk_test(1, 2, 3, 4, 5, 6)
#키워드인자 활용
def asterisk_test(a, **kargs):
print(a, kargs)
print(type(kargs))
asterisk_test(1, b=2, c=3, d=4, e=5, f=6)
#unpacking
def asterisk_test(a, args):
print(a, *args)
print(type(args))
... | 9
12
| MIT | Python-for-ML/2-6-asterisk.ipynb | lee-kyubong/DSC2018 |
Box plot array visualizationBased on this: https://stackoverflow.com/questions/41384040/subplot-for-seaborn-boxplot | f, axes = plt.subplots(5, 3, figsize=(11,11), sharex='col')
plt.style.use('seaborn-whitegrid')
for buildingtype in buildingtypes:
# Draw lines on single plot
MAPE = {}
NMBE = {}
CVRSME = {}
for i in range(len(models)):
dataframes =... | _____no_output_____ | MIT | model_notebooks/.ipynb_checkpoints/metrics-visualization-by-type-checkpoint.ipynb | buds-lab/building-prediction-benchmarking |
Risk Study for REPLACE MESee the [ISO 27005 Risk Cookbook](http://www.businessofsecurity.com/docs/FAIR%20-%20ISO_IEC_27005%20Cookbook.pdf)for a more detailed explanation of this template. AssetDefine the asset or assets at risk Threat CommunityExplain the threat community. This should include where they operate, how... | tcap.min <- 0
tcap.likely <- 50
tcap.max <- 100
tcap.confidence <- 10 | _____no_output_____ | MIT | RiskStudy.ipynb | iamjoeker/fair_notebook |
ControlsDefine the controls that resist the threat community. Provide any necessary links and descriptions. Control StrengthDefine the ability of the controls in play to overcome the threat agents.|Rating |Value ||----------------------|------||Very High (Top 2%) |98-100||High (Top 16%) |84-9... | cs.min <- 0
cs.likely <- 50
cs.max <- 100
cs.confidence <- 10 | _____no_output_____ | MIT | RiskStudy.ipynb | iamjoeker/fair_notebook |
Threat Event FrequencyThreat Event Frequency. Number assumes an annual value. Example valuesare as follows:|Rating |Value ||---------|------||Very High|> 100 ||High |10-100||Moderate |1-10 ||Low |> .1 ||Very Low |< .1 | | tef <- .25 | _____no_output_____ | MIT | RiskStudy.ipynb | iamjoeker/fair_notebook |
Loss MagnitudeDefine the types of loss that could occur during a loss event for this study.|Primary |ISO/IEC 27005 Direct Operational Impacts ||:--------------|:-------------------------------------------------------------------------||Productivity |The financial replacement v... | loss.probable <- 100000 | _____no_output_____ | MIT | RiskStudy.ipynb | iamjoeker/fair_notebook |
Worst Case LossSet the worst case amount a single loss event. This is a combination in dollars of both the primary and secondary loss factors | loss.worstCase <- 1000000 | _____no_output_____ | MIT | RiskStudy.ipynb | iamjoeker/fair_notebook |
Qualified risk based on loss tolerance | loss.veryHigh <- 10000000
loss.high <- 1000000
loss.moderate <- 100000
loss.low <- 50000
loss.veryLow <- 10000 | _____no_output_____ | MIT | RiskStudy.ipynb | iamjoeker/fair_notebook |
Generate distribution of samples | sampleSize <- 100000
cs <- rpert(sampleSize, cs.min, cs.likely, cs.max, cs.confidence)
tcap <- rpert(sampleSize, tcap.min, tcap.likely, tcap.max, tcap.confidence)
csPlot <- ggplot(data.frame(cs), aes(x = cs))
csPlot <- csPlot + geom_histogram(aes(y = ..density..), color="black",fill="white", binwidth=1)
csPlot <- csPlo... | _____no_output_____ | MIT | RiskStudy.ipynb | iamjoeker/fair_notebook |
Vulnerability Function | CalculateVulnerability <- function() {
if (sampleSize < 100) {
stop("Sample size needs to be at least 100 to get statistically significant results")
}
vulnerability <- 0
for (i in 1:sampleSize) {
if (tcap[i] > cs[i]) {
vulnerability <- vulnerability + 1
}
}
... | _____no_output_____ | MIT | RiskStudy.ipynb | iamjoeker/fair_notebook |
Loss Event Frequency Function | CalculateLossEventFrequency <- function() {
return(CalculateVulnerability() * tef)
} | _____no_output_____ | MIT | RiskStudy.ipynb | iamjoeker/fair_notebook |
Risk Function | CalculateRisk <- function(loss) {
if (loss >= loss.veryHigh) {
return("Very High")
} else if (loss < loss.veryHigh && loss >= loss.high) {
return("High")
} else if (loss < loss.high && loss >= loss.moderate) {
return("Moderate")
} else if (loss < loss.moderate && loss >= loss.ver... | _____no_output_____ | MIT | RiskStudy.ipynb | iamjoeker/fair_notebook |
Annualized Loss Function | CalculateAnnualizedLoss <- function(lef, lm) {
return(lm * lef)
} | _____no_output_____ | MIT | RiskStudy.ipynb | iamjoeker/fair_notebook |
Calculate | lossEventFrequency <- CalculateLossEventFrequency()
worstCaseLoss <- CalculateAnnualizedLoss(lossEventFrequency, loss.worstCase)
probableLoss <- CalculateAnnualizedLoss(lossEventFrequency, loss.probable)
worstCaseRisk <- CalculateRisk(worstCaseLoss)
probableRisk <- CalculateRisk(probableLoss) | _____no_output_____ | MIT | RiskStudy.ipynb | iamjoeker/fair_notebook |
Final Results | cat("Probable Risk:", probableRisk, dollar_format()(probableLoss), "\n")
cat("Worst Case Risk:", worstCaseRisk, dollar_format()(worstCaseLoss), "\n") | Probable Risk: Low $12,510
Worst Case Risk: Moderate $125,100
| MIT | RiskStudy.ipynb | iamjoeker/fair_notebook |
Testing ARMA hidden semi-Markov models | import numpy as np
import seaborn as sns
import time
from types import SimpleNamespace
from bioslds import sources
from bioslds.arma import Arma, make_random_arma
from bioslds.arma_hsmm import sample_switching_models, ArmaHSMM
from bioslds.plotting import FigureManager | _____no_output_____ | MIT | examples/tests/example_integration_arma_hsmm.ipynb | ttesileanu/bio-time-series |
Test `sample_switching_models` Generate a sawtooth signal | sawtooth = SimpleNamespace(
arma1=Arma([1.0], [], bias=0.05, default_source=sources.Constant(0)),
arma2=Arma([1.0], [], bias=-0.05, default_source=sources.Constant(0)),
usage_seq=np.tile(np.repeat([0, 1], 20), 10),
)
sawtooth.n = len(sawtooth.usage_seq)
sawtooth.sig = sample_switching_models(
[sawtooth... | _____no_output_____ | MIT | examples/tests/example_integration_arma_hsmm.ipynb | ttesileanu/bio-time-series |
Generate a noisy step signal | rng = np.random.default_rng(1)
noisy_step = SimpleNamespace(
arma1=Arma([0.8], [], bias=1.0, default_source=sources.GaussianNoise(1, scale=0.1)),
arma2=Arma(
[0.75], [], bias=-0.5, default_source=sources.GaussianNoise(2, scale=0.1)
),
arma3=Arma(
[0.85], [], bias=0.2, default_source=sour... | _____no_output_____ | MIT | examples/tests/example_integration_arma_hsmm.ipynb | ttesileanu/bio-time-series |
Test `ArmaHSMM` Generate a signal with switching ARs, using minimal dwell time | random_switching = SimpleNamespace(
arma1=Arma([0.8], [], default_source=sources.GaussianNoise(1)),
arma2=Arma([-0.5], [], default_source=sources.GaussianNoise(2)),
n=10000,
)
random_switching.arma_hsmm = ArmaHSMM(
[random_switching.arma1, random_switching.arma2],
min_dwell=15,
dwell_times=[25,... | _____no_output_____ | MIT | examples/tests/example_integration_arma_hsmm.ipynb | ttesileanu/bio-time-series |
Check $K_5$ and $K_{3,3}$ without one edge | almost_K5 = PlanarityChecker(5)
graph_almost_K5 = nx.Graph()
graph_almost_K5.add_nodes_from(range(5))
for i in range(5):
for j in range(i + 1, 5):
if (i != 0 or j != 1):
almost_K5.add_edge(i, j)
graph_almost_K5.add_edge(i, j)
nx.draw(graph_almost_K5)
print("almost K5. number of edges... | Almost K3,3. number of edges: 8, is planar: 1
| MIT | Planarity check example.ipynb | Keksozavr/graph_planarity |
Check $K_5$ and $K_{3,3}$ | K5 = almost_K5
K5.add_edge(0, 1)
graph_K5 = graph_almost_K5
graph_K5.add_edge(0, 1)
nx.draw(graph_K5)
print("K5. number of edges: %d, is planar: %d" % (K5.edges_count, K5.is_planar()))
K33 = almost_K33
K33.add_edge(1, 4)
graph_K33 = graph_almost_K33
graph_K33.add_edge(1, 4)
nx.draw(graph_K33)
print("K33. number of edge... | K33. number of edges: 9, is planar: 0
| MIT | Planarity check example.ipynb | Keksozavr/graph_planarity |
Stress test Generate a lot of graphs with probability of every edge=$p$ and check planarity with PlanarityChecker and planarity library (https://pypi.org/project/planarity/) | def generate_graphs(n, p):
"""Generate Graph and nx.Graph with n vertexes, where p is a probability of edge existance"""
G = PlanarityChecker(n)
nx_G = nx.Graph()
nx_G.add_nodes_from(range(n))
for i in range(n):
for j in range(i + 1, n):
if random() < p:
G.add_ed... | 141 859
| MIT | Planarity check example.ipynb | Keksozavr/graph_planarity |
It works correctly. Check execution time | n = 20000
m = 40000
G = PlanarityChecker(n)
edges = set()
for i in range(m):
a = randint(0, n)
b = randint(0, n)
while (a, b) in edges or a == b:
a = randint(0, n)
b = randint(0, n)
edges.add((a, b))
for e in edges:
G.add_edge(e[0], e[1])
import sys
sys.setrecursionlimit(20000)
%%tim... | CPU times: user 82.8 ms, sys: 9.68 ms, total: 92.4 ms
Wall time: 89.6 ms
| MIT | Planarity check example.ipynb | Keksozavr/graph_planarity |
This notebook is part of the $\omega radlib$ documentation: https://docs.wradlib.org.Copyright (c) $\omega radlib$ developers.Distributed under the MIT License. See LICENSE.txt for more info. Supported radar data formats The binary encoding of many radar products is a major obstacle for many potential radar users. Oft... | import wradlib as wrl
import warnings
warnings.filterwarnings('ignore')
import matplotlib.pyplot as pl
import numpy as np
try:
get_ipython().magic("matplotlib inline")
except:
pl.ion() | _____no_output_____ | MIT | notebooks/fileio/wradlib_radar_formats.ipynb | earthobservations/wradlib-notebooks |
German Weather Service: DX format The German Weather Service uses the DX file format to encode local radar sweeps. DX data are in polar coordinates. The naming convention is as follows: raa00-dx_<location-id>-<YYMMDDHHMM>-<location-abreviation>---bin or raa00-dx_<location-id>-<YYYYMMDDHHMM&g... | fpath = 'dx/raa00-dx_10908-0806021655-fbg---bin.gz'
f = wrl.util.get_wradlib_data_file(fpath)
data, metadata = wrl.io.read_dx(f) | _____no_output_____ | MIT | notebooks/fileio/wradlib_radar_formats.ipynb | earthobservations/wradlib-notebooks |
Here, ``data`` is a two dimensional array of shape (number of azimuth angles, number of range gates). This means that the number of rows of the array corresponds to the number of azimuth angles of the radar sweep while the number of columns corresponds to the number of range gates per ray. | print(data.shape)
print(metadata.keys())
fig = pl.figure(figsize=(10, 10))
ax, im = wrl.vis.plot_ppi(data, fig=fig, proj='cg') | _____no_output_____ | MIT | notebooks/fileio/wradlib_radar_formats.ipynb | earthobservations/wradlib-notebooks |
German Weather Service: RADOLAN (quantitative) composit The quantitative composite format of the DWD (German Weather Service) was established in the course of the [RADOLAN project](https://www.dwd.de/DE/leistungen/radolan/radolan.html). Most quantitative composite products from the DWD are distributed in this format, ... | fpath = 'radolan/misc/raa01-rw_10000-1408102050-dwd---bin.gz'
f = wrl.util.get_wradlib_data_file(fpath)
data, metadata = wrl.io.read_radolan_composite(f) | _____no_output_____ | MIT | notebooks/fileio/wradlib_radar_formats.ipynb | earthobservations/wradlib-notebooks |
Here, ``data`` is a two dimensional integer array of shape (number of rows, number of columns). Different product types might need different levels of postprocessing, e.g. if the product contains rain rates or accumulations, you will normally have to divide data by factor 10. ``metadata`` is again a dictionary which pr... | print(data.shape)
print(metadata.keys()) | _____no_output_____ | MIT | notebooks/fileio/wradlib_radar_formats.ipynb | earthobservations/wradlib-notebooks |
Masking the NoData (or missing) values can be done by: | maskeddata = np.ma.masked_equal(data,
metadata["nodataflag"])
fig = pl.figure(figsize=(10, 8))
# get coordinates
radolan_grid_xy = wrl.georef.get_radolan_grid(900, 900)
x = radolan_grid_xy[:, :, 0]
y = radolan_grid_xy[:, :, 1]
# create quick plot with colorbar and title
pl.figure(figsi... | _____no_output_____ | MIT | notebooks/fileio/wradlib_radar_formats.ipynb | earthobservations/wradlib-notebooks |
HDF5 OPERA HDF5 (ODIM_H5) [HDF5](https://www.hdfgroup.org/HDF5/) is a data model, library, and file format for storing and managing data. The [OPERA 3 program](http://www.eumetnet.eu/opera) developed a convention (or information model) on how to store and exchange radar data in hdf5 format. It is based on the work of... | fpath = 'hdf5/knmi_polar_volume.h5'
f = wrl.util.get_wradlib_data_file(fpath)
fcontent = wrl.io.read_opera_hdf5(f) | _____no_output_____ | MIT | notebooks/fileio/wradlib_radar_formats.ipynb | earthobservations/wradlib-notebooks |
The user should inspect the output obtained from his or her hdf5 file in order to see how access those items which should be further processed. In order to get a readable overview of the output dictionary, one can use the pretty printing module: | # which keyswords can be used to access the content?
print(fcontent.keys())
# print the entire content including values of data and metadata
# (numpy arrays will not be entirely printed)
print(fcontent['dataset1/data1/data']) | _____no_output_____ | MIT | notebooks/fileio/wradlib_radar_formats.ipynb | earthobservations/wradlib-notebooks |
Please note that in order to experiment with such datasets, you can download hdf5 sample data from the [OPERA](http://eumetnet.eu/activities/observations-programme/current-activities/opera/) or use the example data provided with the [wradlib-data](https://github.com/wradlib/wradlib-data/) repository. | fig = pl.figure(figsize=(10, 10))
im = wrl.vis.plot_ppi(fcontent['dataset1/data1/data'], fig=fig, proj='cg') | _____no_output_____ | MIT | notebooks/fileio/wradlib_radar_formats.ipynb | earthobservations/wradlib-notebooks |
GAMIC HDF5 GAMIC refers to the commercial [GAMIC Enigma MURAN software](https://www.gamic.com) which exports data in hdf5 format. The concept is quite similar to the above [OPERA HDF5 (ODIM_H5)](OPERA-HDF5-(ODIM_H5)) format. Such a file (typical ending: *.mvol*) can be read by: | fpath = 'hdf5/2014-08-10--182000.ppi.mvol'
f = wrl.util.get_wradlib_data_file(fpath)
data, metadata = wrl.io.read_gamic_hdf5(f) | _____no_output_____ | MIT | notebooks/fileio/wradlib_radar_formats.ipynb | earthobservations/wradlib-notebooks |
While metadata represents the usual dictionary of metadata, the data variable is a dictionary which might contain several numpy arrays with the keywords of the dictionary indicating different moments. | print(metadata.keys())
print(metadata['VOL'])
print(metadata['SCAN0'].keys())
print(data['SCAN0'].keys())
print(data['SCAN0']['PHIDP'].keys())
print(data['SCAN0']['PHIDP']['data'].shape)
fig = pl.figure(figsize=(10, 10))
im = wrl.vis.plot_ppi(data['SCAN0']['ZH']['data'], fig=fig, proj='cg') | _____no_output_____ | MIT | notebooks/fileio/wradlib_radar_formats.ipynb | earthobservations/wradlib-notebooks |
Generic HDF5 This is a generic hdf5 reader, which will read any hdf5 structure. | fpath = 'hdf5/2014-08-10--182000.ppi.mvol'
f = wrl.util.get_wradlib_data_file(fpath)
fcontent = wrl.io.read_generic_hdf5(f)
print(fcontent.keys())
print(fcontent['where'])
print(fcontent['how'])
print(fcontent['scan0/moment_3'].keys())
print(fcontent['scan0/moment_3']['attrs'])
print(fcontent['scan0/moment_3']['data'].... | _____no_output_____ | MIT | notebooks/fileio/wradlib_radar_formats.ipynb | earthobservations/wradlib-notebooks |
NetCDF The NetCDF format also claims to be self-describing. However, as for all such formats, the developers of netCDF also admit that "[...] the mere use of netCDF is not sufficient to make data self-describing and meaningful to both humans and machines [...]" (see [here](https://www.unidata.ucar.edu/software/netcdf/... | fpath = 'netcdf/example_cfradial_ppi.nc'
f = wrl.util.get_wradlib_data_file(fpath)
outdict = wrl.io.read_generic_netcdf(f)
for key in outdict.keys():
print(key) | _____no_output_____ | MIT | notebooks/fileio/wradlib_radar_formats.ipynb | earthobservations/wradlib-notebooks |
Please see [this example notebook](wradlib_generic_netcdf_example.ipynb) to get started. EDGE NetCDF EDGE is a commercial software for radar control and data analysis provided by the Enterprise Electronics Corporation. It allows for netCDF data export. The resulting files can be read by [wradlib.io.read_generic_netcdf... | fpath = 'netcdf/edge_netcdf.nc'
f = wrl.util.get_wradlib_data_file(fpath)
data, metadata = wrl.io.read_edge_netcdf(f)
print(data.shape)
print(metadata.keys()) | _____no_output_____ | MIT | notebooks/fileio/wradlib_radar_formats.ipynb | earthobservations/wradlib-notebooks |
Gematronik Rainbow Rainbow refers to the commercial [RAINBOW®5 APPLICATION SOFTWARE](http://www.de.selex-es.com/capabilities/meteorology/products/components/rainbow5) which exports data in an XML flavour, which due to binary data blobs violates XML standard. Gematronik provided python code for implementing this reader... | fpath = 'rainbow/2013070308340000dBuZ.azi'
f = wrl.util.get_wradlib_data_file(fpath)
fcontent = wrl.io.read_rainbow(f) | _____no_output_____ | MIT | notebooks/fileio/wradlib_radar_formats.ipynb | earthobservations/wradlib-notebooks |
The user should inspect the output obtained from his or her Rainbow file in order to see how access those items which should be further processed. In order to get a readable overview of the output dictionary, one can use the pretty printing module: | # which keyswords can be used to access the content?
print(fcontent.keys())
# print the entire content including values of data and metadata
# (numpy arrays will not be entirely printed)
print(fcontent['volume']['sensorinfo']) | _____no_output_____ | MIT | notebooks/fileio/wradlib_radar_formats.ipynb | earthobservations/wradlib-notebooks |
You can check this [example notebook](wradlib_load_rainbow_example.ipynb) for getting a first impression. Vaisala Sigmet IRIS [IRIS](https://www.vaisala.com/en/products/instruments-sensors-and-other-measurement-devices/weather-radar-products/iris-focus) refers to the commercial Vaisala Sigmet **I**nteractive **R**ada... | fpath = 'sigmet/cor-main131125105503.RAW2049'
f = wrl.util.get_wradlib_data_file(fpath)
fcontent = wrl.io.read_iris(f)
# which keywords can be used to access the content?
print(fcontent.keys())
# print the entire content including values of data and
# metadata of the first sweep
# (numpy arrays will not be entirely pr... | _____no_output_____ | MIT | notebooks/fileio/wradlib_radar_formats.ipynb | earthobservations/wradlib-notebooks |
Research Imports | import pandas as pd
import pandas_datareader as dr
from pandas_datareader import data as web
import matplotlib.pyplot as plt
from matplotlib import style
import numpy as np
import datetime
import mplfinance as mpl
import plotly.graph_objects as go
import plotly
import yfinance as yf | _____no_output_____ | MIT | Stock Project.ipynb | SPC7/dlensInternship |
Data Import | df = pd.read_csv('data/data2.csv', index_col='Symbol') | _____no_output_____ | MIT | Stock Project.ipynb | SPC7/dlensInternship |
Sorting Data | df
isInfoTech = df['Sector']== 'Information Technology'
print(isInfoTech.head())
df_InfoTech = df[isInfoTech]
df_InfoTech | _____no_output_____ | MIT | Stock Project.ipynb | SPC7/dlensInternship |
IBM INTEL NVIDIA | #looking at IBM,INTEL,NVIDIA,
start = datetime.datetime(2017,1,1)
end = datetime.datetime(2021,6,22)
ibm = yf.download("IBM",start, end)
intel = yf.download("INTC",start, end)
nvidia = yf.download("NVDA",start, end)
trch = yf.download("TRCH",start, end)
ibm.to_csv('IBM_STOCK.csv')
#ibm stock
intel.to_csv('INTC_STOCK.c... | _____no_output_____ | MIT | Stock Project.ipynb | SPC7/dlensInternship |
Volumes | ibm['Volume'].plot(label='IBM',figsize=(15,7))
intel['Volume'].plot(label='Intel')
nvidia['Volume'].plot(label='Nvidia')
plt.ylabel('Volume Traded')
plt.title('Volumes of IBM, Intel and Nvidia')
plt.legend() | _____no_output_____ | MIT | Stock Project.ipynb | SPC7/dlensInternship |
Total Traded / ~Market Cap | ibm['Total Traded'] = ibm['Open'] * ibm['Volume']
intel['Total Traded'] = intel['Open'] * intel['Volume']
nvidia['Total Traded'] = nvidia['Open'] * nvidia['Volume']
ibm['Total Traded'].plot(label=('IBM'),figsize=(15,7))
intel['Total Traded'].plot(label=('Intel'))
nvidia['Total Traded'].plot(label=('Nvidia'))
plt.ylabel... | _____no_output_____ | MIT | Stock Project.ipynb | SPC7/dlensInternship |
50 and 200 Day Rolling EMA | intel['Open'].plot(figsize=(15,7))
intel['MA50']=intel['Open'].rolling(50).mean()
intel['MA50'].plot(label='MA50')
intel['MA200']=intel['Open'].rolling(200).mean()
intel['MA200'].plot(label='MA200')
plt.legend()
plt.title('Intel Open, 50EMA, 200EMA')
ibm['Open'].plot(figsize=(15,7))
ibm['MA50']=ibm['Open'].rolling(50).... | _____no_output_____ | MIT | Stock Project.ipynb | SPC7/dlensInternship |
Time Series Analysis AutoCorrelation | def autocorr_daily(intel):
returns = intel.pct_change()
autocorrelation = returns['Adj Close'].autocorr()
return autocorrelation
autocorr_daily(intel)
autocorr_daily(ibm)
autocorr_daily(nvidia)
autocorr_daily(trch) | _____no_output_____ | MIT | Stock Project.ipynb | SPC7/dlensInternship |
Scatter Matrix Based off Open Price | from pandas.plotting import scatter_matrix
tech_comp = pd.concat([ibm['Open'],intel['Open'],nvidia['Open']],axis =1)
tech_comp.columns = ['IBM Open','Intel Open','Nvidia Open']
scatter_matrix(tech_comp,figsize=(8,8),hist_kwds={'bins':50}) | _____no_output_____ | MIT | Stock Project.ipynb | SPC7/dlensInternship |
CandleStick Analysis CandleStick Analysis | candleIntel = intel.iloc[100:160]
mpl.plot(candleIntel,type='candle',volume=True)
candleIBM = ibm.iloc[100:160]
mpl.plot(candleIBM,type='candle',volume=True)
candleNvidia = nvidia.iloc[100:160]
mpl.plot(candleNvidia,type='candle',volume=True) | _____no_output_____ | MIT | Stock Project.ipynb | SPC7/dlensInternship |
Monte Carlo Stock Price Predictor | monte_end = datetime.datetime.now()
monte_start = monte_end - datetime.timedelta(days=300)
prices = yf.download("NVDA",monte_start,monte_end)['Close']
returns = prices.pct_change()
meanReturns = returns.mean()
last_price = prices[-1]
num_sims = 100
num_days = 300
sim_df = pd.DataFrame()
for x in range(num_sims... | _____no_output_____ | MIT | Stock Project.ipynb | SPC7/dlensInternship |
SUBSET SELECTION | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import scipy
import sklearn
import seaborn as sns
import xlrd
import time
import statsmodels.api as sm
data=pd.read_excel('Data/Mini Project EFSA.xlsx')
data.rename(columns={'sex \n(0=M, 1=F)':'sex'}, inplace=True)
data
from funzioni import forward | _____no_output_____ | MIT | Notebooks/.ipynb_checkpoints/ciccione-checkpoint.ipynb | AndreaPrati98/EFSA_study |
I dati sono le colonne originali | import numpy as np
from sklearn.preprocessing import PolynomialFeatures
#Prepare the datas
y = data.response
weights = data.SD
X = data.drop(columns=["response","SD"])
#Devo estrarre l'endpoint dalla matrice in modo da avere 2 variabili categoriche usate per fare i 3 endpoint
endpoint1 = X['endpoint'] == 1
endpoint2 ... | _____no_output_____ | MIT | Notebooks/.ipynb_checkpoints/ciccione-checkpoint.ipynb | AndreaPrati98/EFSA_study |
2 - Use subset selection to estimate separate models for the 3 endpoints using gender as categorical variable. 3 - Use subset selection to estimate a unique model using gender and endpoint as categorical variablesForward solo con i predittori lineari | models_fwd = pd.DataFrame(columns=["RSS", "model","number_of_predictors"])
tic = time.time()
predictors = []
for i in range(1,len(X.columns)+1):
models_fwd.loc[i] = forward(y,X,predictors,weights)
predictors = models_fwd.loc[i]["model"].model.exog_names
toc = time.time()
print("Total elapsed time:", (toc-tic... | WLS Regression Results
==============================================================================
Dep. Variable: response R-squared: 0.926
Model: WLS Adj. R-squared: 0.906
Meth... | MIT | Notebooks/.ipynb_checkpoints/ciccione-checkpoint.ipynb | AndreaPrati98/EFSA_study |
Confrontiamo ora questi modelli con criteri oggettivi | for i in range(1, models_fwd.shape[0]):
model = models_fwd.loc[i,"model"]
models_fwd.loc[i,"aic"] = model.aic
models_fwd.loc[i,"bic"] = model.bic
models_fwd.loc[i,"mse"] = model.mse_total
models_fwd.loc[i,"adj_rsquare"] = model.rsquared_adj
models_fwd
#Quelli da minimizzare
for criteria in ["bi... | Cuina!
| MIT | Notebooks/.ipynb_checkpoints/ciccione-checkpoint.ipynb | AndreaPrati98/EFSA_study |
COM418 - Computers and MusicPaolo Prandoni, LCAV, EPFLNon-Harmonic Distortion in a Quantized Sinusoid (Tsividis' Paradox) | %matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import scipy.signal as sp
import scipy.special as ss
from scipy.io import wavfile
import IPython
import ipywidgets as widgets
plt.rcParams["figure.figsize"] = (14,4)
# helper functions
def play_sound(SF, s, volume=1):
# play a sound with a volum... | _____no_output_____ | CC0-1.0 | Quantization/QuantizationError/QS_slides.ipynb | Jadouille/COM418 |
Quantization in A/D conversion The classic A/D converter * $x(t)$ bandlimited to $F_s/2$ * sample at $F_s$ Hz * uniform quantization with $M$ levels Uniform scalar quantization * $M$-level uniform scalar quantizer: $q: \mathbb{R} \rightarrow \{\hat{x}_0, \ldots, \hat{x}_{M-1}\}$ * non-overload region: $[-1,1]$ * q... | def quantize(x, M):
if M == 0:
return x
elif M % 2 == 0:
# using a mid-riser quantizer
M = M / 2
k = np.floor(x * M)
k = np.maximum(np.minimum(k, M-1), -M)
return (k + 0.5) / M
else:
# using a deadzone quantizer
k = np.round(np.abs(x) * M / 2)
... | _____no_output_____ | CC0-1.0 | Quantization/QuantizationError/QS_slides.ipynb | Jadouille/COM418 |
High-resolution hypothesis * $e[n]$ white noise uncorrelated with $x[n]$ * $\sigma_e[n] = \Delta^2/12$ * $\mathrm{SNR} = 6M~\mathrm{dB}$ Tsividis' paradox * sampling and quantization are memoryless: they can be swapped * let's swap them: but $\mathcal{Q}$ discontinuous so $\hat{x}(t)$ no longer bandlimited $~... | sf, f0, M = 8000, 440, 9
# one second per clipping level
w = 2 * np.pi * f0 / sf * np.arange(0, M * sf)
x = np.sin(w)
x_c, x_q = np.zeros(len(w)), np.zeros(len(w))
for n, level in enumerate(range(M, 1, -1)):
s = slice(n * sf, (n + 1) * sf)
# progessively harder clipping
x_c[s] = np.clip(np.sin(w[s]), -lev... | _____no_output_____ | CC0-1.0 | Quantization/QuantizationError/QS_slides.ipynb | Jadouille/COM418 |
Aside: non-harmonic distortion due to intermodulationWhen more than a single sinusoid is considered, things get complicated quickly * $r(x) = \sum_{n=0}^{\infty} a_n \, x^n$ (Taylor series expansion) * $\sin^n \alpha = \gamma_0 + \sum_{k=1}^{n} \gamma_k \sin k\alpha$ * $\sin \alpha \sin \beta = \mu_0 \sin(\alpha + \b... | for n, level in enumerate(range(M, 1, -1)):
s = slice(n * sf, (n + 1) * sf)
x_c[s] = np.clip((np.sin(w[s]) + np.sin(1.5 * w[s])) / 2, -level/M, level/M) * M / level
play_sound(sf, x_c, volume=0.3) | _____no_output_____ | CC0-1.0 | Quantization/QuantizationError/QS_slides.ipynb | Jadouille/COM418 |
Ravel's Bolero An impressive dynamic range | clips = {}
for name in ['boleroA', 'boleroM', 'boleroZ']:
sf, audio = wavfile.read('snd/' + name + '.wav')
clips['sf'], clips[name] = sf, audio / 32767.0
multiplay(clips['sf'], [clips['boleroA'], clips['boleroZ']], ['beginning, full res', 'ending, full res']) | _____no_output_____ | CC0-1.0 | Quantization/QuantizationError/QS_slides.ipynb | Jadouille/COM418 |
* live performances have an dynamic range of 100dBs or more * 16-bit audio covers about 96dBs * ... but vinyl is no better: about 70dB dynamic range Aside: oreloBBolero is much louder at the end but vinyls suffer from _end of side_ distortion: * rotational speed constant, but inner grooves shorter * reading speed ge... | levels=[2 ** 16, 2 ** 8]
multiplay(clips['sf'], [quantize(clips['boleroM'], m) for m in levels], [f'middle, {m}-level quantization' for m in levels])
levels=[2 ** 16, 2 ** 8]
multiplay(clips['sf'], [quantize(clips['boleroA'], m) for m in levels], [f'beginning, {m}-level quantization' for m in levels]) | _____no_output_____ | CC0-1.0 | Quantization/QuantizationError/QS_slides.ipynb | Jadouille/COM418 |
Numerical Experiments Sampling a sine wave with rational normalized frequency(the opening flute in the Bolero is close to a pure sinusoid) * conventional setup: sampling followed by quantization * $x(t) = \sin(2\pi f_0 t)$, sampled at $F_s$ and $f_0 = \frac{A}{B}F_s$ with $A$ and $B$ coprime * $x[n] = \sin\left(2\p... | def quantized_sinusoid(A, B, M=0, initial_phase=1):
# add an initial phase non commensurable with pi to eliminate quantization of zero values
x = np.sin(initial_phase + 2 * np.pi * ((A * np.arange(0, B)) % B) / B)
qx = quantize(x, M)
return {
'original' : x,
'quantized' : qx,
#... | _____no_output_____ | CC0-1.0 | Quantization/QuantizationError/QS_slides.ipynb | Jadouille/COM418 |
Introducing quantization * $\mathbf{x} \rightarrow \hat{\mathbf{x}}$ * $\hat{\mathbf{x}}$ still periodic with a period of $B$ samples Distortion: * harmonic distortion will affects the DFS coefficient whose index is a multiple of $A$ * non-harmonic distortion will affect the other coefficients First note in the Bole... | def find_nhd(A, dfs, full=False):
# zero out harmonic components to highlight non-harmonic content
N = int(np.ceil(len(dfs) / 2)) if full else len(dfs)
nhd = np.copy(dfs[:N])
nhd[::A] = 0
return max(nhd), nhd
def show_nhd(A=3, B=257, M=2):
s = quantized_sinusoid(A, B, int(M))
peak, nhd = fin... | _____no_output_____ | CC0-1.0 | Quantization/QuantizationError/QS_slides.ipynb | Jadouille/COM418 |
Searching for the worst case * try to get a sense for how bad non-harmonic distortion can get * let's iterate over all non-reducible $A/B$ ratios between $0$ and $1/2$ **Farey sequence** of order $N$ is the sequence of _non-reducible_ fractions in the unit interval with denominator smaller or equal than $N$ | def farey_sequence(n):
"""Build the order-N Farey sequence up to 1/2."""
farey = []
(a, b, c, d) = (0, 1, 1, n)
while (c <= n):
k = (n + b) // d
(a, b, c, d) = (c, d, k * c - a, k * d - b)
farey.append((a, b))
if a/b >= 0.5:
break
return farey
for (a, b)... | _____no_output_____ | CC0-1.0 | Quantization/QuantizationError/QS_slides.ipynb | Jadouille/COM418 |
Non-harmonic distortion for Farey ratiosMaximum square magnitude of non-harmonic DFS coefficient as a function of $B$ and parametrized in $A$ | find_max_nhd(100, 2, parametric=True)
find_max_nhd(100, 3, parametric=True)
find_max_nhd(100, 32768, parametric=True) | _____no_output_____ | CC0-1.0 | Quantization/QuantizationError/QS_slides.ipynb | Jadouille/COM418 |
Let's also look at the non-parametrized plots. The reason for the step-ladder patterns will be hopefully clear by the end. | find_max_nhd(150, 2)
find_max_nhd(150, 3) | _____no_output_____ | CC0-1.0 | Quantization/QuantizationError/QS_slides.ipynb | Jadouille/COM418 |
Theoretical Analysis Some DSP archeology Here is a really interesting paper from 1947 For context, in 1947 this was happening My second favorite quote of the paper: My favorite quote of all time: Quantization before sampling | t = np.arange(0, 2 * np.pi, 0.001)
plt.plot(t, quantize(np.sin(t), 15)); | _____no_output_____ | CC0-1.0 | Quantization/QuantizationError/QS_slides.ipynb | Jadouille/COM418 |
Fundamental idea: * decompose this piecewise-constant periodic waveform as the sum of $N$ pairs of rectangular steps of appropriate width * express $\hat{x}(t)$ using a Fourier series expansion:$$ \hat{x}(t) = \sum_{h=1}^{N} \sum_{k=0}^{\infty} \frac{4}{\pi N (2k+1)} \cos\left[(2k+1)\arcsin\left(\frac{2h-1}{2N}\r... | def quantized_sinusoid_fs(N, terms=1000):
t = np.arange(0, 2 * np.pi, 0.001)
x = np.zeros(len(t))
for h in range(1, N):
for k in range(0, terms):
x = x + np.cos((2 * k + 1) * np.arcsin((2 * h - 1) / N / 2)) * np.sin((2 * k + 1) * t) / (2 * k + 1)
x = x * 4 / np.pi / N
return t, x... | _____no_output_____ | CC0-1.0 | Quantization/QuantizationError/QS_slides.ipynb | Jadouille/COM418 |
Fundamental intuition: * $q(\sin(t))$ **contains harmonics at all odd multiples of the fundamental frequency** * quantization of a continuous-time sine wave produces only harmonic distortion * NHD is given by spectral lines beyond the Nyquist frequency aliased by the sampler More recent timesMoving on to Robert G... | x = np.arange(-1, 1, .001)
for ix, M in enumerate([2, 3, 8]):
plt.subplot(1, 3, ix+1)
e = (quantize(x, M) - x) / (2 / M)
plt.plot(x, e);
plt.plot(x, e, '.'); | _____no_output_____ | CC0-1.0 | Quantization/QuantizationError/QS_slides.ipynb | Jadouille/COM418 |
* $\eta(x)$ can be expressed as a Fourier Series$$ \eta(x) = \sum_{k=1}^{\infty} \frac{(-1)^{kM}}{\pi k}\sin\left(\pi k M x\right)$$ * $(-1)^{kM}$ is identically one for mid-riser quantizers and alternates in sign for deadzone quantizers. | def nqe_fs(x, M, terms=1000):
e = np.zeros(len(x))
s = [1, -1 if M % 2 == 1 else 1]
for k in range(1, terms):
e = e + s[k % 2] * np.sin(np.pi * k * x * M) / (np.pi * k)
return x, e
for ix, M in enumerate([2, 3, 8]):
plt.subplot(1, 3, ix+1)
plt.plot(*nqe_fs(np.arange(-1, 1, .01), M)) | _____no_output_____ | CC0-1.0 | Quantization/QuantizationError/QS_slides.ipynb | Jadouille/COM418 |
Quantization noise for a sinusoidal input * back to sampling followed by quantization * $x[n] = \sin(\omega_0 n + \theta)$ with $0 \le \omega_0 < 2\pi$. * $\eta[n] = \eta(\sin(\omega_0 n + \theta))$ and we are interested in computing its spectrum. * using complex exponentials for the Fourier series:$$ \eta(x) = ... | def nqe_sin_psd(A, B, M, phase=1):
s = [1, -1 if M % 2 == 1 else 1]
b = np.zeros(B, dtype=complex)
m_lim, k_lim = max(1500, 2 * B), 600
for m in range(-m_lim, m_lim):
c = 0
for k in range(1, k_lim):
c += s[k % 2] * ss.jv(2 * m + 1, np.pi * k * M) / k
c /= 1j * np.pi
... | Max NHD (theory): 0.014076477031128238
Max NHD (FFT): 0.014262281437017315
| CC0-1.0 | Quantization/QuantizationError/QS_slides.ipynb | Jadouille/COM418 |
Case 2: irrational normalized frequencyAssume $\omega_0$ not a rational multiple of $2\pi$ * the normalized frequency $\nu = \omega_0/(2\pi)$ will be an irrational number in $[0, 1)$ * the set of _normalized_ frequencies $\Omega'(\nu) = \{(2m+1)\nu \mod 1\}_{m \in \mathbb{Z}} = \{ \langle (2m+1)\nu \rangle\}_{m \in ... | P = (150, 1021, 2)
stem(nqe_sin_psd(*P), 'tab:green')
stem(nqe_sin_dfs(*P), 'tab:red') | Max NHD (theory): 0.004830057419924902
Max NHD (FFT): 0.00405292728721497
| CC0-1.0 | Quantization/QuantizationError/QS_slides.ipynb | Jadouille/COM418 |
Back to the non-harmonic distortion patternsRecall the plot of the maximum non-harmonic distortion as a function of normalized frequency and its curious "stepladder" pattern: | find_max_nhd(150, 2) | _____no_output_____ | CC0-1.0 | Quantization/QuantizationError/QS_slides.ipynb | Jadouille/COM418 |
Consider the non-normalized quantization error for a sinusoid of frequency $\omega_0 = 2\pi\nu$, with $0 < \nu < 1/2$:$$\begin{align*} \frac{2}{M}\, \eta(\sin(2\pi\nu n))&= \sum_{m=-\infty}^{\infty} \left[ \frac{2}{M}\sum_{k = 1}^{\infty} \frac{(-1)^{kM}}{j\pi k}J_{2m+1}(\pi k M) \right] e^{j 2\pi(2m+1)\nu n} \\ ... | def c_m(N, M=2):
k_lim = 600000
s = [1, -1 if M % 2 == 1 else 1]
c = np.zeros(N, dtype=complex)
for m in range(0, N):
for k in range(1, k_lim):
c[m] += s[k % 2] * ss.jv(2 * m + 1, np.pi * k * M) / k
c[m] /= 1j * np.pi
return np.abs(c * (2 / M)) ** 2
c2 = c_m(20, 2)
stem(c... | _____no_output_____ | CC0-1.0 | Quantization/QuantizationError/QS_slides.ipynb | Jadouille/COM418 |
* the max NHD is dominated by the first aliased component:max NHD is $|c_M(m_0)|^2$ where $m_0$ is the minimum integer for which $(2m_0+1)\nu > 1/2$. * for $\nu > 1/6$, NHD $\approx |c_M(1)|^2$ * for $1/10 < \nu < 1/6$, NHD $\approx |c_M(2)|^2$ * ... | find_max_nhd(150, 2)
for m in range(1, 5):
plt.plot([0.5/(2*m+1), 0.5/(2*m+1)], [0, 0.015], color=plt.cm.tab10(m))
plt.plot([0, 0.5], [c2[m], c2[m]], color=plt.cm.tab10(m)) | _____no_output_____ | CC0-1.0 | Quantization/QuantizationError/QS_slides.ipynb | Jadouille/COM418 |
What about $M=3$ ? * $c_3(2) \approx 0$ * $c_3(m)$ non-monotonic * NHD approx the same for $1/18 < \nu < 1/6$. | c3 = c_m(20, 3)
stem(c3)
find_max_nhd(150, 3)
for m in range(1, 5):
plt.plot([0.5/(2*m+1), 0.5/(2*m+1)], [0, 0.015], color=plt.cm.tab10(m))
plt.plot([0, 0.5], [c3[m], c3[m]], color=plt.cm.tab10(m)) | _____no_output_____ | CC0-1.0 | Quantization/QuantizationError/QS_slides.ipynb | Jadouille/COM418 |
Large dataset testing---Checking if the new large dataset class, which lazily loads batch files instead of diving a giant pre-loaded one, works well to train my models. Importing the necessary packages | import os # os handles directory/workspace changes
import comet_ml # Comet.ml can log training metrics, parameters, do version control and parameter optimization
import torch # PyTorch to create and apply deep learning models
# im... | _____no_output_____ | MIT | notebooks/.ipynb_checkpoints/large-dataset-testing-checkpoint.ipynb | AndreCNF/data-utils |
Initializing variables Comet ML settings: | comet_ml_project_name = input('Comet ML project name:')
comet_ml_workspace = input('Comet ML workspace:')
comet_ml_api_key = getpass.getpass('Comet ML API key') | _____no_output_____ | MIT | notebooks/.ipynb_checkpoints/large-dataset-testing-checkpoint.ipynb | AndreCNF/data-utils |
Dataset parameters: | dataset_mode = None # The mode in which we'll use the data, either one hot encoded or pre-embedded
ml_core = None # The core machine learning type we'll use; either traditional ML or DL
use_delta_ts = None # Indicates if we'll use time variation ... | _____no_output_____ | MIT | notebooks/.ipynb_checkpoints/large-dataset-testing-checkpoint.ipynb | AndreCNF/data-utils |
Data types: | dtype_dict = dict(patientunitstayid='uint',
ts='uint',
int_col='Int32',
float_col='float32',
cat_1_bool_1='UInt8',
cat_1_bool_2='UInt8',
cat_2_bool_1='UInt8',
cat_3_bool_1='UInt8',
... | _____no_output_____ | MIT | notebooks/.ipynb_checkpoints/large-dataset-testing-checkpoint.ipynb | AndreCNF/data-utils |
One hot encoding columns categorization: | cat_feat_ohe = dict(cat_1=['cat_1_bool_1', 'cat_1_bool_2'],
cat_2=['cat_2_bool_1'],
cat_3=['cat_3_bool_1', 'cat_3_bool_2', 'cat_3_bool_3', 'cat_3_bool_4'])
cat_feat_ohe
list(cat_feat_ohe.keys()) | _____no_output_____ | MIT | notebooks/.ipynb_checkpoints/large-dataset-testing-checkpoint.ipynb | AndreCNF/data-utils |
Training parameters: | test_train_ratio = 0.25 # Percentage of the data which will be used as a test set
validation_ratio = 1/3 # Percentage of the data from the training set which is used for validation purposes
batch_size = 2 # Number of unit stays in a mini batch
n_epochs ... | _____no_output_____ | MIT | notebooks/.ipynb_checkpoints/large-dataset-testing-checkpoint.ipynb | AndreCNF/data-utils |
Testing parameters: | metrics = ['loss', 'accuracy', 'AUC', 'AUC_weighted'] | _____no_output_____ | MIT | notebooks/.ipynb_checkpoints/large-dataset-testing-checkpoint.ipynb | AndreCNF/data-utils |
Creating large dummy data Create each individual column as a NumPy array: | patientunitstayid_col = np.concatenate([np.repeat(1, 25),
np.repeat(2, 17),
np.repeat(3, 56),
np.repeat(4, 138),
np.repeat(5, 2000),
... | _____no_output_____ | MIT | notebooks/.ipynb_checkpoints/large-dataset-testing-checkpoint.ipynb | AndreCNF/data-utils |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.