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
As before, a list of tuples with custom names can be passed:
ftuples = [('Durchschnitt', 'mean'), ('Abweichung', np.var)] #@P: mean and var is named with different name as Durchschnitt and Abweichung) grouped[['tip_pct', 'total_bill']].agg(ftuples)
_____no_output_____
MIT
10_Data Aggregation and Group Operations.ipynb
quangphu1912/Py-data-analysis-McKinney
Now, suppose you wanted to *apply potentially different functions* to one or more of the columns. To do this, `pass a dict to agg that contains a mapping of column names` to any of the function specifications listed so far:
grouped.agg({'tip' : np.max, 'size' : 'sum'}) grouped.agg({'tip_pct' : ['min', 'max', 'mean', 'std'], 'size' : 'sum'})
_____no_output_____
MIT
10_Data Aggregation and Group Operations.ipynb
quangphu1912/Py-data-analysis-McKinney
10.2.2. Returning Aggregated Data Without Row Indexes In all of the examples up until now, `the aggregated data comes back with an index, potentially hierarchical, composed from the unique group key combinations`. Since this isn’t always desirable, *you can disable this behavior in most cases by passing* `as_index=Fal...
tips.groupby(['day', 'smoker'], as_index=False).mean()
_____no_output_____
MIT
10_Data Aggregation and Group Operations.ipynb
quangphu1912/Py-data-analysis-McKinney
10.3. Apply: General split-apply-combine 10.3.0 Returning to the tipping dataset from before, *suppose you wanted to select the top five tip_pct values by group*. * First, write a function that selects the rows with the largest values in a particular column:
def top(df, n=5, column='tip_pct'): return df.sort_values(by=column)[-n:] top(tips, n=6)
_____no_output_____
MIT
10_Data Aggregation and Group Operations.ipynb
quangphu1912/Py-data-analysis-McKinney
Now, if we group by smoker, say, and call apply with this function, we get the following:
tips.groupby('smoker').apply(top)
_____no_output_____
MIT
10_Data Aggregation and Group Operations.ipynb
quangphu1912/Py-data-analysis-McKinney
What has happened here? * The top function is called on each row group from the DataFrame, and then the results are glued together using `pandas.concat`, labeling the pieces with the group names. The result therefore has *a hierarchical index* whose inner level contains index values from the original DataFrame. If you ...
tips.groupby(['smoker', 'day']).apply(top, n=1, column='total_bill') #@P: additional config to the function: n= 1 and apply the function on column total_bill, not the default n =5 and column='tip_pct'
_____no_output_____
MIT
10_Data Aggregation and Group Operations.ipynb
quangphu1912/Py-data-analysis-McKinney
**NOTE** Beyond these basic usage mechanics, getting the most out of apply may require some creativity. What occurs inside the function passed is up to you; `it only needs to return a pandas object or a scalar value`. The rest of this chapter will mainly consist of examples showing you how to solve various problems usi...
result = tips.groupby('smoker')['tip_pct'].describe() result result.unstack('smoker')
_____no_output_____
MIT
10_Data Aggregation and Group Operations.ipynb
quangphu1912/Py-data-analysis-McKinney
Inside GroupBy, when you invoke a method like `describe`, *it is actually just a shortcut for*:
f = lambda x: x.describe() grouped.apply(f)
_____no_output_____
MIT
10_Data Aggregation and Group Operations.ipynb
quangphu1912/Py-data-analysis-McKinney
10.3.1. Suppressing the Group Keys In the preceding examples, you see that the *resulting object has a hierarchical index* formed from the group keys along with the indexes of each piece of the original object. You can *disable this by passing* `group_keys=False`to *groupby*:
tips.groupby('smoker', group_keys=False).apply(top)
_____no_output_____
MIT
10_Data Aggregation and Group Operations.ipynb
quangphu1912/Py-data-analysis-McKinney
10.3.2. Quantile and Bucket Analysis As you may `recall from Chapter 8`, pandas has some tools, in particular `cut and qcut`, *for slicing data up into buckets with bins of your choosing or by sample quantiles*. `Combining these functions with groupby makes it convenient to perform bucket or quantile analysis on a dat...
#@P checking syntax docstring np.random.randn?? #@P checking syntax docstring pd.cut? frame = pd.DataFrame({'data1': np.random.randn(1000), 'data2': np.random.randn(1000)}) quartiles = pd.cut(frame.data1, 4) #@P: cut the data1 to 4 group (not equal) quartiles[:10]
_____no_output_____
MIT
10_Data Aggregation and Group Operations.ipynb
quangphu1912/Py-data-analysis-McKinney
The `Categorical object` `returned by cut` can be passed directly to groupby. So we could compute a set of statistics for the data2 column like so:
#@P vietsub: get_stats is to obtain min, max, count, mean of the group def get_stats(group): return {'min': group.min(), 'max': group.max(), 'count': group.count(), 'mean': group.mean()} grouped = frame.data2.groupby(quartiles) grouped.apply(get_stats).unstack()
_____no_output_____
MIT
10_Data Aggregation and Group Operations.ipynb
quangphu1912/Py-data-analysis-McKinney
These were equal-length buckets; to `compute equal-size buckets based on sample quantiles`, use `qcut`. I’ll pass labels=False to just get quantile numbers:
pd.qcut?? # Return quantile numbers grouping = pd.qcut(frame.data1, 10, labels=False) #cut data1 to 10 equal group grouped = frame.data2.groupby(grouping) grouped.apply(get_stats).unstack()
_____no_output_____
MIT
10_Data Aggregation and Group Operations.ipynb
quangphu1912/Py-data-analysis-McKinney
10.3.3. Example: Filling Missing Values with Group-Specific Values When cleaning up missing data, in some cases you will replace data observations using dropna, but in others you may want to impute (fill in) the null (NA) values using a fixed value or some value derived from the data. `fillna is the right tool t...
s = pd.Series(np.random.randn(6)) s[::2] = np.nan s s.fillna(s.mean())
_____no_output_____
MIT
10_Data Aggregation and Group Operations.ipynb
quangphu1912/Py-data-analysis-McKinney
`Suppose you need the fill value to vary by group`. One way to do this is to group the data and use apply with a function that calls fillna on each data chunk. Here is some sample data on US states divided into eastern and western regions:
states = ['Ohio', 'New York', 'Vermont', 'Florida', 'Oregon', 'Nevada', 'California', 'Idaho'] group_key = ['East'] * 4 + ['West'] * 4 data = pd.Series(np.random.randn(8), index=states) data
_____no_output_____
MIT
10_Data Aggregation and Group Operations.ipynb
quangphu1912/Py-data-analysis-McKinney
Note that the syntax ['East'] * 4 produces a list containing four copies of the elements in ['East']. Adding lists together concatenates them. Let’s set some values in the data to be missing:
data[['Vermont', 'Nevada', 'Idaho']] = np.nan data data.groupby(group_key).mean()
_____no_output_____
MIT
10_Data Aggregation and Group Operations.ipynb
quangphu1912/Py-data-analysis-McKinney
We can fill the NA values using the group means like so:
fill_mean = lambda g: g.fillna(g.mean()) data.groupby(group_key).apply(fill_mean)
_____no_output_____
MIT
10_Data Aggregation and Group Operations.ipynb
quangphu1912/Py-data-analysis-McKinney
In another case, you might have predefined fill values in your code that vary by group. Since the groups have a `name` attribute set internally, we can use that:
fill_values = {'East': 0.5, 'West': -1} fill_func = lambda g: g.fillna(fill_values[g.name]) data.groupby(group_key).apply(fill_func)
_____no_output_____
MIT
10_Data Aggregation and Group Operations.ipynb
quangphu1912/Py-data-analysis-McKinney
10.3.4. Example: Random Sampling and Permutation `Suppose you wanted to draw a random sample (with or without replacement) from a large dataset` for Monte Carlo simulation purposes or some other application. *There are a number of ways to perform the “draws”*; *here we use the sample method for Series*. To demonstrate...
# Hearts, Spades, Clubs, Diamonds suits = ['H', 'S', 'C', 'D'] card_val = (list(range(1, 11)) + [10] * 3) * 4 #@P: đoạn 10 *3 để thêm value cho J, K, Q = 10 như kết quả bên dưới base_names = ['A'] + list(range(2, 11)) + ['J', 'K', 'Q'] cards = [] for suit in ['H', 'S', 'C', 'D']: cards.extend(str(num) + suit...
_____no_output_____
MIT
10_Data Aggregation and Group Operations.ipynb
quangphu1912/Py-data-analysis-McKinney
So now we have a Series of length 52 whose index contains card names and values are the ones used in Blackjack and other games (to keep things simple, I just let the ace 'A' be 1):
deck[:20]
_____no_output_____
MIT
10_Data Aggregation and Group Operations.ipynb
quangphu1912/Py-data-analysis-McKinney
Now, based on what I said before, drawing a hand of five cards from the deck could be written as:
def draw(deck, n=5): return deck.sample(n) draw(deck)
_____no_output_____
MIT
10_Data Aggregation and Group Operations.ipynb
quangphu1912/Py-data-analysis-McKinney
Suppose you wanted two random cards from each suit (@P: suits = ['H', 'S', 'C', 'D'] -- Hearts, Spades, Clubs, Diamonds). Because the suit is the last character of each card name, we can group based on this and use apply:
get_suit = lambda card: card[-1] # last letter is suit deck.groupby(get_suit).apply(draw, n=2)
_____no_output_____
MIT
10_Data Aggregation and Group Operations.ipynb
quangphu1912/Py-data-analysis-McKinney
Alternatively, we could write:
deck.groupby(get_suit, group_keys=False).apply(draw, n=2)
_____no_output_____
MIT
10_Data Aggregation and Group Operations.ipynb
quangphu1912/Py-data-analysis-McKinney
10.3.5. Example: Group Weighted Average and Correlation Under the split-apply-combine paradigm of `groupby`, operations between columns in a DataFrame or two Series, such as a group weighted average, are possible. As an example, take this dataset containing group keys, values, and some weights:
df = pd.DataFrame({'category': ['a', 'a', 'a', 'a', 'b', 'b', 'b', 'b'], 'data': np.random.randn(8), 'weights': np.random.rand(8)}) df
_____no_output_____
MIT
10_Data Aggregation and Group Operations.ipynb
quangphu1912/Py-data-analysis-McKinney
The group weighted average by `category` would then be:
grouped = df.groupby('category') get_wavg = lambda g: np.average(g['data'], weights=g['weights']) grouped.apply(get_wavg)
_____no_output_____
MIT
10_Data Aggregation and Group Operations.ipynb
quangphu1912/Py-data-analysis-McKinney
As another example, consider a financial dataset originally obtained from Yahoo! Finance containing end-of-day prices for a few stocks and the S&P 500 index (the SPX symbol):
close_px = pd.read_csv('examples/stock_px_2.csv', parse_dates=True, index_col=0) close_px.info() close_px[-4:]
<class 'pandas.core.frame.DataFrame'> DatetimeIndex: 2214 entries, 2003-01-02 to 2011-10-14 Data columns (total 4 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 AAPL 2214 non-null float64 1 MSFT 2214 non-null float64 2 XOM 2214 non-null float64 3 SPX ...
MIT
10_Data Aggregation and Group Operations.ipynb
quangphu1912/Py-data-analysis-McKinney
One task of interest might be to compute a DataFrame consisting of the yearly correlations of daily returns (computed from percent changes) with SPX. As one way to do this, we first create a function that computes the pairwise correlation of each column with the 'SPX' column:
spx_corr = lambda x: x.corrwith(x['SPX']) #@P 20210903: SPX: S&P500 Index
_____no_output_____
MIT
10_Data Aggregation and Group Operations.ipynb
quangphu1912/Py-data-analysis-McKinney
Next, we compute percent change on `close_px` using `pct_change`:
rets = close_px.pct_change().dropna()
_____no_output_____
MIT
10_Data Aggregation and Group Operations.ipynb
quangphu1912/Py-data-analysis-McKinney
Lastly, we group these percent changes by year, which can be extracted from each row label with a one-line function that returns the `year` attribute of each `datetime` label:
get_year = lambda x: x.year by_year = rets.groupby(get_year) by_year.apply(spx_corr)
_____no_output_____
MIT
10_Data Aggregation and Group Operations.ipynb
quangphu1912/Py-data-analysis-McKinney
You could also compute inter-column correlations. Here we compute the annual correlation between Apple and Microsoft:
by_year.apply(lambda g: g['AAPL'].corr(g['MSFT']))
_____no_output_____
MIT
10_Data Aggregation and Group Operations.ipynb
quangphu1912/Py-data-analysis-McKinney
10.3.6. Example: Group-Wise Linear Regression In the same theme as the previous example, you can use `groupby` to perform more complex group-wise statistical analysis, as long as the function returns a pandas object or scalar value. For example, I can define the following `regress` function (using the `statsmodels` ec...
import statsmodels.api as sm def regress(data, yvar, xvars): Y = data[yvar] X = data[xvars] X['intercept'] = 1. result = sm.OLS(Y, X).fit() return result.params
_____no_output_____
MIT
10_Data Aggregation and Group Operations.ipynb
quangphu1912/Py-data-analysis-McKinney
Now, to run a yearly linear regression of *AAPL* on *SPX* returns, execute:
by_year.apply(regress, 'AAPL', ['SPX'])
_____no_output_____
MIT
10_Data Aggregation and Group Operations.ipynb
quangphu1912/Py-data-analysis-McKinney
10.4. Pivot Tables and Cross-Tabulation A pivot table is a data summarization tool frequently found in spreadsheet programs and other data analysis software. It aggregates a table of data by one or more keys, arranging the data in a rectangle with some of the group keys along the rows and some along the columns. `Pivo...
tips.pivot_table(index=['day', 'smoker'])
_____no_output_____
MIT
10_Data Aggregation and Group Operations.ipynb
quangphu1912/Py-data-analysis-McKinney
`This could have been produced with groupby directly`. Now, suppose we want to aggregate only *tip_pct* and *size*, and additionally group by time. I’ll put *smoker* in the table columns and *day* in the rows:
tips.pivot_table(['tip_pct', 'size'], index=['time', 'day'], columns='smoker')
_____no_output_____
MIT
10_Data Aggregation and Group Operations.ipynb
quangphu1912/Py-data-analysis-McKinney
We could augment this table to include partial totals by passing *margins=True*. This has the effect of *adding All row and column labels*, with corresponding values being the group statistics for all the data within a single tier: @P 20210903: it like a subtotal for each group in Excel pivotable? (P guess they use the...
tips.pivot_table(['tip_pct', 'size'], index=['time', 'day'], columns='smoker', margins=True)
_____no_output_____
MIT
10_Data Aggregation and Group Operations.ipynb
quangphu1912/Py-data-analysis-McKinney
Here, the All values are means without taking into account smoker versus non-smoker (the All columns) or any of the two levels of grouping on the rows (the All row). *To use a different aggregation function*, pass it to `aggfunc`. For example, *'count'* or *len* will give you a cross-tabulation (count or frequency) of ...
tips.pivot_table('tip_pct', index=['time', 'smoker'], columns='day', aggfunc=len, margins=True)
_____no_output_____
MIT
10_Data Aggregation and Group Operations.ipynb
quangphu1912/Py-data-analysis-McKinney
If some combinations are empty (or otherwise NA), you may wish to pass a `fill_value`:
tips.pivot_table('tip_pct', index=['time', 'size', 'smoker'], columns='day', aggfunc='mean', fill_value=0)
_____no_output_____
MIT
10_Data Aggregation and Group Operations.ipynb
quangphu1912/Py-data-analysis-McKinney
10.4.1 Cross-Tabulations: Crosstab A `cross-tabulation` (or `crosstab` for short) is *a special case* of a pivot table that computes group frequencies. Here is an example:
from io import StringIO data = """\ Sample Nationality Handedness 1 USA Right-handed 2 Japan Left-handed 3 USA Right-handed 4 Japan Right-handed 5 Japan Left-handed 6 Japan Right-handed 7 USA Right-handed 8 USA Left-handed 9 Japan Right-handed 10 USA Right-handed""" ...
_____no_output_____
MIT
10_Data Aggregation and Group Operations.ipynb
quangphu1912/Py-data-analysis-McKinney
As part of some survey analysis, we might want to summarize this data by nationality and handedness. *You could use pivot_table to do this*, but the `pandas.crosstab function` can be more convenient:
pd.crosstab(data.Nationality, data.Handedness, margins=True)
_____no_output_____
MIT
10_Data Aggregation and Group Operations.ipynb
quangphu1912/Py-data-analysis-McKinney
*The first two arguments to crosstab *can each either `be an array` or `Series` or `a list of arrays`. As in the tips data:
pd.crosstab([tips.time, tips.day], tips.smoker, margins=True) pd.options.display.max_rows = PREVIOUS_MAX_ROWS
_____no_output_____
MIT
10_Data Aggregation and Group Operations.ipynb
quangphu1912/Py-data-analysis-McKinney
区域卷积神经网络(R-CNN)系列:label:`sec_rcnn`除了 :numref:`sec_ssd` 中描述的单发多框检测之外,区域卷积神经网络(region-based CNN或regions with CNN features,R-CNN) :cite:`Girshick.Donahue.Darrell.ea.2014` 也是将深度模型应用于目标检测的开创性工作之一。在本节中,我们将介绍R-CNN及其一系列改进方法:快速的R-CNN(Fast R-CNN) :cite:`Girshick.2015` 、更快的R-CNN(Faster R-CNN) :cite:`Ren.He.Girshick.ea.2015` 和掩码R...
import torch import torchvision X = torch.arange(16.).reshape(1, 1, 4, 4) X
_____no_output_____
MIT
d2l/chapter_computer-vision/rcnn.ipynb
atlasbioinfo/myDLNotes_Pytorch
让我们进一步假设输入图像的高度和宽度都是40像素,且选择性搜索在此图像上生成了两个提议区域。每个区域由5个元素表示:区域目标类别、左上角和右下角的 $(x, y)$ 坐标。
rois = torch.Tensor([[0, 0, 0, 20, 20], [0, 0, 10, 30, 30]])
_____no_output_____
MIT
d2l/chapter_computer-vision/rcnn.ipynb
atlasbioinfo/myDLNotes_Pytorch
由于 `X` 的高和宽是输入图像高和宽的 $1/10$,因此,两个提议区域的坐标先按 `spatial_scale` 乘以 0.1。然后,在 `X` 上分别标出这两个兴趣区域 `X[:, :, 1:4, 0:4]` 和 `X[:, :, 1:4, 0:4]` 。最后,在 $2\times 2$ 的兴趣区域汇聚层中,每个兴趣区域被划分为子窗口网格,并进一步抽取相同形状 $2\times 2$ 的特征。
torchvision.ops.roi_pool(X, rois, output_size=(2, 2), spatial_scale=0.1)
_____no_output_____
MIT
d2l/chapter_computer-vision/rcnn.ipynb
atlasbioinfo/myDLNotes_Pytorch
Clean ZIMAS / zoning file* Dissolve zoning file so they are multipolygons* Use parser in `laplan.zoning` to parse ZONE_CMPLT* Manually list the failed to parse observations and fix* Use this to build crosswalk of height, density, etc restrictions
import boto3 import geopandas as gpd import intake import numpy as np import os import pandas as pd import laplan import utils catalog = intake.open_catalog("../catalogs/*.yml") s3 = boto3.client('s3') bucket_name = 'city-planning-entitlements' # Default value of display.max_rows is 10 i.e. at max 10 rows will be prin...
# obs in zoning: 60588 # unique types of zoning: 1934
Apache-2.0
notebooks/A3-parse-zoning.ipynb
CityOfLosAngeles/planning-entitlements
Parse zoning string
parsed_col_names = ['Q', 'T', 'zone_class', 'specific_plan', 'height_district', 'D', 'overlay'] def parse_zoning(row): try: z = laplan.zoning.ZoningInfo(row.ZONE_CMPLT) return pd.Series([z.Q, z.T, z.zone_class, z.specific_plan, z.height_district, z.D, z.overlay], index = p...
_____no_output_____
Apache-2.0
notebooks/A3-parse-zoning.ipynb
CityOfLosAngeles/planning-entitlements
Fix parse fails
fails_crosswalk = pd.read_parquet(f's3://{bucket_name}/data/crosswalk_zone_parse_fails.parquet') print(f'# obs in fails_crosswalk: {len(fails_crosswalk)}') # Grab all obs in our df that shows up in the fails_crosswalk, even if it was parsed correctly # There were some other ones that were added because they weren't va...
# obs in df: 1934 # obs in df2: 1934
Apache-2.0
notebooks/A3-parse-zoning.ipynb
CityOfLosAngeles/planning-entitlements
Need to do something about overlays and specific plans...* leave as list? -> then split (ZONE_CMPLT, geometry) from the rest, so we can save geojson and tabular separately* GeoJSON can't take lists. Convert to strings...later make it a list again?
# Fill in Nones, otherwise cannot do the apply to make the list a string df2.overlay = df2.overlay.fillna('') just_overlay = df2[df2.overlay != ''][['ZONE_CMPLT', 'overlay']] just_overlay['no_brackets'] = just_overlay['overlay'].apply(', '.join) split = just_overlay.no_brackets.str.split(',', expand = True).fillna('')...
_____no_output_____
Apache-2.0
notebooks/A3-parse-zoning.ipynb
CityOfLosAngeles/planning-entitlements
Merge and export
col_order = ['ZONE_CMPLT', 'ZONE_SMRY', 'Q', 'T', 'zone_class', 'height_district', 'D', 'specific_plan', 'no_brackets', 'geometry'] # Geometry is messed up, so let's get it back from original dissolve final = (pd.merge(df[['ZONE_CMPLT', 'geometry']], df3.drop(columns = "geometry"), ...
Path name: ../gis/raw/parsed_zoning Dirname (1st element of path): ../gis/raw/parsed_zoning Shapefile name: parsed_zoning.shp Shapefile component parts folder: ../gis/raw/parsed_zoning/parsed_zoning.shp
Apache-2.0
notebooks/A3-parse-zoning.ipynb
CityOfLosAngeles/planning-entitlements
Flax BasicsThis notebook will walk you through the following workflow:* Instantiating a model from Flax built-in layers or third-party models.* Initializing parameters of the model and manually written training.* Using optimizers provided by Flax to ease training.* Serialization of parameters and other objects...
# Install the latest JAXlib version. !pip install --upgrade -q pip jax jaxlib # Install Flax at head: !pip install --upgrade -q git+https://github.com/google/flax.git import jax from typing import Any, Callable, Sequence, Optional from jax import lax, random, numpy as jnp import flax from flax.core import freeze, unfre...
_____no_output_____
Apache-2.0
docs/notebooks/flax_basics.ipynb
harry-stark/flax
Linear regression with FlaxIn the previous *JAX for the impatient* notebook, we finished up with a linear regression example. As we know, linear regression can also be written as a single dense neural network layer, which we will show in the following so that we can compare how it's done.A dense layer is a layer that ...
# We create one dense layer instance (taking 'features' parameter as input) model = nn.Dense(features=5)
_____no_output_____
Apache-2.0
docs/notebooks/flax_basics.ipynb
harry-stark/flax
Layers (and models in general, we'll use that word from now on) are subclasses of the `linen.Module` class. Model parameters & initializationParameters are not stored with the models themselves. You need to initialize parameters by calling the `init` function, using a PRNGKey and a dummy input parameter.
key1, key2 = random.split(random.PRNGKey(0)) x = random.normal(key1, (10,)) # Dummy input params = model.init(key2, x) # Initialization call jax.tree_map(lambda x: x.shape, params) # Checking output shapes
WARNING:absl:No GPU/TPU found, falling back to CPU. (Set TF_CPP_MIN_LOG_LEVEL=0 and rerun for more info.)
Apache-2.0
docs/notebooks/flax_basics.ipynb
harry-stark/flax
*Note: JAX and Flax, like NumPy, are row-based systems, meaning that vectors are represented as row vectors and not column vectors. This can be seen in the shape of the kernel here.*The result is what we expect: bias and kernel parameters of the correct size. Under the hood:* The dummy input variable `x` is used to t...
try: params['new_key'] = jnp.ones((2,2)) except ValueError as e: print("Error: ", e)
Error: FrozenDict is immutable.
Apache-2.0
docs/notebooks/flax_basics.ipynb
harry-stark/flax
To evaluate the model with a given set of parameters (never stored with the model), we just use the `apply` method by providing it the parameters to use as well as the input:
model.apply(params, x)
_____no_output_____
Apache-2.0
docs/notebooks/flax_basics.ipynb
harry-stark/flax
Gradient descentIf you jumped here directly without going through the JAX part, here is the linear regression formulation we're going to use: from a set of data points $\{(x_i,y_i), i\in \{1,\ldots, k\}, x_i\in\mathbb{R}^n,y_i\in\mathbb{R}^m\}$, we try to find a set of parameters $W\in \mathcal{M}_{m,n}(\mathbb{R}), b...
# Set problem dimensions. n_samples = 20 x_dim = 10 y_dim = 5 # Generate random ground truth W and b. key = random.PRNGKey(0) k1, k2 = random.split(key) W = random.normal(k1, (x_dim, y_dim)) b = random.normal(k2, (y_dim,)) # Store the parameters in a pytree. true_params = freeze({'params': {'bias': b, 'kernel': W}}) ...
x shape: (20, 10) ; y shape: (20, 5)
Apache-2.0
docs/notebooks/flax_basics.ipynb
harry-stark/flax
We copy the same training loop that we used in the JAX pytree linear regression example with `jax.value_and_grad()`, but here we can use `model.apply()` instead of having to define our own feed-forward function (`predict_pytree()` in the JAX example).
# Same as JAX version but using model.apply(). def mse(params, x_batched, y_batched): # Define the squared loss for a single pair (x,y) def squared_error(x, y): pred = model.apply(params, x) return jnp.inner(y-pred, y-pred) / 2.0 # Vectorize the previous to compute the average of the loss on all samples. ...
_____no_output_____
Apache-2.0
docs/notebooks/flax_basics.ipynb
harry-stark/flax
And finally perform the gradient descent.
learning_rate = 0.3 # Gradient step size. print('Loss for "true" W,b: ', mse(true_params, x_samples, y_samples)) loss_grad_fn = jax.value_and_grad(mse) @jax.jit def update_params(params, learning_rate, grads): params = jax.tree_map( lambda p, g: p - learning_rate * g, params, grads) return params for i in ...
Loss for "true" W,b: 0.023639778 Loss step 0: 38.094772 Loss step 10: 0.44692168 Loss step 20: 0.10053458 Loss step 30: 0.035822745 Loss step 40: 0.018846875 Loss step 50: 0.013864839 Loss step 60: 0.012312559 Loss step 70: 0.011812928 Loss step 80: 0.011649306 Loss step 90: 0.011595251 Loss step 100: 0.011...
Apache-2.0
docs/notebooks/flax_basics.ipynb
harry-stark/flax
Optimizing with OptaxFlax used to use its own `flax.optim` package for optimization, but with[FLIP 1009](https://github.com/google/flax/blob/main/docs/flip/1009-optimizer-api.md)this was deprecated in favor of[Optax](https://github.com/deepmind/optax).Basic usage of Optax is straightforward:1. Choose an optimization...
import optax tx = optax.sgd(learning_rate=learning_rate) opt_state = tx.init(params) loss_grad_fn = jax.value_and_grad(mse) for i in range(101): loss_val, grads = loss_grad_fn(params, x_samples, y_samples) updates, opt_state = tx.update(grads, opt_state) params = optax.apply_updates(params, updates) if i % 10 =...
Loss step 0: 0.011576377 Loss step 10: 0.0115710115 Loss step 20: 0.011569244 Loss step 30: 0.011568661 Loss step 40: 0.011568454 Loss step 50: 0.011568379 Loss step 60: 0.011568358 Loss step 70: 0.01156836 Loss step 80: 0.01156835 Loss step 90: 0.011568353 Loss step 100: 0.011568348
Apache-2.0
docs/notebooks/flax_basics.ipynb
harry-stark/flax
Serializing the resultNow that we're happy with the result of our training, we might want to save the model parameters to load them back later. Flax provides a serialization package to enable you to do that.
from flax import serialization bytes_output = serialization.to_bytes(params) dict_output = serialization.to_state_dict(params) print('Dict output') print(dict_output) print('Bytes output') print(bytes_output)
Dict output {'params': {'bias': DeviceArray([-1.4540135, -2.0262308, 2.0806582, 1.2201802, -0.9964547], dtype=float32), 'kernel': DeviceArray([[ 1.0106664 , 0.19014716, 0.04533899, -0.92722285, 0.34720102], [ 1.7320251 , 0.9901233 , 1.1662225 , 1.1027892 , -0....
Apache-2.0
docs/notebooks/flax_basics.ipynb
harry-stark/flax
To load the model back, you'll need to use as a template the model parameter structure, like the one you would get from the model initialization. Here, we use the previously generated `params` as a template. Note that this will produce a new variable structure, and not mutate in-place.*The point of enforcing structure ...
serialization.from_bytes(params, bytes_output)
_____no_output_____
Apache-2.0
docs/notebooks/flax_basics.ipynb
harry-stark/flax
Defining your own modelsFlax allows you to define your own models, which should be a bit more complicated than a linear regression. In this section, we'll show you how to build simple models. To do so, you'll need to create subclasses of the base `nn.Module` class.*Keep in mind that we imported* `linen as nn` *and thi...
class ExplicitMLP(nn.Module): features: Sequence[int] def setup(self): # we automatically know what to do with lists, dicts of submodules self.layers = [nn.Dense(feat) for feat in self.features] # for single submodules, we would just write: # self.layer1 = nn.Dense(feat1) def __call__(self, inpu...
initialized parameter shapes: {'params': {'layers_0': {'bias': (3,), 'kernel': (4, 3)}, 'layers_1': {'bias': (4,), 'kernel': (3, 4)}, 'layers_2': {'bias': (5,), 'kernel': (4, 5)}}} output: [[ 4.2292815e-02 -4.3807115e-02 2.9323792e-02 6.5492536e-03 -1.7147182e-02] [ 1.2967806e-01 -1.4551792e-01 9.4432183e-02 1...
Apache-2.0
docs/notebooks/flax_basics.ipynb
harry-stark/flax
As we can see, a `nn.Module` subclass is made of:* A collection of data fields (`nn.Module` are Python dataclasses) - here we only have the `features` field of type `Sequence[int]`.* A `setup()` method that is being called at the end of the `__postinit__` where you can register submodules, variables, parameters you...
try: y = model(x) # Returns an error except AttributeError as e: print(e)
"ExplicitMLP" object has no attribute "layers"
Apache-2.0
docs/notebooks/flax_basics.ipynb
harry-stark/flax
Since here we have a very simple model, we could have used an alternative (but equivalent) way of declaring the submodules inline in the `__call__` using the `@nn.compact` annotation like so:
class SimpleMLP(nn.Module): features: Sequence[int] @nn.compact def __call__(self, inputs): x = inputs for i, feat in enumerate(self.features): x = nn.Dense(feat, name=f'layers_{i}')(x) if i != len(self.features) - 1: x = nn.relu(x) # providing a name is optional though! #...
initialized parameter shapes: {'params': {'layers_0': {'bias': (3,), 'kernel': (4, 3)}, 'layers_1': {'bias': (4,), 'kernel': (3, 4)}, 'layers_2': {'bias': (5,), 'kernel': (4, 5)}}} output: [[ 4.2292815e-02 -4.3807115e-02 2.9323792e-02 6.5492536e-03 -1.7147182e-02] [ 1.2967806e-01 -1.4551792e-01 9.4432183e-02 1...
Apache-2.0
docs/notebooks/flax_basics.ipynb
harry-stark/flax
There are, however, a few differences you should be aware of between the two declaration modes:* In `setup`, you are able to name some sublayers and keep them around for further use (e.g. encoder/decoder methods in autoencoders).* If you want to have multiple methods, then you **need** to declare the module using `...
class SimpleDense(nn.Module): features: int kernel_init: Callable = nn.initializers.lecun_normal() bias_init: Callable = nn.initializers.zeros @nn.compact def __call__(self, inputs): kernel = self.param('kernel', self.kernel_init, # Initialization function ...
initialized parameters: FrozenDict({ params: { kernel: DeviceArray([[ 0.6503669 , 0.86789787, 0.4604268 ], [ 0.05673932, 0.9909285 , -0.63536596], [ 0.76134115, -0.3250529 , -0.65221626], [-0.82430327, 0.4150194 , 0.19405058]], dtype=float...
Apache-2.0
docs/notebooks/flax_basics.ipynb
harry-stark/flax
Here, we see how to both declare and assign a parameter to the model using the `self.param` method. It takes as input `(name, init_fn, *init_args)` : * `name` is simply the name of the parameter that will end up in the parameter structure.* `init_fn` is a function with input `(PRNGKey, *init_args)` returning an Arr...
class BiasAdderWithRunningMean(nn.Module): decay: float = 0.99 @nn.compact def __call__(self, x): # easy pattern to detect if we're initializing via empty variable tree is_initialized = self.has_variable('batch_stats', 'mean') ra_mean = self.variable('batch_stats', 'mean', ...
initialized variables: FrozenDict({ batch_stats: { mean: DeviceArray([0., 0., 0., 0., 0.], dtype=float32), }, params: { bias: DeviceArray([0., 0., 0., 0., 0.], dtype=float32), }, }) updated state: FrozenDict({ batch_stats: { mean: DeviceArray([[0.01, 0.01, 0.01, 0.01, 0.01]...
Apache-2.0
docs/notebooks/flax_basics.ipynb
harry-stark/flax
Here, `updated_state` returns only the state variables that are being mutated by the model while applying it on data. To update the variables and get the new parameters of the model, we can use the following pattern:
for val in [1.0, 2.0, 3.0]: x = val * jnp.ones((10,5)) y, updated_state = model.apply(variables, x, mutable=['batch_stats']) old_state, params = variables.pop('params') variables = freeze({'params': params, **updated_state}) print('updated state:\n', updated_state) # Shows only the mutable part
updated state: FrozenDict({ batch_stats: { mean: DeviceArray([[0.01, 0.01, 0.01, 0.01, 0.01]], dtype=float32), }, }) updated state: FrozenDict({ batch_stats: { mean: DeviceArray([[0.0299, 0.0299, 0.0299, 0.0299, 0.0299]], dtype=float32), }, }) updated state: FrozenDict({ batch_sta...
Apache-2.0
docs/notebooks/flax_basics.ipynb
harry-stark/flax
From this simplified example, you should be able to derive a full BatchNorm implementation, or any layer involving a state. To finish, let's add an optimizer to see how to play with both parameters updated by an optimizer and state variables.*This example isn't doing anything and is only for demonstration purposes.*
def update_step(tx, apply_fn, x, opt_state, params, state): def loss(params): y, updated_state = apply_fn({'params': params, **state}, x, mutable=list(state.keys())) l = ((x - y) ** 2).sum() return l, updated_state (l, state), grads = jax.value_and_grad(loss, has_aux=Tr...
Updated state: FrozenDict({ batch_stats: { mean: DeviceArray([[0.01, 0.01, 0.01, 0.01, 0.01]], dtype=float32), }, }) Updated state: FrozenDict({ batch_stats: { mean: DeviceArray([[0.0199, 0.0199, 0.0199, 0.0199, 0.0199]], dtype=float32), }, }) Updated state: FrozenDict({ batch_sta...
Apache-2.0
docs/notebooks/flax_basics.ipynb
harry-stark/flax
SIRAH Candidate Pipeline Demo NotebookThis notebook demostrates how to set up and run the SIRAH candidate pipeline and desribes its basic features by Mi DaiApril 13, 2020 **0. prerequisites** **0.0 Before you start, follow the instructions under README [here](https://github.com/mi-dai/sirahtargetspipeline-to-select...
%load_ext autoreload %autoreload 2 import pandas as pd import numpy as np import matplotlib.pyplot as plt import os
_____no_output_____
MIT
demo_notebook.ipynb
mi-dai/sirahtargets-public
**0.4 Define the follow environment variables if you haven't done so**
os.environ['SFD_DIR'] = '/home/mi/sfddata-master' #modify this to point to the dust map downloaded from https://github.com/kbarbary/sfddata os.environ['SIRAHPIPE_DIR'] = os.getcwd() #Or your sirah_target_pipe dir if you are running in other directories
_____no_output_____
MIT
demo_notebook.ipynb
mi-dai/sirahtargets-public
**1. Using the pipeline** **1.1 import the SIRAHPipe module first**
from pipeline import SIRAHPipe
_____no_output_____
MIT
demo_notebook.ipynb
mi-dai/sirahtargets-public
**1.2 initialize the pipeline** This cell defines the pipeline and chooses the brokers, crossmatch calalogues, and the selection cuts **Currently implemented brokers:** [alerce](http://alerce.science/), [lasair](https://lasair.roe.ac.uk/streams/),[tns](https://wis-tns.weizmann.ac.il/) **Crossmatch catalogues:** [sd...
pipe = SIRAHPipe(brokers=['alerce','lasair','tns'],xmatch_catalogues=['sdss','ned','glade'], selection_cuts=['zcut','ztflimcut','hostdistcut','olddetectioncut','magzcut','rbcut'])
Setting up SkyServer... Setting up local db [db/glade_v23.db] Brokers to query: ['alerce', 'lasair', 'tns'] Crossmatch catalogues: ['sdss', 'ned', 'glade'] Cuts to apply: ['zcut', 'ztflimcut', 'hostdistcut', 'olddetectioncut', 'magzcut', 'rbcut']
MIT
demo_notebook.ipynb
mi-dai/sirahtargets-public
**1.3 using the realtime mode**Let's record current date and time. The pipeline can run in realtime or non-realtime mode. if `realtime==True`, the sql query includes conditions on the latest magnitude provided by the brokers; if `realtime==False`, the latest magnitudes are calculated offline by querying all the detect...
from astropy.time import Time from datetime import datetime print(Time(datetime.today()),'mjd=',Time(datetime.today()).mjd) realtime = True
2020-04-22 18:13:58.102328 mjd= 58961.75970026116
MIT
demo_notebook.ipynb
mi-dai/sirahtargets-public
**1.4 running the pipeline** This is the main part of the pipeline that many options can be specified. Here I list some useful ones (and their default values): - **[query options]** - **mjdstart, mjdend:** mjd range to query - **gmax(=20.), rmax(=20.), gmin(=16.), rmin(=16.):** max/min magnitude ranges to query...
import time today = Time(datetime.today()).mjd start = time.time() pipe.run(mjdstart=today-10,mjdend=today,qlim=100,zerrlim=0.01,dmag_max=4.5,gmax=22,rmax=22,realtime=realtime,skip_ztf=True,use_sherlock=True) # pipe.run(mjdstart=today-10,mjdend=today,qlim=100,zerrlim=0.01,dmag_max=4.5,gmax=22,rmax=22,realtime=realtime...
queryresult size: 100 queryresult size: 100 queryresult size: 166 Table [sncoor] uploaded successfully. Query Job is submitted. JobID=47354091 Job 47354091 is finished Cross-matching GLADE catalog using astropy module search_around_sky Done. Time=0.021483612060546876 minutes Cross match NED for 0.01 < sdss_photoz < 0.0...
MIT
demo_notebook.ipynb
mi-dai/sirahtargets-public
**1.5 Miscellaneous features**Here I describe some miscellaneous features that may be useful in analyzing the query results 1.5.1 *SIRAHPipe.results*After the pipeline runs, all the query results, including the selection cut flags, are saved in `SIRAHPipe.results`
pipe.results.head()
_____no_output_____
MIT
demo_notebook.ipynb
mi-dai/sirahtargets-public
1.5.2 the *SIRAHPipe.MakeCuts* module- **(re)applying cuts using** ***SIRAHPipe.MakeCuts.[Cutname]*** The `SIRAHPipe.MakeCuts` module contains all the selection cut functions that can be reapplied after the pipeline runs to change the selection criteria. e.g. We can reapply the redshift cut with narrower `zerrlim=0.00...
## apply additional cut here pipe.MakeCuts.zcut(zerrlim=0.005) # pipe.MakeCuts.olddetectioncut() pipe.MakeCuts.magzcut(dmag_max=3.,dmag_min=0.,magabs=-18) # pipe.MakeCuts.ztflimcut() pipe.MakeCuts.plot(magabs=-18,magz_plot=True,sedmodel='snana-2004fe',phase=[-10,-5,0]) # pipe.MakeCuts.plot(magabs=-19,magz_plot=True) p...
Selecting 0.016 < z < 0.080 and zerr < 0.005 Selecting candidates based on mag vs z: 0.00 < dmag (from max) < 3.00 Plotting MakeCuts...
MIT
demo_notebook.ipynb
mi-dai/sirahtargets-public
**2. Making plots for selected candidates** The main function for making light curve and phase estimate plots is *utils.gen_plots* `gen_plots()` requires a pandas DataFrame as input that comes from running the pipeline or a self-defined `pd.DataFrame` that has the required columns as the pipeline results - set **inter...
from utils import * import matplotlib.pyplot as plt import os from PyPDF2 import PdfFileMerger # %matplotlib inline interactive = False savepdf = True querydate = date.today() if not os.path.isdir('demo'): os.mkdir('demo') if savepdf: pdf_file = 'demo/Candidates_{}.pdf'.format(querydate.strftime("%m-%d-%Y")) ...
ZTF20aaurfhs: z=0.0352 +/- 0.0010 ra = 17:01:22.507 dec = +20:18:58.35 mwebv=0.058
MIT
demo_notebook.ipynb
mi-dai/sirahtargets-public
SageMaker Serverless Inference XGBoost Regression ExampleAmazon SageMaker Serverless Inference is a purpose-built inference option that makes it easy for customers to deploy and scale ML models. Serverless Inference is ideal for workloads which have idle periods between traffic spurts and can tolerate cold starts. Ser...
# Fallback in case wheels are unavailable ! pip install sagemaker botocore boto3 awscli --upgrade import subprocess def execute_cmd(cmd): print(cmd) output = subprocess.getstatusoutput(cmd) return output def _download_from_s3(_file_path): _path = f"s3://reinvent21-sm-rc-wheels/{_file_path}" prin...
_____no_output_____
Apache-2.0
serverless-inference/Serverless-Inference-Walkthrough.ipynb
jkroll-aws/amazon-sagemaker-examples
SageMaker SetupTo begin, we import the AWS SDK for Python (Boto3) and set up our environment, including an IAM role and an S3 bucket to store our data.
import boto3 import sagemaker from sagemaker.estimator import Estimator boto_session = boto3.session.Session() region = boto_session.region_name print(region) sagemaker_session = sagemaker.Session() base_job_prefix = "xgboost-example" role = sagemaker.get_execution_role() print(role) default_bucket = sagemaker_sessi...
_____no_output_____
Apache-2.0
serverless-inference/Serverless-Inference-Walkthrough.ipynb
jkroll-aws/amazon-sagemaker-examples
Retrieve the Abalone dataset from a publicly hosted S3 bucket.
# retrieve data ! curl https://sagemaker-sample-files.s3.amazonaws.com/datasets/tabular/uci_abalone/train_csv/abalone_dataset1_train.csv > abalone_dataset1_train.csv
_____no_output_____
Apache-2.0
serverless-inference/Serverless-Inference-Walkthrough.ipynb
jkroll-aws/amazon-sagemaker-examples
Upload the Abalone dataset to the default S3 bucket.
# upload data to S3 !aws s3 cp abalone_dataset1_train.csv s3://{default_bucket}/xgboost-regression/train.csv
_____no_output_____
Apache-2.0
serverless-inference/Serverless-Inference-Walkthrough.ipynb
jkroll-aws/amazon-sagemaker-examples
Model Training Now, we train an ML model using the XGBoost Algorithm. In this example, we use a SageMaker-provided [XGBoost](https://docs.aws.amazon.com/sagemaker/latest/dg/xgboost.html) container image and configure an estimator to train our model.
from sagemaker.inputs import TrainingInput training_path = f"s3://{default_bucket}/xgboost-regression/train.csv" train_input = TrainingInput(training_path, content_type="text/csv") model_path = f"s3://{default_bucket}/{s3_prefix}/xgb_model" # retrieve xgboost image image_uri = sagemaker.image_uris.retrieve( frame...
_____no_output_____
Apache-2.0
serverless-inference/Serverless-Inference-Walkthrough.ipynb
jkroll-aws/amazon-sagemaker-examples
Train the model on the Abalone dataset.
# Fit model xgb_train.fit({"train": train_input})
_____no_output_____
Apache-2.0
serverless-inference/Serverless-Inference-Walkthrough.ipynb
jkroll-aws/amazon-sagemaker-examples
Deployment After training the model, retrieve the model artifacts so that we can deploy the model to an endpoint.
# Retrieve model data from training job model_artifacts = xgb_train.model_data model_artifacts
_____no_output_____
Apache-2.0
serverless-inference/Serverless-Inference-Walkthrough.ipynb
jkroll-aws/amazon-sagemaker-examples
Model CreationCreate a model by providing your model artifacts, the container image URI, environment variables for the container (if applicable), a model name, and the SageMaker IAM role.
from time import gmtime, strftime model_name = "xgboost-serverless" + strftime("%Y-%m-%d-%H-%M-%S", gmtime()) print("Model name: " + model_name) # dummy environment variables byo_container_env_vars = {"SAGEMAKER_CONTAINER_LOG_LEVEL": "20", "SOME_ENV_VAR": "myEnvVar"} create_model_response = client.create_model( ...
_____no_output_____
Apache-2.0
serverless-inference/Serverless-Inference-Walkthrough.ipynb
jkroll-aws/amazon-sagemaker-examples
Endpoint Configuration CreationThis is where you can adjust the Serverless Configuration for your endpoint. The current max concurrent invocations for a single endpoint, known as MaxConcurrency, can be any value from 1 to 50, and MemorySize can be any of the following: 1024 MB, 2048 MB, 3072 MB, 4096 MB, 5120 MB, or 6...
xgboost_epc_name = "xgboost-serverless-epc" + strftime("%Y-%m-%d-%H-%M-%S", gmtime()) endpoint_config_response = client.create_endpoint_config( EndpointConfigName=xgboost_epc_name, ProductionVariants=[ { "VariantName": "byoVariant", "ModelName": model_name, "Serverle...
_____no_output_____
Apache-2.0
serverless-inference/Serverless-Inference-Walkthrough.ipynb
jkroll-aws/amazon-sagemaker-examples
Serverless Endpoint CreationNow that we have an endpoint configuration, we can create a serverless endpoint and deploy our model to it. When creating the endpoint, provide the name of your endpoint configuration and a name for the new endpoint.
endpoint_name = "xgboost-serverless-ep" + strftime("%Y-%m-%d-%H-%M-%S", gmtime()) create_endpoint_response = client.create_endpoint( EndpointName=endpoint_name, EndpointConfigName=xgboost_epc_name, ) print("Endpoint Arn: " + create_endpoint_response["EndpointArn"])
_____no_output_____
Apache-2.0
serverless-inference/Serverless-Inference-Walkthrough.ipynb
jkroll-aws/amazon-sagemaker-examples
Wait until the endpoint status is InService before invoking the endpoint.
# wait for endpoint to reach a terminal state (InService) using describe endpoint import time describe_endpoint_response = client.describe_endpoint(EndpointName=endpoint_name) while describe_endpoint_response["EndpointStatus"] == "Creating": describe_endpoint_response = client.describe_endpoint(EndpointName=endpo...
_____no_output_____
Apache-2.0
serverless-inference/Serverless-Inference-Walkthrough.ipynb
jkroll-aws/amazon-sagemaker-examples
Endpoint InvocationInvoke the endpoint by sending a request to it. The following is a sample data point grabbed from the CSV file downloaded from the public Abalone dataset.
response = runtime.invoke_endpoint( EndpointName=endpoint_name, Body=b".345,0.224414,.131102,0.042329,.279923,-0.110329,-0.099358,0.0", ContentType="text/csv", ) print(response["Body"].read())
_____no_output_____
Apache-2.0
serverless-inference/Serverless-Inference-Walkthrough.ipynb
jkroll-aws/amazon-sagemaker-examples
Clean UpDelete any resources you created in this notebook that you no longer wish to use.
client.delete_model(ModelName=model_name) client.delete_endpoint_config(EndpointConfigName=xgboost_epc_name) client.delete_endpoint(EndpointName=endpoint_name)
_____no_output_____
Apache-2.0
serverless-inference/Serverless-Inference-Walkthrough.ipynb
jkroll-aws/amazon-sagemaker-examples
import numpy as np import pandas as pd from numpy.linalg import eig from scipy.linalg import hilbert from copy import copy
_____no_output_____
Apache-2.0
method5.ipynb
ancka019/ComputationsMethods6sem
Степенной метод
def pow_method(a,eps,x0=None): if x0 is None: x0 = np.random.uniform(-1,1,size=a.shape[1]) x1 = a@x0 num_of_iters = 1 lambda0 = x1[0]/x0[0] while True: x0,x1 = x1, a@x1 lambda1 = x1[0]/x0[0] if abs(lambda1-lambda0)<eps or num_of_iters > 5000: break ...
_____no_output_____
Apache-2.0
method5.ipynb
ancka019/ComputationsMethods6sem
метод скалярных произведений
def scal_method(a,eps,x0=None): if x0 is None: x0 = np.random.uniform(-1,1,size=a.shape[1]) num_of_iters = 1 x1 = a@x0 y0 = copy(x0) a_T = np.transpose(a) y1 = a_T@x0 lambda0 = np.dot(x1,y1)/np.dot(x0,y0) while True: x0,x1 = x1, a@x1 y0,y1 = y1, a_T@y1 ...
_____no_output_____
Apache-2.0
method5.ipynb
ancka019/ComputationsMethods6sem
Решение
result = [] for size in [3,5,11]: A = hilbert(size) data = [] lambda_acc = max(abs(np.linalg.eig(A)[0])) for eps in range(-6, -1): eps = 10**eps data.append({ 'eps': eps, 'Степенной метод (К-во итераций)': pow_method(A, eps)[1], 'Степенной...
_____no_output_____
Apache-2.0
method5.ipynb
ancka019/ComputationsMethods6sem
Data Summary
elnino.head(20) # Print statistical summary print("Statistical summary for the 'Elnino' file: \n") print(elnino.describe(), "\n \n") # display types for variables print("The variable types are as follow: \n") print(elnino.dtypes, "\n") ## get name of columns in dataset print("The name of the columns in dataset are: \n"...
_____no_output_____
Apache-2.0
el_nino.ipynb
nohitme/psu-daan888-project
Naive Bayes and Support vector machines using TF-IDF vectorizerIn this model both algorithms, Naive Bayes and Support Vector Machines are tested using the TF-IDF vectorizer, implemented in the scikit-learn's library. This vectorizer transforms a cou...
import numpy as np import matplotlib.pyplot as plt import pandas as pd from nltk.tokenize import word_tokenize from nltk import pos_tag from nltk.corpus import stopwords from nltk.stem import WordNetLemmatizer from sklearn.preprocessing import LabelEncoder from collections import defaultdict from nltk.corpus import wor...
-----------------Support Vector Machine CM------------------ Accuracy Score -> 82.27485834268128 [[ 4993 761 2883] [ 1365 1399 5762] [ 880 674 50817]] precision recall f1-score support Positive 0.69 0.58 0.63 8637 Neutral 0.49 0.16 0.25 ...
MIT
Naive_Bayes_&_SVM_tfidfVectorizer.ipynb
panayiotiska/Sentiment-Analysis-Reviews
CARTO frames workshopFull details at the [documentation](https://cartodb.github.io/cartoframes/) page. I'm using the `master` branch installed using```shpip install cartoframes jupyter seaborn```
import cartoframes from cartoframes import Credentials, CartoContext import pandas as pd import os
_____no_output_____
CC-BY-4.0
06-sdks/exercises/python_SDK/CARTO_Frames.ipynb
oss-spanish-geoserver/carto-workshop
Load the credentials
try: cc = cartoframes.CartoContext() print('Getting the credentials from a previous session') except Exception as e: print('Getting the credentials from your environment or here') BASEURL = os.environ.get('CARTO_API_URL','https://jsanz.carto.com') # <-- replace with your username or set up the envvar ...
Getting the credentials from a previous session
CC-BY-4.0
06-sdks/exercises/python_SDK/CARTO_Frames.ipynb
oss-spanish-geoserver/carto-workshop
Load the typical `Populated Places` dataset from CARTO You can import this dataset from the Data Library
df = cc.read('populated_places') df.head()
_____no_output_____
CC-BY-4.0
06-sdks/exercises/python_SDK/CARTO_Frames.ipynb
oss-spanish-geoserver/carto-workshop
It's a Pandas data frameYou can get the `featurecla` field counts
df.groupby('featurecla').featurecla.count()
_____no_output_____
CC-BY-4.0
06-sdks/exercises/python_SDK/CARTO_Frames.ipynb
oss-spanish-geoserver/carto-workshop
Run SQL queries
cc.query(''' SELECT featurecla,count(*) as counts FROM populated_places GROUP BY featurecla ''')
_____no_output_____
CC-BY-4.0
06-sdks/exercises/python_SDK/CARTO_Frames.ipynb
oss-spanish-geoserver/carto-workshop
Draw graphics using SeabornMore about seaborn [here](https://seaborn.pydata.org/)
import seaborn as sns import matplotlib.pyplot as plt import warnings warnings.filterwarnings('ignore') %matplotlib inline f, ax = plt.subplots(figsize=(16, 6)) sns.boxplot(x="featurecla", y="pop_max", data=df);
_____no_output_____
CC-BY-4.0
06-sdks/exercises/python_SDK/CARTO_Frames.ipynb
oss-spanish-geoserver/carto-workshop
Render your tables from CARTO
from cartoframes import Layer, styling l = Layer( 'populated_places', color={'column': 'featurecla','scheme': styling.prism(9)}, size ={'column': 'pop_max','bin_method':'quantiles','bins' : 4, 'min': 3, 'max':10} ) cc.map(layers=l, interactive=True)
_____no_output_____
CC-BY-4.0
06-sdks/exercises/python_SDK/CARTO_Frames.ipynb
oss-spanish-geoserver/carto-workshop