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
9.0 Conclusions 9.1 Final Model
# model performance with unseen data xgb_final_model = XGBClassifier(objective='binary:logistic', n_estimators = 1000, eta=0.03, subsample = 0.7, min_child_weight = 3, max_depth = 30, colssample_bytree = 0.7, scale_pos_weight=80, verbosity=0) xgb_final_model.fit(X_train, y_train) pred_final = xgb_final_model.predict(X_...
_____no_output_____
MIT
Churn-Prediction.ipynb
Leonardodsch/churn-prediction
9.2 Business Questions
df9 = df2.copy()
_____no_output_____
MIT
Churn-Prediction.ipynb
Leonardodsch/churn-prediction
9.2.1 Qual a taxa atual de Churn da TopBank?
churn_rate = df9['exited'].value_counts(normalize=True).reset_index() churn_rate['exited'] = churn_rate['exited']*100 churn_rate.columns = ['churn', 'exited (%)'] churn_rate sns.countplot(df9['exited']).set_title('Churn Rate')
_____no_output_____
MIT
Churn-Prediction.ipynb
Leonardodsch/churn-prediction
**A taxa atual de churn do TopBank é de 20.4%** 9.2.2 Qual o retorno esperado, em termos de faturamento, se a empresa utilizar seu modelo para evitar o churn dos clientes? - Para realização do cálculo de retorno financeiro foi utilizado uma amostra de 1000 clientes (10% do dataset). - Para comparação com os dados re...
aux = pd.concat([X_test9, y_test9], axis=1) mean_salary = df9['estimated_salary'].mean() aux['pred_exited'] = pred_final aux['client_return'] = aux['estimated_salary'].apply(lambda x: x*0.15 if x < mean_salary else x*0.20)
_____no_output_____
MIT
Churn-Prediction.ipynb
Leonardodsch/churn-prediction
- Cálculo do retorno total para todos os clintes que entraram em churn na amostra
total_return = aux[aux['exited'] == 1]['client_return'].sum() print('O retorno total de todos os clientes que entraram em churn é de ${}' .format(total_return))
O retorno total de todos os clientes que entraram em churn é de $3658649.9845000003
MIT
Churn-Prediction.ipynb
Leonardodsch/churn-prediction
- Selecionando os clientes que o modelo previu corretamente que entraram em churn. - Se fosse possível evitar que todos os clientes entrassem em churn seria possível recuperar aproximadamente 70% do valor total calculado acima.
churn_return = aux[(aux['pred_exited'] == 1) & (aux['exited'] == 1)]['client_return'].sum() print('O retorno total dos clientes que o modelo previu que entrariam em churn é de ${}' .format(churn_return))
O retorno total dos clientes que o modelo previu que entrariam em churn é de $2540855.073
MIT
Churn-Prediction.ipynb
Leonardodsch/churn-prediction
9.2.3 Incentivo Financeiro Uma possível ação para evitar que o cliente entre em churn é oferecer um cupom de desconto, ou algum outro incentivo financeiro para ele renovar seu contrato por mais 12 meses.- Para quais clientes você daria o incentivo financeiro e qual seria esse valor, de modo a maximizar o ROI (Retorno ...
threshold = 0.95 proba_list = [] for i in range (len(pred_final_proba)): proba = pred_final_proba[i][1] proba_list.append(proba) aux['pred_exited_proba'] = proba_list aux2 = aux[(aux['exited'] == 1) & (aux['pred_exited'] ==1)] aux2 = aux2[aux2['pred_exited_proba'] > threshold] aux2.sample(10) # definindo incent...
_____no_output_____
MIT
Churn-Prediction.ipynb
Leonardodsch/churn-prediction
- Supondo que fosse possível evitar que todos os clientes que receberam o incentivo entrassem em churn, e então consequentemente renovassem seus contratos, seria possível obter um retorno finaceiro de $ 938.235,39
total_return = aux2['client_return'].sum() print('O Retorno financeiro total a partir dos clientes que receberam o incentivo foi de $ {}'.format(total_return))
O Retorno financeiro total a partir dos clientes que receberam o incentivo foi de $ 1602619.6835
MIT
Churn-Prediction.ipynb
Leonardodsch/churn-prediction
10.0 Deploy
#saving models final_model = XGBClassifier(objective='binary:logistic', n_estimators = 1000, eta=0.03, subsample = 0.7, min_child_weight = 3, max_depth = 30, colssample_bytree = 0.7, scale_pos_weight=80, verbosity=0) final_model.fit(X_train, y_train) joblib.dump(final_model, 'Model/final_...
_____no_output_____
MIT
Churn-Prediction.ipynb
Leonardodsch/churn-prediction
10.1 Churn Class
import joblib import pandas as pd import inflection class Churn (object): def __init__(self): self.scaler = joblib.load('Parameters/scaler_mm.joblib') self.encoder_le = joblib.load('Parameters/label_encoder.joblib') def data_cleaning(self, df1): # rename columns co...
_____no_output_____
MIT
Churn-Prediction.ipynb
Leonardodsch/churn-prediction
10.2 API Handler
import joblib import pandas as pd from churn.Churn import Churn from flask import Flask, request, Response model = joblib.load('Model/final_model_XGB.joblib') # initialize API app = Flask(__name__) @app.route('/churn/predict', methods=['POST']) def churn_predict(): test_json = request.get_json() if tes...
_____no_output_____
MIT
Churn-Prediction.ipynb
Leonardodsch/churn-prediction
10.3 API Tester
df10 = pd.read_csv('data/churn.csv') # convert dataframe to json data = df10.to_json() url = 'http://0.0.0.0:5000/churn/predict' header = {'Content-type': 'application/json'} r = requests.post(url=url, data=data, headers=header) r.status_code r.json() d1 = pd.DataFrame( r.json(), columns=r.json()[0].keys() ) d1
_____no_output_____
MIT
Churn-Prediction.ipynb
Leonardodsch/churn-prediction
https://py.checkio.org/blog/design-patterns-part-2/https://py.checkio.org/en/mission/dialogues/share/07bc869edadfc11858e1caeaa4415987/
windows = dict.fromkeys(['main', 'settings', 'help']) windows text = """Karl said: Hi! What's new?R2D2 said: Hello, human. Could we speak later about it?""" text = text.replace('a', '0').replace('e', '0').replace('i', '0').replace('o', '0').replace('u', '0').replace('A', '0').replace('E', '0').replace('I', '0').replac...
Lucy is a search dog. Lucy is sitting. Lucy is searching.
MIT
Other/Behavior Design Pattern - Mediator.ipynb
deepaksood619/Python-Competitive-Programming
Approach 2: Use Traditional statestical modelsIn this notebook we will discuss following models on daily sampled data. 1. MA 2. Simple Exponential Smoothing 3. Holt Linear 4. Holt-Winters These models are implemented using statsmodels library. **Objective: Implement above models and calculate RMSE to compa...
# Load data data = pd.read_csv("daily_data.csv",parse_dates=[0], index_col=0) data.head()
_____no_output_____
MIT
Portfolio/TS_Traditional_Methods.ipynb
anujakapre/E-commerce-Market-Analysis-
Decompose time seriesA series is thought to be an aggregate or combination of these four components.All series have a level and noise. The trend and seasonality components are optional.These components combine either additively or multiplicatively. Additive ModelAn additive model suggests that the components are added...
#Decompose time series into trend, seasonality and noise rcParams['figure.figsize'] = 11, 9 result = sm.tsa.seasonal_decompose(data, model='additive') result.plot() plt.show() #Print trend, seasality, residual print(result.trend) print(result.seasonal) print(result.resid) #print(result.observed) #Find out outliers sns...
_____no_output_____
MIT
Portfolio/TS_Traditional_Methods.ipynb
anujakapre/E-commerce-Market-Analysis-
**Z score denotes how many standerd deviation away your sample is from the mean. Hence we remove all samples which are 3 std. deviations away from mean**
#Calculate Z score for all samples z = np.abs(stats.zscore(data)) #Locate outliers outliers = data[(z > 3).all(axis=1)] outliers #Replace outliers by median value median = data[(z < 3).all(axis=1)].median() data.loc[data['Total Price'] > 71858, 'Total Price'] = np.nan data.fillna(median,inplace=True) median #Plot data...
_____no_output_____
MIT
Portfolio/TS_Traditional_Methods.ipynb
anujakapre/E-commerce-Market-Analysis-
**Below we can see time series clearly, there is exponential growth in trend at start but linear towards the end. Seasonality is not increasing exponentialy, rather it's constant. Hece we can say that our time serie is additive.**
#Plot the data rcParams['figure.figsize'] = 20, 10 result = sm.tsa.seasonal_decompose(data, model='additive') result.plot() plt.show() #Train and test data train=data[0:-100] test=data[-100:] y_hat = test.copy()
_____no_output_____
MIT
Portfolio/TS_Traditional_Methods.ipynb
anujakapre/E-commerce-Market-Analysis-
1. Moving Average: In this method, we use the mean of the previous data. Using the prices of the initial period would highly affect the forecast for the next period. Therefore, we will take the average of the prices for last few recent time periods only. Such forecasting technique which uses window of time period for...
#Calculate MA: use last 50 data points rcParams['figure.figsize'] = 17, 5 y_hat['moving_avg_forecast'] = train['Total Price'].rolling(50).mean().iloc[-1] plt.plot(train['Total Price'], label='Train') plt.plot(test['Total Price'], label='Test') plt.plot(y_hat['moving_avg_forecast'], label='Moving Average Forecast') plt....
11707.529420000003
MIT
Portfolio/TS_Traditional_Methods.ipynb
anujakapre/E-commerce-Market-Analysis-
Method 2 : Simple Exponential SmoothingThis method takes into account all the data while weighing the data points differently. For example it may be sensible to attach larger weights to more recent observations than to observations from the distant past. The technique which works on this principle is called Simple exp...
#Fit the mosel fit1 = SimpleExpSmoothing(train).fit() y_hat['SES'] = fit1.forecast(len(test)).rename(r'$\alpha=%s$'%fit1.model.params['smoothing_level']) alpha = fit1.model.params['smoothing_level']
C:\Users\Snigdha\AppData\Local\conda\conda\envs\neuralnets\lib\site-packages\statsmodels\tsa\base\tsa_model.py:171: ValueWarning: No frequency information was provided, so inferred frequency D will be used. % freq, ValueWarning)
MIT
Portfolio/TS_Traditional_Methods.ipynb
anujakapre/E-commerce-Market-Analysis-
where 0≤ α ≤1 is the smoothing parameter.The one-step-ahead forecast for time T+1 is a weighted average of all the observations in the series y1,…,yT. The rate at which the weights decrease is controlled by the parameter α.
alpha #Plot the data rcParams['figure.figsize'] = 17, 5 plt.plot(train['Total Price'], label='Train') plt.plot(test['Total Price'], label='Test') plt.plot(y_hat['SES'], label='SES') plt.legend(loc='best') plt.show() #Calculate rmse rmse = sqrt(mean_squared_error(test['Total Price'], y_hat.SES)) print(rmse) #Calculate m...
14885.45052998217
MIT
Portfolio/TS_Traditional_Methods.ipynb
anujakapre/E-commerce-Market-Analysis-
Method 3 – Holt’s Linear Trend methodIf we use any of the above methods, it won’t take into account this trend. Trend is the general pattern of prices that we observe over a period of time. In this case we can see that there is an increasing trend.Hence we use Holt’s Linear Trend method that can map the trend accurate...
#Holt-Linear model fit2 = Holt(np.asarray(train['Total Price'])).fit() y_hat['Holt_linear'] = fit2.forecast(len(test)) print("Smooting level", fit2.model.params['smoothing_level']) print("Smoothing slope",fit2.model.params['smoothing_slope']) #Plot the result rcParams['figure.figsize'] = 17, 5 plt.plot(train['Total Pri...
14058.411166558843
MIT
Portfolio/TS_Traditional_Methods.ipynb
anujakapre/E-commerce-Market-Analysis-
If we observe closely, there are spikes in sales in middle of the month.
data.tail(100).plot()
_____no_output_____
MIT
Portfolio/TS_Traditional_Methods.ipynb
anujakapre/E-commerce-Market-Analysis-
Method 4 : Holt-Winters MethodDatasets which show a similar set of pattern after fixed intervals of a time period have from seasonality.Hence we need a method that takes into account both trend and seasonality to forecast future prices. One such algorithm that we can use in such a scenario is Holt’s Winter method. The...
#Fit model fit3 = ExponentialSmoothing(np.asarray(train['Total Price']) ,seasonal_periods= 30, trend='add', seasonal='add').fit() y_hat['Holt_Winter'] = fit3.forecast(len(test)) #Plot the data rcParams['figure.figsize'] = 17, 5 plt.plot( train['Total Price'], label='Train') plt.plot(test['Total Price'], label='Test') p...
14214.30484223988
MIT
Portfolio/TS_Traditional_Methods.ipynb
anujakapre/E-commerce-Market-Analysis-
Load DataAs usual, let's start by loading some network data. This time round, we have a [physician trust](http://konect.uni-koblenz.de/networks/moreno_innovation) network, but slightly modified such that it is undirected rather than directed.> This directed network captures innovation spread among 246 physicians in fo...
# Load the network. This network, while in reality is a directed graph, # is intentionally converted to an undirected one for simplification. G = cf.load_physicians_network() # Make a Circos plot of the graph from nxviz import CircosPlot c = CircosPlot(G) c.draw()
_____no_output_____
MIT
archive/4-cliques-triangles-structures-instructor.ipynb
ChrisKeefe/Network-Analysis-Made-Simple
QuestionWhat can you infer about the structure of the graph from the Circos plot? My answer: The structure is interesting. The graph looks like the physician trust network is comprised of discrete subnetworks. Structures in a GraphWe can leverage what we have learned in the previous notebook to identify special struc...
# Example code. def in_triangle(G, node): """ Returns whether a given node is present in a triangle relationship or not. """ # Then, iterate over every pair of the node's neighbors. for nbr1, nbr2 in combinations(G.neighbors(node), 2): # Check to see if there is an edge between the node'...
_____no_output_____
MIT
archive/4-cliques-triangles-structures-instructor.ipynb
ChrisKeefe/Network-Analysis-Made-Simple
In reality, NetworkX already has a function that *counts* the number of triangles that any given node is involved in. This is probably more useful than knowing whether a node is present in a triangle or not, but the above code was simply for practice.
nx.triangles(G, 3)
_____no_output_____
MIT
archive/4-cliques-triangles-structures-instructor.ipynb
ChrisKeefe/Network-Analysis-Made-Simple
ExerciseCan you write a function that takes in one node and its associated graph as an input, and returns a list or set of itself + all other nodes that it is in a triangle relationship with? Do not return the triplets, but the `set`/`list` of nodes. (5 min.)**Possible Implementation:** If I check every pair of my nei...
# Possible answer def get_triangles(G, node): neighbors1 = set(G.neighbors(node)) triangle_nodes = set() triangle_nodes.add(node) """ Fill in the rest of the code below. """ for nbr1, nbr2 in combinations(neighbors1, 2): if G.has_edge(nbr1, nbr2): triangle_nodes.add(nbr1)...
_____no_output_____
MIT
archive/4-cliques-triangles-structures-instructor.ipynb
ChrisKeefe/Network-Analysis-Made-Simple
Friend Recommendation: Open TrianglesNow that we have some code that identifies closed triangles, we might want to see if we can do some friend recommendations by looking for open triangles.Open triangles are like those that we described earlier on - A knows B and B knows C, but C's relationship with A isn't captured ...
def get_open_triangles(G, node): """ There are many ways to represent this. One may choose to represent only the nodes involved in an open triangle; this is not the approach taken here. Rather, we have a code that explicitly enumrates every open triangle present. """ open_triangle_node...
_____no_output_____
MIT
archive/4-cliques-triangles-structures-instructor.ipynb
ChrisKeefe/Network-Analysis-Made-Simple
Triangle closure is also the core idea behind social networks' friend recommendation systems; of course, it's definitely more complicated than what we've implemented here. CliquesWe have figured out how to find triangles. Now, let's find out what **cliques** are present in the network. Recall: what is the definition o...
list(nx.find_cliques(G))[0:20]
_____no_output_____
MIT
archive/4-cliques-triangles-structures-instructor.ipynb
ChrisKeefe/Network-Analysis-Made-Simple
ExerciseTry writing a function `maximal_cliques_of_size(size, G)` that implements a search for all maximal cliques of a given size. (3 min.)
def maximal_cliqes_of_size(size, G): # Defensive programming check. assert isinstance(size, int), "size has to be an integer" assert size >= 2, "cliques are of size 2 or greater." return [i for i in list(nx.find_cliques(G)) if len(i) == size] maximal_cliqes_of_size(2, G)[0:20]
_____no_output_____
MIT
archive/4-cliques-triangles-structures-instructor.ipynb
ChrisKeefe/Network-Analysis-Made-Simple
Connected ComponentsFrom [Wikipedia](https://en.wikipedia.org/wiki/Connected_component_%28graph_theory%29):> In graph theory, a connected component (or just component) of an undirected graph is a subgraph in which any two vertices are connected to each other by paths, and which is connected to no additional vertices i...
ccsubgraph_nodes = list(nx.connected_components(G)) ccsubgraph_nodes
_____no_output_____
MIT
archive/4-cliques-triangles-structures-instructor.ipynb
ChrisKeefe/Network-Analysis-Made-Simple
ExerciseDraw a circos plot of the graph, but now colour and order the nodes by their connected component subgraph. (5 min.)Recall Circos API:```pythonc = CircosPlot(G, node_order='...', node_color='...')c.draw()plt.show() or plt.savefig(...)```
# Start by labelling each node in the master graph G by some number # that represents the subgraph that contains the node. for i, nodeset in enumerate(ccsubgraph_nodes): for n in nodeset: G.nodes[n]['subgraph'] = i c = CircosPlot(G, node_color='subgraph', node_order='subgraph') c.draw() plt.savefig('images/...
_____no_output_____
MIT
archive/4-cliques-triangles-structures-instructor.ipynb
ChrisKeefe/Network-Analysis-Made-Simple
Atmospheric, oceanic and land data handlingIn this notebook we discuss the subtleties of how NetCDF-SCM handles different data 'realms' and why these choices are made. The realms of intereset to date are atmosphere, ocean and land and the distinction between the realms follows the [CMIP6 realm controlled vocabulary](h...
import traceback from os.path import join import iris import iris.quickplot as qplt import matplotlib.pyplot as plt import numpy as np from netcdf_scm.iris_cube_wrappers import CMIP6OutputCube from netcdf_scm.utils import broadcast_onto_lat_lon_grid from pandas.plotting import register_matplotlib_converters register_...
_____no_output_____
BSD-2-Clause
notebooks/atmos-land-ocean-handling.ipynb
lewisjared/netcdf-scm
Note that all of our data is on a regular grid, data on native model grids does not plot as nicely.
tas_file = join( DATA_PATH_TEST, "cmip6output", "CMIP6", "CMIP", "IPSL", "IPSL-CM6A-LR", "historical", "r1i1p1f1", "Amon", "tas", "gr", "v20180803", "tas_Amon_IPSL-CM6A-LR_historical_r1i1p1f1_gr_191001-191003.nc" ) gpp_file = tas_file.replace( "Amon", "Lmon" ).re...
_____no_output_____
BSD-2-Clause
notebooks/atmos-land-ocean-handling.ipynb
lewisjared/netcdf-scm
OceansWe start by loading our data.
hfds = CMIP6OutputCube() hfds.load_data_from_path(hfds_file)
Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working
BSD-2-Clause
notebooks/atmos-land-ocean-handling.ipynb
lewisjared/netcdf-scm
NetCDF-SCM will assume whether the data is "ocean", "land" or "atmosphere". The assumed realm can be checked by examining a `SCMCube`'s `netcdf_scm_realm` property. In our case we have "ocean" data.
hfds.netcdf_scm_realm
_____no_output_____
BSD-2-Clause
notebooks/atmos-land-ocean-handling.ipynb
lewisjared/netcdf-scm
If we have ocean data, then there is no data which will go in a "land" box. Hence, if we request e.g. `World|Land` data, an error will be raised.
try: hfds.get_scm_timeseries(regions=["World", "World|Land"]) except ValueError as e: traceback.print_exc(limit=0, chain=False)
Traceback (most recent call last): ValueError: All weights are zero for region: `World|Land`
BSD-2-Clause
notebooks/atmos-land-ocean-handling.ipynb
lewisjared/netcdf-scm
As there is no land data, the `World` mean is equal to the `World|Ocean` mean.
hfds_scm_ts = hfds.get_scm_timeseries( regions=["World", "World|Ocean"] ) hfds_scm_ts.line_plot(linestyle="region") np.testing.assert_allclose( hfds_scm_ts.filter(region="World").values, hfds_scm_ts.filter(region="World|Ocean").values, );
Not calculating land fractions as all required cubes are not available Performing lazy conversion to datetime for calendar: 365_day. This may cause subtle errors in operations that depend on the length of time between dates Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, ...
BSD-2-Clause
notebooks/atmos-land-ocean-handling.ipynb
lewisjared/netcdf-scm
When taking averages, there are 3 obvious options:- unweighted average- area weighted average- area and surface fraction weighted averageIn NetCDF-SCM, we always go for the third type in order to make sure that our weights are both area weighted and take into account how much each cell represents the SCM box of interes...
def compare_weighting_options(input_scm_cube): unweighted_mean = input_scm_cube.cube.collapsed( ["latitude", "longitude"], iris.analysis.MEAN ) area_cell = input_scm_cube.get_metadata_cube( input_scm_cube.areacell_var ).cube area_weights = broadcast_onto_lat_lon_grid( ...
Collapsing spatial coordinate 'latitude' without weighting
BSD-2-Clause
notebooks/atmos-land-ocean-handling.ipynb
lewisjared/netcdf-scm
We go to the trouble of taking these area-surface fraction weightings because they matter. In particular, the area weight is required to not overweight the poles (on whatever grid we're working) whilst the surface fraction ensures that the cells' contribution to the averages reflects how much they belong in a given 'SC...
hfds.areacell_var hfds_area_cell = hfds.get_metadata_cube(hfds.areacell_var).cube qplt.contourf( hfds_area_cell, );
_____no_output_____
BSD-2-Clause
notebooks/atmos-land-ocean-handling.ipynb
lewisjared/netcdf-scm
We can check which variable is being used for the surface fraction by loooking at `SCMCube.surface_fraction_var`. For ocean data this is `sftof`.
hfds.surface_fraction_var hfds_surface_frac = hfds.get_metadata_cube(hfds.surface_fraction_var).cube qplt.contourf( hfds_surface_frac, );
_____no_output_____
BSD-2-Clause
notebooks/atmos-land-ocean-handling.ipynb
lewisjared/netcdf-scm
The product of the area of the cells and the surface fraction gives us the area-surface fraction weights.
hfds_area_sf = hfds_area_cell * hfds_surface_frac plt.figure(figsize=(16, 9)) plt.subplot(121) qplt.contourf( hfds_area_sf, ) plt.subplot(122) lat_con = iris.Constraint(latitude=lambda cell: -50 < cell < -20) lon_con = iris.Constraint(longitude=lambda cell: 140 < cell < 160) qplt.contourf( hfds_area_sf.extrac...
_____no_output_____
BSD-2-Clause
notebooks/atmos-land-ocean-handling.ipynb
lewisjared/netcdf-scm
The timeseries calculated by NetCDF-SCM is the same as the timeseries calculated using the surface fraction and area weights.
hfds_area_sf_weights = broadcast_onto_lat_lon_grid( hfds, hfds_area_sf.data ) hfds_area_sf_weighted_mean = hfds.cube.collapsed( ["latitude", "longitude"], iris.analysis.MEAN, weights=hfds_area_sf_weights ) netcdf_scm_calculated = hfds.get_scm_timeseries( regions=["World"] ).timeseries() np.te...
Not calculating land fractions as all required cubes are not available Performing lazy conversion to datetime for calendar: 365_day. This may cause subtle errors in operations that depend on the length of time between dates
BSD-2-Clause
notebooks/atmos-land-ocean-handling.ipynb
lewisjared/netcdf-scm
LandNext we look at land data.
gpp = CMIP6OutputCube() gpp.load_data_from_path(gpp_file) csoilfast = CMIP6OutputCube() csoilfast.load_data_from_path(csoilfast_file) gpp.netcdf_scm_realm csoilfast.netcdf_scm_realm
_____no_output_____
BSD-2-Clause
notebooks/atmos-land-ocean-handling.ipynb
lewisjared/netcdf-scm
If we have land data, then there is no data which will go in a "ocean" box. Hence, if we request e.g. `World|Ocean` data, an error will be raised.
try: gpp.get_scm_timeseries(regions=["World", "World|Ocean"]) except ValueError as e: traceback.print_exc(limit=0, chain=False)
Traceback (most recent call last): ValueError: All weights are zero for region: `World|Ocean`
BSD-2-Clause
notebooks/atmos-land-ocean-handling.ipynb
lewisjared/netcdf-scm
As there is no ocean data, the `World` mean is equal to the `World|Land` mean.
gpp_scm_ts = gpp.get_scm_timeseries( regions=["World", "World|Land"] ) gpp_scm_ts.line_plot(linestyle="region") np.testing.assert_allclose( gpp_scm_ts.filter(region="World").values, gpp_scm_ts.filter(region="World|Land").values, ); compare_weighting_options(gpp) compare_weighting_options(csoilfast)
Collapsing a non-contiguous coordinate. Metadata may not be fully descriptive for 'latitude'. Collapsing a non-contiguous coordinate. Metadata may not be fully descriptive for 'longitude'.
BSD-2-Clause
notebooks/atmos-land-ocean-handling.ipynb
lewisjared/netcdf-scm
AtmosphereFinally we look at atmospheric data.
tas = CMIP6OutputCube() tas.load_data_from_path(tas_file) tas.netcdf_scm_realm
_____no_output_____
BSD-2-Clause
notebooks/atmos-land-ocean-handling.ipynb
lewisjared/netcdf-scm
If we have atmosphere data, then we have global coverage and so can split data into both the land and ocean boxes.
fig = plt.figure(figsize=(16, 14)) ax1 = fig.add_subplot(311) tas.get_scm_timeseries( regions=[ "World", "World|Land", "World|Ocean", "World|Northern Hemisphere", "World|Southern Hemisphere", ] ).line_plot(color="region", ax=ax1) ax2 = fig.add_subplot(312, sharey=ax1, sh...
Collapsing spatial coordinate 'latitude' without weighting
BSD-2-Clause
notebooks/atmos-land-ocean-handling.ipynb
lewisjared/netcdf-scm
As our data is global, the "World" data is simply an area-weighted mean.
tas_area = tas.get_metadata_cube( tas.areacell_var ).cube tas_area_weights = broadcast_onto_lat_lon_grid( tas, tas_area.data ) tas_area_weighted_mean = tas.cube.collapsed( ["latitude", "longitude"], iris.analysis.MEAN, weights=tas_area_weights ) netcdf_scm_calculated = tas.get_scm_timeseries(...
Not calculating land fractions as all required cubes are not available
BSD-2-Clause
notebooks/atmos-land-ocean-handling.ipynb
lewisjared/netcdf-scm
The "World|Land" data is surface fraction weighted.
tas_sf = tas.get_metadata_cube( tas.surface_fraction_var ).cube tas_area_sf = tas_area * tas_sf tas_area_sf_weights = broadcast_onto_lat_lon_grid( tas, tas_area_sf.data ) tas_area_sf_weighted_mean = tas.cube.collapsed( ["latitude", "longitude"], iris.analysis.MEAN, weights=tas_area_sf_weights...
Not calculating land fractions as all required cubes are not available
BSD-2-Clause
notebooks/atmos-land-ocean-handling.ipynb
lewisjared/netcdf-scm
The "World|Ocean" data is also surface fraction weighted (calculated as 100 minus land surface fraction).
tas_sf_ocean = tas.get_metadata_cube( tas.surface_fraction_var ).cube tas_sf_ocean.data = 100 - tas_sf_ocean.data tas_area_sf_ocean = tas_area * tas_sf_ocean tas_area_sf_ocean_weights = broadcast_onto_lat_lon_grid( tas, tas_area_sf_ocean.data ) tas_area_sf_ocean_weighted_mean = tas.cube.collapsed( ["...
Not calculating land fractions as all required cubes are not available
BSD-2-Clause
notebooks/atmos-land-ocean-handling.ipynb
lewisjared/netcdf-scm
Decision Tree Classification Part 4
import numpy as np import matplotlib.pyplot as plt import pandas as pd import warnings warnings.filterwarnings("ignore") # yahoo finance is used to fetch data import yfinance as yf yf.pdr_override() # input symbol = 'AMD' start = '2014-01-01' end = '2019-01-01' # Read data dataset = yf.download(symbol,start,end) ...
_____no_output_____
MIT
Stock_Algorithms/Decision_Trees_Classification_Part4.ipynb
NTForked-ML/Deep-Learning-Machine-Learning-Stock
T81-558: Applications of Deep Neural Networks**Module 11: Natural Language Processing with Hugging Face*** Instructor: [Jeff Heaton](https://sites.wustl.edu/jeffheaton/), McKelvey School of Engineering, [Washington University in St. Louis](https://engineering.wustl.edu/Programs/Pages/default.aspx)* For more informati...
try: %tensorflow_version 2.x COLAB = True print("Note: using Google CoLab") except: print("Note: not using Google CoLab") COLAB = False
Note: using Google CoLab
Apache-2.0
t81_558_class_11_04_hf_train.ipynb
igunduz/t81_558_deep_learning
Part 11.4: Training Hugging Face Models Up to this point, we've used data and models from the Hugging Face hub unmodified. In this section, we will transfer and train a Hugging Face model. To achieve this training, we will use Hugging Face data sets, tokenizers, and pretrained models.We begin by installing Hugging Fac...
# HIDE OUTPUT !pip install transformers !pip install transformers[sentencepiece] !pip install datasets
Collecting transformers Downloading transformers-4.17.0-py3-none-any.whl (3.8 MB)  |████████████████████████████████| 3.8 MB 15.1 MB/s [?25hRequirement already satisfied: requests in /usr/local/lib/python3.7/dist-packages (from transformers) (2.23.0) Requirement already satisfied: regex!=2019.12.17 in /usr/l...
Apache-2.0
t81_558_class_11_04_hf_train.ipynb
igunduz/t81_558_deep_learning
We begin by loading the emotion data set from the Hugging Face hub. Emotion is a dataset of English Twitter messages with six basic emotions: anger, fear, joy, love, sadness, and surprise. The following code loads the emotion data set from the Hugging Face hub.
# HIDE OUTPUT from datasets import load_dataset emotions = load_dataset("emotion")
_____no_output_____
Apache-2.0
t81_558_class_11_04_hf_train.ipynb
igunduz/t81_558_deep_learning
You can see a single observation from the training data set here. This observation includes both the text sample and the assigned emotion label. The label is a numeric index representing the assigned emotion.
emotions['train'][2]
_____no_output_____
Apache-2.0
t81_558_class_11_04_hf_train.ipynb
igunduz/t81_558_deep_learning
We can display the labels in order of their index labels.
emotions['train'].features
_____no_output_____
Apache-2.0
t81_558_class_11_04_hf_train.ipynb
igunduz/t81_558_deep_learning
Next, we utilize Hugging Face tokenizers and data sets together. The following code tokenizes the entire emotion data set. You can see below that the code has transformed the training set into subword tokens that are now ready to be used in conjunction with a transformer for either inference or training.
# HIDE OUTPUT from transformers import AutoTokenizer def tokenize(rows): return tokenizer(rows['text'], padding="max_length", truncation=True) model_ckpt = "distilbert-base-uncased" tokenizer=AutoTokenizer.from_pretrained(model_ckpt) emotions.set_format(type=None) tokenized_datasets = emotions.map(tokenize, batch...
_____no_output_____
Apache-2.0
t81_558_class_11_04_hf_train.ipynb
igunduz/t81_558_deep_learning
We will utilize the Hugging Face DefaultDataCollator to transform the emotion data set into TensorFlow type data that we can use to finetune a neural network.
from transformers import DefaultDataCollator data_collator = DefaultDataCollator(return_tensors="tf")
_____no_output_____
Apache-2.0
t81_558_class_11_04_hf_train.ipynb
igunduz/t81_558_deep_learning
Now we generate a shuffled training and evaluation data set.
small_train_dataset = tokenized_datasets["train"].shuffle(seed=42) small_eval_dataset = tokenized_datasets["test"].shuffle(seed=42)
_____no_output_____
Apache-2.0
t81_558_class_11_04_hf_train.ipynb
igunduz/t81_558_deep_learning
We can now generate the TensorFlow data sets. We specify which columns should map to the input features and labels. We do not need to shuffle because we previously shuffled the data.
tf_train_dataset = small_train_dataset.to_tf_dataset( columns=["attention_mask", "input_ids", "token_type_ids"], label_cols=["labels"], shuffle=True, collate_fn=data_collator, batch_size=8, ) tf_validation_dataset = small_eval_dataset.to_tf_dataset( columns=["attention_mask", "input_ids", "toke...
_____no_output_____
Apache-2.0
t81_558_class_11_04_hf_train.ipynb
igunduz/t81_558_deep_learning
We will now load the distilbert model for classification. We will adjust the pretrained weights to predict the emotions of text lines.
# HIDE OUTPUT import tensorflow as tf from transformers import TFAutoModelForSequenceClassification model = TFAutoModelForSequenceClassification.from_pretrained(\ "distilbert-base-uncased", num_labels=6)
_____no_output_____
Apache-2.0
t81_558_class_11_04_hf_train.ipynb
igunduz/t81_558_deep_learning
We now train the neural network. Because the network is already pretrained, we use a small learning rate.
model.compile( optimizer=tf.keras.optimizers.Adam(learning_rate=5e-5), loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=tf.metrics.SparseCategoricalAccuracy(), ) model.fit(tf_train_dataset, validation_data=tf_validation_dataset, \ epochs=5)
Epoch 1/5 2000/2000 [==============================] - 360s 174ms/step - loss: 0.3720 - sparse_categorical_accuracy: 0.8669 - val_loss: 0.1728 - val_sparse_categorical_accuracy: 0.9180 Epoch 2/5 2000/2000 [==============================] - 347s 174ms/step - loss: 0.1488 - sparse_categorical_accuracy: 0.9338 - val_loss:...
Apache-2.0
t81_558_class_11_04_hf_train.ipynb
igunduz/t81_558_deep_learning
Paired a x b cross tableAlternative of z-test and chi-square test
# Enable the commands below when running this program on Google Colab. # !pip install arviz==0.7 # !pip install pymc3==3.8 # !pip install Theano==1.0.4 import numpy as np import pandas as pd from scipy import stats import matplotlib.pyplot as plt import seaborn as sns import pymc3 as pm import math plt.style.use('s...
_____no_output_____
MIT
src/bayes/proportion/cross_table/paired_axb.ipynb
shigeodayo/ex_design_analysis
Q. A restaurant counted up what wines (red, rose, and white) customers chose for their main dishes (roast veal, pasta gorgonzola, and sole meuniere). Analyze the relationship between main dish and wine.
a = 3 # Kinds of man dishes b = 3 # Kinds of wines data = pd.DataFrame([[19, 12, 6], [8, 8, 4], [15, 19, 18]], columns=['Veal', 'Pasta', 'Sole'], index=['Red', 'Rose', 'White']) observed = [data['Veal']['Red'], data['Pasta']['Red'], data['Sole']['Red'], data['Veal']['Rose'], ...
_____no_output_____
MIT
src/bayes/proportion/cross_table/paired_axb.ipynb
shigeodayo/ex_design_analysis
Bayesian analysis
with pm.Model() as model: # Prior distribution p_ = pm.Uniform('p_', 0, 1, shape=(a * b)) p = pm.Deterministic('p', p_ / pm.math.sum(p_)) # Likelihood x = pm.Multinomial('x', n=N, p=p, observed=observed) # Marginal probability p1d = pm.Deterministic('p1d', p[0] + p[1] + p[2]) # p1. = p11 + p12 + p13 ...
_____no_output_____
MIT
src/bayes/proportion/cross_table/paired_axb.ipynb
shigeodayo/ex_design_analysis
Independence and association
plt.boxplot( [chain['e'][:,0], chain['e'][:,1], chain['e'][:,2], chain['e'][:,3], chain['e'][:,4], chain['e'][:,5], chain['e'][:,6], chain['e'][:,7], chain['e'][:,8],], labels=['e11', 'e12', 'e13', 'e21', 'e22', 'e23', 'e31', 'e32', 'e33']) plt.show() print("Cramer's ass...
_____no_output_____
MIT
src/bayes/proportion/cross_table/paired_axb.ipynb
shigeodayo/ex_design_analysis
RQ1: 「子牛」料理を選んだ客は「赤」を選び「白」は避け、「舌平目」料理を選んだ客は「白」を選び「赤」は避ける
val_1 = (chain['e'][:,0] > 0).mean() * (chain['e'][:,8] > 0).mean() * (chain['e'][:,6] < 0).mean() * (chain['e'][:,2] < 0).mean() print('Probability: {:.3f} %'.format(val_1 * 100))
_____no_output_____
MIT
src/bayes/proportion/cross_table/paired_axb.ipynb
shigeodayo/ex_design_analysis
RQ2: 「子牛」料理を選んだ客は「赤」を選び「白」は避け、「舌平目」料理を選んだ客は「白」を選ぶ
val_2 = (chain['e'][:,0] > 0).mean() * (chain['e'][:,8] > 0).mean() * (chain['e'][:,6] < 0).mean() print('Probability: {:.3f} %'.format(val_2 * 100))
_____no_output_____
MIT
src/bayes/proportion/cross_table/paired_axb.ipynb
shigeodayo/ex_design_analysis
RQ3: 「子牛」料理を選んだ客は「赤」を選び、「舌平目」料理を選んだ客は「白」を選ぶ
val_3 = (chain['e'][:,0] > 0).mean() * (chain['e'][:,8] > 0).mean() print('Probability: {:.3f} %'.format(val_3 * 100))
_____no_output_____
MIT
src/bayes/proportion/cross_table/paired_axb.ipynb
shigeodayo/ex_design_analysis
Sebastian Raschka, 2015 Python Machine Learning Essentials Chapter 3 - A Tour of Machine Learning Classifiers Using Scikit-Learn Note that the optional watermark extension is a small IPython notebook plugin that I developed to make the code reproducible. You can just skip the following line(s).
%load_ext watermark %watermark -a 'Sebastian Raschka' -u -d -v -p numpy,pandas,matplotlib,scikit-learn # to install watermark just uncomment the following line: #%install_ext https://raw.githubusercontent.com/rasbt/watermark/master/watermark.py
_____no_output_____
MIT
3547_03_Code.ipynb
varunmuriyanat/Python-Machine-Learning
Sections- [First steps with scikit-learn](First-steps-with-scikit-learn) - [Loading and preprocessing the data](Loading-and-preprocessing-the-data ) - [Training a perceptron via scikit-learn](Training-a-perceptron-via-scikit-learn)- [Modeling class probabilities via logistic regression](Modeling-class-probabilit...
from sklearn import datasets import numpy as np iris = datasets.load_iris() X = iris.data[:, [2, 3]] y = iris.target print('Class labels:', np.unique(y))
Class labels: [0 1 2]
MIT
3547_03_Code.ipynb
varunmuriyanat/Python-Machine-Learning
Splitting data into 70% training and 30% test data:
from sklearn.cross_validation import train_test_split X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.3, random_state=0)
_____no_output_____
MIT
3547_03_Code.ipynb
varunmuriyanat/Python-Machine-Learning
Standardizing the features:
from sklearn.preprocessing import StandardScaler sc = StandardScaler() sc.fit(X_train) X_train_std = sc.transform(X_train) X_test_std = sc.transform(X_test)
_____no_output_____
MIT
3547_03_Code.ipynb
varunmuriyanat/Python-Machine-Learning
Training a perceptron via scikit-learn [[back to top](Sections)] Redefining the `plot_decision_region` function from chapter 2:
from sklearn.linear_model import Perceptron ppn = Perceptron(n_iter=40, eta0=0.1, random_state=0) ppn.fit(X_train_std, y_train) y_test.shape y_pred = ppn.predict(X_test_std) print('Misclassified samples: %d' % (y_test != y_pred).sum()) from sklearn.metrics import accuracy_score print('Accuracy: %.2f' % accuracy_score...
_____no_output_____
MIT
3547_03_Code.ipynb
varunmuriyanat/Python-Machine-Learning
Training a perceptron model using the standardized training data:
%matplotlib inline X_combined_std = np.vstack((X_train_std, X_test_std)) y_combined = np.hstack((y_train, y_test)) plot_decision_regions(X=X_combined_std, y=y_combined, classifier=ppn, test_idx=range(105,150)) plt.xlabel('petal length [standardized]') plt.ylabel('petal width [standardized]') pl...
_____no_output_____
MIT
3547_03_Code.ipynb
varunmuriyanat/Python-Machine-Learning
Modeling class probabilities via logistic regression [[back to top](Sections)] Plot sigmoid function:
%matplotlib inline import matplotlib.pyplot as plt import numpy as np def sigmoid(z): return 1.0 / (1.0 + np.exp(-z)) z = np.arange(-7, 7, 0.1) phi_z = sigmoid(z) plt.plot(z, phi_z) plt.axvline(0.0, color='k') plt.ylim(-0.1, 1.1) plt.xlabel('z') plt.ylabel('$\phi (z)$') # y axis ticks and gridline plt.yticks([0...
_____no_output_____
MIT
3547_03_Code.ipynb
varunmuriyanat/Python-Machine-Learning
Plot cost function:
def cost_1(z): return - np.log(sigmoid(z)) def cost_0(z): return - np.log(1 - sigmoid(z)) z = np.arange(-10, 10, 0.1) phi_z = sigmoid(z) c1 = [cost_1(x) for x in z] plt.plot(phi_z, c1, label='J(w) if y=1') c0 = [cost_0(x) for x in z] plt.plot(phi_z, c0, linestyle='--', label='J(w) if y=0'...
_____no_output_____
MIT
3547_03_Code.ipynb
varunmuriyanat/Python-Machine-Learning
Regularization path:
weights, params = [], [] for c in np.arange(-5, 5): lr = LogisticRegression(C=10**c, random_state=0) lr.fit(X_train_std, y_train) weights.append(lr.coef_[1]) params.append(10**c) weights = np.array(weights) plt.plot(params, weights[:, 0], label='petal length') plt.plot(params, weights[:, 1], ...
_____no_output_____
MIT
3547_03_Code.ipynb
varunmuriyanat/Python-Machine-Learning
Maximum margin classification with support vector machines [[back to top](Sections)]
from sklearn.svm import SVC svm = SVC(kernel='linear', C=1.0, random_state=0) svm.fit(X_train_std, y_train) plot_decision_regions(X_combined_std, y_combined, classifier=svm, test_idx=range(105,150)) plt.xlabel('petal length [standardized]') plt.ylabel('petal width [standardized]') plt.legend(lo...
_____no_output_____
MIT
3547_03_Code.ipynb
varunmuriyanat/Python-Machine-Learning
Solving non-linear problems using a kernel SVM [[back to top](Sections)]
import matplotlib.pyplot as plt import numpy as np %matplotlib inline np.random.seed(0) X_xor = np.random.randn(200, 2) y_xor = np.logical_xor(X_xor[:, 0] > 0, X_xor[:, 1] > 0) y_xor = np.where(y_xor, 1, -1) plt.scatter(X_xor[y_xor==1, 0], X_xor[y_xor==1, 1], c='b', marker='x', label='1') plt.scatter(X_xor[y_xor==-1,...
_____no_output_____
MIT
3547_03_Code.ipynb
varunmuriyanat/Python-Machine-Learning
Decision trees learning
from sklearn.tree import DecisionTreeClassifier tree = DecisionTreeClassifier(criterion='entropy', max_depth=3, random_state=0) tree.fit(X_train, y_train) X_combined = np.vstack((X_train, X_test)) y_combined = np.hstack((y_train, y_test)) plot_decision_regions(X_combined, y_combined, classifier...
_____no_output_____
MIT
3547_03_Code.ipynb
varunmuriyanat/Python-Machine-Learning
[[back to top](Sections)]
import matplotlib.pyplot as plt import numpy as np %matplotlib inline def gini(p): return (p)*(1 - (p)) + (1-p)*(1 - (1-p)) def entropy(p): return - p*np.log2(p) - (1 - p)*np.log2((1 - p)) def error(p): return 1 - np.max([p, 1 - p]) x = np.arange(0.0, 1.0, 0.01) ent = [entropy(p) if p != 0 else None fo...
_____no_output_____
MIT
3547_03_Code.ipynb
varunmuriyanat/Python-Machine-Learning
Combining weak to strong learners via random forests [[back to top](Sections)]
from sklearn.ensemble import RandomForestClassifier forest = RandomForestClassifier(criterion='entropy', n_estimators=10, random_state=1, n_jobs=2) forest.fit(X_train, y_train) plot_decision_regions(X_combined, y_combined...
_____no_output_____
MIT
3547_03_Code.ipynb
varunmuriyanat/Python-Machine-Learning
K-nearest neighbors - a lazy learning algorithm [[back to top](Sections)]
from sklearn.neighbors import KNeighborsClassifier knn = KNeighborsClassifier(n_neighbors=5, p=2, metric='minkowski') knn.fit(X_train_std, y_train) plot_decision_regions(X_combined_std, y_combined, classifier=knn, test_idx=range(105,150)) plt.xlabel('petal length [standardized]') plt.ylabel('p...
_____no_output_____
MIT
3547_03_Code.ipynb
varunmuriyanat/Python-Machine-Learning
12. Interactive Mapping with FoliumIn previous lessons we used `Geopandas` and `matplotlib` to create choropleth and point maps of our data. In this notebook we will take it to the next level by creating `interactive maps` with the **folium** library. > References>>This notebook provides an introduction to `folium`. ...
import pandas as pd import geopandas as gpd import numpy as np import matplotlib # base python plotting library import matplotlib.pyplot as plt # submodule of matplotlib # To display plots, maps, charts etc in the notebook %matplotlib inline import folium # popular python web mapping tool for creating Leaflet maps...
_____no_output_____
MIT
12_OPTIONAL_Interactive_Mapping_with_Folium.ipynb
reeshav-netizen/Geospatial-Fundamentals-in-Python
Check your version of `folium` and `geopandas`.Folium is a new and evolving Python library so make sure you have version 0.10.1 or later installed.
print(folium.__version__) # Make sure you have version 0.10.1 or later of folium! print(gpd.__version__) # Make sure you have version 0.7.0 or later of GeoPandas!
_____no_output_____
MIT
12_OPTIONAL_Interactive_Mapping_with_Folium.ipynb
reeshav-netizen/Geospatial-Fundamentals-in-Python
12.1 IntroductionInteractive maps serve two very important purposes in geospatial analysis. First, they provde new tools for exploratory data analysis. With an interactive map you can:- `pan` over the mapped data, - `zoom` into a smaller arear that is not easily visible when the full extent of the map is displayed, an...
%%html <iframe src="notebook_data/bartmap_example.html" width="1000" height="600"></iframe>
_____no_output_____
MIT
12_OPTIONAL_Interactive_Mapping_with_Folium.ipynb
reeshav-netizen/Geospatial-Fundamentals-in-Python
12.2 Interactive Mapping with FoliumUnder the hood, `folium` is a Python package for creating interactive maps with [Leaflet](https://leafletjs.com), a popular javascript web mapping library. Let's start by creating a interactive map with the `folium.Map` function and display it in the notebook.
# Create a new folium map and save it to the variable name map1 map1 = folium.Map(location=[37.8721, -122.2578], # lat, lon around which to center the map width="100%", # the width & height of the output map height=500, # in pixels (int) or i...
_____no_output_____
MIT
12_OPTIONAL_Interactive_Mapping_with_Folium.ipynb
reeshav-netizen/Geospatial-Fundamentals-in-Python
Let's discuss the map above and the code we used to generate it.At any time you can enter the following command to get help with `folium.Map`:
# uncomment to see help docs ?folium.Map
_____no_output_____
MIT
12_OPTIONAL_Interactive_Mapping_with_Folium.ipynb
reeshav-netizen/Geospatial-Fundamentals-in-Python
Let's make another folium map using the code below:
# Create a new folium map and save it to the variable name map1 # map1 = folium.Map(location=[37.8721, -122.2578], # lat, lon around which to center the map tiles='CartoDB Positron', #width=800, # the width & height of the output map #height=60...
_____no_output_____
MIT
12_OPTIONAL_Interactive_Mapping_with_Folium.ipynb
reeshav-netizen/Geospatial-Fundamentals-in-Python
Questions- What's new in the code?- How do you think that will change the map?Let's display the map and see what changes...
map1 # display map in notebook
_____no_output_____
MIT
12_OPTIONAL_Interactive_Mapping_with_Folium.ipynb
reeshav-netizen/Geospatial-Fundamentals-in-Python
Notice how the map changes when you change the underlying **tileset** from the default, which is `OpenStreetMap`, to `CartoDB Positron`. > [OpenStreetMap](https://www.openstreetmap.org/map=5/38.007/-95.844) is the largest free and open source dataset of geographic information about the world. So it is the default basem...
# Make changes to the code below to change the folium Map ## Try changing the values for the zoom_start and tiles parameters. map1 = folium.Map(location=[37.8721, -122.2578], # lat, lon around which to center the map tiles='Stamen Watercolor', # basemap aka baselay or tile set ...
_____no_output_____
MIT
12_OPTIONAL_Interactive_Mapping_with_Folium.ipynb
reeshav-netizen/Geospatial-Fundamentals-in-Python
12.3 Adding a Map Layer Now that we have created a folium map, let's add our California County data to the map. First, let's read that data into a Geopandas geodataframe.
# Alameda county census tract data with the associated ACS 5yr variables. ca_counties_gdf = gpd.read_file("notebook_data/california_counties/CaliforniaCounties.shp")
_____no_output_____
MIT
12_OPTIONAL_Interactive_Mapping_with_Folium.ipynb
reeshav-netizen/Geospatial-Fundamentals-in-Python
Take another brief look at the geodataframe to recall the contents.
# take a look at first two rows ca_counties_gdf.head(2) # take a look at all column names ca_counties_gdf.columns
_____no_output_____
MIT
12_OPTIONAL_Interactive_Mapping_with_Folium.ipynb
reeshav-netizen/Geospatial-Fundamentals-in-Python
Adding a layer with folium.GeoJsonFolium provides a number of ways to add vector data - points, lines, and polygons - to a map. The data we are working with are in Geopandas geodataframes. The main folium function for adding these to the map is `folium.GeoJson`.Let's build on our last map and add the census tracts as ...
map1 = folium.Map(location=[37.8721, -122.2578], # lat, lon around which to center the map tiles='CartoDB positron', # basemap aka baselay or tile set width=800, # the width & height of the output map height=600, # i...
_____no_output_____
MIT
12_OPTIONAL_Interactive_Mapping_with_Folium.ipynb
reeshav-netizen/Geospatial-Fundamentals-in-Python
That was pretty straight-forward, but `folium.GeoJSON` provides a lot of arguments for customizing the display of the data in the map. We will review some of these soon. However, at any time you can get more information about `folium.GeoJSON` by taking a look at the function documentation.
# Uncomment to view documentation # folium.GeoJson?
_____no_output_____
MIT
12_OPTIONAL_Interactive_Mapping_with_Folium.ipynb
reeshav-netizen/Geospatial-Fundamentals-in-Python
Checking and Transforming the CRSIt's always a good idea to check the **CRS** of your geodata before doing anything with that data. This is true when we use `folium` to make an interactive map. Here is how folium deals with the CRS of a geodataframe before mapping it:- Folium checks to see if the gdf has a defined CRS...
# Check the CRS of the data print(...)
_____no_output_____
MIT
12_OPTIONAL_Interactive_Mapping_with_Folium.ipynb
reeshav-netizen/Geospatial-Fundamentals-in-Python
*Click here for answers*<!--- What is the CRS of the tract data?tracts_gdf.crs How is folium dealing with the CRS of this gdf? Dynamically transformed to WGS84 (but it already is in that projection so no change)---> Styling features with `folium.GeoJson`Let's dive deeper into the `folium.GeoJson` function. Below is an...
# Define the basemap map1 = folium.Map(location=[37.8721, -122.2578], # lat, lon around which to center the map tiles='CartoDB Positron', width=1000, # the width & height of the output map height=600, # in pixels ...
_____no_output_____
MIT
12_OPTIONAL_Interactive_Mapping_with_Folium.ipynb
reeshav-netizen/Geospatial-Fundamentals-in-Python
ExerciseCopy the code from our last map and paste it below. Take a few minutes edit the code to change the style of the census tract polygons.
# Your code here map1 = folium.Map(location=[37.8721, -122.2578], # lat, lon around which to center the map tiles='Stamen Watercolor', width=1000, # the width & height of the output map height=600, # in pixels ...
_____no_output_____
MIT
12_OPTIONAL_Interactive_Mapping_with_Folium.ipynb
reeshav-netizen/Geospatial-Fundamentals-in-Python