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 |
|---|---|---|---|---|---|
The signal is defined as 100 Hz SSSR | signal = np.zeros((32,200,int(sfreq*0.2)))
xt = np.linspace(0,0.2,sfreq*0.2)
for iChannel in range(32):
for iTrial in range(200):
signal[iChannel,iTrial,:] = np.sin(xt*100*2*np.pi+phase_list[iChannel])
# plot first two channels to show the phase differences
plt.plot(xt,signal[0:2,0,:].transpose()) | <string>:6: DeprecationWarning: object of type <class 'float'> cannot be safely interpreted as an integer.
| MIT | mtcplv_discrepancy.ipynb | HaoLu-a/cPCA-erratum |
The signal to noise ratio (SNR) in the simulated data was set as -40 dB for all channels | std = 10**(40/20)*np.sqrt((signal**2).mean())
noise = np.random.normal(0,std,signal.shape) | _____no_output_____ | MIT | mtcplv_discrepancy.ipynb | HaoLu-a/cPCA-erratum |
The simulated data was analyzed through the code from the function anlffr.spectral.mtcplv | params = dict(Fs = sfreq, tapers = [1,1], fpass = [80, 120], itc = 0, pad = 1)
x=signal + noise
#codes from the dpss tool of anlffr to make sure the multitaper part is consistent
if(len(x.shape) == 3):
timedim = 2
trialdim = 1
ntrials = x.shape[trialdim]
nchans = x.shape[0]
nfft, f, fInd = spec... | _____no_output_____ | MIT | mtcplv_discrepancy.ipynb | HaoLu-a/cPCA-erratum |
The mtcplv did capture the 100 Hz component | plt.plot(f,plv)
plt.xlabel('frequency')
plt.ylabel('output of mtcPLV') | _____no_output_____ | MIT | mtcplv_discrepancy.ipynb | HaoLu-a/cPCA-erratum |
However, the output of mtcplv perfectly overlaps with the average of squared single-channel PLV stored in matrix C | plt.plot(f,abs(C**2).mean(0)[fInd], label='average of square', alpha=0.5)
plt.plot(f,plv,label = 'mtcplv', alpha = 0.5)
plt.plot(f,abs(C**2).mean(0)[fInd] - plv, label='difference')
plt.legend()
plt.xlabel('frequency')
plt.ylabel('PLV') | _____no_output_____ | MIT | mtcplv_discrepancy.ipynb | HaoLu-a/cPCA-erratum |
We then check the eigen value decomposition around the 100 Hz peak and there is only one non-zero eigen value as expected | fi = np.argmax(plv)+np.argwhere(fInd==True).min()
Csd = np.outer(C[:, fi], C[:, fi].conj())
vals = linalg.eigh(Csd, eigvals_only=True)
plt.bar(np.arange(32),vals[::-1])
plt.xlabel('Principle Components')
plt.ylabel('Eigen Values') | _____no_output_____ | MIT | mtcplv_discrepancy.ipynb | HaoLu-a/cPCA-erratum |
Statistics IntroductionIn this chapter, you'll learn about how to do statistics with code. We already saw some statistics in the chapter on probability and random processes: here we'll focus on computing basic statistics and using statistical tests. We'll make use of the excellent [*pingouin*](https://pingouin-stats.... | import numpy as np
from scipy import stats
import matplotlib.pyplot as plt
import pandas as pd
import pingouin as pg
import statsmodels.formula.api as smf
from numpy.random import Generator, PCG64
# Set seed for random numbers
seed_for_prng = 78557
prng = Generator(PCG64(seed_for_prng)) | _____no_output_____ | MIT | econmt-statistics.ipynb | lnsongxf/coding-for-economists |
Basic statisticsLet's start with computing the simplest statistics you can think of using some synthetic data. Many of the functions have lots of extra options that we won't explore here (like weights or normalisation); remember that you can see these using the `help()` method. We'll generate a vector with 100 entries... | data = np.array(range(100))
data
from myst_nb import glue
import sympy
import warnings
warnings.filterwarnings("ignore")
dict_fns = {'mean': np.mean(data),
'std': np.std(data),
'mode': stats.mode([0, 1, 2, 3, 3, 3, 5])[0][0],
'median': np.median(data)}
for name, eval_fn in dict_fns... | _____no_output_____ | MIT | econmt-statistics.ipynb | lnsongxf/coding-for-economists |
Okay, let's see how some basic statistics are computed. The mean is `np.mean(data)=` {glue:}`mean`, the standard deviation is `np.std(data)=` {glue:}`std`, and the median is given by `np.median(data)= `{glue:}`median`. The mode is given by `stats.mode([0, 1, 2, 3, 3, 3, 5])[0]=` {glue:}`mode` (access the counts using `... | np.quantile(data, 0.25) | _____no_output_____ | MIT | econmt-statistics.ipynb | lnsongxf/coding-for-economists |
As with **pandas**, **numpy** and **scipy** work on scalars, vectors, matrices, and tensors: you just need to specify the axis that you'd like to apply a function to: | data = np.fromfunction(lambda i, j: i + j, (3, 6), dtype=int)
data
np.mean(data, axis=0) | _____no_output_____ | MIT | econmt-statistics.ipynb | lnsongxf/coding-for-economists |
Remember that, for discrete data points, the $k$th (unnormalised) moment is$$\hat{m}_k = \frac{1}{n}\displaystyle\sum_{i=1}^{n} \left(x_i - \bar{x}\right)^k$$To compute this use scipy's `stats.moment(a, moment=1)`. For instance for the kurtosis ($k=4$), it's | stats.moment(data, moment=4, axis=1) | _____no_output_____ | MIT | econmt-statistics.ipynb | lnsongxf/coding-for-economists |
Covariances are found using `np.cov`. | np.cov(np.array([[0, 1, 2], [2, 1, 0]])) | _____no_output_____ | MIT | econmt-statistics.ipynb | lnsongxf/coding-for-economists |
Note that, as expected, the $C_{01}$ term is -1 as the vectors are anti-correlated. Parametric testsReminder: parametric tests assume that data are effectively drawn a probability distribution that can be described with fixed parameters. One-sample t-testThe one-sample t-test tells us whether a given parameter for th... | x = [8.5, 5.4, 6.8, 9.6, 4.2, 7.2, 8.8, 8.1]
pg.ttest(x, 8).round(2) | _____no_output_____ | MIT | econmt-statistics.ipynb | lnsongxf/coding-for-economists |
(The returned object is a **pandas** dataframe.) We only have 8 data points, and so that is a great big confidence interval! It's worth remembering what a t-statistic and t-test really are. In this case, the statistic that is constructed to test whether the sample mean is different from a known parameter $\mu$ is$$T = ... | import scipy.stats as st
def plot_t_stat(x, mu):
T = np.linspace(-7, 7, 500)
pdf_vals = st.t.pdf(T, len(x)-1)
sigma_hat = np.sqrt(np.sum( (x-np.mean(x))**2)/(len(x)-1))
actual_T_stat = (np.sqrt(len(x))*(np.mean(x) - mu))/sigma_hat
alpha = 0.05
T_alpha_over_2 = st.t.ppf(1.0-alpha/2, len(x)-1)
... | _____no_output_____ | MIT | econmt-statistics.ipynb | lnsongxf/coding-for-economists |
In this case, we would reject the alternative hypothesis. You can see why from the plot; the test statistic we have constructed lies within the interval where we cannot reject the null hypothesis. $\bar{x}-\mu$ is close enough to zero to give us cause for concern. (You can also see from the plot why this is a two-taile... | # 'Observe' extra data
extra_data = prng.uniform(5.5, 8.5, size=(30))
# Add it in to existing vector
x_prime = np.concatenate((np.array(x), extra_data), axis=None)
# Run t-test
pg.ttest(x_prime, 8).round(2) | _____no_output_____ | MIT | econmt-statistics.ipynb | lnsongxf/coding-for-economists |
Okay, what happened? Our extra observations have seen the confidence interval shrink considerably, and the p-value is effectively 0. There's a large negative t-statistic too. Unsurprisingly, as we chose a uniform distribution that only just included 8 but was centered on $(8-4.5)/2$ *and* we had more points, the test n... | plot_t_stat(x_prime, mu) | _____no_output_____ | MIT | econmt-statistics.ipynb | lnsongxf/coding-for-economists |
Now our test statistic is safely outside the interval. Connection to linear regressionNote that testing if $\mu\neq0$ is equivalent to having the alternative hypothesis that a single, non-zero scalar value is a good expected value for $x$, i.e. that $\mathbb{E}(x) \neq 0$. Which may sound familiar if you've run **linea... | pg.ttest(x, 0).round(3) | _____no_output_____ | MIT | econmt-statistics.ipynb | lnsongxf/coding-for-economists |
And, as an alternative, regressing x on a constant, again noting the interval, t-stat, and p-value: | import statsmodels.formula.api as smf
df = pd.DataFrame(x, columns=['x'])
res = smf.ols(formula='x ~ 1', data=df).fit()
# Show only the info relevant to the intercept (there are no other coefficients)
print(res.summary().tables[1]) | _____no_output_____ | MIT | econmt-statistics.ipynb | lnsongxf/coding-for-economists |
Many tests have an equivalent linear model. Other information provided by **Pingouin** testsWe've covered the degrees of freedom, the T statistic, the p-value, and the confidence interval. So what's all that other gunk in our t-test? Cohen's d is a measure of whether the difference being measured in our test is large... | pre = [5.5, 2.4, 6.8, 9.6, 4.2, 5.9]
post = [6.4, 3.4, 6.4, 11., 4.8, 6.2]
pg.ttest(pre, post, paired=True, tail='two-sided').round(2) | _____no_output_____ | MIT | econmt-statistics.ipynb | lnsongxf/coding-for-economists |
In this case, we cannot reject the null hypothesis that the means are the same pre- and post-intervention. Pearson correlationThe Pearson correlation coefficient measures the linear relationship between two datasets. Strictly speaking, it requires that each dataset be normally distributed. | mean, cov = [4, 6], [(1, .5), (.5, 1)]
x, y = prng.multivariate_normal(mean, cov, 30).T
# Compute Pearson correlation
pg.corr(x, y).round(3) | _____no_output_____ | MIT | econmt-statistics.ipynb | lnsongxf/coding-for-economists |
Welch's t-testIn the case where you have two samples with unequal variances (or, really, unequal sample sizes too), Welch's t-test is appropriate. With `correction='true'`, it assumes that variances are not equal. | x = prng.normal(loc=7, size=20)
y = prng.normal(loc=6.5, size=15)
pg.ttest(x, y, correction='true') | _____no_output_____ | MIT | econmt-statistics.ipynb | lnsongxf/coding-for-economists |
One-way ANOVAAnalysis of variance (ANOVA) is a technique for testing hypotheses about means, for example testing the equality of the means of $k>2$ groups. The model would be$$X_{ij} = \mu_i + \epsilon_{ij} \quad j=1, \dots, n_i \quad i=1, \dots, k.$$so that the $i$th group has $n_i$ observations. The null hypothesis ... | df = pg.read_dataset('mixed_anova')
df.head()
# Run the ANOVA
pg.anova(data=df, dv='Scores', between='Group', detailed=True) | _____no_output_____ | MIT | econmt-statistics.ipynb | lnsongxf/coding-for-economists |
Multiple pairwise t-testsThere's a problem with running multiple t-tests: if you run enough of them, something is bound to come up as significant! As such, some *post-hoc* adjustments exist that correct for the fact that multiple tests are occurring simultaneously. In the example below, multiple pairwise comparisons a... | pg.pairwise_ttests(data=df, dv='Scores', within='Time', subject='Subject',
parametric=True, padjust='fdr_bh', effsize='hedges').round(3) | _____no_output_____ | MIT | econmt-statistics.ipynb | lnsongxf/coding-for-economists |
One-way ANCOVAAnalysis of covariance (ANCOVA) is a general linear model which blends ANOVA and regression. ANCOVA evaluates whether the means of a dependent variable (dv) are equal across levels of a categorical independent variable (between) often called a treatment, while statistically controlling for the effects of... | df = pg.read_dataset('ancova')
df.head()
pg.ancova(data=df, dv='Scores', covar='Income', between='Method') | _____no_output_____ | MIT | econmt-statistics.ipynb | lnsongxf/coding-for-economists |
Power calculationsOften, it's quite useful to know what sample size is needed to avoid certain types of testing errors. **Pingouin** offers ways to compute effect sizes and test powers to help with these questions.As an example, let's assume we have a new drug (`x`) and an old drug (`y`) that are both intended to redu... | cohen_d = -0.25 # Fixed effect size
sample_size_array = np.arange(1, 500, 50) # Incrementing sample size
# Compute the achieved power
pwr = pg.power_ttest(d=cohen_d, n=sample_size_array, alpha=0.05,
contrast='two-samples', tail='less')
fig, ax = plt.subplots()
ax.plot(sample_size_array, pwr, 'ko-... | _____no_output_____ | MIT | econmt-statistics.ipynb | lnsongxf/coding-for-economists |
From this, we can see we need a sample size of at least 200 in order to have a power of 0.8. The `pg.power_ttest` function takes any three of the four of `d`, `n`, `power`, and `alpha` (ie leave one of these out), and then returns what the missing parameter should be. We passed in `d`, `n`, and `alpha`, and so the `pow... | x = [20, 22, 19, 20, 22, 18, 24, 20, 19, 24, 26, 13]
y = [38, 37, 33, 29, 14, 12, 20, 22, 17, 25, 26, 16]
pg.wilcoxon(x, y, tail='two-sided').round(2) | _____no_output_____ | MIT | econmt-statistics.ipynb | lnsongxf/coding-for-economists |
Mann-Whitney U Test (aka Wilcoxon rank-sum test)The Mann–Whitney U test is a non-parametric test of the null hypothesis that it is equally likely that a randomly selected value from one sample will be less than or greater than a randomly selected value from a second sample. It is the non-parametric version of the two-... | x = prng.uniform(low=0, high=1, size=20)
y = prng.uniform(low=0.2, high=1.2, size=20)
pg.mwu(x, y, tail='greater') | _____no_output_____ | MIT | econmt-statistics.ipynb | lnsongxf/coding-for-economists |
Spearman CorrelationThe Spearman correlation coefficient is the Pearson correlation coefficient between the rank variables, and does not assume normality of data. | mean, cov = [4, 6], [(1, .5), (.5, 1)]
x, y = prng.multivariate_normal(mean, cov, 30).T
pg.corr(x, y, method="spearman").round(2) | _____no_output_____ | MIT | econmt-statistics.ipynb | lnsongxf/coding-for-economists |
Kruskal-WallaceThe Kruskal-Wallis H-test tests the null hypothesis that the population median of all of the groups are equal. It is a non-parametric version of ANOVA. The test works on 2 or more independent samples, which may have different sizes. | df = pg.read_dataset('anova')
df.head()
pg.kruskal(data=df, dv='Pain threshold', between='Hair color') | _____no_output_____ | MIT | econmt-statistics.ipynb | lnsongxf/coding-for-economists |
The Chi-Squared TestThe chi-squared test is used to determine whether there is a significant difference between the expected frequencies and the observed frequencies in one or more categories. This test can be used to evaluate the quality of a categorical variable in a classification problem or to check the similarity... | chi_data = pg.read_dataset('chi2_independence')
chi_data['sex'].value_counts(ascending=True) | _____no_output_____ | MIT | econmt-statistics.ipynb | lnsongxf/coding-for-economists |
If gender is *not* a predictor, we would expect a roughly similar split between those who have heart disease and those who do not. Let's look at the observerd versus the expected split once we categorise by gender and 'target' (heart disease or not). | expected, observed, stats = pg.chi2_independence(chi_data, x='sex', y='target')
observed - expected | _____no_output_____ | MIT | econmt-statistics.ipynb | lnsongxf/coding-for-economists |
So we have fewer in the 0, 0 and 1, 1 buckets than expected but more in the 0, 1 and 1, 0 buckets. Let's now see how the test interprets this: | stats.round(3) | _____no_output_____ | MIT | econmt-statistics.ipynb | lnsongxf/coding-for-economists |
From these, it is clear we can reject the null and therefore it seems like gender is a good predictor of heart disease. Shapiro-Wilk Test for NormalityNote that the null here is that the distribution *is* normal, so normality is only rejected when the p-value is sufficiently small. | x = prng.normal(size=20)
pg.normality(x) | _____no_output_____ | MIT | econmt-statistics.ipynb | lnsongxf/coding-for-economists |
The test can also be run on multiple variables in a dataframe: | df = pg.read_dataset('ancova')
pg.normality(df[['Scores', 'Income', 'BMI']], method='normaltest').round(3) | _____no_output_____ | MIT | econmt-statistics.ipynb | lnsongxf/coding-for-economists |
If you don't want to train the network skip the cell righ below and dowload the pre-trained model. After downloading the pre-trained model run the cell below to the immediate below cell. | batch_size = 32
epoch_num = 50
saving_path = 'K:/autoencoder_color_to_gray/SavedModel/AutoencoderColorToGray.ckpt'
saver_ = tf.train.Saver(max_to_keep = 3)
batch_img = dataset_source[0:batch_size]
batch_out = dataset_target[0:batch_size]
num_batches = num_images//batch_size
sess = tf.Session()
sess.run(init)
for ... | (100, 128, 128, 1)
| CC-BY-2.0 | RGB_to_GRAY_scale_Autoencoder.ipynb | NeoBoy/RGB_to_GRAYSCALE_Autoencoder- |
CarND Object Detection LabLet's get started! | import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
from PIL import ImageDraw
from PIL import ImageColor
import time
from scipy.stats import norm
%matplotlib inline
plt.style.use('ggplot') | /root/miniconda3/envs/carnd-term1/lib/python3.5/site-packages/matplotlib/font_manager.py:273: UserWarning: Matplotlib is building the font cache using fc-list. This may take a moment.
warnings.warn('Matplotlib is building the font cache using fc-list. This may take a moment.')
/root/miniconda3/envs/carnd-term1/lib/py... | MIT | CarND-Object-Detection-Lab.ipynb | 48cfu/Object-Detection-Lab |
MobileNets[*MobileNets*](https://arxiv.org/abs/1704.04861), as the name suggests, are neural networks constructed for the purpose of running very efficiently (high FPS, low memory footprint) on mobile and embedded devices. *MobileNets* achieve this with 3 techniques:1. Perform a depthwise convolution followed by a 1x1... | def vanilla_conv_block(x, kernel_size, output_channels):
"""
Vanilla Conv -> Batch Norm -> ReLU
"""
x = tf.layers.conv2d(
x, output_channels, kernel_size, (2, 2), padding='SAME')
x = tf.layers.batch_normalization(x)
return tf.nn.relu(x)
# TODO: implement MobileNet conv block
def mobilen... | _____no_output_____ | MIT | CarND-Object-Detection-Lab.ipynb | 48cfu/Object-Detection-Lab |
**[Sample solution](./exercise-solutions/e1.py)**Let's compare the number of parameters in each block. | # constants but you can change them so I guess they're not so constant :)
INPUT_CHANNELS = 32
OUTPUT_CHANNELS = 512
KERNEL_SIZE = 3
IMG_HEIGHT = 256
IMG_WIDTH = 256
with tf.Session(graph=tf.Graph()) as sess:
# input
x = tf.constant(np.random.randn(1, IMG_HEIGHT, IMG_WIDTH, INPUT_CHANNELS), dtype=tf.float32)
... | _____no_output_____ | MIT | CarND-Object-Detection-Lab.ipynb | 48cfu/Object-Detection-Lab |
Your solution should show the majority of the parameters in *MobileNet* block stem from the pointwise convolution. *MobileNet* SSDIn this section you'll use a pretrained *MobileNet* [SSD](https://arxiv.org/abs/1512.02325) model to perform object detection. You can download the *MobileNet* SSD and other models from the... | # Frozen inference graph files. NOTE: change the path to where you saved the models.
SSD_GRAPH_FILE = 'ssd_mobilenet_v1_coco_11_06_2017/frozen_inference_graph.pb'
RFCN_GRAPH_FILE = 'rfcn_resnet101_coco_11_06_2017/frozen_inference_graph.pb'
FASTER_RCNN_GRAPH_FILE = 'faster_rcnn_inception_resnet_v2_atrous_coco_11_06_2017... | _____no_output_____ | MIT | CarND-Object-Detection-Lab.ipynb | 48cfu/Object-Detection-Lab |
Below are utility functions. The main purpose of these is to draw the bounding boxes back onto the original image. | # Colors (one for each class)
cmap = ImageColor.colormap
print("Number of colors =", len(cmap))
COLOR_LIST = sorted([c for c in cmap.keys()])
#
# Utility funcs
#
def filter_boxes(min_score, boxes, scores, classes):
"""Return boxes with a confidence >= `min_score`"""
n = len(classes)
idxs = []
for i in... | _____no_output_____ | MIT | CarND-Object-Detection-Lab.ipynb | 48cfu/Object-Detection-Lab |
Below we load the graph and extract the relevant tensors using [`get_tensor_by_name`](https://www.tensorflow.org/api_docs/python/tf/Graphget_tensor_by_name). These tensors reflect the input and outputs of the graph, or least the ones we care about for detecting objects. | detection_graph = load_graph(SSD_GRAPH_FILE)
# detection_graph = load_graph(RFCN_GRAPH_FILE)
# detection_graph = load_graph(FASTER_RCNN_GRAPH_FILE)
# The input placeholder for the image.
# `get_tensor_by_name` returns the Tensor with the associated name in the Graph.
image_tensor = detection_graph.get_tensor_by_name('... | _____no_output_____ | MIT | CarND-Object-Detection-Lab.ipynb | 48cfu/Object-Detection-Lab |
Run detection and classification on a sample image. | # Load a sample image.
image = Image.open('./assets/sample1.jpg')
image_np = np.expand_dims(np.asarray(image, dtype=np.uint8), 0)
with tf.Session(graph=detection_graph) as sess:
# Actual detection.
(boxes, scores, classes) = sess.run([detection_boxes, detection_scores, detection_classes],
... | _____no_output_____ | MIT | CarND-Object-Detection-Lab.ipynb | 48cfu/Object-Detection-Lab |
Timing DetectionThe model zoo comes with a variety of models, each its benefits and costs. Below you'll time some of these models. The general tradeoff being sacrificing model accuracy for seconds per frame (SPF). | def time_detection(sess, img_height, img_width, runs=10):
image_tensor = sess.graph.get_tensor_by_name('image_tensor:0')
detection_boxes = sess.graph.get_tensor_by_name('detection_boxes:0')
detection_scores = sess.graph.get_tensor_by_name('detection_scores:0')
detection_classes = sess.graph.get_tensor_b... | _____no_output_____ | MIT | CarND-Object-Detection-Lab.ipynb | 48cfu/Object-Detection-Lab |
Exercise 4 - Model TradeoffsDownload a few models from the [model zoo](https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/detection_model_zoo.md) and compare the timings. Detection on a VideoFinally run your pipeline on [this short video](https://s3-us-west-1.amazonaws.com/udacity-selfdr... | # Import everything needed to edit/save/watch video clips
from moviepy.editor import VideoFileClip
from IPython.display import HTML
HTML("""
<video width="960" height="600" controls>
<source src="{0}" type="video/mp4">
</video>
""".format('driving.mp4')) | _____no_output_____ | MIT | CarND-Object-Detection-Lab.ipynb | 48cfu/Object-Detection-Lab |
Exercise 5 - Object Detection on a VideoRun an object detection pipeline on the above clip. | clip = VideoFileClip('driving.mp4')
# TODO: Complete this function.
# The input is an NumPy array.
# The output should also be a NumPy array.
def pipeline(img):
pass | _____no_output_____ | MIT | CarND-Object-Detection-Lab.ipynb | 48cfu/Object-Detection-Lab |
**[Sample solution](./exercise-solutions/e5.py)** | with tf.Session(graph=detection_graph) as sess:
image_tensor = sess.graph.get_tensor_by_name('image_tensor:0')
detection_boxes = sess.graph.get_tensor_by_name('detection_boxes:0')
detection_scores = sess.graph.get_tensor_by_name('detection_scores:0')
detection_classes = sess.graph.get_tensor_by_name('de... | _____no_output_____ | MIT | CarND-Object-Detection-Lab.ipynb | 48cfu/Object-Detection-Lab |
[](https://neutronimaging.pages.ornl.gov/tutorial/notebooks/shifting_time_offset/) Select Your IPTS | from __code.select_files_and_folders import SelectFiles, SelectFolder
from __code.shifting_time_offset import ShiftTimeOffset
from __code import system
system.System.select_working_dir()
from __code.__all import custom_style
custom_style.style() | _____no_output_____ | BSD-3-Clause | notebooks/converted_notebooks/shifting_time_offset.ipynb | mabrahamdevops/python_notebooks |
Select Folder | o_shift = ShiftTimeOffset()
o_select = SelectFolder(system=system, is_input_folder=True, next_function=o_shift.display_counts_vs_time) | _____no_output_____ | BSD-3-Clause | notebooks/converted_notebooks/shifting_time_offset.ipynb | mabrahamdevops/python_notebooks |
Repeat on other folders? | o_other_folders = SelectFolder(working_dir=o_shift.working_dir,
is_input_folder=True,
multiple_flags=True,
next_function=o_shift.selected_other_folders) | _____no_output_____ | BSD-3-Clause | notebooks/converted_notebooks/shifting_time_offset.ipynb | mabrahamdevops/python_notebooks |
Output Images | o_shift.offset_images() | _____no_output_____ | BSD-3-Clause | notebooks/converted_notebooks/shifting_time_offset.ipynb | mabrahamdevops/python_notebooks |
Spline WidgetA spline widget can be enabled and disabled by the:func:`pyvista.WidgetHelper.add_spline_widget` and:func:`pyvista.WidgetHelper.clear_spline_widgets` methods respectively.This widget allows users to interactively create a poly line (spline) througha scene and use that spline.A common task with splines is ... | import pyvista as pv
import numpy as np
mesh = pv.Wavelet()
# initial spline to seed the example
points = np.array([[-8.64208925, -7.34294559, -9.13803458],
[-8.25601497, -2.54814702, 0.93860914],
[-0.30179377, -3.21555997, -4.19999019],
[ 3.24099167, 2.058147... | _____no_output_____ | MIT | locale/examples/03-widgets/spline-widget.ipynb | tkoyama010/pyvista-doc-translations |
Using Neural Network Formulations in OMLTIn this notebook we show how OMLT can be used to build different optimization formulations of neural networks within Pyomo. It specifically demonstrates the following examples:1.) A neural network with smooth sigmoid activation functions represented using full-space and reduced... | #Start by importing the following libraries
#data manipulation and plotting
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib
matplotlib.rc('font', size=24)
plt.rc('axes', titlesize=24)
#tensorflow objects
from tensorflow.keras.models import Sequential, Model
from tensorflow.keras.layers import Den... | _____no_output_____ | BSD-3-Clause | docs/notebooks/neuralnet/neural_network_formulations.ipynb | fracek/OMLT |
Import the Data We begin by training neural networks that learn from data given the following imported dataframe. In practice, this data could represent the output of a simulation, real sensor measurements, or some other external data source. The data contains a single input `x` and a single output `y` and contains 10... | df = pd.read_csv("../data/sin_quadratic.csv",index_col=[0]); | _____no_output_____ | BSD-3-Clause | docs/notebooks/neuralnet/neural_network_formulations.ipynb | fracek/OMLT |
The data we use for training is plotted below (on the left figure). We also scale the training data to a mean of zero with unit standard deviation. The scaled inputs and outputs are added to the dataframe and plotted next to the original data values (on the right). | #retrieve input 'x' and output 'y' from the dataframe
x = df["x"]
y = df["y"]
#calculate mean and standard deviation, add scaled 'x' and scaled 'y' to the dataframe
mean_data = df.mean(axis=0)
std_data = df.std(axis=0)
df["x_scaled"] = (df['x'] - mean_data['x']) / std_data['x']
df["y_scaled"] = (df['y'] - mean_data['y... | _____no_output_____ | BSD-3-Clause | docs/notebooks/neuralnet/neural_network_formulations.ipynb | fracek/OMLT |
Train the Neural NetworksAfter importing the dataset we use Tensorflow (with Keras) to train three neural network models. Each neural network contains 2 layers with 100 nodes per layer with a single output layer. 1.) The first network (`nn1`) uses sigmoid activation functions for both layers.2.) The second network (`n... | #sigmoid neural network
nn1 = Sequential(name='sin_wave_sigmoid')
nn1.add(Input(1))
nn1.add(Dense(100, activation='sigmoid'))
nn1.add(Dense(100, activation='sigmoid'))
nn1.add(Dense(1))
nn1.compile(optimizer=Adam(), loss='mse')
#relu neural network
nn2 = Sequential(name='sin_wave_relu')
nn2.add(Input(1))
nn2.add(Dense... | Epoch 1/50
313/313 [==============================] - 1s 2ms/step - loss: 1.0197
Epoch 2/50
313/313 [==============================] - 1s 2ms/step - loss: 0.9949
Epoch 3/50
313/313 [==============================] - 1s 2ms/step - loss: 0.9749
Epoch 4/50
313/313 [==============================] - 1s 2ms/step - loss: 0.7... | BSD-3-Clause | docs/notebooks/neuralnet/neural_network_formulations.ipynb | fracek/OMLT |
Check the predictionsBefore we formulate our trained neural networks in OMLT, we check to see that they adequately represent the data. While we would normally use some accuracy measure, we suffice with a visual plot of the fits. | #note: we calculate the unscaled output for each neural network to check the predictions
#nn1
y_predict_scaled_sigmoid = nn1.predict(x=df['x_scaled'])
y_predict_sigmoid = y_predict_scaled_sigmoid*(std_data['y']) + mean_data['y']
#nn2
y_predict_scaled_relu = nn2.predict(x=df['x_scaled'])
y_predict_relu = y_predict_scal... | _____no_output_____ | BSD-3-Clause | docs/notebooks/neuralnet/neural_network_formulations.ipynb | fracek/OMLT |
Formulating Neural Networks with OMLTWe now show how OMLT can formulate neural networks within Pyomo. We specifically show how to specify and build different neural network optimization formulations and how to connect them with a broader Pyomo model. In these examples we use Pyomo solvers to find the input that minimi... | #create an omlt scaling object
scaler = omlt.scaling.OffsetScaling(offset_inputs=[mean_data['x']],
factor_inputs=[std_data['x']],
offset_outputs=[mean_data['y']],
factor_outputs=[std_data['y']])
#create the input bounds. note that the key `0` corresponds to i... | <omlt.scaling.OffsetScaling object at 0x7fdd940bc850>
Scaled input bounds: {0: (-1.731791015101997, 1.731791015101997)}
| BSD-3-Clause | docs/notebooks/neuralnet/neural_network_formulations.ipynb | fracek/OMLT |
Neural Network 1: Sigmoid Activations with Full-Space and Reduced-Space FormulationsThe first neural network contains sigmoid activation functions which we formulate with full-space and reduced-space representations and solve with Ipopt. Reduced Space ModelWe begin with the reduced-space formulation and build the Pyom... | #create a network definition
net_sigmoid = keras_reader.load_keras_sequential(nn1,scaler,input_bounds)
#create a pyomo model with variables x and y
model1_reduced = pyo.ConcreteModel()
model1_reduced.x = pyo.Var(initialize = 0)
model1_reduced.y = pyo.Var(initialize = 0)
model1_reduced.obj = pyo.Objective(expr=(model1_... | Reduced Space Solution:
# of variables: 6
# of constraints: 5
x = -1.4257385602216635
y = 1.3405352390223917
Solve Time: 0.16946029663085938
| BSD-3-Clause | docs/notebooks/neuralnet/neural_network_formulations.ipynb | fracek/OMLT |
Full Space ModelFor the full-space representation we use `NeuralNetworkFormulation` instead of `ReducedSpaceNeuralNetworkFormulation`. The key difference is that this formulation creates additional variables and constraints to represent each node and activation function in the neural network.Note that when we print th... | net_sigmoid = keras_reader.load_keras_sequential(nn1,scaler,input_bounds)
model1_full = pyo.ConcreteModel()
model1_full.x = pyo.Var(initialize = 0)
model1_full.y = pyo.Var(initialize = 0)
model1_full.obj = pyo.Objective(expr=(model1_full.y))
model1_full.nn = OmltBlock()
formulation2_full = NeuralNetworkFormulation(ne... | Full Space Solution:
# of variables: 409
# of constraints: 408
x = -0.27928922891858343
y = -0.8853885901469711
Solve Time: 0.3363785743713379
| BSD-3-Clause | docs/notebooks/neuralnet/neural_network_formulations.ipynb | fracek/OMLT |
Neural Network 2: ReLU Neural Network using Complementarity Constraints and Binary VariablesThe second neural network contains ReLU activation functions which we represent using complementarity constraints and binary variables. ReLU Complementarity ConstraintsTo represent ReLU using complementarity constraints we use ... | net_relu = keras_reader.load_keras_sequential(nn2,scaler,input_bounds)
model2_comp = pyo.ConcreteModel()
model2_comp.x = pyo.Var(initialize = 0)
model2_comp.y = pyo.Var(initialize = 0)
model2_comp.obj = pyo.Objective(expr=(model2_comp.y))
model2_comp.nn = OmltBlock()
formulation2_comp = NeuralNetworkFormulation(net_r... | ReLU Complementarity Solution:
# of variables: 609
# of constraints: 808
x = -0.2970834231188838
y = -0.8747695437296246
Solve Time: 0.3795132637023926
| BSD-3-Clause | docs/notebooks/neuralnet/neural_network_formulations.ipynb | fracek/OMLT |
ReLU with Binary Variables and BigM ConstraintsFor the binary variable formulation of ReLU we use the default activation function settings. These are applied automatically if a `NetworkDefinition` contains ReLU activation functions. Note that we solve the optimization problem with Cbc which can handle binary decisions... | net_relu = keras_reader.load_keras_sequential(nn2,scaler,input_bounds)
model2_bigm = pyo.ConcreteModel()
model2_bigm.x = pyo.Var(initialize = 0)
model2_bigm.y = pyo.Var(initialize = 0)
model2_bigm.obj = pyo.Objective(expr=(model2_bigm.y))
model2_bigm.nn = OmltBlock()
formulation2_bigm = NeuralNetworkFormulation(net_r... | ReLU BigM Solution:
# of variables: 609
# of constraints: 1008
x = -0.29708481
y = -0.87476544
Solve Time: 82.65653038024902
| BSD-3-Clause | docs/notebooks/neuralnet/neural_network_formulations.ipynb | fracek/OMLT |
Neural Network 3: Mixed ReLU and Sigmoid Activation FunctionsThe last neural network contains both ReLU and sigmoid activation functions. These networks can be represented by using the complementarity formulation of relu and mixing it with the full-space formulation for the sigmoid functions. | net_mixed = keras_reader.load_keras_sequential(nn3,scaler,input_bounds)
model3_mixed = pyo.ConcreteModel()
model3_mixed.x = pyo.Var(initialize = 0)
model3_mixed.y = pyo.Var(initialize = 0)
model3_mixed.obj = pyo.Objective(expr=(model3_mixed.y))
model3_mixed.nn = OmltBlock()
formulation3_mixed = NeuralNetworkFormulati... | Mixed NN Solution:
# of variables: 509
# of constraints: 608
x = -0.33286905796510236
y = -0.9116201725726657
Solve Time: 0.6036348342895508
| BSD-3-Clause | docs/notebooks/neuralnet/neural_network_formulations.ipynb | fracek/OMLT |
Final Plots and DiscussionWe lastly plot the results of each optimization problem. Some of the main take-aways from this notebook are as follows:- A broad set of dense neural network architectures can be represented in Pyomo using OMLT. This notebook used the Keras reader to import sequential Keras models but OMLT als... | #create a plot with 3 subplots
fig,axs = plt.subplots(1,3,figsize = (24,8))
#nn1 - sigmoid
axs[0].plot(x,y_predict_sigmoid,linewidth = 3.0,linestyle="dotted",color = "orange")
axs[0].set_title("sigmoid")
axs[0].scatter([solution_1_reduced[0]],[solution_1_reduced[1]],color = "black",s = 300, label="reduced space")
axs[... | _____no_output_____ | BSD-3-Clause | docs/notebooks/neuralnet/neural_network_formulations.ipynb | fracek/OMLT |
transmissibility-based TPA: FRF based In this example a numerical example is used to demonstrate a FRF based TPA example. | import pyFBS
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.colors import LogNorm
%matplotlib inline | _____no_output_____ | MIT | examples/17_TPA_FRF_based.ipynb | anantagrg/FBS_Substructuring |
Example datasets Load the required predefined datasets: | pyFBS.download_lab_testbench()
xlsx_pos = r"./lab_testbench/Measurements/TPA_synt.xlsx"
stl_A = r"./lab_testbench/STL/A.stl"
stl_B = r"./lab_testbench/STL/B.stl"
stl_AB = r"./lab_testbench/STL/AB.stl"
df_acc_AB = pd.read_excel(xlsx_pos, sheet_name='Sensors_AB')
df_chn_AB = pd.read_excel(xlsx_pos, sheet_name='Channels... | _____no_output_____ | MIT | examples/17_TPA_FRF_based.ipynb | anantagrg/FBS_Substructuring |
Numerical model Load the corresponding .full and .ress file from the example datasets: | full_file_AB = r"./lab_testbench/FEM/AB.full"
ress_file_AB = r"./lab_testbench/FEM/AB.rst" | _____no_output_____ | MIT | examples/17_TPA_FRF_based.ipynb | anantagrg/FBS_Substructuring |
Create an MK model for each component: | MK_AB = pyFBS.MK_model(ress_file_AB, full_file_AB, no_modes=100, recalculate=False) | C:\Users\tomaz.bregar\Anaconda3\lib\site-packages\pyvista\core\pointset.py:610: UserWarning: VTK 9 no longer accepts an offset array
warnings.warn('VTK 9 no longer accepts an offset array')
| MIT | examples/17_TPA_FRF_based.ipynb | anantagrg/FBS_Substructuring |
The locations and directions of responses and excitations often do not match exactly with the numerical model, so we need to find the nodes closest to these points. Only the locations are updated, the directions remain the same. | df_chn_AB_up = MK_AB.update_locations_df(df_chn_AB)
df_imp_AB_up = MK_AB.update_locations_df(df_imp_AB) | _____no_output_____ | MIT | examples/17_TPA_FRF_based.ipynb | anantagrg/FBS_Substructuring |
3D view Open 3D viewer in the background. With the 3D viewer the subplot capabilities of PyVista can be used. | view3D = pyFBS.view3D(show_origin=False, show_axes=False, title="TPA") | _____no_output_____ | MIT | examples/17_TPA_FRF_based.ipynb | anantagrg/FBS_Substructuring |
Add the STL file of structure AB to the plot and show the corresponding accelerometer, channels and impacts. | view3D.plot.add_text("AB", position='upper_left', font_size=10, color="k", font="times", name="AB_structure")
view3D.add_stl(stl_AB, name="AB_structure", color="#8FB1CC", opacity=.1)
view3D.plot.add_mesh(MK_AB.mesh, scalars=np.zeros(MK_AB.mesh.points.shape[0]), show_scalar_bar=False, name="mesh_AB", cmap="coolwarm", s... | _____no_output_____ | MIT | examples/17_TPA_FRF_based.ipynb | anantagrg/FBS_Substructuring |
FRF sythetization Perform the FRF sythetization for each component based on the updated locations: | MK_AB.FRF_synth(df_chn_AB_up, df_imp_AB_up, f_start=0, modal_damping=0.003, frf_type="accelerance") | _____no_output_____ | MIT | examples/17_TPA_FRF_based.ipynb | anantagrg/FBS_Substructuring |
First, structural admittance $\boldsymbol{\text{Y}}_{31}^{\text{AB}}$ is obtained. | imp_loc = 10
Y31_AB = MK_AB.FRF[:, 9:12, imp_loc:imp_loc+1]
Y31_AB.shape | _____no_output_____ | MIT | examples/17_TPA_FRF_based.ipynb | anantagrg/FBS_Substructuring |
Then, structural admittance $\boldsymbol{\text{Y}}_{41}^{\text{AB}}$ is obtained. | Y41_AB = MK_AB.FRF[:, :9, imp_loc:imp_loc+1]
Y41_AB.shape | _____no_output_____ | MIT | examples/17_TPA_FRF_based.ipynb | anantagrg/FBS_Substructuring |
Aplication of the FRF based TPA Calculation of transmissibility matrix $\boldsymbol{\text{T}}_{34, f_1}^{\text{AB}}$: | T34 = Y31_AB @ np.linalg.pinv(Y41_AB)
T34.shape | _____no_output_____ | MIT | examples/17_TPA_FRF_based.ipynb | anantagrg/FBS_Substructuring |
Define operational displacements $\boldsymbol{\text{u}}_4$: | u4 = MK_AB.FRF[:, :9, imp_loc:imp_loc+1]
u4.shape | _____no_output_____ | MIT | examples/17_TPA_FRF_based.ipynb | anantagrg/FBS_Substructuring |
Calcualting response $\boldsymbol{\text{u}}_3^{\text{TPA}}$. | u3 = T34 @ u4
u3.shape | _____no_output_____ | MIT | examples/17_TPA_FRF_based.ipynb | anantagrg/FBS_Substructuring |
On board validation: comparison of predicted $\boldsymbol{\text{u}}_{3}^{\text{TPA}}$ and operational $\boldsymbol{\text{u}}_{3}^{\text{MK}}$: | plt.figure(figsize=(10, 5))
u3_MK = MK_AB.FRF[:, 9:12, imp_loc:imp_loc+1]
sel = 0
plt.subplot(211)
plt.semilogy(np.abs(u3_MK[:,sel,0]), label='MK');
plt.semilogy(np.abs(u3[:,sel,0]), '--', label='TPA');
plt.ylim(10**-8, 10**4);
plt.xlim(0, 2000)
plt.legend(loc=0);
plt.subplot(413)
plt.plot(np.angle(u3_MK[:,sel,0]));... | _____no_output_____ | MIT | examples/17_TPA_FRF_based.ipynb | anantagrg/FBS_Substructuring |
Which is better text embedding or graph embedding? | # define this question
data[(data['kg_id'] == data['GT_kg_id']) & (data['kg_id'] != '')] | _____no_output_____ | MIT | exact-match-centroid-pipeline/embedding_eval.ipynb | nicklein/table-linker-pipelines |
By cell linking task. Count/compute- Number of tasks- Number and fraction of tasks with known ground truth- Number and fraction of tasks with ground truth in the candidate set- Number and fraction of singleton candidate sets- Number and fraction of singleton candidate sets containing ground truth- Top-1 accuracy, Top-... | row_idx, col_idx = 2, 0
relevant_df = data[(data['column'] == col_idx) & (data['row'] == row_idx) & (data['kg_id'] != '')]
num_tasks = len(relevant_df)
num_tasks
num_tasks_known_gt = len(relevant_df[relevant_df['GT_kg_id'] != ''])
num_tasks_known_gt
is_gt_in_candidate = len(relevant_df[relevant_df['GT_kg_id'] == rele... | _____no_output_____ | MIT | exact-match-centroid-pipeline/embedding_eval.ipynb | nicklein/table-linker-pipelines |
Graphs | import matplotlib.pyplot as plt
import sys
candidate_eval_data = pd.read_csv('./candidate_eval_no_empty.csv', index_col=False)
candidate_eval_data
# Line plot of top-1, top-5 and NDCG versus size of candidate set
x_candidate_set_size = list(pd.unique(candidate_eval_data['count']))
x_candidate_set_size.sort()
y_r_top_o... | /Users/summ7t/dev/novartis/novartis_env/lib/python3.6/site-packages/ipykernel_launcher.py:8: UserWarning: Matplotlib is currently using module://ipykernel.pylab.backend_inline, which is a non-GUI backend, so cannot show the figure.
| MIT | exact-match-centroid-pipeline/embedding_eval.ipynb | nicklein/table-linker-pipelines |
02/16 stats on each eval file | import pandas as pd
candidate_eval_data = pd.read_csv('./candidate_eval.csv', index_col=False)
candidate_eval_data
# candidate_eval_data = candidate_eval_data.drop(['Unnamed: 0'], axis=1)
# candidate_eval_data
import os
eval_file_names = []
eval_file_ids = []
for (dirpath, dirnames, filenames) in os.walk('/Users/summ... | /Users/summ7t/dev/novartis/novartis_env/lib/python3.6/site-packages/ipykernel_launcher.py:7: UserWarning: Matplotlib is currently using module://ipykernel.pylab.backend_inline, which is a non-GUI backend, so cannot show the figure.
import sys
| MIT | exact-match-centroid-pipeline/embedding_eval.ipynb | nicklein/table-linker-pipelines |
02/17 More plots | candidate_eval_data[candidate_eval_data['count'] == 1]
[all_tables[tid]['num_tasks_with_singleton_candidate'] for tid in all_tables]
# x_axis percetage of singleton
x_pos = [all_tables[tid]['num_tasks_with_singleton_candidate'] for tid in all_tables]
x_posgt = [all_tables[tid]['num_tasks_with_singleton_candidate_with_... | /Users/summ7t/dev/novartis/novartis_env/lib/python3.6/site-packages/ipykernel_launcher.py:9: UserWarning: Matplotlib is currently using module://ipykernel.pylab.backend_inline, which is a non-GUI backend, so cannot show the figure.
if __name__ == '__main__':
| MIT | exact-match-centroid-pipeline/embedding_eval.ipynb | nicklein/table-linker-pipelines |
02/19 More experiments: wrong singleton | import pandas as pd
candidate_eval_data = pd.read_csv('./candidate_eval_no_empty.csv', index_col=False)
candidate_eval_data
# Sub all singleton candidate set to see how "good" the algorithm can be
subbed_candidate_eval_data = candidate_eval_data.copy()
for i, row in subbed_candidate_eval_data.iterrows():
if row['co... | _____no_output_____ | MIT | exact-match-centroid-pipeline/embedding_eval.ipynb | nicklein/table-linker-pipelines |
Homework 5: Problems Due Wednesday 28 October, before class PHYS 440/540, Fall 2020https://github.com/gtrichards/PHYS_440_540/ Problems 1&2Complete Chapters 1 and 2 in the *unsupervised learning* course in Data Camp. The last video (and the two following code examples) in Chapter 2 are off topic, but we'll discuss th... | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler
from sklearn.metrics.cluster import homogeneity_score
from sklearn.datasets import make_blobs
from sklearn.neighbors import KernelDensity
from astroML.density_estimation import KNeighborsDensity
from ... | _____no_output_____ | MIT | homeworks/PHYS_440_540_F20_HW5.ipynb | KleinWang/PHYS_440_540 |
Setup up the data set. We will do both density estimation and clustering on it. | from sklearn.datasets import make_blobs
#Make two blobs with 3 features and 1000 samples
N=1000
X,y = make_blobs(n_samples=N, centers=5, n_features=2, random_state=25)
plt.figure(figsize=(10,10))
plt.scatter(X[:, 0], X[:, 1], s=100, c=y) | _____no_output_____ | MIT | homeworks/PHYS_440_540_F20_HW5.ipynb | KleinWang/PHYS_440_540 |
Start with kernel density estimation, including a grid search to find the best bandwidth | bwrange = np.linspace(____,____,____) # Test 30 bandwidths from 0.1 to 1.0 ####
K = ____ # 5-fold cross validation ####
grid = GridSearchCV(KernelDensity(), {'bandwidth': ____}, cv=K) ####
grid.fit(X) #Fit the histogram data that we started the lecture with.
h_opt = ____.best_params_['bandwidth'] ####
print(h_opt)
kde... | _____no_output_____ | MIT | homeworks/PHYS_440_540_F20_HW5.ipynb | KleinWang/PHYS_440_540 |
--- Now try a nearest neighbors approach to estimating the density. What value of $k$ do you need to make the plot look similar to the one above? | # Compute density with Bayesian nearest neighbors
k=____ ####
nbrs = KNeighborsDensity('bayesian',n_neighbors=____) ####
nbrs.____(X) ####
dens_nbrs = nbrs.eval(Xgrid) / N
plt.scatter(Xgrid[:,0],Xgrid[:,1], c=dens_nbrs, cmap="Purples", edgecolor="None")
plt.colorbar() | _____no_output_____ | MIT | homeworks/PHYS_440_540_F20_HW5.ipynb | KleinWang/PHYS_440_540 |
--- Now do a Gaussian mixture model. Do a grid search for between 1 and 10 components. | #Kludge to fix the bug with draw_ellipse in astroML v1.0
from matplotlib.patches import Ellipse
def draw_ellipse(mu, C, scales=[1, 2, 3], ax=None, **kwargs):
if ax is None:
ax = plt.gca()
# find principal components and rotation angle of ellipse
sigma_x2 = C[0, 0]
sigma_y2 = C[1, 1]
sigma_... | _____no_output_____ | MIT | homeworks/PHYS_440_540_F20_HW5.ipynb | KleinWang/PHYS_440_540 |
Do you get the same answer (the same number of components) each time you run it? --- Now try Kmeans. Here we will scale the data. | kmeans = KMeans(n_clusters=5)
scaler = StandardScaler()
X_scaled = ____.____(X) ####
kmeans.fit(X_scaled)
centers=kmeans.____ #location of the clusters ####
labels=kmeans.predict(____) #labels for each of the points ####
centers_unscaled = scaler.____(centers) ####
fig,ax = plt.subplots(1,2,figsize=(16, 8))
ax[0].scatt... | _____no_output_____ | MIT | homeworks/PHYS_440_540_F20_HW5.ipynb | KleinWang/PHYS_440_540 |
Let's evaluate how well we did in two other ways: a matrix and a score. | df = pd.DataFrame({'predictions': labels, 'truth': y})
ct = pd.crosstab(df['predictions'], df['truth'])
print(ct)
from sklearn.metrics.cluster import homogeneity_score
score = homogeneity_score(df['truth'], df['predictions'])
print(score) | _____no_output_____ | MIT | homeworks/PHYS_440_540_F20_HW5.ipynb | KleinWang/PHYS_440_540 |
What is the score for 3 clusters? --- Finally, let's use DBSCAN. Note that outliers are flagged as `labels_=-1`, so there is one more class that you might think.Full credit if you can get a score of 0.6 or above. Extra credit (0.1 of 5 points) for a score of 0.85 or above. | def plot_dbscan(dbscan, X, size, show_xlabels=True, show_ylabels=True):
core_mask = np.zeros_like(dbscan.labels_, dtype=bool)
core_mask[dbscan.core_sample_indices_] = True
anomalies_mask = dbscan.labels_ == -1
non_core_mask = ~(core_mask | anomalies_mask)
cores = dbscan.components_
anomalies = ... | _____no_output_____ | MIT | homeworks/PHYS_440_540_F20_HW5.ipynb | KleinWang/PHYS_440_540 |
Dataset Source:About this fileBoston House Price dataset columns:* CRIM per capita crime rate by town* ZN proportion of residential land zoned for lots over 25,000 sq.ft.* INDUS proportion of non-retail business acres per town* CHAS Charles River dummy variable (= 1 if tract bounds river; 0 otherwise... | import numpy as np # linear algebra python library
import pandas as pd # data structure for tabular data.
import matplotlib.pyplot as plt # visualization library
%matplotlib inline | _____no_output_____ | Apache-2.0 | boston_housing/house_price_prediction.ipynb | Mohamed-3ql/RegressionProjects |
Loading data | filename = "housing.csv"
boston_data = pd.read_csv(filename, delim_whitespace=True, header=None)
header = ["CRIM","ZN","INDUS","CHAS","NOX","RM",
"AGE","DIS","RAD","TAX","PTRATIO","B","LSTAT","MEDV"]
boston_data.columns = header
# display the first 10 rows of dataframe.
boston_data.head(10) | _____no_output_____ | Apache-2.0 | boston_housing/house_price_prediction.ipynb | Mohamed-3ql/RegressionProjects |
Inspecting variable types | boston_data.dtypes | _____no_output_____ | Apache-2.0 | boston_housing/house_price_prediction.ipynb | Mohamed-3ql/RegressionProjects |
In many datasets, integer variables are cast as float. So, after inspectingthe data type of the variable, even if you get float as output, go aheadand check the unique values to make sure that those variables are discreteand not continuous. Inspecting all variables inspecting distinct values of `RAD`(index of accessib... | boston_data['RAD'].unique() | _____no_output_____ | Apache-2.0 | boston_housing/house_price_prediction.ipynb | Mohamed-3ql/RegressionProjects |
inspecting distinct values of `CHAS` Charles River dummy variable (= 1 if tract bounds river; 0 otherwise). | boston_data['CHAS'].unique() | _____no_output_____ | Apache-2.0 | boston_housing/house_price_prediction.ipynb | Mohamed-3ql/RegressionProjects |
inspecting the first 20 distinct values of all continous variables as following:* CRIM per capita crime rate by town* ZN proportion of residential land zoned for lots over 25,000 sq.ft.* INDUS proportion of non-retail business acres per town* NOX nitric oxides concentration (parts per 10 million)* R... | boston_data['CRIM'].unique()[0:20] | _____no_output_____ | Apache-2.0 | boston_housing/house_price_prediction.ipynb | Mohamed-3ql/RegressionProjects |
ZN proportion of residential land zoned for lots over 25,000 sq.ft. | boston_data['ZN'].unique()[0:20] | _____no_output_____ | Apache-2.0 | boston_housing/house_price_prediction.ipynb | Mohamed-3ql/RegressionProjects |
INDUS proportion of non-retail business acres per town | boston_data['INDUS'].unique()[0:20] | _____no_output_____ | Apache-2.0 | boston_housing/house_price_prediction.ipynb | Mohamed-3ql/RegressionProjects |
NOX nitric oxides concentration (parts per 10 million) | boston_data['NOX'].unique()[0:20] | _____no_output_____ | Apache-2.0 | boston_housing/house_price_prediction.ipynb | Mohamed-3ql/RegressionProjects |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.