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 |
|---|---|---|---|---|---|
Calculate CoM from WDFUse force plate data to predict rider CoM position | Ffwt_fx = np.array(89.28) #measured force on plate under front wheel with rider
Ffwt_fx = Ffwt_fx / 2.205 * g #convert from lb to N
Lcmrc_fx = (Ffwt_fx - Ffwb) * Lt / Wr
Lcmfc_fx = Lt - Lcmrc_fx
Lcmbb_fx = Lcmfc_fx - Lfc
print(Lcmbb_fx) | -0.009825275032207537
| MIT | docs/calculate-wdf.ipynb | ross-wilkinson/vantage-com |
**Knowing our data** | import pandas as pd
import numpy as np
data = 'https://s3-us-west-2.amazonaws.com/streamlit-demo-data/uber-raw-data-sep14.csv.gz'
df = pd.read_csv(data, nrows=500)
df.head() | _____no_output_____ | MIT | Project-Uber/Support_notebook.ipynb | rafaelgrecco/Streamlit-library-Projects |
**Putting the column names in a lower case**To avoid mistakes | lower_str = lambda x: str(x).lower()
df.rename(lower_str, axis='columns', inplace=True)
df.head() | _____no_output_____ | MIT | Project-Uber/Support_notebook.ipynb | rafaelgrecco/Streamlit-library-Projects |
As you can see the column names are in lower case **Checking if dates are on datetime**To access only the hours of our column `date/time`.We have to make sure that this column is in datetime | df.dtypes | _____no_output_____ | MIT | Project-Uber/Support_notebook.ipynb | rafaelgrecco/Streamlit-library-Projects |
As we can see the column is an object type, so we will convert it to datetime | df['date/time'] = pd.to_datetime(df['date/time'])
df.dtypes | _____no_output_____ | MIT | Project-Uber/Support_notebook.ipynb | rafaelgrecco/Streamlit-library-Projects |
"Unambiguous fire pixels" test 1 (daytime, normal conditions). | firecond1 = np.logical_and(R75 > 2.5, rho7 > .5)
firecond1 = np.logical_and(firecond1, rho7 - rho5 > .3)
firecond1_masked = np.ma.masked_where(
~firecond1, np.ones((ymax, xmax))) | _____no_output_____ | MIT | ipynb_viirs1/Landsat8 fire detection dev notes.ipynb | chryss/VIFDAHL |
"Unambiguous fire pixels" test 2 (daytime, sensor anomalies) | firecond2 = np.logical_and(rho6 > .8, rho1 < .2)
firecond2 = np.logical_and(firecond2,
np.logical_or(rho5 > .4, rho7 < .1)
)
firecond2_masked = np.ma.masked_where(
~firecond2, np.ones((ymax, xmax))) | _____no_output_____ | MIT | ipynb_viirs1/Landsat8 fire detection dev notes.ipynb | chryss/VIFDAHL |
"Relaxed conditions" | firecond3 = np.logical_and(R75 > 1.8, rho7 - rho5 > .17)
firecond3_masked = np.ma.masked_where(
~firecond3, np.ones((ymax, xmax))) | _____no_output_____ | MIT | ipynb_viirs1/Landsat8 fire detection dev notes.ipynb | chryss/VIFDAHL |
"Extra tests" for relaxed conditions:1. R76 > 1.62. R75 at least 3 sigma and 0.8 larger than avg of a 61x61 window of valid pixels3. rho7 at least 3 sigma and 0.08 larger than avg of a 61x61 window of valid pixelsValid pixels are:1. Not "unambiguous fire pixel"2. rho7 > 0 3. Not water as per water test 1: rho4 > rho5 A... | newfirecandidates = np.logical_and(~firecond1, ~firecond2)
newfirecandidates = np.logical_and(newfirecandidates, firecond3)
newfirecandidates = np.logical_and(newfirecandidates, R76 > 0)
sum(sum(newfirecandidates)) | _____no_output_____ | MIT | ipynb_viirs1/Landsat8 fire detection dev notes.ipynb | chryss/VIFDAHL |
We'll need a +-30 pixel window around a coordinate pair to carry out the averaging for the contextual tests | iidxmax, jidxmax = landsat.band1.data.shape
def get_window(ii, jj, N, iidxmax, jidxmax):
"""Return 2D Boolean array that is True where a window of size N
around a given point is masked out """
imin = max(0, ii-N)
imax = min(iidxmax, ii+N)
jmin = max(0, jj-N)
jmax = min(jidxmax, jj+N)
mask1... | _____no_output_____ | MIT | ipynb_viirs1/Landsat8 fire detection dev notes.ipynb | chryss/VIFDAHL |
We can then get the union of those windows over all detected fire pixel candidates. | windows = [get_window(ii, jj, 30, iidxmax, jidxmax) for ii, jj in np.argwhere(newfirecandidates)]
window = np.any(windows, axis=0)
plt.imshow(window , cmap=cmap3, vmin=0, vmax=1) | _____no_output_____ | MIT | ipynb_viirs1/Landsat8 fire detection dev notes.ipynb | chryss/VIFDAHL |
We also need a water mask... | def get_l8watermask_frombands(
rho1, rho2, rho3,
rho4, rho5, rho6, rho7):
"""
Takes L8 bands, returns 2D Boolean numpy array of same shape
"""
turbidwater = get_l8turbidwater(rho1, rho2, rho3, rho4, rho5, rho6, rho7)
deepwater = get_l8deepwater(rho1, rho2, rho3, rho4, rho5, rho6, rho... | _____no_output_____ | MIT | ipynb_viirs1/Landsat8 fire detection dev notes.ipynb | chryss/VIFDAHL |
Let's try out the two components, out of interest... apparently, only the "deep water" test catches the water bodies here. | turbidwater = get_l8turbidwater(rho1, rho2, rho3, rho4, rho5, rho6, rho7)
deepwater = get_l8deepwater(rho1, rho2, rho3, rho4, rho5, rho6, rho7)
plt.imshow(~turbidwater , cmap=cmap3, vmin=0, vmax=1)
plt.show()
plt.imshow(~deepwater , cmap=cmap3, vmin=0, vmax=1)
def get_valid_pixels(otherfirecond, rho1, rho2, rho3,
... | _____no_output_____ | MIT | ipynb_viirs1/Landsat8 fire detection dev notes.ipynb | chryss/VIFDAHL |
So this works! Now we can do the same using the module that incorporates the above code: | testfire, highfire, anomfire, lowfire = lfire.get_l8fire(landsat)
sum(sum(lowfire))
sum(sum(testfire))
firecond1_masked = np.ma.masked_where(
~testfire, np.ones((ymax, xmax)))
firecondlow_masked = np.ma.masked_where(
~lowfire, np.ones((ymax, xmax)))
fig1 = plt.figure(1, figsize=(15, 15))
ax1 = fig1.add_... | _____no_output_____ | MIT | ipynb_viirs1/Landsat8 fire detection dev notes.ipynb | chryss/VIFDAHL |
Finding fraud patterns with FP-growth Data Collection and Investigation | import pandas as pd
# Input data files are available in the "../input/" directory
df = pd.read_csv('D:/Python Project/Credit Card Fraud Detection/benchmark dataset/Test FP-Growth.csv')
# printing the first 5 columns for data visualization
df.head()
| _____no_output_____ | Apache-2.0 | Python/Benchmark dataset/Finding fraud patterns with FP-growth benchmark dataset.ipynb | limkhashing/Credit-Card-Fraud-Detection |
Execute FP-growth algorithm Spark | # import environment path to pyspark
import os
import sys
spark_path = r"D:\apache-spark" # spark installed folder
os.environ['SPARK_HOME'] = spark_path
sys.path.insert(0, spark_path + "/bin")
sys.path.insert(0, spark_path + "/python/pyspark/")
sys.path.insert(0, spark_path + "/python/lib/pyspark.zip")
sys.path.insert... | _____no_output_____ | Apache-2.0 | Python/Benchmark dataset/Finding fraud patterns with FP-growth benchmark dataset.ipynb | limkhashing/Credit-Card-Fraud-Detection |
__minSupport__: The minimum support for an itemset to be identified as frequent. For example, if an item appears 3 out of 5 transactions, it has a support of 3/5=0.6.__minConfidence__: Minimum confidence for generating Association Rule. Confidence is an indication of how often an association rule has been found to be t... | model = FPGrowth.train(transactions, minSupport=0.6, numPartitions=10)
result = model.freqItemsets().collect()
print("Frequent Itemsets : Item Support")
print("====================================")
for index, frequent_itemset in enumerate(result):
print(str(frequent_itemset.items) + ' : ' + str(frequent_itemset.f... | _____no_output_____ | Apache-2.0 | Python/Benchmark dataset/Finding fraud patterns with FP-growth benchmark dataset.ipynb | limkhashing/Credit-Card-Fraud-Detection |
Before we can validate models, we need an understanding of how to create and work with them. This chapter provides an introduction to running regression and classification models in scikit-learn. We will use this model building foundation throughout the remaining chapters. | ### Seen vs. unseen data
# The model is fit using X_train and y_train
model.fit(X_train, y_train)
# Create vectors of predictions
train_predictions = model.predict(X_train)
test_predictions = model.predict(X_test)
# Train/Test Errors
train_error = mae(y_true=y_train, y_pred=train_predictions)
test_error = mae(y_true... | _____no_output_____ | MIT | Model Validation in Python/.ipynb_checkpoints/Model Validation in Python-checkpoint.ipynb | frankgarciav/Datacamp-Courses |
This chapter focuses on the basics of model validation. From splitting data into training, validation, and testing datasets, to creating an understanding of the bias-variance tradeoff, we build the foundation for the techniques of K-Fold and Leave-One-Out validation practiced in chapter three. | ## Create one holdout set
# Create dummy variables using pandas
X = pd.get_dummies(tic_tac_toe.iloc[:,0:9])
y = tic_tac_toe.iloc[:, 9]
# Create training and testing datasets. Use 10% for the test set
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.1, random_state=1111)
## Create two holdout sets... | _____no_output_____ | MIT | Model Validation in Python/.ipynb_checkpoints/Model Validation in Python-checkpoint.ipynb | frankgarciav/Datacamp-Courses |
Holdout sets are a great start to model validation. However, using a single train and test set if often not enough. Cross-validation is considered the gold standard when it comes to validating model performance and is almost always used when tuning model hyper-parameters. This chapter focuses on performing cross-valida... | ### Two samples
# Create two different samples of 200 observations
sample1 = tic_tac_toe.sample(200, random_state=1111)
sample2 = tic_tac_toe.sample(200, random_state=1171)
# Print the number of common observations
print(len([index for index in sample1.index if index in sample2.index]))
# Print the number of obser... | _____no_output_____ | MIT | Model Validation in Python/.ipynb_checkpoints/Model Validation in Python-checkpoint.ipynb | frankgarciav/Datacamp-Courses |
The first three chapters focused on model validation techniques. In chapter 4 we apply these techniques, specifically cross-validation, while learning about hyperparameter tuning. After all, model validation makes tuning possible and helps us select the overall best model. | ### Creating Hyperparameters
# Review the parameters of rfr
print(rfr.get_params())
# Maximum Depth
max_depth = [4, 8, 12]
# Minimum samples for a split
min_samples_split = [2, 5, 10]
# Max features
max_features = [4, 6, 8, 10]
### Running a model using ranges
from sklearn.ensemble import RandomForestRegressor
#... | _____no_output_____ | MIT | Model Validation in Python/.ipynb_checkpoints/Model Validation in Python-checkpoint.ipynb | frankgarciav/Datacamp-Courses |
Goals Learn how to change train validation splits Table of Contents [0. Install](0) [1. Load experiment with defaut transforms](1) [2. Reset Transforms andapply new transforms](2) Install Monk - git clone https://github.com/Tessellate-Imaging/monk_v1.git - cd monk_v1/installation/Linux && pip install -r requireme... | !git clone https://github.com/Tessellate-Imaging/monk_v1.git
# Select the requirements file as per OS and CUDA version
!cd monk_v1/installation/Linux && pip install -r requirements_cu9.txt | _____no_output_____ | Apache-2.0 | study_roadmaps/1_getting_started_roadmap/5_update_hyperparams/2_data_params/6) Dataset Transforms.ipynb | kshitij12345/monk_v1 |
Dataset - Broad Leaved Dock Image Classification - https://www.kaggle.com/gavinarmstrong/open-sprayer-images | ! wget --load-cookies /tmp/cookies.txt "https://docs.google.com/uc?export=download&confirm=$(wget --save-cookies /tmp/cookies.txt --keep-session-cookies --no-check-certificate 'https://docs.google.com/uc?export=download&id=1uL-VV4nV_u0kry3gLH1TATUTu8hWJ0_d' -O- | sed -rn 's/.*confirm=([0-9A-Za-z_]+).*/\1\n/p')&id=1uL-V... | _____no_output_____ | Apache-2.0 | study_roadmaps/1_getting_started_roadmap/5_update_hyperparams/2_data_params/6) Dataset Transforms.ipynb | kshitij12345/monk_v1 |
Imports | # Monk
import os
import sys
sys.path.append("monk_v1/monk/");
#Using mxnet-gluon backend
from gluon_prototype import prototype | _____no_output_____ | Apache-2.0 | study_roadmaps/1_getting_started_roadmap/5_update_hyperparams/2_data_params/6) Dataset Transforms.ipynb | kshitij12345/monk_v1 |
Load experiment with default transforms | gtf = prototype(verbose=1);
gtf.Prototype("project", "understand_transforms");
gtf.Default(dataset_path="open_sprayer_images/train",
model_name="resnet18_v1",
freeze_base_network=True,
num_epochs=5);
#Read the summary generated once you run this cell. | Dataset Details
Train path: open_sprayer_images/train
Val path: None
CSV train path: None
CSV val path: None
Dataset Params
Input Size: 224
Batch Size: 4
Data Shuffle: True
Processors: 4
Train-val split: 0.7
Pre-Composed Train Transforms
[{'RandomHorizontalFlip'... | Apache-2.0 | study_roadmaps/1_getting_started_roadmap/5_update_hyperparams/2_data_params/6) Dataset Transforms.ipynb | kshitij12345/monk_v1 |
Default Transforms are Train Transforms {'RandomHorizontalFlip': {'p': 0.8}}, {'Normalize': {'mean': [0.485, 0.456, 0.406], 'std': [0.229, 0.224, 0.225]}}] Val Transforms {'RandomHorizontalFlip': {'p': 0.8}}, {'Normalize': {'mean': [0.485, 0.456, 0.406], 'std': [0.229, 0... | # Reset train and validation transforms
gtf.reset_transforms();
# Reset test transforms
gtf.reset_transforms(test=True); | _____no_output_____ | Apache-2.0 | study_roadmaps/1_getting_started_roadmap/5_update_hyperparams/2_data_params/6) Dataset Transforms.ipynb | kshitij12345/monk_v1 |
Apply new transforms | gtf.List_Transforms();
# Transform applied to only train and val
gtf.apply_center_crop(224,
train=True,
val=True,
test=False)
# Transform applied to all train, val and test
gtf.apply_normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, ... | Pre-Composed Train Transforms
[{'CenterCrop': {'input_size': 224}}, {'Normalize': {'mean': [0.485, 0.456, 0.406], 'std': [0.229, 0.224, 0.225]}}]
Pre-Composed Val Transforms
[{'CenterCrop': {'input_size': 224}}, {'Normalize': {'mean': [0.485, 0.456, 0.406], 'std': [0.229, 0.224, 0.225]}}]
Dataset Numbers
Num trai... | Apache-2.0 | study_roadmaps/1_getting_started_roadmap/5_update_hyperparams/2_data_params/6) Dataset Transforms.ipynb | kshitij12345/monk_v1 |
Dataproc - Submit Hadoop Job Intended UseA Kubeflow Pipeline component to submit a Apache Hadoop MapReduce job on Apache Hadoop YARN in Google Cloud Dataproc service. Run-Time Parameters:Name | Description:--- | :----------project_id | Required. The ID of the Google Cloud Platform project that the cluster belongs to.... | PROJECT_ID = '<Please put your project ID here>'
CLUSTER_NAME = '<Please put your existing cluster name here>'
OUTPUT_GCS_PATH = '<Please put your output GCS path here>'
REGION = 'us-central1'
MAIN_CLASS = 'org.apache.hadoop.examples.WordCount'
INTPUT_GCS_PATH = 'gs://ml-pipeline-playground/shakespeare1.txt'
EXPERIMENT... | _____no_output_____ | Apache-2.0 | components/gcp/dataproc/submit_hadoop_job/sample.ipynb | ryan-williams/pipelines |
Insepct Input DataThe input file is a simple text file: | !gsutil cat $INTPUT_GCS_PATH | With which he yoketh your rebellious necks Razeth your cities and subverts your towns And in a moment makes them desolate
| Apache-2.0 | components/gcp/dataproc/submit_hadoop_job/sample.ipynb | ryan-williams/pipelines |
Clean up existing output files (Optional)This is needed because the sample code requires the output folder to be a clean folder.To continue to run the sample, make sure that the service account of the notebook server has access to the `OUTPUT_GCS_PATH`.**CAUTION**: This will remove all blob files under `OUTPUT_GCS_PAT... | !gsutil rm $OUTPUT_GCS_PATH/** | CommandException: No URLs matched: gs://hongyes-ml-tests/dataproc/hadoop/output/**
| Apache-2.0 | components/gcp/dataproc/submit_hadoop_job/sample.ipynb | ryan-williams/pipelines |
Install KFP SDKInstall the SDK (Uncomment the code if the SDK is not installed before) | # KFP_PACKAGE = 'https://storage.googleapis.com/ml-pipeline/release/0.1.12/kfp.tar.gz'
# !pip3 install $KFP_PACKAGE --upgrade | _____no_output_____ | Apache-2.0 | components/gcp/dataproc/submit_hadoop_job/sample.ipynb | ryan-williams/pipelines |
Load component definitions | import kfp.components as comp
dataproc_submit_hadoop_job_op = comp.load_component_from_url(COMPONENT_SPEC_URI)
display(dataproc_submit_hadoop_job_op) | _____no_output_____ | Apache-2.0 | components/gcp/dataproc/submit_hadoop_job/sample.ipynb | ryan-williams/pipelines |
Here is an illustrative pipeline that uses the component | import kfp.dsl as dsl
import kfp.gcp as gcp
import json
@dsl.pipeline(
name='Dataproc submit Hadoop job pipeline',
description='Dataproc submit Hadoop job pipeline'
)
def dataproc_submit_hadoop_job_pipeline(
project_id = PROJECT_ID,
region = REGION,
cluster_name = CLUSTER_NAME,
main_jar_file_ur... | _____no_output_____ | Apache-2.0 | components/gcp/dataproc/submit_hadoop_job/sample.ipynb | ryan-williams/pipelines |
Compile the pipeline | pipeline_func = dataproc_submit_hadoop_job_pipeline
pipeline_filename = pipeline_func.__name__ + '.pipeline.tar.gz'
import kfp.compiler as compiler
compiler.Compiler().compile(pipeline_func, pipeline_filename) | _____no_output_____ | Apache-2.0 | components/gcp/dataproc/submit_hadoop_job/sample.ipynb | ryan-williams/pipelines |
Submit the pipeline for execution | #Specify pipeline argument values
arguments = {}
#Get or create an experiment and submit a pipeline run
import kfp
client = kfp.Client()
experiment = client.create_experiment(EXPERIMENT_NAME)
#Submit a pipeline run
run_name = pipeline_func.__name__ + ' run'
run_result = client.run_pipeline(experiment.id, run_name, pi... | _____no_output_____ | Apache-2.0 | components/gcp/dataproc/submit_hadoop_job/sample.ipynb | ryan-williams/pipelines |
Inspect the outputsThe sample in the notebook will count the words in the input text and output them in sharded files. Here is the command to inspect them: | !gsutil cat $OUTPUT_GCS_PATH/* | AccessDeniedException: 403
| Apache-2.0 | components/gcp/dataproc/submit_hadoop_job/sample.ipynb | ryan-williams/pipelines |
- The data used for the calculations is soil water balance data from CGIAR-CSI available at http://www.cgiar-csi.org/data/global-high-resolution-soil-water-balance.- Data on irrigation are from the FAO's AQUASTAT information system available at http://www.fao.org/nr/water/aquastat/irrigationmap/index10.stm.- Soil data ... | import os
from ftplib import FTP | _____no_output_____ | MIT | python/0_download_files.ipynb | ethz-esd/compaction_stoessel_2018 |
Specify your data directory to where you want to download the files: | data_dir = os.path.join('..', 'data/soilgrids') | _____no_output_____ | MIT | python/0_download_files.ipynb | ethz-esd/compaction_stoessel_2018 |
Download files: | # connect to data folder on ftp-server:
ftp = FTP('ftp.soilgrids.org')
ftp.login()
ftp.cwd('data/recent')
# select download directory:
os.chdir(data_dir)
# download the given files:
files = ['CLYPPT_M_sl1_250m.tif', 'CLYPPT_M_sl2_250m.tif', 'CLYPPT_M_sl3_250m.tif',
'CLYPPT_M_sl4_250m.tif']
for filename in fil... | _____no_output_____ | MIT | python/0_download_files.ipynb | ethz-esd/compaction_stoessel_2018 |
Random Variables:label:`sec_random_variables`In :numref:`sec_prob` we saw the basics of how to work with discrete random variables, which in our case refer to those random variables which take either a finite set of possible values, or the integers. In this section, we develop the theory of *continuous random variabl... | %matplotlib inline
from d2l import mxnet as d2l
from IPython import display
from mxnet import np, npx
npx.set_np()
# Plot the probability density function for some random variable
x = np.arange(-5, 5, 0.01)
p = 0.2*np.exp(-(x - 3)**2 / 2)/np.sqrt(2 * np.pi) + \
0.8*np.exp(-(x + 1)**2 / 2)/np.sqrt(2 * np.pi)
d2l.p... | _____no_output_____ | MIT | d2l-en/mxnet/chapter_appendix-mathematics-for-deep-learning/random-variables.ipynb | gr8khan/d2lai |
The locations where the function value is large indicates regions where we are more likely to find the random value. The low portions are areas where we are unlikely to find the random value. Probability Density FunctionsLet us now investigate this further. We have already seen what a probability density function is ... | # Approximate probability using numerical integration
epsilon = 0.01
x = np.arange(-5, 5, 0.01)
p = 0.2*np.exp(-(x - 3)**2 / 2) / np.sqrt(2 * np.pi) + \
0.8*np.exp(-(x + 1)**2 / 2) / np.sqrt(2 * np.pi)
d2l.set_figsize()
d2l.plt.plot(x, p, color='black')
d2l.plt.fill_between(x.tolist()[300:800], p.tolist()[300:800]... | _____no_output_____ | MIT | d2l-en/mxnet/chapter_appendix-mathematics-for-deep-learning/random-variables.ipynb | gr8khan/d2lai |
It turns out that these two properties describe exactly the space of possible probability density functions (or *p.d.f.*'s for the commonly encountered abbreviation). They are non-negative functions $p(x) \ge 0$ such that$$\int_{-\infty}^{\infty} p(x) \; dx = 1.$$:eqlabel:`eq_pdf_int_one`We interpret this function by ... | # Define a helper to plot these figures
def plot_chebyshev(a, p):
d2l.set_figsize()
d2l.plt.stem([a-2, a, a+2], [p, 1-2*p, p], use_line_collection=True)
d2l.plt.xlim([-4, 4])
d2l.plt.xlabel('x')
d2l.plt.ylabel('p.m.f.')
d2l.plt.hlines(0.5, a - 4 * np.sqrt(2 * p),
a + 4 * np.s... | _____no_output_____ | MIT | d2l-en/mxnet/chapter_appendix-mathematics-for-deep-learning/random-variables.ipynb | gr8khan/d2lai |
The second shows that at $p = 1/8$, the interval exactly touches the two points. This shows that the inequality is *sharp*, since no smaller interval could be taken while keeping the inequality true. | # Plot interval when p = 1/8
plot_chebyshev(0.0, 0.125) | _____no_output_____ | MIT | d2l-en/mxnet/chapter_appendix-mathematics-for-deep-learning/random-variables.ipynb | gr8khan/d2lai |
The third shows that for $p < 1/8$ the interval only contains the center. This does not invalidate the inequality since we only needed to ensure that no more than $1/4$ of the probability falls outside the interval, which means that once $p < 1/8$, the two points at $a-2$ and $a+2$ can be discarded. | # Plot interval when p < 1/8
plot_chebyshev(0.0, 0.05) | _____no_output_____ | MIT | d2l-en/mxnet/chapter_appendix-mathematics-for-deep-learning/random-variables.ipynb | gr8khan/d2lai |
Means and Variances in the ContinuumThis has all been in terms of discrete random variables, but the case of continuous random variables is similar. To intuitively understand how this works, imagine that we split the real number line into intervals of length $\epsilon$ given by $(\epsilon i, \epsilon (i+1)]$. Once w... | # Plot the Cauchy distribution p.d.f.
x = np.arange(-5, 5, 0.01)
p = 1 / (1 + x**2)
d2l.plot(x, p, 'x', 'p.d.f.') | _____no_output_____ | MIT | d2l-en/mxnet/chapter_appendix-mathematics-for-deep-learning/random-variables.ipynb | gr8khan/d2lai |
This function looks innocent, and indeed consulting a table of integrals will show it has area one under it, and thus it defines a continuous random variable.To see what goes astray, let us try to compute the variance of this. This would involve using :eqref:`eq_var_def` computing$$\int_{-\infty}^\infty \frac{x^2}{1+x... | # Plot the integrand needed to compute the variance
x = np.arange(-20, 20, 0.01)
p = x**2 / (1 + x**2)
d2l.plot(x, p, 'x', 'integrand') | _____no_output_____ | MIT | d2l-en/mxnet/chapter_appendix-mathematics-for-deep-learning/random-variables.ipynb | gr8khan/d2lai |
This function clearly has infinite area under it since it is essentially the constant one with a small dip near zero, and indeed we could show that$$\int_{-\infty}^\infty \frac{x^2}{1+x^2}\; dx = \infty.$$This means it does not have a well-defined finite variance.However, looking deeper shows an even more disturbing re... | # Plot a few random variables adjustable covariance
covs = [-0.9, 0.0, 1.2]
d2l.plt.figure(figsize=(12, 3))
for i in range(3):
X = np.random.normal(0, 1, 500)
Y = covs[i]*X + np.random.normal(0, 1, (500))
d2l.plt.subplot(1, 4, i+1)
d2l.plt.scatter(X.asnumpy(), Y.asnumpy())
d2l.plt.xlabel('X')
d... | _____no_output_____ | MIT | d2l-en/mxnet/chapter_appendix-mathematics-for-deep-learning/random-variables.ipynb | gr8khan/d2lai |
Let us see some properties of covariances:* For any random variable $X$, $\mathrm{Cov}(X, X) = \mathrm{Var}(X)$.* For any random variables $X, Y$ and numbers $a$ and $b$, $\mathrm{Cov}(aX+b, Y) = \mathrm{Cov}(X, aY+b) = a\mathrm{Cov}(X, Y)$.* If $X$ and $Y$ are independent then $\mathrm{Cov}(X, Y) = 0$.In addition, we ... | # Plot a few random variables adjustable correlations
cors = [-0.9, 0.0, 1.0]
d2l.plt.figure(figsize=(12, 3))
for i in range(3):
X = np.random.normal(0, 1, 500)
Y = cors[i] * X + np.sqrt(1 - cors[i]**2) * np.random.normal(0, 1, 500)
d2l.plt.subplot(1, 4, i + 1)
d2l.plt.scatter(X.asnumpy(), Y.asnumpy())... | _____no_output_____ | MIT | d2l-en/mxnet/chapter_appendix-mathematics-for-deep-learning/random-variables.ipynb | gr8khan/d2lai |
Copyright 2018 The TensorFlow Authors. | #@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under... | _____no_output_____ | Apache-2.0 | tools/templates/subsite/g3doc/tutorials/notebook.ipynb | manivaradarajan/docs |
Gaia Real data!gully Sept 28, 2017 Outline:1. Batch download GaiaSource **Import these first-- I auto import them every time!:** | import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
%config InlineBackend.figure_format = 'retina'
%matplotlib inline | _____no_output_____ | MIT | notebooks/adrasteia_04-01_get_gaiaSource_data.ipynb | gully/adrasteia |
1. Batch download the data | import os
i_max = 256 | _____no_output_____ | MIT | notebooks/adrasteia_04-01_get_gaiaSource_data.ipynb | gully/adrasteia |
```pythonfor j in range(21): if j == 20: i_max = 111 for i in range(i_max): fn = 'http://cdn.gea.esac.esa.int/Gaia/gaia_source/csv/GaiaSource_000-{:03d}-{:03d}.csv.gz'.format(j,i) executable = 'wget --directory-prefix=../data/GaiaSource/ '+fn print(executable) os.system(executab... | ! ls ../data/GaiaSource/ | tail | GaiaSource_000-000-069.csv.gz
GaiaSource_000-000-070.csv.gz
GaiaSource_000-000-071.csv.gz
GaiaSource_000-000-072.csv.gz
GaiaSource_000-000-073.csv.gz
GaiaSource_000-000-074.csv.gz
GaiaSource_000-000-075.csv.gz
GaiaSource_000-000-076.csv.gz
GaiaSource_000-000-077.csv.gz
GaiaSource_000-000-078.csv.gz
| MIT | notebooks/adrasteia_04-01_get_gaiaSource_data.ipynb | gully/adrasteia |
How many files are there? | 20*256+110 | _____no_output_____ | MIT | notebooks/adrasteia_04-01_get_gaiaSource_data.ipynb | gully/adrasteia |
Each file is about 40 MB. How many GB total is the dataset? | 5230*40/1000 | _____no_output_____ | MIT | notebooks/adrasteia_04-01_get_gaiaSource_data.ipynb | gully/adrasteia |
Capstone Project - Madiun Cafe Location Introduction / business problemi am looking to open a cafe in Madiun City, **the question is**, where is the best location for open new cafe? **The background of the problem** it is not worth setting up a cafe in the close promixity of existing ones. because the location of the ... | !conda install -c conda-forge folium=0.5.0 --yes
import pandas as pd
import folium
import requests
# The code was removed by Watson Studio for sharing.
request_parameters = {
"client_id": CLIENT_ID,
"client_secret": CLIENT_SECRET,
"v": VERSION,
"section": "coffee",
"near": "Madiun",
"radius": 10... | _____no_output_____ | MIT | Week 4/Capstone Project - Madiun Cafe Location Final.ipynb | Symefa/Coursera_Capstone-Madiun-Cafe |
Applying Heatmap to Map Some density based estimator is a good to be used to determine where to start a new coffee business. Using HeatMap plugin in Folium, to visualize all the existing Cafes to same map: |
from folium import plugins
# create map of Helsinki using latitude and longitude values
map_madiun = folium.Map(location=[madiun_center["lat"], madiun_center["lng"]], zoom_start=14)
folium.LatLngPopup().add_to(map_madiun)
def add_markers(df):
for (j, row) in df.iterrows():
label = folium.Popup(row["name"... | /opt/conda/envs/Python36/lib/python3.6/site-packages/ipykernel/__main__.py:22: FutureWarning: Method .as_matrix will be removed in a future version. Use .values instead.
| MIT | Week 4/Capstone Project - Madiun Cafe Location Final.ipynb | Symefa/Coursera_Capstone-Madiun-Cafe |
Result After further analysis, the best location for a new cafe is on Tulus Bakti Street, because it is not in close proximity with other cafe, and located near school and on densest population region in madiun. [BPS DATA](https://madiunkota.bps.go.id/statictable/2015/06/08/141/jumlah-penduduk-menurut-kecamatan-dan-ag... | lat = -7.6393
lng = 111.5285
school_1_lat = -7.6403
school_1_lng = 111.5316
map_best = folium.Map(location=[lat, lng], zoom_start=17)
add_markers(df)
folium.CircleMarker(
[school_1_lat, school_1_lng],
radius=15,
popup="School",
color='Yellow',
fill=True,
fill_color='#3186cc',
fill_opacity=... | _____no_output_____ | MIT | Week 4/Capstone Project - Madiun Cafe Location Final.ipynb | Symefa/Coursera_Capstone-Madiun-Cafe |
**Artificial Intelligence - MSc**This notebook is designed specially for the moduleET5003 - MACHINE LEARNING APPLICATIONS Instructor: Enrique NaredoET5003_BayesianNN© All rights reserved to the author, do not share outside this module. Introduction A [Bayesian network](https://en.wikipedia.org/wiki/Bayesian_network) ... | # Suppressing Warnings:
import warnings
warnings.filterwarnings("ignore")
# https://pypi.org/project/GPy/
!pip install gpy
import GPy as GPy
import numpy as np
import pylab as pb
import pymc3 as pm
%matplotlib inline | _____no_output_____ | BSD-3-Clause | Week-5/ET5003_BayesianNN.ipynb | davidnol/ET5003_SEM1_2021-2 |
Data generationGenerate data from a nonlinear function and use a Gaussian Process to sample it. | # seed the legacy random number generator
# to replicate experiments
seed = None
#seed = 7
np.random.seed(seed)
# Gaussian Processes
# https://gpy.readthedocs.io/en/deploy/GPy.kern.html
# Radial Basis Functions
# https://scikit-learn.org/stable/auto_examples/svm/plot_rbf_parameters.html
# kernel is a function that spec... | _____no_output_____ | BSD-3-Clause | Week-5/ET5003_BayesianNN.ipynb | davidnol/ET5003_SEM1_2021-2 |
In this example, first generate a nonlinear functions and then generate noisy training data from that function.The constrains are:* Training samples $x$ belong to either interval $[-0.8,-0.2]$ or $[0.2,0.8]$.* There is not data training samples from the interval $[-0.2,0.2]$. * The goal is to evaluate the extrapolation... | # plot
pb.figure()
pb.plot(X_new_test,TF_new,c='b',label='True Function',zorder=100)
# training data
pb.scatter(X_new_train,y_new_train,c='g',label='Train Samples',alpha=0.5)
pb.xlabel("x",fontsize=16);
pb.ylabel("y",fontsize=16,rotation=0)
pb.legend()
pb.savefig("New_data.pdf") | _____no_output_____ | BSD-3-Clause | Week-5/ET5003_BayesianNN.ipynb | davidnol/ET5003_SEM1_2021-2 |
Bayesian NNWe address the previous nonlinear regression problem by using a Bayesian NN.**The model is basically very similar to polynomial regression**. We first define the nonlinear function (NN)and the place a prior over the unknown parameters. We then compute the posterior. | # https://theano-pymc.readthedocs.io/en/latest/
import theano
# add a column of ones to include an intercept in the model
x1 = np.vstack([np.ones(len(X_new_train)), X_new_train]).T
floatX = theano.config.floatX
l = 15
# Initialize random weights between each layer
# we do that to help the numerical algorithm that c... | WARNING (theano.tensor.blas): We did not find a dynamic library in the library_dir of the library we use for blas. If you use ATLAS, make sure to compile it with dynamics library.
WARNING (theano.tensor.blas): We did not find a dynamic library in the library_dir of the library we use for blas. If you use ATLAS, make su... | BSD-3-Clause | Week-5/ET5003_BayesianNN.ipynb | davidnol/ET5003_SEM1_2021-2 |
Specifically, PyMC3 supports the following Variational Inference (VI) methods: * Automatic Differentiation Variational Inference (ADVI): 'advi' * ADVI full rank: 'fullrank_advi' * Stein Variational Gradient Descent (SVGD): 'svgd' * Amortized Stein Variational Gradient Descent (ASVGD): 'asvgd' * Normalizing Flow wi... | # we can do instead an approximated inference
param3 = 1000 # start with 1000, then use 50000+
VI = 'advi' # 'advi', 'fullrank_advi', 'svgd', 'asvgd', 'nfvi'
OP = pm.adam # pm.adam, pm.sgd, pm.adagrad, pm.adagrad_window, pm.adadelta
LR = 0.01
with neural_network:
approx = pm.fit(param3, method=VI, obj_optimiz... | _____no_output_____ | BSD-3-Clause | Week-5/ET5003_BayesianNN.ipynb | davidnol/ET5003_SEM1_2021-2 |
Now, we compute the prediction for each sample. * Note that we use `np.tanh` instead of `pm.math.tanh`for speed reason. * `pm.math.tanh` is slower outside a Pymc3 model because it converts all data in theano format.* It is convenient to do GPU-based training, but it is slow when we only need to compute predictions. | # add a column of ones to include an intercept in the model
x2 = np.vstack([np.ones(len(X_new_test)), X_new_test]).T
y_pred = []
for i in range(posterior['w_1'].shape[0]):
#inner layer
t1 = np.tanh(np.dot(posterior['w_1'][i,:,:].T,x2.T))
#outer layer
y_pred.append(np.dot(posterior['w_0'][i,:],t1))
# p... | _____no_output_____ | BSD-3-Clause | Week-5/ET5003_BayesianNN.ipynb | davidnol/ET5003_SEM1_2021-2 |
We first plot the mean of `y_pred`, this is very similar to the prediction that Keras returns | # plot
pb.plot(X_new_test,TF_new,label='true')
pb.plot(X_new_test,y_pred.mean(axis=0),label='Bayes NN mean')
pb.scatter(X_new_train,y_new_train,c='r',alpha=0.5)
pb.legend()
pb.ylim([-1,1])
pb.xlabel("x",fontsize=16);
pb.ylabel("y",fontsize=16,rotation=0)
pb.savefig("BayesNN_mean.pdf") | _____no_output_____ | BSD-3-Clause | Week-5/ET5003_BayesianNN.ipynb | davidnol/ET5003_SEM1_2021-2 |
Now, we plot the uncertainty, by plotting N nonlinear regression lines from the posterior | # plot
pb.plot(X_new_test,TF_new,label='true',Zorder=100)
pb.plot(X_new_test,y_pred.mean(axis=0),label='Bayes NN mean',Zorder=100)
N = 500
# nonlinear regression lines
for i in range(N):
pb.plot(X_new_test,y_pred[i,:],c='gray',alpha=0.05)
pb.scatter(X_new_train,y_new_train,c='r',alpha=0.5)
pb.xlabel("x",fontsize... | _____no_output_____ | BSD-3-Clause | Week-5/ET5003_BayesianNN.ipynb | davidnol/ET5003_SEM1_2021-2 |
函数- 函数可以用来定义可重复代码,组织和简化- 一般来说一个函数在实际开发中为一个小功能- 一个类为一个大功能- 同样函数的长度不要超过一屏 Python中的所有函数实际上都是有返回值(return None),如果你没有设置return,那么Python将不显示None.如果你设置return,那么将返回出return这个值. | def HJN():
print('Hello')
return 1000
b=HJN()
print(b)
HJN
def panduan(number):
if number % 2 == 0:
print('O')
else:
print('J')
panduan(number=1)
panduan(2) | O
| Apache-2.0 | 7.20.ipynb | hzdhhh/Python |
定义一个函数def function_name(list of parameters): do something- 以前使用的random 或者range 或者print.. 其实都是函数或者类 函数的参数如果有默认值的情况,当你调用该函数的时候:可以不给予参数值,那么就会走该参数的默认值否则的话,就走你给予的参数值. | import random
def hahah():
n = random.randint(0,5)
while 1:
N = eval(input('>>'))
if n == N:
print('smart')
break
elif n < N:
print('太小了')
elif n > N:
print('太大了')
| _____no_output_____ | Apache-2.0 | 7.20.ipynb | hzdhhh/Python |
调用一个函数- functionName()- "()" 就代表调用 | def H():
print('hahaha')
def B():
H()
B()
def A(f):
f()
A(B) | hahaha
| Apache-2.0 | 7.20.ipynb | hzdhhh/Python |
 带返回值和不带返回值的函数- return 返回的内容- return 返回多个值- 一般情况下,在多个函数协同完成一个功能的时候,那么将会有返回值 - 当然也可以自定义返回None EP: | def main():
print(min(min(5,6),(51,6)))
def min(n1,n2):
a = n1
if n2 < a:
a = n2
main() | _____no_output_____ | Apache-2.0 | 7.20.ipynb | hzdhhh/Python |
类型和关键字参数- 普通参数- 多个参数- 默认值参数- 不定长参数 普通参数 多个参数 默认值参数 强制命名 | def U(str_):
xiaoxie = 0
for i in str_:
ASCII = ord(i)
if 97<=ASCII<=122:
xiaoxie +=1
elif xxxx:
daxie += 1
elif xxxx:
shuzi += 1
return xiaoxie,daxie,shuzi
U('HJi12') | H
J
i
1
2
| Apache-2.0 | 7.20.ipynb | hzdhhh/Python |
不定长参数- \*args> - 不定长,来多少装多少,不装也是可以的 - 返回的数据类型是元组 - args 名字是可以修改的,只是我们约定俗成的是args- \**kwargs > - 返回的字典 - 输入的一定要是表达式(键值对)- name,\*args,name2,\**kwargs 使用参数名 | def TT(a,b)
def TT(*args,**kwargs):
print(kwargs)
print(args)
TT(1,2,3,4,6,a=100,b=1000)
{'key':'value'}
TT(1,2,4,5,7,8,9,)
def B(name1,nam3):
pass
B(name1=100,2)
def sum_(*args,A='sum'):
res = 0
count = 0
for i in args:
res +=i
count += 1
if A == "sum":
return r... | _____no_output_____ | Apache-2.0 | 7.20.ipynb | hzdhhh/Python |
变量的作用域- 局部变量 local- 全局变量 global- globals 函数返回一个全局变量的字典,包括所有导入的变量- locals() 函数会以字典类型返回当前位置的全部局部变量。 | a = 1000
b = 10
def Y():
global a,b
a += 100
print(a)
Y()
def YY(a1):
a1 += 100
print(a1)
YY(a)
print(a) | 1200
1100
| Apache-2.0 | 7.20.ipynb | hzdhhh/Python |
注意:- global :在进行赋值操作的时候需要声明- 官方解释:This is because when you make an assignment to a variable in a scope, that variable becomes local to that scope and shadows any similarly named variable in the outer scope.-  Homework- 1 | def getPentagonalNumber(n):
count = 0
for n in range(100):
y=int(n*(3*n-1)/2)
print(y,end=' ')
count += 1
if count %10 == 0:
print()
getPentagonalNumber(100) | 0 1 5 12 22 35 51 70 92 117
145 176 210 247 287 330 376 425 477 532
590 651 715 782 852 925 1001 1080 1162 1247
1335 1426 1520 1617 1717 1820 1926 2035 2147 2262
2380 2501 2625 2752 2882 3015 3151 3290 3432 3577
3725 3876 4030 4187 4347 4510 4676 4845 5017 5192
5370 5551 5735 5922 6112 6305 6501 6700 6902 7107
7... | Apache-2.0 | 7.20.ipynb | hzdhhh/Python |
- 2  | def sumDigits(n):
bai=n//100
shi=n//10%10
ge=n%10
y=bai+shi+ge
print('%d(%d+%d+%d)'%(y,bai,shi,ge))
sumDigits(234) | 9(2+3+4)
| Apache-2.0 | 7.20.ipynb | hzdhhh/Python |
- 3 | def displaySortedNumber():
num1,num2,num3=map(float,input('Enter three number:').split(','))
a=[num1,num2,num3]
a.sort()
print(a)
displaySortedNumber() | Enter three number:2,1.0,3
[1.0, 2.0, 3.0]
| Apache-2.0 | 7.20.ipynb | hzdhhh/Python |
- 4 | def futureInvestmentValue(principal,rate,years):
for i in range(years):
principal = principal * (1+rate)
print("{}年内总额{}: ".format(i+1,principal))
principal = eval(input("输入存款金额: "))
rate = eval(input("输入利率: "))
years = eval(input("输入年份:" ))
futureInvestmentValue(principal,rate,years) | 输入存款金额: 1000
输入利率: 9
输入年份:30
1年内总额10000:
2年内总额100000:
3年内总额1000000:
4年内总额10000000:
5年内总额100000000:
6年内总额1000000000:
7年内总额10000000000:
8年内总额100000000000:
9年内总额1000000000000:
10年内总额10000000000000:
11年内总额100000000000000:
12年内总额1000000000000000:
13年内总额10000000000000000:
14年内总额100000000000000000:
15年内总额1000000... | Apache-2.0 | 7.20.ipynb | hzdhhh/Python |
- 5 | def printChars():
count=0
for i in range(49,91):
print(chr(i),end=' ')
count=count+1
if count%10==0:
print()
printChars() | 1 2 3 4 5 6 7 8 9 :
; < = > ? @ A B C D
E F G H I J K L M N
O P Q R S T U V W X
Y Z | Apache-2.0 | 7.20.ipynb | hzdhhh/Python |
- 6 | def numberofDaysInAYear():
for year in range(2010,2021):
if (year%4==0 and year%100!=0) or (year%400==0):
print('%d年366天'%year)
else:
print('%d年365天'%year)
numberofDaysInAYear() | 2010年365天
2011年365天
2012年366天
2013年365天
2014年365天
2015年365天
2016年366天
2017年365天
2018年365天
2019年365天
2020年366天
| Apache-2.0 | 7.20.ipynb | hzdhhh/Python |
- 7 | import numpy as np
import math
def xsj(x1,y1,x2,y2):
p1=np.array([x1,y1])
p2=np.array([x2,y2])
p3=p2-p1
p4=math.hypot(p3[0],p3[1])
print(p4)
x1,y1,x2,y2=map(int,input().split(','))
xsj(x1,y1,x2,y2) | 1,2,3,4
2.8284271247461903
| Apache-2.0 | 7.20.ipynb | hzdhhh/Python |
- 8 - 9 | import time
localtime = time.asctime(time.localtime(time.time()))
print("本地时间为 :", localtime)
2019 - 1970 | _____no_output_____ | Apache-2.0 | 7.20.ipynb | hzdhhh/Python |
- 10 | import random
num1=random.randrange(1,7)
num2=random.randrange(1,7)
sum_=num1+num2
if sum_==2 or sum_==3 or sum_==12:
print('You rolled %d+%d=%d'%(num1,num2,sum_))
print('you lose')
elif sum_==7 or sum_==11:
print('You rolled %d+%d=%d'%(num1,num2,sum_))
print('you win')
else:
print('You rolled %d+... | You rolled 5+2=7
you win
| Apache-2.0 | 7.20.ipynb | hzdhhh/Python |
Goals for Total number of goals scored so far this seasonGoals againstTotal number of goals conceded so far thisseasonGoals Differential Goals for – Goals againstPower Play Success Rate Ratio – scoring a goal when 5 on 4Power Kill Success Rate Ratio – not conceding a goal when 4 on 5Shot % Goal scored/shots takenSave %... | feat_Pisch = [ 'faceOffWinPercentage', | _____no_output_____ | MIT | Note_books/Explore_Models/Feature_Partitions.ipynb | joeyamosjohns/final_project_nhl_prediction_first_draft |
Системы координатТвердое тело обладает шестью степенями свободы, которые можно представить в виде трех перемещений и трех вращений.Чтобы описать положение тела оказывается удобным описать положение _локальной системы координат_ (ЛСК), жестко связанной с этим телом.Тогда описание п... | %matplotlib notebook
import matplotlib.pyplot as plt
import numpy as np | _____no_output_____ | MIT | 1 - Coordinate System.ipynb | red-hara/jupyter-dh-notation |
Зададим положение и ориентацию ЛСК в двумерном пространстве: | x = 10
y = 7
alpha = np.deg2rad(15) | _____no_output_____ | MIT | 1 - Coordinate System.ipynb | red-hara/jupyter-dh-notation |
И отобразим ее: | fig = plt.figure(figsize=(6, 6))
ax = fig.add_subplot()
ax.axis("equal")
ax.set_xlim((-3, 12)); ax.set_ylim((-3, 12))
ax.arrow(0, 0, 5, 0, color="#ff0000", linewidth=6)
ax.arrow(0, 0, 0, 5, color="#00ff00", linewidth=6)
ax.arrow(x, y, np.cos(alpha), np.sin(alpha), color="#ff0000", linewidth=2)
ax.arrow(x, y, -np.sin(... | _____no_output_____ | MIT | 1 - Coordinate System.ipynb | red-hara/jupyter-dh-notation |
Casos de prueba | var ex11 = "abcd";
var ex12 = "abdc";
var ex21 = "abcde";
var ex22 = "abc"; | _____no_output_____ | Unlicense | Chap1/2 CheckPermutation.ipynb | jenivial/cracking-the-coding-interview |
Solución | bool IsPermutation(string firstString,string secondString)
{
var dic = new Dictionary<char,int>();
foreach(var c in firstString)
{
if(!dic.ContainsKey(c))
{
dic.Add(c,0);
}
dic[c] = dic[c] + 1;
}
foreach(var c in secondString)
{
if(!dic.Conta... | True
False
| Unlicense | Chap1/2 CheckPermutation.ipynb | jenivial/cracking-the-coding-interview |
Linear RegressionWe will implement a linear regression model by using the Keras library. | %matplotlib inline
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np | _____no_output_____ | MIT | Implementaciones/LinearRegression/LinearRegression-Keras.ipynb | sergiomora03/deep-learning-basics |
Data set: Weight and heightActive Drive and read the csv file with the weight and height data | df = pd.read_csv('/content/drive/My Drive/Colab Notebooks/DeepLearning-Intro-part2/weight-height.csv')
df.head()
df.plot(kind='scatter',
x='Height',
y='Weight',
title='Weight and Height in adults') | _____no_output_____ | MIT | Implementaciones/LinearRegression/LinearRegression-Keras.ipynb | sergiomora03/deep-learning-basics |
Model building | # Import the type of model: Sequential, because we will add elements to this model in a sequence
from keras.models import Sequential
# To build a linear model we will need only dense layers
from keras.layers import Dense
# Import the optimizers, they change the weights and biases looking for the minimum cost
from keras... | Using TensorFlow backend.
| MIT | Implementaciones/LinearRegression/LinearRegression-Keras.ipynb | sergiomora03/deep-learning-basics |
Define the model | # define the model to be sequential
model = Sequential() | _____no_output_____ | MIT | Implementaciones/LinearRegression/LinearRegression-Keras.ipynb | sergiomora03/deep-learning-basics |
```Dense(units, activation=None, use_bias=True, kernel_initializer='glorot_uniform', bias_initializer='zeros', kernel_regularizer=None, bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, bias_constraint=None, **kwargs)```Just your regular densely-connected NN layer.Dense implements the operation:... | # we add to the model a dense layer
# the first parammeter is the number of units that is how many outputs this layer will have
# Since this is a linear regression we will require a model with one output and one input
model.add(Dense(1, input_shape=(1,))) #this code implements a model x*w+b
model.summary() | Model: "sequential_1"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
dense_1 (Dense) (None, 1) 2
==================================... | MIT | Implementaciones/LinearRegression/LinearRegression-Keras.ipynb | sergiomora03/deep-learning-basics |
We have a single layer called 'dense_1' the Output Shape is 1 number and it has 2 parameters. The reason that the Output Shape is (None, 1) is because the model can accept multiple points at once, instead of passing a single value we can ask for many values of x in one single call. When we compile the model, Keras will... | # we will compile using the cost function (loss) 'mean_squared_error'
model.compile(Adam(lr=0.8), 'mean_squared_error') | _____no_output_____ | MIT | Implementaciones/LinearRegression/LinearRegression-Keras.ipynb | sergiomora03/deep-learning-basics |
Fit the model | X = df[['Height']].values #input data
y_true = df['Weight'].values #output data | _____no_output_____ | MIT | Implementaciones/LinearRegression/LinearRegression-Keras.ipynb | sergiomora03/deep-learning-basics |
Fit the model by using the input data, X, and the output data, y_true. In each iteration the loss is decreasing by looking for the W and B values. In this example it will search 40 times (40 epochs). | model.fit(X, y_true, epochs=40)
y_pred = model.predict(X)
df.plot(kind='scatter',
x='Height',
y='Weight',
title='Weight and Height in adults')
plt.plot(X, y_pred, color='red') | _____no_output_____ | MIT | Implementaciones/LinearRegression/LinearRegression-Keras.ipynb | sergiomora03/deep-learning-basics |
Extract the values of W (slope) and B (bias). | W, B = model.get_weights()
W
B | _____no_output_____ | MIT | Implementaciones/LinearRegression/LinearRegression-Keras.ipynb | sergiomora03/deep-learning-basics |
Performance of the model | from sklearn.metrics import r2_score
print("The R2 score is {:0.3f}".format(r2_score(y_true, y_pred))) | The R2 score is 0.829
| MIT | Implementaciones/LinearRegression/LinearRegression-Keras.ipynb | sergiomora03/deep-learning-basics |
Train/test split | from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y_true,
test_size=0.2)
len(X_train)
len(X_test)
#reset the parameters of the model
W[0, 0] = 0.0
B[0] = 0.0
model.set_weights((W, B))
#retrain the model in the ... | The R2 score on the Train set is: 0.837
The R2 score on the Test set is: 0.827
| MIT | Implementaciones/LinearRegression/LinearRegression-Keras.ipynb | sergiomora03/deep-learning-basics |
A demo of K-Means clustering on the handwritten digits dataIn this example we compare the various initialization strategies forK-means in terms of runtime and quality of the results.As the ground truth is known here, we also apply different clusterquality metrics to judge the goodness of fit of the cluster labels to ... | def bench_k_means(estimator, name, data):
t0 = time()
estimator.fit(data)
print('%-9s\t%.2fs\t%i\t%.3f\t%.3f\t%.3f\t%.3f\t%.3f\t%.3f'
% (name, (time() - t0), estimator.inertia_,
metrics.homogeneity_score(labels, estimator.labels_),
metrics.completeness_score(labels, estim... | _____no_output_____ | Apache-2.0 | Tutorials_PCA_KMeans_DBSCAN_Autoencoder_with_MNIST/PCA_mnist_kmeans_blog.ipynb | ustundag/2D-3D-Semantics |
Training vs validation loss[](https://colab.research.google.com/github/parrt/fundamentals-of-deep-learning/blob/main/notebooks/3.train-test-diabetes.ipynb)By [Terence Parr](https://explained.ai).This notebook explores how to use a validation set... | import os
import sys
import torch
import copy
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_diabetes
from sklearn.metrics import r2_score
from sklearn.ensemble import RandomForestRegress... | _____no_output_____ | MIT | notebooks/deep-learning/3.train-test-diabetes.ipynb | edithlee972/msds621 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.