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
Identifier for storing these features on disk and referring to them later.
feature_list_id = 'tfidf'
_____no_output_____
MIT
notebooks/feature-tfidf.ipynb
MinuteswithMetrics/kaggle-quora-question-pairs
Read Data Preprocessed and tokenized questions.
tokens_train = kg.io.load(project.preprocessed_data_dir + 'tokens_lowercase_spellcheck_no_stopwords_train.pickle') tokens_test = kg.io.load(project.preprocessed_data_dir + 'tokens_lowercase_spellcheck_no_stopwords_test.pickle') tokens = tokens_train + tokens_test
_____no_output_____
MIT
notebooks/feature-tfidf.ipynb
MinuteswithMetrics/kaggle-quora-question-pairs
Extract a set of unique question texts (document corpus).
all_questions_flat = np.array(tokens).ravel() documents = list(set(' '.join(question) for question in all_questions_flat)) del all_questions_flat
_____no_output_____
MIT
notebooks/feature-tfidf.ipynb
MinuteswithMetrics/kaggle-quora-question-pairs
Train TF-IDF vectorizer Create a bag-of-token-unigrams vectorizer.
vectorizer = TfidfVectorizer( encoding='utf-8', analyzer='word', strip_accents='unicode', ngram_range=(1, 1), lowercase=True, norm='l2', use_idf=True, smooth_idf=True, sublinear_tf=True, ) vectorizer.fit(documents) model_filename = 'tfidf_vectorizer_{}_ngrams_{}_{}_penalty_{}.pickle'...
_____no_output_____
MIT
notebooks/feature-tfidf.ipynb
MinuteswithMetrics/kaggle-quora-question-pairs
Vectorize train and test sets, compute distances
def compute_pair_distances(pair): q1_doc = ' '.join(pair[0]) q2_doc = ' '.join(pair[1]) pair_dtm = vectorizer.transform([q1_doc, q2_doc]) q1_doc_vec = pair_dtm[0] q2_doc_vec = pair_dtm[1] return [ cosine_distances(q1_doc_vec, q2_doc_vec)[0][0], euclidean_distances(q1_do...
X_train: (404290, 2) X_test: (2345796, 2)
MIT
notebooks/feature-tfidf.ipynb
MinuteswithMetrics/kaggle-quora-question-pairs
Save features
feature_names = [ 'tfidf_cosine', 'tfidf_euclidean', ] project.save_features(X_train, X_test, feature_names, feature_list_id)
_____no_output_____
MIT
notebooks/feature-tfidf.ipynb
MinuteswithMetrics/kaggle-quora-question-pairs
PyMC3 Examples GLM Robust Regression with Outlier Detection**A minimal reproducable example of Robust Regression with Outlier Detection using Hogg 2010 Signal vs Noise method.**+ This is a complementary approach to the Student-T robust regression as illustrated in Thomas Wiecki's notebook in the [PyMC3 documentation](...
%matplotlib inline %qtconsole --colors=linux import warnings warnings.filterwarnings('ignore') import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from scipy import optimize import pymc3 as pm import theano as thno import theano.tensor as T # configure some basic options sns...
_____no_output_____
Apache-2.0
docs/notebooks/GLM-robust-with-outlier-detection.ipynb
ds7788/hello-world
Load and Prepare Data We'll use the Hogg 2010 data available at https://github.com/astroML/astroML/blob/master/astroML/datasets/hogg2010test.pyIt's a very small dataset so for convenience, it's hardcoded below
#### cut & pasted directly from the fetch_hogg2010test() function ## identical to the original dataset as hardcoded in the Hogg 2010 paper dfhogg = pd.DataFrame(np.array([[1, 201, 592, 61, 9, -0.84], [2, 244, 401, 25, 4, 0.31], [3, 47, 583, 38, 11, 0.64...
_____no_output_____
Apache-2.0
docs/notebooks/GLM-robust-with-outlier-detection.ipynb
ds7788/hello-world
**Observe**: + Even judging just by eye, you can see these datapoints mostly fall on / around a straight line with positive gradient+ It looks like a few of the datapoints may be outliers from such a line ------ Create Conventional OLS Model The *linear model* is really simple and conventional:$$\bf{y} = \beta^{T} \b...
with pm.Model() as mdl_ols: ## Define weakly informative Normal priors to give Ridge regression b0 = pm.Normal('b0_intercept', mu=0, sd=100) b1 = pm.Normal('b1_slope', mu=0, sd=100) ## Define linear model yest = b0 + b1 * dfhoggs['x'] ## Use y error from dataset, convert into theano ...
_____no_output_____
Apache-2.0
docs/notebooks/GLM-robust-with-outlier-detection.ipynb
ds7788/hello-world
Sample
with mdl_ols: ## find MAP using Powell, seems to be more robust start_MAP = pm.find_MAP(fmin=optimize.fmin_powell, disp=True) ## take samples traces_ols = pm.sample(2000, start=start_MAP, step=pm.NUTS(), progressbar=True)
Optimization terminated successfully. Current function value: 145.777745 Iterations: 3 Function evaluations: 118 [-----------------100%-----------------] 2000 of 2000 complete in 0.9 sec
Apache-2.0
docs/notebooks/GLM-robust-with-outlier-detection.ipynb
ds7788/hello-world
View Traces**NOTE**: I'll 'burn' the traces to only retain the final 1000 samples
_ = pm.traceplot(traces_ols[-1000:], figsize=(12,len(traces_ols.varnames)*1.5), lines={k: v['mean'] for k, v in pm.df_summary(traces_ols[-1000:]).iterrows()})
_____no_output_____
Apache-2.0
docs/notebooks/GLM-robust-with-outlier-detection.ipynb
ds7788/hello-world
**NOTE:** We'll illustrate this OLS fit and compare to the datapoints in the final plot ------ Create Robust Model: Student-T Method I've added this brief section in order to directly compare the Student-T based method exampled in Thomas Wiecki's notebook in the [PyMC3 documentation](http://pymc-devs.github.io/pymc3/G...
with pm.Model() as mdl_studentt: ## Define weakly informative Normal priors to give Ridge regression b0 = pm.Normal('b0_intercept', mu=0, sd=100) b1 = pm.Normal('b1_slope', mu=0, sd=100) ## Define linear model yest = b0 + b1 * dfhoggs['x'] ## Use y error from dataset, convert into th...
_____no_output_____
Apache-2.0
docs/notebooks/GLM-robust-with-outlier-detection.ipynb
ds7788/hello-world
Sample
with mdl_studentt: ## find MAP using Powell, seems to be more robust start_MAP = pm.find_MAP(fmin=optimize.fmin_powell, disp=True) ## two-step sampling to allow Metropolis for nu (which is discrete) step1 = pm.NUTS([b0, b1]) step2 = pm.Metropolis([nu]) ## take samples traces_studentt ...
Optimization terminated successfully. Current function value: 107.488021 Iterations: 3 Function evaluations: 77 [-----------------100%-----------------] 2000 of 2000 complete in 1.0 sec
Apache-2.0
docs/notebooks/GLM-robust-with-outlier-detection.ipynb
ds7788/hello-world
View Traces
_ = pm.traceplot(traces_studentt[-1000:] ,figsize=(12,len(traces_studentt.varnames)*1.5) ,lines={k: v['mean'] for k, v in pm.df_summary(traces_studentt[-1000:]).iterrows()})
_____no_output_____
Apache-2.0
docs/notebooks/GLM-robust-with-outlier-detection.ipynb
ds7788/hello-world
**Observe:**+ Both parameters `b0` and `b1` show quite a skew to the right, possibly this is the action of a few samples regressing closer to the OLS estimate which is towards the left+ The `nu` parameter seems very happy to stick at `nu = 1`, indicating that a fat-tailed Student-T likelihood has a better fit than a th...
def logp_signoise(yobs, is_outlier, yest_in, sigma_y_in, yest_out, sigma_y_out): ''' Define custom loglikelihood for inliers vs outliers. NOTE: in this particular case we don't need to use theano's @as_op decorator because (as stated by Twiecki in conversation) that's only required if the likelih...
_____no_output_____
Apache-2.0
docs/notebooks/GLM-robust-with-outlier-detection.ipynb
ds7788/hello-world
Sample
with mdl_signoise: ## two-step sampling to create Bernoulli inlier/outlier flags step1 = pm.NUTS([frac_outliers, yest_out, sigma_y_out, b0, b1]) step2 = pm.BinaryMetropolis([is_outlier], tune_interval=100) ## find MAP using Powell, seems to be more robust start_MAP = pm.find_MAP(fmin=optimize.fmin...
Optimization terminated successfully. Current function value: 155.449990 Iterations: 3 Function evaluations: 213 [-----------------100%-----------------] 2000 of 2000 complete in 169.1 sec
Apache-2.0
docs/notebooks/GLM-robust-with-outlier-detection.ipynb
ds7788/hello-world
View Traces
_ = pm.traceplot(traces_signoise[-1000:], figsize=(12,len(traces_signoise.varnames)*1.5), lines={k: v['mean'] for k, v in pm.df_summary(traces_signoise[-1000:]).iterrows()})
_____no_output_____
Apache-2.0
docs/notebooks/GLM-robust-with-outlier-detection.ipynb
ds7788/hello-world
**NOTE:**+ During development I've found that 3 datapoints id=[1,2,3] are always indicated as outliers, but the remaining ordering of datapoints by decreasing outlier-hood is unstable between runs: the posterior surface appears to have a small number of solutions with very similar probability.+ The NUTS sampler seems t...
outlier_melt = pd.melt(pd.DataFrame(traces_signoise['is_outlier', -1000:], columns=['[{}]'.format(int(d)) for d in dfhoggs.index]), var_name='datapoint_id', value_name='is_outlier') ax0 = sns.pointplot(y='datapoint_id', x='is_outlier', data=outlier_melt, ...
_____no_output_____
Apache-2.0
docs/notebooks/GLM-robust-with-outlier-detection.ipynb
ds7788/hello-world
**Observe**:+ The plot above shows the number of samples in the traces in which each datapoint is marked as an outlier, expressed as a percentage.+ In particular, 3 points [1, 2, 3] spend >=95% of their time as outliers+ Contrastingly, points at the other end of the plot close to 0% are our strongest inliers.+ For comp...
cutoff = 5 dfhoggs['outlier'] = np.percentile(traces_signoise[-1000:]['is_outlier'],cutoff, axis=0) dfhoggs['outlier'].value_counts()
_____no_output_____
Apache-2.0
docs/notebooks/GLM-robust-with-outlier-detection.ipynb
ds7788/hello-world
Posterior Prediction Plots for OLS vs StudentT vs SignalNoise
g = sns.FacetGrid(dfhoggs, size=8, hue='outlier', hue_order=[True,False], palette='Set1', legend_out=False) lm = lambda x, samp: samp['b0_intercept'] + samp['b1_slope'] * x pm.glm.plot_posterior_predictive(traces_ols[-1000:], eval=np.linspace(-3, 3, 10), lm=lm, samples=200, color='#22CC00', ...
_____no_output_____
Apache-2.0
docs/notebooks/GLM-robust-with-outlier-detection.ipynb
ds7788/hello-world
Sample plots
# load libraries import os import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt %matplotlib inline os.listdir()
_____no_output_____
MIT
datascience/plots_ds_python_pandas_1.ipynb
futureseadev/hgwxx7
sample plot 1
# load csv train = pd.read_csv('restaurant-and-market-health-inspections.csv') train.info() train.head() train['grade'].unique() train.select_dtypes('object') # plot the count of Unique Values in integer Columns train.select_dtypes(np.int64).nunique().value_counts().sort_index().plot.bar(color = 'red', ...
_____no_output_____
MIT
datascience/plots_ds_python_pandas_1.ipynb
futureseadev/hgwxx7
sample 2
# plotting different categories from collections import OrderedDict plt.figure(figsize = (20, 16)) plt.style.use('fivethirtyeight') # Color mapping colors = OrderedDict({'A': 'red', 'B': 'orange', 'C': 'blue', ' ': 'green'}) mapping = OrderedDict({'A': 'extreme', 'B': 'moderate', 'C': 'vulnerable', ' ': 'non vulnerab...
c:\py37\lib\site-packages\scipy\stats\stats.py:1713: FutureWarning: Using a non-tuple sequence for multidimensional indexing is deprecated; use `arr[tuple(seq)]` instead of `arr[seq]`. In the future this will be interpreted as an array index, `arr[np.array(seq)]`, which will result either in an error or a different res...
MIT
datascience/plots_ds_python_pandas_1.ipynb
futureseadev/hgwxx7
Plot Categoricals
# plot two categorical variables def plot_categoricals(x, y, data, annotate=False): """Plot counts of two categoricals. Size is raw count for each grouping. Percentages are for a given value of y.""" # Raw counts raw_counts = pd.DataFrame(data.groupby(y)[x].value_counts(normalize = False)) ...
_____no_output_____
MIT
datascience/plots_ds_python_pandas_1.ipynb
futureseadev/hgwxx7
Value Count Plots
# plot value counts of a column def plot_value_counts(df, col, condition=False): """Plot value counts of a column, optionally with only the heads of a household""" # apply condition here if required if condition: # define condition below <> df = df.loc[df[col] == condition].copy() ...
_____no_output_____
MIT
datascience/plots_ds_python_pandas_1.ipynb
futureseadev/hgwxx7
Demos: Lecture 4
import pennylane as qml import numpy as np
/opt/conda/envs/pennylane/lib/python3.8/site-packages/_distutils_hack/__init__.py:30: UserWarning: Setuptools is replacing distutils. warnings.warn("Setuptools is replacing distutils.")
MIT
demos/Lecture04-Demos.ipynb
annabellegrimes/CPEN-400Q
Demo 1: `qml.ctrl`
def some_function(): qml.PauliX(wires=1) qml.CNOT(wires=[1, 2]) qml.Hadamard(wires=2) qml.CRX(0.3, wires=[2, 1]) dev = qml.device('default.qubit', wires=3) @qml.qnode(dev) def control_the_thing(): qml.Hadamard(wires=0) qml.ctrl(some_function, control=0)() return qml.state() c...
0: ──H──╭C──╭C──╭ControlledPhaseShift(1.57)──╭C─────────╭ControlledPhaseShift(1.57)──╭C─────────╭C─────────╭C──╭C──────────╭C──╭C──────────╭┤ State 1: ─────╰X──├C──│────────────────────────────│──────────│────────────────────────────╰RZ(1.57)──╰RY(0.15)──├X──╰RY(-0.15)──├X──╰RZ(-1.57)──├┤ State 2: ─────────╰X──╰Co...
MIT
demos/Lecture04-Demos.ipynb
annabellegrimes/CPEN-400Q
Demo 2: multi-qubit measurements
dev = qml.device('default.qubit', wires=3)#, shots=10) @qml.qnode(dev) def something_parametrized(x, y): qml.Hadamard(wires=0) qml.CRX(x, wires=[0, 1]) qml.CRY(y, wires=[1, 2]) return qml.probs(wires=[0]) something_parametrized(0.1, 0.2)
_____no_output_____
MIT
demos/Lecture04-Demos.ipynb
annabellegrimes/CPEN-400Q
Demo 3: multi-qubit expectation values
dev = qml.device('default.qubit', wires=3)#, shots=10) @qml.qnode(dev) def something_parametrized(x, y): qml.Hadamard(wires=0) qml.CRX(x, wires=[0, 1]) qml.CRY(y, wires=[1, 2]) return qml.expval(qml.PauliZ(0)), qml.expval(qml.PauliZ(1)), qml.expval(qml.PauliZ(2)) something_parametrized(0.3, 0.4) d...
_____no_output_____
MIT
demos/Lecture04-Demos.ipynb
annabellegrimes/CPEN-400Q
Demo 4: superdense coding
dev = qml.device('default.qubit', wires=2, shots=1) def create_entangled_state(wires=None): qml.Hadamard(wires=wires[0]) qml.CNOT(wires=[wires[0], wires[1]]) @qml.qnode(dev) def superdense_coding(b1=0, b2=0): create_entangled_state(wires=[0, 1]) if b1 == 1: qml.PauliZ(wires=0) ...
_____no_output_____
MIT
demos/Lecture04-Demos.ipynb
annabellegrimes/CPEN-400Q
1 - Getting Started The main application for `scikit-gstat` is variogram analysis and [Kriging](https://en.wikipedia.org/wiki/Kriging). This Tutorial will guide you through the most basic functionality of `scikit-gstat`. There are other tutorials that will explain specific methods or attributes in `scikit-gstat` in mo...
import numpy as np import pandas as pd import matplotlib.pyplot as plt from pprint import pprint plt.style.use('ggplot')
_____no_output_____
MIT
docs/tutorials/01_getting_started.ipynb
rhugonnet/scikit-gstat
The `Variogram` and `OrdinaryKriging` classes can be loaded directly from `skgstat`. This is the name of the Python module.
from skgstat import Variogram, OrdinaryKriging
_____no_output_____
MIT
docs/tutorials/01_getting_started.ipynb
rhugonnet/scikit-gstat
At the current version, there are some deprecated attributes and method in the `Variogram` class. They do not raise `DeprecationWarning`s, but rather print a warning message to the screen. You can suppress this warning by adding an `SKG_SUPPRESS` environment variable
%set_env SKG_SUPPRESS=true
env: SKG_SUPPRESS=true
MIT
docs/tutorials/01_getting_started.ipynb
rhugonnet/scikit-gstat
1.1 Load data You can find a prepared example data set in the `./data` subdirectory. This example is extracted from a generated Gaussian random field. We can expect the field to be stationary and show a nice spatial dependence, because it was created that way.We can load one of the examples and have a look at the data...
data = pd.read_csv('./data/sample_sr.csv') print("Loaded %d rows and %d columns" % data.shape) data.head()
Loaded 200 rows and 3 columns
MIT
docs/tutorials/01_getting_started.ipynb
rhugonnet/scikit-gstat
Get a first overview of your data by plotting the `x` and `y` coordinates and visually inspect how the `z` spread out.
fig, ax = plt.subplots(1, 1, figsize=(9, 9)) art = ax.scatter(data.x,data.y, s=50, c=data.z, cmap='plasma') plt.colorbar(art);
_____no_output_____
MIT
docs/tutorials/01_getting_started.ipynb
rhugonnet/scikit-gstat
We can already see a lot from here: * The small values seem to concentrate on the upper left and lower right corner* Larger values are arranged like a band from lower left to upper right corner* To me, each of these blobs seem to have a diameter of something like 30 or 40 units.* The distance between the minimum and ma...
V = Variogram(data[['x', 'y']].values, data.z.values, normalize=False, maxlag=60, n_lags=15) fig = V.plot(show=False)
_____no_output_____
MIT
docs/tutorials/01_getting_started.ipynb
rhugonnet/scikit-gstat
The upper subplot show the histogram for the count of point-pairs in each lag class. You can see various things here:* As expected, there is a clear spatial dependency, because semi-variance increases with distance (blue dots)* The default `spherical` variogram model is well fitted to the experimental data* The shape o...
print('Sample variance: %.2f Variogram sill: %.2f' % (data.z.var(), V.describe()['sill']))
Sample variance: 1.10 Variogram sill: 1.26
MIT
docs/tutorials/01_getting_started.ipynb
rhugonnet/scikit-gstat
The `describe` method will return the most important parameters as a dictionary. And we can simply print the variogram ob,ect to the screen, to see all parameters.
pprint(V.describe()) print(V)
spherical Variogram ------------------- Estimator: matheron Effective Range: 39.50 Sill: 1.26 Nugget: 0.00
MIT
docs/tutorials/01_getting_started.ipynb
rhugonnet/scikit-gstat
1.3 Kriging The Kriging class will now use the Variogram from above to estimate the Kriging weights for each grid cell. This is done by solving a linear equation system. For an unobserved location $s_0$, we can use the distances to 5 observation points and build the system like:$$\begin{pmatrix}\gamma(s_1, s_1) & \gam...
ok = OrdinaryKriging(V, min_points=5, max_points=15, mode='exact')
_____no_output_____
MIT
docs/tutorials/01_getting_started.ipynb
rhugonnet/scikit-gstat
The `transform` method will apply the interpolation for passed arrays of coordinates. It requires each dimension as a single 1D array. We can easily build a meshgrid of 100x100 coordinates and pass them to the interpolator. To recieve a 2D result, we can simply reshape the result. The Kriging error will be available as...
# build the target grid xx, yy = np.mgrid[0:99:100j, 0:99:100j] field = ok.transform(xx.flatten(), yy.flatten()).reshape(xx.shape) s2 = ok.sigma.reshape(xx.shape)
_____no_output_____
MIT
docs/tutorials/01_getting_started.ipynb
rhugonnet/scikit-gstat
And finally, we can plot the result.
fig, axes = plt.subplots(1, 2, figsize=(16, 8)) art = axes[0].matshow(field.T, origin='lower', cmap='plasma') axes[0].set_title('Interpolation') axes[0].plot(data.x, data.y, '+k') axes[0].set_xlim((0,100)) axes[0].set_ylim((0,100)) plt.colorbar(art, ax=axes[0]) art = axes[1].matshow(s2.T, origin='lower', cmap='YlGn_r'...
_____no_output_____
MIT
docs/tutorials/01_getting_started.ipynb
rhugonnet/scikit-gstat
KNN
import pickle import numpy as np from sklearn.neighbors import KNeighborsClassifier from sklearn.model_selection import train_test_split, cross_val_score from sklearn.metrics import classification_report, confusion_matrix from sklearn.model_selection import GridSearchCV from sklearn.model_selection import StratifiedSh...
{'n_neighbors': 5} [[6164 75 373 345 0] [ 71 6402 356 352 0] [ 351 360 8975 105 0] [ 368 397 123 8683 0] [ 5 5 7 25 1]] precision recall f1-score support 0 0.89 0.89 0.89 6957 1 0.88 0.89 0.89 71...
MIT
MLGame/games/snake/ml/train.py.ipynb
Liuian/1092_INTRODUCTION-TO-MACHINE-LEARNING-AND-ITS-APPLICATION-TO-GAMING
Bayesian Regression Using NumPyroIn this tutorial, we will explore how to do bayesian regression in NumPyro, using a simple example adapted from Statistical Rethinking [[1](References)]. In particular, we would like to explore the following: - Write a simple model using the `sample` NumPyro primitive. - Run inference ...
%reset -s -f import jax import jax.numpy as np from jax import random, vmap from jax.config import config; config.update("jax_platform_name", "cpu") from jax.scipy.special import logsumexp import matplotlib import matplotlib.pyplot as plt import numpy as onp import pandas as pd import seaborn as sns from numpyro.diagn...
_____no_output_____
MIT
notebooks/source/bayesian_regression.ipynb
Anthonymcqueen21/numpyro
DatasetFor this example, we will use the `WaffleDivorce` dataset from Chapter 05, Statistical Rethinking [[1](References)]. The dataset contains divorce rates in each of the 50 states in the USA, along with predictors such as population, median age of marriage, whether it is a Southern state and, curiously, number of ...
DATASET_URL = 'https://raw.githubusercontent.com/rmcelreath/rethinking/master/data/WaffleDivorce.csv' dset = pd.read_csv(DATASET_URL, sep=';') dset
_____no_output_____
MIT
notebooks/source/bayesian_regression.ipynb
Anthonymcqueen21/numpyro
Let us plot the pair-wise relationship amongst the main variables in the dataset, using `seaborn.pairplot`.
vars = ['Population', 'MedianAgeMarriage', 'Marriage', 'WaffleHouses', 'South', 'Divorce'] sns.pairplot(dset, x_vars=vars, y_vars=vars, palette='husl');
_____no_output_____
MIT
notebooks/source/bayesian_regression.ipynb
Anthonymcqueen21/numpyro
From the plots above, we can clearly observe that there is a relationship between divorce rates and marriage rates in a state (as might be expected), and also between divorce rates and median age of marriage. There is also a weak relationship between number of Waffle Houses and divorce rates, which is not obvious from ...
sns.regplot('WaffleHouses', 'Divorce', dset);
_____no_output_____
MIT
notebooks/source/bayesian_regression.ipynb
Anthonymcqueen21/numpyro
Regression Model to Predict Divorce RateLet us now write a regressionn model in *NumPyro* to predict the divorce rate as a linear function of marriage rate and median age of marriage in each of the states. First, note that our predictor variables have somewhat different scales. It is a good practice to standardize our...
dset['AgeScaled'] = (dset.MedianAgeMarriage - onp.mean(dset.MedianAgeMarriage)) / onp.std(dset.MedianAgeMarriage) dset['MarriageScaled'] = (dset.Marriage - onp.mean(dset.Marriage)) / onp.std(dset.Marriage) dset['DivorceScaled'] = (dset.Divorce - onp.mean(dset.Divorce)) / onp.std(dset.Divorce)
_____no_output_____
MIT
notebooks/source/bayesian_regression.ipynb
Anthonymcqueen21/numpyro
We write the NumPyro model as follows. While the code should largely be self-explanatory, take note of the following: - In NumPyro, model code is any Python callable that can accept arguments and keywords. For HMC which we will be using for this tutorial, these arguments and keywords cannot change during model executio...
def model(marriage=None, age=None, divorce=None): a = sample('a', dist.Normal(0., 0.2)) M, A = 0., 0. if marriage is not None: bM = sample('bM', dist.Normal(0., 0.5)) M = bM * marriage if age is not None: bA = sample('bA', dist.Normal(0., 0.5)) A = bA * age sigma = sa...
_____no_output_____
MIT
notebooks/source/bayesian_regression.ipynb
Anthonymcqueen21/numpyro
Model 1: Predictor - Marriage RateWe first try to model the divorce rate as depending on a single variable, marriage rate. As mentioned above, we can use the same `model` code as earlier, but only pass values for `marriage` and `divorce` keyword arguments. We will use the No U-Turn Sampler (see [[5](References)] for m...
# Start from this source of randomness. We will split keys for subsequent operations. rng = random.PRNGKey(0) rng_, rng = random.split(rng) # Initialize the model. init_params, potential_fn, constrain_fn = initialize_model(rng_, model, marriage=dset.MarriageS...
warmup: 100%|██████████| 1000/1000 [00:12<00:00, 78.24it/s, 1 steps of size 6.99e-01. acc. prob=0.79] sample: 100%|██████████| 2000/2000 [00:03<00:00, 515.37it/s, 3 steps of size 6.99e-01. acc. prob=0.88]
MIT
notebooks/source/bayesian_regression.ipynb
Anthonymcqueen21/numpyro
Posterior Distribution over the Regression ParametersWe notice that the progress bar gives us online statistics on the acceptance probability, step size and number of steps taken per sample while running NUTS. In particular, during warmup, we adapt the step size and mass matrix to achieve a certain target acceptance p...
def plot_regression(x, y_mean, y_hpdi): # Sort values for plotting by x axis idx = np.argsort(x) marriage = x[idx] mean = y_mean[idx] hpdi = y_hpdi[:, idx] divorce = dset.DivorceScaled.values[idx] # Plot fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(6, 6)) ax.plot(marriage, mean...
_____no_output_____
MIT
notebooks/source/bayesian_regression.ipynb
Anthonymcqueen21/numpyro
Posterior Predictive DistributionLet us now look at the posterior predictive distribution to see how our predictive distribution looks with respect to the observed divorce rates. To get samples from the posterior predictive distribution, we need to run the model by substituting the latent parameters with samples from ...
def predict(rng, post_samples, model, *args, **kwargs): model = substitute(seed(model, rng), post_samples) model_trace = trace(model).get_trace(*args, **kwargs) return model_trace['obs']['value'] # vectorize predictions via vmap predict_fn = vmap(lambda rng, samples: predict(rng, samples, model, marriage=ds...
_____no_output_____
MIT
notebooks/source/bayesian_regression.ipynb
Anthonymcqueen21/numpyro
We will use the same `plot_regression` function as earlier. We notice that our CI for the predictive distribution is much broader as compared to the last plot due to the additional noise introduced by the `sigma` parameter. Note that most data points lie well within the 90% CI, which indicates a good fit. Model Log Lik...
def log_lk(rng, params, model, *args, **kwargs): model = substitute(seed(model, rng), params) model_trace = trace(model).get_trace(*args, **kwargs) obs_node = model_trace['obs'] return np.sum(obs_node['fn'].log_prob(obs_node['value'])) def expected_log_likelihood(rng, params, model, *args, **kwargs...
Log likelihood: -68.14618682861328
MIT
notebooks/source/bayesian_regression.ipynb
Anthonymcqueen21/numpyro
Model 2: Predictor - Median Age of MarriageWe will now model the divorce rate as a function of the median age of marriage. The computations are mostly a reproduction of what we did for Model 1. Notice the following: - Divorce rate is inversely related to the age of marriage. Hence states where the median age of marria...
rng, rng_ = random.split(rng) init_params, potential_fn, constrain_fn = initialize_model(rng_, model, age=dset.AgeScaled.values, divorce=dset.DivorceScaled.values) samples_2 = mcmc(num_warmup, num_sa...
Log likelihood: -60.926387786865234
MIT
notebooks/source/bayesian_regression.ipynb
Anthonymcqueen21/numpyro
Model 3: Predictor - Marriage Rate and Median Age of MarriageFinally, we will also model divorce rate as depending on both marriage rate as well as the median age of marriage. Note that there is no increase in the model's log likelihood over Model 2 which likely indicates that the marginal information from marriage ra...
rng, rng_ = random.split(rng) init_params, potential_fn, constrain_fn = initialize_model(rng_, model, marriage=dset.MarriageScaled.values, age=dset.AgeScaled.values, ...
Log likelihood: -61.04328918457031
MIT
notebooks/source/bayesian_regression.ipynb
Anthonymcqueen21/numpyro
Divorce Rate Residuals by StateThe regression plots above shows that the observed divorce rates for many states differs considerably from the mean regression line. To dig deeper into how the last model (Model 3) under-predicts or over-predicts for each of the states, we will plot the posterior predictive and residuals...
# Predictions for Model 3. rng, rng_ = random.split(rng) predict_fn = vmap(lambda rng, samples: predict(rng, samples, model, marriage=dset.MarriageScaled.values, age=dset.AgeScaled.values)) predictions_3 = predict_fn(random.sp...
_____no_output_____
MIT
notebooks/source/bayesian_regression.ipynb
Anthonymcqueen21/numpyro
The plot on the left shows the mean predictions with 90% CI for each of the states using Model 3. The gray markers indicate the actual observed divorce rates. The right plot shows the residuals for each of the states, and both these plots are sorted by the residuals, i.e. at the bottom, we are looking at states where t...
def model_se(marriage, age, divorce_sd, divorce=None): a = sample('a', dist.Normal(0., 0.2)) bM = sample('bM', dist.Normal(0., 0.5)) M = bM * marriage bA = sample('bA', dist.Normal(0., 0.5)) A = bA * age sigma = sample('sigma', dist.Exponential(1.)) mu = a + M + A divorce_rate = sample('...
warmup: 100%|██████████| 1000/1000 [00:19<00:00, 50.19it/s, 15 steps of size 2.16e-01. acc. prob=0.89] sample: 100%|██████████| 3000/3000 [00:06<00:00, 442.19it/s, 15 steps of size 2.16e-01. acc. prob=0.94]
MIT
notebooks/source/bayesian_regression.ipynb
Anthonymcqueen21/numpyro
Effect of Incorporating Measurement Noise on ResidualsNotice that our values for the regression coefficients is very similar to Model 3. However, introducing measurement noise allows us to more closely match our predictive distributions to the observed values. We can see this if we plot the residuals as earlier.
rng, rng_ = random.split(rng) predict_fn = vmap(lambda rng, samples: predict(rng, samples, model_se, marriage=dset.MarriageScaled.values, age=dset.AgeScaled.values, divorce_sd=ds...
_____no_output_____
MIT
notebooks/source/bayesian_regression.ipynb
Anthonymcqueen21/numpyro
The plot above shows the residuals for each of the states, along with the measurement noise given by inner error bar. The gray dots are the mean residuals from our earlier Model 3. Notice how having an additional degree of freedom to model the measurement noise has shrunk the residuals. In particular, for Idaho and Mai...
fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(10, 6)) x = dset.DivorceScaledSD.values y1 = np.mean(residuals_3, 0) y2 = np.mean(residuals_4, 0) ax.plot(x, y1, ls='none', marker='o') ax.plot(x, y2, ls='none', marker='o') for i, (j, k) in enumerate(zip(y1, y2)): ax.plot([x[i], x[i]], [j, k], '--', color='gray');...
_____no_output_____
MIT
notebooks/source/bayesian_regression.ipynb
Anthonymcqueen21/numpyro
Mutation analysis1. Calculate the mutation rate (number of mutations/number of unique sequences) 2. Consider only the sequences between 2000 and 20203. Write the different files (Year : Mutation rate)
from google.colab import drive drive.mount('/content/gdrive') %cd 'gdrive/MyDrive/Machine Learning/coronavirus/analysis' !ls import os import pandas as pd import numpy as np #List all the directory names dir_name = os.listdir('./H1N_H9N') for name in dir_name: df = pd.read_csv('./H1N_H9N/' + name) #Select only se...
_____no_output_____
MIT
analysis/Mutation_analysis.ipynb
chuducthang77/coronavirus
Table of Contents 0.0.1&nbsp;&nbsp;Cover Slide 10.0.2&nbsp;&nbsp;Cover Slide 21&nbsp;&nbsp;Headline Slide2&nbsp;&nbsp;Preprocessing3&nbsp;&nbsp;Headline Subslide4&nbsp;&nbsp;Fragment4.0.1&nbsp;&nbsp;Divider5&nbsp;&nbsp;Markdown Examples5.0.0.1&nbsp;&nbsp;Text6&nbsp;&nbsp;Headline Subslide6.0.0.1&nbsp;&nbsp;Code7&nbsp;...
# Add all necessary imports here import matplotlib.pyplot as plt %matplotlib inline plt.style.reload_library() plt.style.use("ggplot")
_____no_output_____
MIT
reports/Presentations/Presentation_241117/timing_presentation.ipynb
EstevaoVieira/spikelearn
Cover Slide 1
<image> <section data-background="img/cover.jpg" data-state="img-transparent no-title-footer"> <div class="intro-body"> <div class="intro_h1"><h1>Title</h1></div> <h3>Subtitle of the Presentation</h3> <p><strong><span class="a">Speaker 1</span></strong> <span class="b"></span> <span>Job Title</span></p> <p><strong><spa...
_____no_output_____
MIT
reports/Presentations/Presentation_241117/timing_presentation.ipynb
EstevaoVieira/spikelearn
Cover Slide 2
<image> <section data-state="no-title-footer"> <div class="intro_h1"><h1>Title</h1></div> <h3>Subtitle of the Presentation</h3> <p><strong><span class="a">Speaker 1</span></strong> <span class="b"></span> <span>Job Title</span></p> <p><strong><span class="a">Speaker 2</span></strong> <span class="b"></span> <span>Job T...
_____no_output_____
MIT
reports/Presentations/Presentation_241117/timing_presentation.ipynb
EstevaoVieira/spikelearn
Headline Slide Preprocessing ![boot0](bootstrap/shuffle_bins0.png) ![boot1](bootstrap/shuffle_bins1.png) ![boot2](bootstrap/shuffle_bins2.png) ![boot3](bootstrap/shuffle_bins3.png) ![boot4](bootstrap/shuffle_bins4.png) ![boot5](bootstrap/shuffle_bins5.png)
def f(x): """a docstring""" return x**2
_____no_output_____
MIT
reports/Presentations/Presentation_241117/timing_presentation.ipynb
EstevaoVieira/spikelearn
Headline Subslide
plt.plot([1,2,3,4]) plt.ylabel('some numbers') plt.show()
_____no_output_____
MIT
reports/Presentations/Presentation_241117/timing_presentation.ipynb
EstevaoVieira/spikelearn
FragmentPress the right arrow. - I am a Fragement - I am another one Divider
<image> </section> <section data-background="#F27C3A" data-state="no-title-footer"> <div class="divider_h1"> <h1>Divider</h1> </div> </section> </image>
_____no_output_____
MIT
reports/Presentations/Presentation_241117/timing_presentation.ipynb
EstevaoVieira/spikelearn
Markdown Examples TextIt's very easy to make some words **bold** and other words *italic* with Markdown. You can even [link to Google!](http://google.com) Headline Subslide Code```javascriptvar s = "JavaScript syntax highlighting";alert(s);``` ```pythons = "Python syntax highlighting"print s``` ```No language indicat...
<image> </section> <section data-background="#0093C9" data-state="no-title-footer"> <div class="divider_h1"> <h1>Questions???</h1> </div> </section> </image>
_____no_output_____
MIT
reports/Presentations/Presentation_241117/timing_presentation.ipynb
EstevaoVieira/spikelearn
test: 30% train-val 70%To simulate noisy label acquisition, assume a labeler quality p. then use a random we first hide the labels of all examples for each dataset. At the point in an experiment when a label is acquired, we generate a label according to the labeler quality p: we assign the example's original label with...
%reload_ext autoreload %autoreload 2 import sys, os, wget sys.path.append('../../') import pandas as pd import numpy as np import load_data import ipywidgets from IPython.display import display args = {'options': ['read', 'download'], 'label': 'read', 'description': 'mode:' , ...
_____no_output_____
Apache-2.0
examples_artin/applied_to_other_datasets.ipynb
artinmajdi/crowd-kit
guide for ipywidgetssource:
widgets.FloatRangeSlider( value=[5, 7.5], min=0, max=10.0, step=0.1, description='Test:', disabled=False, continuous_update=False, orientation='horizontal', readout=True, readout_format='.1f', ) b = widgets.BoundedFloatText( value=7.5, min=0, max=10.0, step=0.1, ...
_____no_output_____
Apache-2.0
examples_artin/applied_to_other_datasets.ipynb
artinmajdi/crowd-kit
XGBoost Cloud Prediction - Iris ClassificationInvoke SageMaker Prediction Service
# Acquire a realtime endpoint endpoint_name = 'xgboost-iris-v1' predictor = sagemaker.predictor.Predictor (endpoint_name=endpoint_name) predictor.serializer = CSVSerializer() # Test predictive quality against data in validation file df_all = pd.read_csv('iris_validation.csv', names=['encoded_class'...
_____no_output_____
Apache-2.0
5 Xgboost/IrisClassification/xgboost_cloud_prediction_template.ipynb
jaypeeml/AWSSagemaker
宣告- 只能存不重複的元素- 因為是無序的,所以每次編譯後的順序都會不同
a = {1, 2, 3, 2, 4, 5, 2} b = set([1, 2, 3, 2, 4, 5, 2]) print(a, type(a)) print(b, type(b)) s1.add(5) print(s1) s1.add(5) print(s1) s1.remove(5) print(s1) # 因為找不到,所以會報錯 #s1.remove(8) #print(s1) a = '1234512' print(set(a)) s1 = {1, 2, 3, 4} s2 = {3, 4, 5, 6} print('交集:', s1 & s2) print('聯集:', s1 | s2) print('對稱差集:',...
交集: {3, 4} 聯集: {1, 2, 3, 4, 5, 6} 對稱差集: {1, 2, 5, 6} 差集1: {1, 2} 差集2: {5, 6}
MIT
Python/[Python] Set.ipynb
ZongSingHuang/Data-Scientist-Tokyo
Image annotations for a batch of samplesUsing this notebook, cardiologists are able to quickly view and annotate MRI images for a batch of samples. These annotated images become the training data for the next round of modeling. Setup This notebook assumes Terra is running custom Docker image ghcr.io/bro...
# TODO(deflaux): remove this cell after gcr.io/broad-ml4cvd/deeplearning:tf2-latest-gpu has this preinstalled. from ml4h.runtime_data_defines import determine_runtime from ml4h.runtime_data_defines import Runtime if Runtime.ML4H_VM == determine_runtime(): !pip3 install --user ipycanvas==0.7.0 ipyannotations==0.2.1 ...
_____no_output_____
BSD-3-Clause
notebooks/review_results/image_annotations.ipynb
deflaux/ml4h
Define the batch of samples to annotate Edit the CSV file path below, if needed, to either a local file or one in Cloud Storage.
#---[ EDIT AND RUN THIS CELL TO READ FROM A LOCAL FILE OR A FILE IN CLOUD STORAGE ]--- SAMPLE_BATCH_FILE = None if SAMPLE_BATCH_FILE: samples_df = pd.read_csv(tf.io.gfile.GFile(SAMPLE_BATCH_FILE)) else: # Normally these would all be the same or similar TMAP. We are using different ones here just to make it # mor...
_____no_output_____
BSD-3-Clause
notebooks/review_results/image_annotations.ipynb
deflaux/ml4h
Annotate the batch! Annotate with pointsUse points to annotate landmarks within the images.
# Note: a zoom level of 1.0 displays the tensor as-is. For higher zoom levels, this code currently # use the PIL library to scale the image. annotator = BatchImageAnnotator(samples=samples_df, zoom=2.0, annotation_categories=['region_of_interest'], ...
_____no_output_____
BSD-3-Clause
notebooks/review_results/image_annotations.ipynb
deflaux/ml4h
Annotate with polygonsUse polygons to annotate arbitrarily shaped regions within the images.
# Note: a zoom level of 1.0 displays the tensor as-is. For higher zoom levels, this code currently # use the PIL library to scale the image. annotator = BatchImageAnnotator(samples=samples_df, zoom=2.0, annotation_categories=['region_of_interest'], ...
_____no_output_____
BSD-3-Clause
notebooks/review_results/image_annotations.ipynb
deflaux/ml4h
Annotate with rectanglesUse rectangles to annotate rectangular regions within the image.
# Note: a zoom level of 1.0 displays the tensor as-is. For higher zoom levels, this code currently # use the PIL library to scale the image. annotator = BatchImageAnnotator(samples=samples_df, zoom=2.0, annotation_categories=['region_of_interest'], ...
_____no_output_____
BSD-3-Clause
notebooks/review_results/image_annotations.ipynb
deflaux/ml4h
View the stored annotations
annotator.view_recent_submissions(count=10)
_____no_output_____
BSD-3-Clause
notebooks/review_results/image_annotations.ipynb
deflaux/ml4h
Provenance
import datetime print(datetime.datetime.now()) %%bash pip3 freeze
_____no_output_____
BSD-3-Clause
notebooks/review_results/image_annotations.ipynb
deflaux/ml4h
'ewm' series is the most stationary out of all the series. Hence we model on 'ewm'
from pandas.tools.plotting import autocorrelation_plot autocorrelation_plot(ewm) from statsmodels.tsa.arima_model import ARIMA model = ARIMA(ewm, order = (15, 1, 0)) model_fit = model.fit(disp = 0) plt.plot(model_fit.fittedvalues) logpred_diff = pd.Series(model_fit.fittedvalues, index = ewm.index) logpred_cumsum = logp...
_____no_output_____
MIT
Gun Violence.ipynb
itsmepiyush2/Effects-of-Gun-Violence-forecast
Testing the functionalities of MetaTuner on bcancer dataset
from mango import MetaTuner # Define different classifiers from scipy.stats import uniform from sklearn import datasets from sklearn.neighbors import KNeighborsClassifier from sklearn.model_selection import cross_val_score data = datasets.load_breast_cancer() X = data.data Y = data.target
_____no_output_____
Apache-2.0
benchmarking/MetaTuner_Examples/MetaTuner-on-bcancer.ipynb
jashanmeet-collab/mango
XGBoost
from xgboost import XGBClassifier param_dict_xgboost = {"learning_rate": uniform(0, 1), "gamma": uniform(0, 5), "max_depth": range(1, 16), "n_estimators": range(1, 4), "booster":['gbtree','gblinear','dart'] } X_xgboost = X Y_xgboost = Y # import...
_____no_output_____
Apache-2.0
benchmarking/MetaTuner_Examples/MetaTuner-on-bcancer.ipynb
jashanmeet-collab/mango
KNN
param_dict_knn = {"n_neighbors": range(1, 101), 'algorithm' : ['auto', 'ball_tree', 'kd_tree', 'brute'] } X_knn = X Y_knn = Y def objective_knn(args_list): global X_knn,Y_knn results = [] for hyper_par in args_list: clf = KNeighborsClassifier() clf.s...
_____no_output_____
Apache-2.0
benchmarking/MetaTuner_Examples/MetaTuner-on-bcancer.ipynb
jashanmeet-collab/mango
SVM
from mango.domain.distribution import loguniform from sklearn import svm param_dict_svm = {"gamma": uniform(0.1, 4), "C": loguniform(-7, 10)} X_svm = X Y_svm = Y def objective_svm(args_list): global X_svm,Y_svm #print('SVM:',args_list) results = [] for hyper_par in args_list: ...
_____no_output_____
Apache-2.0
benchmarking/MetaTuner_Examples/MetaTuner-on-bcancer.ipynb
jashanmeet-collab/mango
Decision Tree
from sklearn.tree import DecisionTreeClassifier param_dict_dtree = { "max_features": ['auto', 'sqrt', 'log2'], "max_depth": range(1,21), "splitter":['best','random'], "criterion":['gini','entropy'] } X_dtree = X Y_dtree = Y print(X_dtree....
[0.9016522788452613, 0.9016244314489928, 0.6264204028589994, 0.6274204028589994, 0.924412884062007, 0.924403601596584, 0.9208948296667595, 0.9402394876079088, 0.91914972616727, 0.8700083542188805, 0.9208948296667595, 0.8893158822983386, 0.9384665367121507, 0.8752900770444629, 0.7431913116123643, 0.924403601596584, 0.88...
Apache-2.0
benchmarking/MetaTuner_Examples/MetaTuner-on-bcancer.ipynb
jashanmeet-collab/mango
A simple chart of function evaluations
def count_elements(seq): """Tally elements from `seq`.""" hist = {} for i in seq: hist[i] = hist.get(i, 0) + 1 return hist def ascii_histogram(seq): """A horizontal frequency-table/histogram plot.""" counted = count_elements(seq) for k in sorted(counted): print('{0:5d} {1}'....
0 ++++ 1 +++ 2 ++++++++++++ 3 +++++++++
Apache-2.0
benchmarking/MetaTuner_Examples/MetaTuner-on-bcancer.ipynb
jashanmeet-collab/mango
May be possible to entangle all ions with global pulse with multiple tones.
from numpy import * from scipy.optimize import curve_fit import matplotlib.pyplot as plt from Error_dist import func_str # 10-ion test N = 11 x = arange(1, N) y = x def func(x, a, b, c, d, e): return (a / x ** 0.5 + b / x ** 0.7 + c / x ** 1 + d / x ** 1.5 + e / x ** 2) # Assume entangling strengt\ scales as 1 ...
_____no_output_____
Apache-2.0
Global beam test.ipynb
jlfly12/qrsim
**4장 – 모델 훈련** _이 노트북은 4장에 있는 모든 샘플 코드와 연습문제 해답을 가지고 있습니다._ 구글 코랩에서 실행하기 설정 먼저 몇 개의 모듈을 임포트합니다. 맷플롯립 그래프를 인라인으로 출력하도록 만들고 그림을 저장하는 함수를 준비합니다. 또한 파이썬 버전이 3.5 이상인지 확인합니다(파이썬 2.x에서도 동작하지만 곧 지원이 중단되므로 파이썬 3을 사용하는 것이 좋습니다). 사이킷런 버전이 0.20 이상인지도 확인합니다.
# 파이썬 ≥3.5 필수 import sys assert sys.version_info >= (3, 5) # 사이킷런 ≥0.20 필수 import sklearn assert sklearn.__version__ >= "0.20" # 공통 모듈 임포트 import numpy as np import os # 노트북 실행 결과를 동일하게 유지하기 위해 np.random.seed(42) # 깔끔한 그래프 출력을 위해 %matplotlib inline import matplotlib as mpl import matplotlib.pyplot as plt mpl.rc('ax...
_____no_output_____
Apache-2.0
04_training_linear_models.ipynb
probationer070/handson-ml2
선형 회귀
import numpy as np X = 2 * np.random.rand(100, 1) y = 4 + 3 * X + np.random.randn(100, 1) plt.plot(X, y, "b.") plt.xlabel("$x_1$", fontsize=18) plt.ylabel("$y$", rotation=0, fontsize=18) plt.axis([0, 2, 0, 15]) save_fig("generated_data_plot") plt.show()
그림 저장: generated_data_plot
Apache-2.0
04_training_linear_models.ipynb
probationer070/handson-ml2
**식 4-4: 정규 방정식**$\hat{\boldsymbol{\theta}} = (\mathbf{X}^T \mathbf{X})^{-1} \mathbf{X}^T \mathbf{y}$
X_b = np.c_[np.ones((100, 1)), X] # 모든 샘플에 x0 = 1을 추가합니다. theta_best = np.linalg.inv(X_b.T.dot(X_b)).dot(X_b.T).dot(y) theta_best
_____no_output_____
Apache-2.0
04_training_linear_models.ipynb
probationer070/handson-ml2
$\hat{y} = \mathbf{X} \boldsymbol{\hat{\theta}}$
X_new = np.array([[0], [2]]) X_new_b = np.c_[np.ones((2, 1)), X_new] # 모든 샘플에 x0 = 1을 추가합니다. y_predict = X_new_b.dot(theta_best) y_predict plt.plot(X_new, y_predict, "r-") plt.plot(X, y, "b.") plt.axis([0, 2, 0, 15]) plt.show()
_____no_output_____
Apache-2.0
04_training_linear_models.ipynb
probationer070/handson-ml2
책에 있는 그림은 범례와 축 레이블이 있는 그래프입니다:
plt.plot(X_new, y_predict, "r-", linewidth=2, label="Predictions") plt.plot(X, y, "b.") plt.xlabel("$x_1$", fontsize=18) plt.ylabel("$y$", rotation=0, fontsize=18) plt.legend(loc="upper left", fontsize=14) plt.axis([0, 2, 0, 15]) save_fig("linear_model_predictions_plot") plt.show() from sklearn.linear_model import Line...
_____no_output_____
Apache-2.0
04_training_linear_models.ipynb
probationer070/handson-ml2
`LinearRegression` 클래스는 `scipy.linalg.lstsq()` 함수("least squares"의 약자)를 사용하므로 이 함수를 직접 사용할 수 있습니다:
# 싸이파이 lstsq() 함수를 사용하려면 scipy.linalg.lstsq(X_b, y)와 같이 씁니다. theta_best_svd, residuals, rank, s = np.linalg.lstsq(X_b, y, rcond=1e-6) theta_best_svd
_____no_output_____
Apache-2.0
04_training_linear_models.ipynb
probationer070/handson-ml2
이 함수는 $\mathbf{X}^+\mathbf{y}$을 계산합니다. $\mathbf{X}^{+}$는 $\mathbf{X}$의 _유사역행렬_ (pseudoinverse)입니다(Moore–Penrose 유사역행렬입니다). `np.linalg.pinv()`을 사용해서 유사역행렬을 직접 계산할 수 있습니다: $\boldsymbol{\hat{\theta}} = \mathbf{X}^{-1}\hat{y}$
np.linalg.pinv(X_b).dot(y)
_____no_output_____
Apache-2.0
04_training_linear_models.ipynb
probationer070/handson-ml2
경사 하강법 배치 경사 하강법 **식 4-6: 비용 함수의 그레이디언트 벡터**$\dfrac{\partial}{\partial \boldsymbol{\theta}} \text{MSE}(\boldsymbol{\theta}) = \dfrac{2}{m} \mathbf{X}^T (\mathbf{X} \boldsymbol{\theta} - \mathbf{y})$**식 4-7: 경사 하강법의 스텝**$\boldsymbol{\theta}^{(\text{next step})} = \boldsymbol{\theta} - \eta \dfrac{\partial}{\partial \bo...
eta = 0.1 # 학습률 n_iterations = 1000 m = 100 theta = np.random.randn(2,1) # 랜덤 초기화 for iteration in range(n_iterations): gradients = 2/m * X_b.T.dot(X_b.dot(theta) - y) theta = theta - eta * gradients theta X_new_b.dot(theta) theta_path_bgd = [] def plot_gradient_descent(theta, eta, theta_path=None): m ...
그림 저장: gradient_descent_plot
Apache-2.0
04_training_linear_models.ipynb
probationer070/handson-ml2
확률적 경사 하강법
theta_path_sgd = [] m = len(X_b) np.random.seed(42) n_epochs = 50 t0, t1 = 5, 50 # 학습 스케줄 하이퍼파라미터 def learning_schedule(t): return t0 / (t + t1) theta = np.random.randn(2,1) # 랜덤 초기화 for epoch in range(n_epochs): for i in range(m): if epoch == 0 and i < 20: # 책에는 없음 y...
_____no_output_____
Apache-2.0
04_training_linear_models.ipynb
probationer070/handson-ml2
미니배치 경사 하강법
theta_path_mgd = [] n_iterations = 50 minibatch_size = 20 np.random.seed(42) theta = np.random.randn(2,1) # 랜덤 초기화 t0, t1 = 200, 1000 def learning_schedule(t): return t0 / (t + t1) t = 0 for epoch in range(n_iterations): shuffled_indices = np.random.permutation(m) X_b_shuffled = X_b[shuffled_indices] ...
그림 저장: gradient_descent_paths_plot
Apache-2.0
04_training_linear_models.ipynb
probationer070/handson-ml2
다항 회귀
import numpy as np import numpy.random as rnd np.random.seed(42) m = 100 X = 6 * np.random.rand(m, 1) - 3 y = 0.5 * X**2 + X + 2 + np.random.randn(m, 1) plt.plot(X, y, "b.") plt.xlabel("$x_1$", fontsize=18) plt.ylabel("$y$", rotation=0, fontsize=18) plt.axis([-3, 3, 0, 10]) save_fig("quadratic_data_plot") plt.show() f...
그림 저장: high_degree_polynomials_plot
Apache-2.0
04_training_linear_models.ipynb
probationer070/handson-ml2
학습 곡선
from sklearn.metrics import mean_squared_error from sklearn.model_selection import train_test_split def plot_learning_curves(model, X, y): X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2, random_state=10) train_errors, val_errors = [], [] for m in range(1, len(X_train) + 1): m...
그림 저장: learning_curves_plot
Apache-2.0
04_training_linear_models.ipynb
probationer070/handson-ml2
규제가 있는 선형 모델 릿지 회귀
np.random.seed(42) m = 20 X = 3 * np.random.rand(m, 1) y = 1 + 0.5 * X + np.random.randn(m, 1) / 1.5 X_new = np.linspace(0, 3, 100).reshape(100, 1)
_____no_output_____
Apache-2.0
04_training_linear_models.ipynb
probationer070/handson-ml2
**식 4-8: 릿지 회귀의 비용 함수**$J(\boldsymbol{\theta}) = \text{MSE}(\boldsymbol{\theta}) + \alpha \dfrac{1}{2}\sum\limits_{i=1}^{n}{\theta_i}^2$
from sklearn.linear_model import Ridge ridge_reg = Ridge(alpha=1, solver="cholesky", random_state=42) ridge_reg.fit(X, y) ridge_reg.predict([[1.5]]) ridge_reg = Ridge(alpha=1, solver="sag", random_state=42) ridge_reg.fit(X, y) ridge_reg.predict([[1.5]]) from sklearn.linear_model import Ridge def plot_model(model_class...
그림 저장: ridge_regression_plot
Apache-2.0
04_training_linear_models.ipynb
probationer070/handson-ml2
**노트**: 향후 버전이 바뀌더라도 동일한 결과를 만들기 위해 사이킷런 0.21 버전의 기본값인 `max_iter=1000`과 `tol=1e-3`으로 지정합니다.
sgd_reg = SGDRegressor(penalty="l2", max_iter=1000, tol=1e-3, random_state=42) sgd_reg.fit(X, y.ravel()) sgd_reg.predict([[1.5]])
_____no_output_____
Apache-2.0
04_training_linear_models.ipynb
probationer070/handson-ml2