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
Everything is working as expected! Now you will see how multiple workers can be used as a distributed strategy. Multi-worker ConfigurationNow let's enter the world of multi-worker training. In TensorFlow, the `TF_CONFIG` environment variable is required for training on multiple machines, each of which possibly has a d...
tf_config = { 'cluster': { 'worker': ['localhost:12345', 'localhost:23456'] }, 'task': {'type': 'worker', 'index': 0} }
_____no_output_____
CC0-1.0
C3_W3_Lab_1_Distributed_Training.ipynb
jimfhahn/Machine-Learning-Tutorials
Here is the same `TF_CONFIG` serialized as a JSON string:
json.dumps(tf_config)
_____no_output_____
CC0-1.0
C3_W3_Lab_1_Distributed_Training.ipynb
jimfhahn/Machine-Learning-Tutorials
Explaining the TF_CONFIG exampleIn this example you set a `TF_CONFIG` with 2 workers on `localhost`. In practice, users would create multiple workers on external IP addresses/ports, and set `TF_CONFIG` on each worker appropriately.Since you set the task `type` to `"worker"` and the task `index` to `0`, **this machine ...
strategy = tf.distribute.MultiWorkerMirroredStrategy()
_____no_output_____
CC0-1.0
C3_W3_Lab_1_Distributed_Training.ipynb
jimfhahn/Machine-Learning-Tutorials
`MultiWorkerMirroredStrategy` creates copies of all variables in the model's layers on each device across all workers. It uses `CollectiveOps`, a TensorFlow op for collective communication, to aggregate gradients and keep the variables in sync. The [official TF distributed training guide](https://www.tensorflow.org/g...
# Implementing distributed strategy via a context manager with strategy.scope(): multi_worker_model = mnist.build_and_compile_cnn_model()
_____no_output_____
CC0-1.0
C3_W3_Lab_1_Distributed_Training.ipynb
jimfhahn/Machine-Learning-Tutorials
Note: `TF_CONFIG` is parsed and TensorFlow's GRPC servers are started at the time `MultiWorkerMirroredStrategy()` is called, so the `TF_CONFIG` environment variable must be set before a `tf.distribute.Strategy` instance is created. **Since `TF_CONFIG` is not set yet the above strategy is effectively single-worker train...
%%writefile main.py import os import json import tensorflow as tf import mnist # Your module # Define batch size per_worker_batch_size = 64 # Get TF_CONFIG from the env variables and save it as JSON tf_config = json.loads(os.environ['TF_CONFIG']) # Infer number of workers from tf_config num_workers = len(tf_config...
Writing main.py
CC0-1.0
C3_W3_Lab_1_Distributed_Training.ipynb
jimfhahn/Machine-Learning-Tutorials
In the code snippet above note that the `global_batch_size`, which gets passed to `Dataset.batch`, is set to `per_worker_batch_size * num_workers`. This ensures that each worker processes batches of `per_worker_batch_size` examples regardless of the number of workers. The current directory should now contain both Pytho...
!ls *.py
main.py mnist.py
CC0-1.0
C3_W3_Lab_1_Distributed_Training.ipynb
jimfhahn/Machine-Learning-Tutorials
Set TF_CONFIG environment variableNow json-serialize the `TF_CONFIG` and add it to the environment variables:
# Set TF_CONFIG env variable os.environ['TF_CONFIG'] = json.dumps(tf_config)
_____no_output_____
CC0-1.0
C3_W3_Lab_1_Distributed_Training.ipynb
jimfhahn/Machine-Learning-Tutorials
And terminate all background processes:
# first kill any previous runs %killbgscripts
All background processes were killed.
CC0-1.0
C3_W3_Lab_1_Distributed_Training.ipynb
jimfhahn/Machine-Learning-Tutorials
Launch the first workerNow, you can launch a worker process that will run the `main.py` and use the `TF_CONFIG`:
%%bash --bg python main.py &> job_0.log
Starting job # 0 in a separate thread.
CC0-1.0
C3_W3_Lab_1_Distributed_Training.ipynb
jimfhahn/Machine-Learning-Tutorials
There are a few things to note about the above command:1. It uses the `%%bash` which is a [notebook "magic"](https://ipython.readthedocs.io/en/stable/interactive/magics.html) to run some bash commands.2. It uses the `--bg` flag to run the `bash` process in the background, because this worker will not terminate. It wait...
# Wait for logs to be written to the file time.sleep(10)
_____no_output_____
CC0-1.0
C3_W3_Lab_1_Distributed_Training.ipynb
jimfhahn/Machine-Learning-Tutorials
Now look what's been output to the worker's logfile so far using the `cat` command:
%%bash cat job_0.log
2021-09-11 18:07:51.001016: E tensorflow/stream_executor/cuda/cuda_driver.cc:271] failed call to cuInit: CUDA_ERROR_NO_DEVICE: no CUDA-capable device is detected 2021-09-11 18:07:51.001099: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:156] kernel driver does not appear to be running on this host (c7276df34cc0)...
CC0-1.0
C3_W3_Lab_1_Distributed_Training.ipynb
jimfhahn/Machine-Learning-Tutorials
The last line of the log file should say: `Started server with target: grpc://localhost:12345`. The first worker is now ready, and is waiting for all the other worker(s) to be ready to proceed. Launch the second workerNow update the `tf_config` for the second worker's process to pick up:
tf_config['task']['index'] = 1 os.environ['TF_CONFIG'] = json.dumps(tf_config)
_____no_output_____
CC0-1.0
C3_W3_Lab_1_Distributed_Training.ipynb
jimfhahn/Machine-Learning-Tutorials
Now launch the second worker. This will start the training since all the workers are active (so there's no need to background this process):
%%bash python main.py
Epoch 1/3 1/70 [..............................] - ETA: 1:31 - loss: 2.3172 - accuracy: 0.0547 2/70 [..............................] - ETA: 10s - loss: 2.3061 - accuracy: 0.0742 ...
CC0-1.0
C3_W3_Lab_1_Distributed_Training.ipynb
jimfhahn/Machine-Learning-Tutorials
Now if you recheck the logs written by the first worker you'll see that it participated in training that model:
%%bash cat job_0.log
2021-09-11 18:07:51.001016: E tensorflow/stream_executor/cuda/cuda_driver.cc:271] failed call to cuInit: CUDA_ERROR_NO_DEVICE: no CUDA-capable device is detected 2021-09-11 18:07:51.001099: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:156] kernel driver does not appear to be running on this host (c7276df34cc0)...
CC0-1.0
C3_W3_Lab_1_Distributed_Training.ipynb
jimfhahn/Machine-Learning-Tutorials
Chip Time vs Bridge Time
keyx = "subChip Time" keyy = "subBeat the Bridge" corr_co = np.corrcoef(df[keyx]/60., df[keyy]/60.) plt.scatter(df[keyx]/60., df[keyy]/60.) plt.xlabel(keyx.replace("sub", "") + " Minutes") plt.ylabel(keyy.replace("sub", "") + " Minutes") print(corr_co[1,0])
0.981240820274
MIT
ABPSoton10k/Data_Analysis.ipynb
RobFirth/zoidberg
Time vs Bib Number
keyx = "subChip Time" keyy = "Bib No" corr_co = np.corrcoef(df[keyx]/60., df[keyy]) plt.scatter(df[keyx]/60., df[keyy]) plt.xlabel(keyx.replace("sub", "") + " Minutes") plt.ylabel(keyy.replace("sub", "")) print(corr_co[1,0]) # plt.scatter(df["Pos"], df["subChip Time"]) # plt.scatter(df["subChip Time"], df["subBeat t...
_____no_output_____
MIT
ABPSoton10k/Data_Analysis.ipynb
RobFirth/zoidberg
- weighted NN based on (possibly batch) grad descent of feature weights- find optimizer engine- find fast KNN for query time- Define metric specific sampling function (based on distance)) (possibly optimize func hyperparams during training, like $\alpha$ for $P_{sample} = Dist^{-\alpha}$ and others)- Define cost functi...
import os from functools import partial import numpy as np from scipy import sparse from scipy.optimize import minimize from skdensity.utils import cos_sim_query, sample_from_dist_array, sparse_mul_row, make_bimodal_regression,make_distplot from skdensity.metrics import kde_entropy, quantile, bimodal_variance, margi...
_____no_output_____
Apache-2.0
notebooks/05_neighbors.ipynb
AlanGanem/scikit-density
Training data
X_train, y_train, X_test, y_test = make_bimodal_regression(10000, random_state = 42, bimodal_inbalance = 5)
_____no_output_____
Apache-2.0
notebooks/05_neighbors.ipynb
AlanGanem/scikit-density
Weighted KNN density estimator cvxpy
from time import time def train_func(x): # draw batch from x #X_train, y_train, n_samples = 40 batch_size = X_train.shape[0]//5 tic = time() n_neighbors = max(2, int(x[-1])) weights = x[:-1] idx = np.random.choice([*range(X_train.shape[0])], size = batch_size, replace = False) X_bat...
_____no_output_____
Apache-2.0
notebooks/05_neighbors.ipynb
AlanGanem/scikit-density
Weighted KNN DensityEstimator PyTorch
import pytorch_lightning as pl from torch.utils.data import TensorDataset, DataLoader import torch from torch import nn from torch.autograd import Variable as V def update_tensor(tensor, new_values): try: tensor = tensor.data.fill_(1)*torch.Tensor(new_values) except: print(tensor.shape, new_val...
_____no_output_____
Apache-2.0
notebooks/05_neighbors.ipynb
AlanGanem/scikit-density
Load Digit Dataset
digits = load_digits() def draw_digits(X, y): fig = plt.figure(1, figsize=(8, 8)) plt.scatter(X[:, 0], X[:, 1], c=y, edgecolor='none', alpha=0.5, cmap=plt.cm.get_cmap('Spectral', 10)) plt.xlabel('component 1') plt.ylabel('component 2') plt.colorbar() plt.show();
_____no_output_____
MIT
PCA/PCA.ipynb
nachiket273/ML_Algo_Implemented
sklearn PCA
pca = PCA(n_components=2, random_state=17).fit(digits.data) data_pca = pca.transform(digits.data) pca.explained_variance_ratio_, pca.explained_variance_, pca.singular_values_, pca.components_ data_pca draw_digits(data_pca, digits.target)
_____no_output_____
MIT
PCA/PCA.ipynb
nachiket273/ML_Algo_Implemented
Our Implementation
pca1 = MyPCA(n_components=2, solver='svd') pca1.fit(digits.data) data_pca1 = pca1.transform(digits.data) pca1.explained_variance_ratio_, pca1.explained_variance_, pca1.singular_values_, pca1.components_ data_pca1 draw_digits(data_pca1, digits.target)
_____no_output_____
MIT
PCA/PCA.ipynb
nachiket273/ML_Algo_Implemented
eig solver
pca_eig = MyPCA(n_components=2, solver='eig') pca_eig.fit(digits.data) data_eig = pca_eig.transform(digits.data) pca_eig.explained_variance_ratio_, pca_eig.explained_variance_, pca_eig.singular_values_, pca_eig.components_ data_eig draw_digits(data_eig, digits.target)
_____no_output_____
MIT
PCA/PCA.ipynb
nachiket273/ML_Algo_Implemented
Iris Dataset Let's try to plot 3 components after PCA.https://scikit-learn.org/stable/auto_examples/decomposition/plot_pca_iris.htmlsphx-glr-auto-examples-decomposition-plot-pca-iris-py
from mpl_toolkits.mplot3d import Axes3D def plot_components(X, y): fig = plt.figure(1, figsize=(12, 8)) plt.clf() ax = Axes3D(fig, rect=[0, 0, .95, 1], elev=48, azim=134) for name, label in [('Setosa', 0), ('Versicolour', 1), ('Virginica', 2)]: ax.text3D(X[y == label, 0].mean(), ...
_____no_output_____
MIT
PCA/PCA.ipynb
nachiket273/ML_Algo_Implemented
sklearn
pca_3d = PCA(n_components=3, random_state=17).fit(X) X_3d = pca_3d.transform(X) plot_components(X_3d, y)
_____no_output_____
MIT
PCA/PCA.ipynb
nachiket273/ML_Algo_Implemented
Our's: Solver:svd
pca_3d_svd = MyPCA(n_components=3) pca_3d_svd.fit(X) X_3d_svd = pca_3d_svd.transform(X) plot_components(X_3d_svd, y)
_____no_output_____
MIT
PCA/PCA.ipynb
nachiket273/ML_Algo_Implemented
Our's: Solver:eig fit_transform
pca_3d_eig = MyPCA(n_components=3, solver='eig') X_3d_eig = pca_3d_eig.fit_transform(X) plot_components(X_3d_eig, y)
_____no_output_____
MIT
PCA/PCA.ipynb
nachiket273/ML_Algo_Implemented
Sobel Operator
#initializing Sobel Operator gx_sobel = [[-1,-2,-1], [0,0,0], [1,2,1]] gy_sobel = [[-1,0,1], [-2,0,2], [-1,0,1]] x_sobel = list(map(list,zip(*gx_sobel))) y_sobel = list(map(list,zip(*gy_sobel)))
_____no_output_____
MIT
Hough Transform Circles.ipynb
Mgosi/Hough-Transform
Applying Gradient
#Used to pad the image img_x = [[0]*902 for i in range(602)] img_y= [[0]*902 for i in range(602)] #Finding the Gradient to distinguish the images clearly. Especially the edges of the images #Along X Axis for i in range(1,img.shape[0]-1): for j in range(1,img.shape[1]-1): img_x[i][j] = img[i+1][j] - img[i-...
C:\Anaconda3.6\lib\site-packages\ipykernel_launcher.py:10: RuntimeWarning: overflow encountered in ubyte_scalars # Remove the CWD from sys.path while we load stuff. C:\Anaconda3.6\lib\site-packages\ipykernel_launcher.py:15: RuntimeWarning: overflow encountered in ubyte_scalars from ipykernel import kernelapp as app...
MIT
Hough Transform Circles.ipynb
Mgosi/Hough-Transform
Convolution
#Convolution import math sobelgx = [[0]*img.shape[1] for i in range(img.shape[0])] #Creating empty 2D Lists sobelgy = [[0]*img.shape[1] for i in range(img.shape[0])] sobel = [[0]*img.shape[1] for i in range(img.shape[0])] sobel_add = [[0]*img.shape[1] for i in range(img.shape[0])] #Multiplying the sobel operator wi...
_____no_output_____
MIT
Hough Transform Circles.ipynb
Mgosi/Hough-Transform
Normalization
theta = [] for i in range(0,360): theta.append(i) theta = np.asarray(theta) img = cv2.imread("T3_Images/Sobel_Y.png", 0) print (img) R = 22 thres_img = np.zeros((img.shape[0], img.shape[1])) for i in range(img.shape[0]): for j in range(img.shape[1]): if img[i][j] > 100: thres_img[i][j] = 255...
519 85
MIT
Hough Transform Circles.ipynb
Mgosi/Hough-Transform
**Important**: This notebook is different from the other as it directly calls **ImageJ Kappa plugin** using the [`scyjava` ImageJ brige](https://github.com/scijava/scyjava).Since Kappa uses ImageJ1 features, you might not be able to run this notebook on an headless machine (need to be tested).
from pathlib import Path import pandas as pd import numpy as np from tqdm.auto import tqdm import sys; sys.path.append("../../") import pykappa # Init ImageJ with Fiji plugins # It can take a while if Java artifacts are not yet cached. import imagej java_deps = [] java_deps.append('org.scijava:Kappa:1.7.1') ij = imag...
_____no_output_____
MIT
Analysis/Notebooks/Spiral Dataset/2_Measure_Curvature.ipynb
fiji/Kappa
Pertussis Model Based on the paper: https://pubmed.ncbi.nlm.nih.gov/11561978/*By: Andrés Felipe Escallón Portilla***March 2021** SIR Pertussis Model (simplified 6x6 ODE):
import numpy as np from scipy.integrate import odeint import matplotlib.pyplot as plt # Total population, N. #N = 15490000 #1996 (Netherlands) #B=80000 #new borns B=100 #% # Initial number of susceptible, infected and recovered individuals S10, V0, I10, S20, I20, R0 = B, 0, 0 , 0, 0, 0 # Model parameters: v_mean,...
_____no_output_____
CC0-1.0
SIR_Pertussis_Model_(simplified_6x6_ODE).ipynb
felipeescallon/Pertussis-Model
Embedding in GTK3 with a navigation toolbarDemonstrate NavigationToolbar with GTK3 accessed via pygobject.
import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk from matplotlib.backends.backend_gtk3 import ( NavigationToolbar2GTK3 as NavigationToolbar) from matplotlib.backends.backend_gtk3agg import ( FigureCanvasGTK3Agg as FigureCanvas) from matplotlib.figure import Figure import numpy as np wi...
_____no_output_____
MIT
matplotlib/gallery_jupyter/user_interfaces/embedding_in_gtk3_panzoom_sgskip.ipynb
kingreatwill/penter
Classification 2 Exercise 1: Exploratory Data Analysis OverviewThe objective of this course is to build models to predict customer churn for a fictitious telco company. Before we start creating models, let's begin by having a closer look at our data and doing some basic data wrangling.Go through this notebook and modi...
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns # TASK: Import visualization libraries, matplotlib and seaborn using standard aliases plt and sns respectively import warnings # silence all warnings warnings.filterwarnings("ignore") # plotting settings plt.style.use(['sea...
_____no_output_____
MIT
classification/learnai_classification2/Exercises/Ex_EDA.start.ipynb
lsantiago002/ai4i-learn
Reading in the Data
# TASK: Read in the Excel file. Use the parameter na_values=" " to convert any empty cells to a NA value. # You may also need to use parameter engine='openpyxl') in newer versions of pandas if you encounter an XLRD error. data = pd.read_excel('../../data/raw/Telco_customer_churn.xlsx', na_values='NA',engine='openpyxl')...
_____no_output_____
MIT
classification/learnai_classification2/Exercises/Ex_EDA.start.ipynb
lsantiago002/ai4i-learn
Basic Information
# TASK: Display the number of rows and columns for the dataset print("Rows & Columns: {}".format(data.shape)) data.info() # TASK: Display the datatypes for the columns in the dataframe i.e. use the dtypes variable # How many columns are numerical and how many are non-numerical obj_cols = data.select_dtypes(include="obj...
_____no_output_____
MIT
classification/learnai_classification2/Exercises/Ex_EDA.start.ipynb
lsantiago002/ai4i-learn
TASK: Display first few values of the dataframeBased on this and the previous display, how would you describe the columns with a small number (less than 10) of unique values?Based from above, we can say that all the customers are in the same country and state. Most of the columns are categorical like Gender with *Male*...
# TASK: Let's analyze the values for the categorical features (columns with less than 10 unique values) for id, row in data.nunique().iteritems(): # this counts the number of unique values for each feature and returns the result as a dictionary if(row < 10): # TASK: Print out the unique values for the featu...
MultipleLines : ['No' 'No phone service' 'Yes'] InternetService : ['DSL' 'Fiber optic' 'No'] OnlineSecurity : ['No' 'No internet service' 'Yes'] OnlineBackup : ['No' 'No internet service' 'Yes'] DeviceProtection : ['No' 'No internet service' 'Yes'] TechSupport : ['No' 'No internet service' 'Yes'] StreamingTV : ['No' 'N...
MIT
classification/learnai_classification2/Exercises/Ex_EDA.start.ipynb
lsantiago002/ai4i-learn
**Observations**- The value 'No phone service' found in MultipleLines is already captured by the PhoneService feature ('No' value)- The value 'No internet service' found in the several features is already captured by InternetService feature ('No' value)- Values that are longer or more complex may need to be simplified....
# Replace 'No phone service' data['MultipleLines'] = data['MultipleLines'].replace({'No phone service':'No'}) # TASK: Replace 'No internet service' for col in ['OnlineSecurity', 'OnlineBackup', 'DeviceProtection', 'TechSupport', 'StreamingTV', 'StreamingMovies']: # similar to the operation for 'No phone service' ab...
_____no_output_____
MIT
classification/learnai_classification2/Exercises/Ex_EDA.start.ipynb
lsantiago002/ai4i-learn
Additional Exploration**TASK:** This is the open-ended section of the exercise. Use any exploration techniques that you know to further explore and understand your data. We expect a number of visualizations that can show the relationships between features as well as between features and the outcome variable 'ChurnLabe...
print("Categorical columns: {}\n".format(obj_cols)) print("Numerical columns: {}\n".format(num_cols)) print("Total columns: {} categorical, {} numerical.".format(len(obj_cols), len(num_cols)))
Categorical columns: Index(['CustomerID', 'Gender', 'SeniorCitizen', 'Partner', 'Dependents', 'PhoneService', 'MultipleLines', 'InternetService', 'OnlineSecurity', 'OnlineBackup', 'DeviceProtection', 'TechSupport', 'StreamingTV', 'StreamingMovies', 'Contract', 'PaperlessBilling', 'PaymentMethod', ...
MIT
classification/learnai_classification2/Exercises/Ex_EDA.start.ipynb
lsantiago002/ai4i-learn
**Utilities Functions**Let's define some helper functions that will help us iterate through all the columns with same datatype.
# Example: Look at Churn vs MonthCharges plt.clf() for label in ['Yes','No']: subset = data[data.ChurnLabel==label] # Draw the density plot sns.distplot(subset['MonthlyCharges'], hist = False, kde = True, kde_kws = {'linewidth': 3, 'shade':True}, label = label) # ...
_____no_output_____
MIT
classification/learnai_classification2/Exercises/Ex_EDA.start.ipynb
lsantiago002/ai4i-learn
Estimating the biomass of terrestrial arthropodsTo estimate the biomass of terrestrial arthropods, we rely on two parallel methods - a method based on average biomass densities of arthropods extrapolated to the global ice-free land surface, and a method based on estimates of the average carbon content of a characteris...
import pandas as pd import numpy as np import matplotlib.pyplot as plt from scipy.stats import gmean import sys sys.path.insert(0, '../../statistics_helper/') from CI_helper import * pd.options.display.float_format = '{:,.1f}'.format # Load global stocks data gc_data = pd.read_excel('terrestrial_arthropods_data.xlsx','...
_____no_output_____
MIT
animals/arhtropods/.ipynb_checkpoints/terrestrial arthropods-checkpoint.ipynb
yinonbaron/biomass_distribution
Here is a sample from Brockie & Moeed:
bm_data = pd.read_excel('terrestrial_arthropods_data.xlsx','Brockie & Moeed',skiprows=1) bm_data.head()
_____no_output_____
MIT
animals/arhtropods/.ipynb_checkpoints/terrestrial arthropods-checkpoint.ipynb
yinonbaron/biomass_distribution
We calculate the sum of biomass of all the groups of arthropods in each study to provide an estimate for the total biomass density of arthropods in litter:
gc_study = gc_data.groupby('Study').sum() bm_study = bm_data.groupby('Study').sum() print('The estimate from Brockie & Moeed:') bm_study print('The estimate from Gist & Crossley:') gc_study
The estimate from Gist & Crossley:
MIT
animals/arhtropods/.ipynb_checkpoints/terrestrial arthropods-checkpoint.ipynb
yinonbaron/biomass_distribution
In cases where data is coflicting between the two studies, we calculate the mean. We merge the data from the papers to generate a list of estimates on the total biomass density of arhtropods
# Concat the data from the two studies conc = pd.concat([gc_study,bm_study]) conc_mean = conc.groupby(conc.index).mean() conc_mean
_____no_output_____
MIT
animals/arhtropods/.ipynb_checkpoints/terrestrial arthropods-checkpoint.ipynb
yinonbaron/biomass_distribution
We calculate from the dry weight and wet weight estimates the biomass density in g C $m^{-2}$ by assuming 70% water content and 50% carbon in dry mass:
# Fill places with no dry weight estimate with 30% of the wet weight estimate conc_mean['Dry weight [g m^-2]'].fillna(conc_mean['Wet weight [g m^-2]']*0.3,inplace=True) # Calculate carbon biomass as 50% of dry weight conc_mean['Biomass density [g C m^-2]'] = conc_mean['Dry weight [g m^-2]']/2 conc_mean['Biomass densi...
_____no_output_____
MIT
animals/arhtropods/.ipynb_checkpoints/terrestrial arthropods-checkpoint.ipynb
yinonbaron/biomass_distribution
We calculate the geometric mean of the estimates from the different studies as our best estimate of the biomass density of litter arthropods.
litter_biomass_density = gmean(conc_mean.iloc[0:5,3]) print('Our best estimate for the biomass density of arthropods in litter is ≈%.0f g C m^-2' %litter_biomass_density)
Our best estimate for the biomass density of arthropods in litter is ≈1 g C m^-2
MIT
animals/arhtropods/.ipynb_checkpoints/terrestrial arthropods-checkpoint.ipynb
yinonbaron/biomass_distribution
Soil arthropod biomassAs our source for estimating the biomass of soil arthropods, we use these data collected from the literature, which are detailed below:
# Load additional data soil_data = pd.read_excel('terrestrial_arthropods_data.xlsx','Soil',index_col='Reference') soil_data
_____no_output_____
MIT
animals/arhtropods/.ipynb_checkpoints/terrestrial arthropods-checkpoint.ipynb
yinonbaron/biomass_distribution
We calculate the geometric mean of the estimate for the biomass density of arthropods in soils:
# Calculate the geometric mean of the estimates of the biomass density of soil arthropods soil_biomass_density = gmean(soil_data['Biomass density [g C m^-2]']) print('Our best estimate for the biomass density of arthropods in soils is ≈%.0f g C m^-2' %soil_biomass_density)
Our best estimate for the biomass density of arthropods in soils is ≈1 g C m^-2
MIT
animals/arhtropods/.ipynb_checkpoints/terrestrial arthropods-checkpoint.ipynb
yinonbaron/biomass_distribution
If we sum the biomass density of soil and litter arthropods, we arrive at an estimate of ≈2 g C m^-2, which is inline with the data from Kitazawa et al. of 1-2 g C m^-2. Canopy arthropod biomassData on the biomass density of canopy arthropods is much less abundant. We extracted from the literature the following values...
# Load the data on the biomass density of canopy arthropods canopy_data = pd.read_excel('terrestrial_arthropods_data.xlsx', 'Canopy',index_col='Reference') canopy_data
_____no_output_____
MIT
animals/arhtropods/.ipynb_checkpoints/terrestrial arthropods-checkpoint.ipynb
yinonbaron/biomass_distribution
We calculate the geometric mean of the estimates for the biomass density of arthropods in canopies:
# Calculate the geometric mean of the estimates of biomass densitiy of canopy arthropods canopy_biomass_density = gmean(canopy_data['Biomass density [g C m^-2]']) print('Our best estimate for the biomass density of arthropods in canopies is ≈%.1f g C m^-2' %canopy_biomass_density)
Our best estimate for the biomass density of arthropods in canopies is ≈0.7 g C m^-2
MIT
animals/arhtropods/.ipynb_checkpoints/terrestrial arthropods-checkpoint.ipynb
yinonbaron/biomass_distribution
To generate our best estimate for the biomass of arthropods using estimates of biomass densities, we sum the estimates for the biomass density of arthropods in soils and in canopies, and apply this density over the entire ice-free land surface of $1.3×10^{14} \: m^2$:
# Sum the biomass densities of arthropods in soils and in canopies total_denisty = litter_biomass_density+soil_biomass_density+canopy_biomass_density # Apply the average biomass density across the entire ice-free land surface method1_estimate = total_denisty*1.3e14 print('Our best estimate for the biomass of terrestr...
Our best estimate for the biomass of terrestrial arthropods using average biomass densities is ≈0.4 Gt C
MIT
animals/arhtropods/.ipynb_checkpoints/terrestrial arthropods-checkpoint.ipynb
yinonbaron/biomass_distribution
Average carbon content methodIn this method, in order to estimate the total biomass of arthropods, we calculate the carbon content of a characteristic arthropod, and multiply this carbon content by an estimate for the total number of arthropods.We rely both on data from Gist & Crossley which detail the total number of...
pd.options.display.float_format = '{:,.1e}'.format # Calculate the carbon content of a single arthropod by dividing the dry weight by 2 (assuming 50% carbon in # dry weight) and dividing the result by the total number of individuals gc_study['Carbon content [g C per individual]'] = gc_study['Dry weight [g m^-2]']/2/gc...
_____no_output_____
MIT
animals/arhtropods/.ipynb_checkpoints/terrestrial arthropods-checkpoint.ipynb
yinonbaron/biomass_distribution
We combine the data from these studies with data from additional sources detailed below:
# Load additional data sources other_carbon_content_data = pd.read_excel('terrestrial_arthropods_data.xlsx', 'Carbon content',index_col='Reference') other_carbon_content_data
_____no_output_____
MIT
animals/arhtropods/.ipynb_checkpoints/terrestrial arthropods-checkpoint.ipynb
yinonbaron/biomass_distribution
We calculate the geometric mean of the estimates from the difference studies and use it as our best estimate for the carbon content of a characteristic arthropod:
# Calculate the geometric mean of the estimates from the different studies on the average carbon content of a single arthropod. average_carbon_content = gmean(pd.concat([other_carbon_content_data,gc_study])['Carbon content [g C per individual]']) print('Our best estimate for the carbon content of a characteristic arthr...
Our best estimate for the carbon content of a characteristic arthropod is 1.2e-04 g C
MIT
animals/arhtropods/.ipynb_checkpoints/terrestrial arthropods-checkpoint.ipynb
yinonbaron/biomass_distribution
To estimate the total biomass of arthropods using the characteristic carbon content method, we multiply our best estiamte of the carbon content of a single arthropod by an estimate of the total number of arthropods made by [Williams](http://dx.doi.org/10.1086/282115). Williams estiamted a total of $~10^{18}$ individual...
# Total number of insects estimated by Williams tot_num_arthropods = 1e18 # Calculate the total biomass of arthropods method2_estimate = average_carbon_content*tot_num_arthropods print('Our best estimate for the biomass of terrestrial arthropods using average biomass densities is ≈%.1f Gt C' %(method2_estimate/1e15))
Our best estimate for the biomass of terrestrial arthropods using average biomass densities is ≈0.1 Gt C
MIT
animals/arhtropods/.ipynb_checkpoints/terrestrial arthropods-checkpoint.ipynb
yinonbaron/biomass_distribution
Our best estimate for the biomass of arthropods is the geometric mean of the estimates from the two methods:
# Calculate the geometric mean of the estimates using the two methods best_estimate = gmean([method1_estimate,method2_estimate]) print('Our best estimate for the biomass of terrestrial arthropods is ≈%.1f Gt C' %(best_estimate/1e15))
Our best estimate for the biomass of terrestrial arthropods is ≈0.2 Gt C
MIT
animals/arhtropods/.ipynb_checkpoints/terrestrial arthropods-checkpoint.ipynb
yinonbaron/biomass_distribution
Uncertainty analysisTo assess the uncertainty associated with the estimate of the biomass of terrestrial arthropods, we compile a collection of the different sources of uncertainty, and combine them to project the total uncertainty. We survey the interstudy uncertainty for estimates within each method, the total uncer...
litter_CI = geo_CI_calc(conc_mean['Biomass density [g C m^-2]']) soil_CI = geo_CI_calc(soil_data['Biomass density [g C m^-2]']) canopy_CI = geo_CI_calc(canopy_data['Biomass density [g C m^-2]']) print('The 95 percent confidence interval for the average biomass density of soil arthropods is ≈%.1f-fold' %litter_CI) print...
The 95 percent confidence interval for the average biomass density of soil arthropods is ≈2.0-fold The 95 percent confidence interval for the average biomass density of soil arthropods is ≈1.8-fold The 95 percent confidence interval for the average biomass density of canopy arthropods is ≈1.9-fold
MIT
animals/arhtropods/.ipynb_checkpoints/terrestrial arthropods-checkpoint.ipynb
yinonbaron/biomass_distribution
To estimate the uncertainty of the global biomass estimate using the average biomass density method, we propagate the uncertainties of the soil and canopy biomass density:
method1_CI = CI_sum_prop(estimates=np.array([litter_biomass_density,soil_biomass_density,canopy_biomass_density]),mul_CIs=np.array([litter_CI,soil_CI,canopy_CI])) print('The 95 percent confidence interval biomass of arthropods using the biomass densities method is ≈%.1f-fold' %method1_CI)
The 95 percent confidence interval biomass of arthropods using the biomass densities method is ≈1.5-fold
MIT
animals/arhtropods/.ipynb_checkpoints/terrestrial arthropods-checkpoint.ipynb
yinonbaron/biomass_distribution
Average carbon content methodAs a measure of the uncertainty of the estimate of the total biomass of arthropods using the average carbon content method, we calculate the 95% confidence interval of the geometric mean of the estimates from different studies of the carbon content of a single arthropod:
carbon_content_CI = geo_CI_calc(pd.concat([other_carbon_content_data,gc_study])['Carbon content [g C per individual]']) print('The 95 percent confidence interval of the carbon content of a single arthropod is ≈%.1f-fold' %carbon_content_CI)
The 95 percent confidence interval of the carbon content of a single arthropod is ≈4.1-fold
MIT
animals/arhtropods/.ipynb_checkpoints/terrestrial arthropods-checkpoint.ipynb
yinonbaron/biomass_distribution
We combine this uncertainty of the average carbon content of a single arthropod with the uncertainty reported in Williams on the total number of insects of about one order of magnitude. This provides us with a measure of the uncertainty of the estimate of the biomass of arthropods using the average carbon content metho...
# The uncertainty of the total number of insects from Williams tot_num_arthropods_CI = 10 # Combine the uncertainties of the average carbon content of a single arthropod and the uncertainty of # the total number of arthropods method2_CI = CI_prod_prop(np.array([carbon_content_CI,tot_num_arthropods_CI])) print('The 95...
The 95 percent confidence interval biomass of arthropods using the average carbon content method is ≈14.9-fold
MIT
animals/arhtropods/.ipynb_checkpoints/terrestrial arthropods-checkpoint.ipynb
yinonbaron/biomass_distribution
Inter-method uncertaintyWe calculate the 95% conficence interval of the geometric mean of the estimates of the biomass of arthropods using the average biomass density or the average carbon content:
inter_CI = geo_CI_calc(np.array([method1_estimate,method2_estimate])) print('The inter-method uncertainty of the geometric mean of the estimates of the biomass of arthropods is ≈%.1f' % inter_CI)
The inter-method uncertainty of the geometric mean of the estimates of the biomass of arthropods is ≈3.0
MIT
animals/arhtropods/.ipynb_checkpoints/terrestrial arthropods-checkpoint.ipynb
yinonbaron/biomass_distribution
As our best projection for the uncertainty associated with the estimate of the biomass of terrestrial arthropods, we take the highest uncertainty among the collection of uncertainties we generate, which is the ≈15-fold uncertainty of the average carbon content method.
mul_CI = np.max([inter_CI,method1_CI,method2_CI]) print('Our best projection for the uncertainty associated with the estimate of the biomass of terrestrial arthropods is ≈%.1f-fold' %mul_CI)
Our best projection for the uncertainty associated with the estimate of the biomass of terrestrial arthropods is ≈14.9-fold
MIT
animals/arhtropods/.ipynb_checkpoints/terrestrial arthropods-checkpoint.ipynb
yinonbaron/biomass_distribution
The biomass of termitesAs we state in the Supplementary Information, there are some groups of terrestrial arthropods for which better estimates are available. An example is the biomass of termites. We use the data in [Sanderson](http://dx.doi.org/10.1029/96GB01893) to estimate the global biomass of termites:
# Load termite data termite_data = pd.read_excel('terrestrial_arthropods_data.xlsx', 'Sanderson', skiprows=1, index_col=0) # Multiply biomass density by biome area and sum over biomes termite_biomass = (termite_data['Area [m^2]']* termite_data['Biomass density [g wet weight m^-2]']).sum() # Calculate carbon mass assu...
The estimate of the total biomass of termites based on Sanderson is ≈0.07 Gt C
MIT
animals/arhtropods/.ipynb_checkpoints/terrestrial arthropods-checkpoint.ipynb
yinonbaron/biomass_distribution
Pandas Exercise
import matplotlib.pyplot as plt import numpy as np np.random.seed(0) import pandas as pd def df_info(df: pd.DataFrame) -> None: return df.head(n=20).style
_____no_output_____
MIT
3_Pandas/08_Exercise2.ipynb
tkaya94/UdemyDataScience
Cars Auction Dataset| Feature | Type | Description ||--------------|---------|-----------------------------...
df = pd.read_csv("../data/USA_cars_datasets.csv") print(df.columns) df.head()
_____no_output_____
MIT
3_Pandas/08_Exercise2.ipynb
tkaya94/UdemyDataScience
you can use sns.axes_style() to return all the styling of the axes and then you can override them with set_style()
# we can read the age mean age value for each category but if you want to be very precise! for pclass in [1, 2, 3]: for sex in ['male', 'female']: print(pclass, sex, round(train[(train['Pclass']==pclass) & (train['Sex']==sex)]['Age'].mean(), 2))
1 male 41.28 1 female 34.61 2 male 30.74 2 female 28.72 3 male 26.51 3 female 21.75
Apache-2.0
Logistic-Regression-Titanic-example.ipynb
arjavanb/Data_practices
in order to define our impute function, the best way is to create a nice structured object to avoid many 'if' estatements
age_class = {1:{'male': 41.28, 'female': 34.61}, 2: {'male': 30.74, 'female': 28.72}, 3: {'male': 25.51, 'female': 21.7}} def impute_age(cols): Age, Pclass, Sex = tuple(cols) if pd.isnull(Age): return age_class[Pclass][Sex] # if pclass==1 and sex=='male': return 41.28 # elif pclass==1...
_____no_output_____
Apache-2.0
Logistic-Regression-Titanic-example.ipynb
arjavanb/Data_practices
we will not use test dataset because it is basically for kaggle competition. But, let's take a look at it
sns.heatmap(test.isnull(), yticklabels=False, cbar=False, cmap='viridis') test['Age'] = test[['Age', 'Pclass', 'Sex']].apply(impute_age, axis=1) test.drop('Cabin', axis=1, inplace=True) test.dropna(inplace=True)
_____no_output_____
Apache-2.0
Logistic-Regression-Titanic-example.ipynb
arjavanb/Data_practices
We need to convert categorical columns to numerical values using dummy variables
test = pd.get_dummies(test, columns=['Sex', 'Embarked'], drop_first=True) test.drop(['PassengerId', 'Name', 'Ticket'], axis=1, inplace=True) X = train.drop('Survived', axis=1) y = train['Survived'] from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=...
_____no_output_____
Apache-2.0
Logistic-Regression-Titanic-example.ipynb
arjavanb/Data_practices
if you go horizontally, you can calculate recall, and vertically yeilds the precision value. avg/Total is the accuracy
confusion_matrix(y_test, predictions) print(classification_report(y_test, predictions))
precision recall f1-score support 0 0.82 0.86 0.84 167 1 0.75 0.69 0.72 100 avg / total 0.80 0.80 0.80 267
Apache-2.0
Logistic-Regression-Titanic-example.ipynb
arjavanb/Data_practices
4. Training In this part of notebook we will try to train the model using feature extracted dataset and do model evaluation to see how well it predicts churn Setup Prerequisite
!pip install pyspark from google.colab import drive drive.mount('/content/drive')
Drive already mounted at /content/drive; to attempt to forcibly remount, call drive.mount("/content/drive", force_remount=True).
MIT
notebooks/4_training.ipynb
fahmiduldul/ds-sparkify
Import Needed Library, Initialize Spark and Load Dataframe
from pyspark.sql import SparkSession import pyspark.sql.functions as F import pyspark.sql.types as T from pyspark.ml.classification import GBTClassifier, RandomForestClassifier from pyspark.ml.feature import VectorAssembler from pyspark.ml.evaluation import BinaryClassificationEvaluator from pyspark.ml import Pipeline...
+-------+-------------------+--------+----------+-------------+------------------+----------+-----------+---------+------------------+----------+-----+------+-----+-----+-------+-------+------------+-------------+----------+------------+-----+ | userId| up_ts|is_churn|song_count|subs_duration| song...
MIT
notebooks/4_training.ipynb
fahmiduldul/ds-sparkify
Vectorize Feature and Do Train Test Split
# features columns feature_cols = df.columns[3:-1] assembler = VectorAssembler(inputCols=feature_cols, outputCol="features") df = assembler.transform(df) # take only features and label column df = df.select(["features", "label"]) train_df, test_df = df.randomSplit([0.9,0.1], seed=42) print("train") train_df.groupby("...
train +-----+-----+ |label|count| +-----+-----+ | 1| 4470| | 0| 9148| +-----+-----+ test +-----+-----+ |label|count| +-----+-----+ | 1| 480| | 0| 1037| +-----+-----+
MIT
notebooks/4_training.ipynb
fahmiduldul/ds-sparkify
We have around 1:2 ratio between 1 and 0 label on both dataset. It shows that we have balanced train and test data split. Build Grid Search, Train Model and Predict Test Data In this case we will use gradient boosted tree (GBT) algorithm to predic churn. I use GBT because it has good accuracy but still give us reasona...
train_df.printSchema() # ML algorithm gbt = GBTClassifier() # GBT algorithm rf = RandomForestClassifier() # RF algorithm # Grid search parameter gbt_grid = ParamGridBuilder() \ .addGrid(gbt.maxDepth, [5, 6, 7]) \ .addGrid(gbt.maxIter, [15, 20, 25]) \ .build() rf_grid = ParamGridBuilder() \ .addGrid(rf...
_____no_output_____
MIT
notebooks/4_training.ipynb
fahmiduldul/ds-sparkify
From the result above, the best model is using 25 trees and 7 depth
gbt_model.bestModel.featureImportances
_____no_output_____
MIT
notebooks/4_training.ipynb
fahmiduldul/ds-sparkify
As seen above, the most important feature in gradient boost model are number 1 (subscription duration) with value 0.2645, number 2 (songs heard per day of subscription) with value 0.1197, number 7 (sessions count) with value 0.087 and number 15 (cancel confirmation page visit) with value 0.109 Evaluate model Before ev...
def evaluate(df, label_col='label', pred_col='prediction'): ''' INPUT: df - spark dataframe label_col - name of label column pred_col - name of prediction column OUTPUT: res - pandas dataframe of metrics ''' temp_df = df.select([label_col, pred_col]).toPandas() return pd.D...
_____no_output_____
MIT
notebooks/4_training.ipynb
fahmiduldul/ds-sparkify
With metrics shown above, We got good f1 and roc auc score. But as you see in the confusion matrix, accuracy value is mostly driven by high true negative value. But We are more concerned about true positive value so we can prevent user from churning. If We want to see how good our model predict churn we can calculate w...
# add weight column train_df_w = train_df.withColumn("weight", F.when(F.col("label") == 1, 1).otherwise(0.7)) train_df_w.show(5)
+--------------------+-----+------+ | features|label|weight| +--------------------+-----+------+ |(18,[0,1,2,3,4,6,...| 0| 0.7| |(18,[0,1,2,3,4,6,...| 0| 0.7| |(18,[0,1,2,3,4,6,...| 0| 0.7| |(18,[0,1,2,3,4,6,...| 0| 0.7| |(18,[0,1,2,3,4,6,...| 0| 0.7| +--------------------+-----+----...
MIT
notebooks/4_training.ipynb
fahmiduldul/ds-sparkify
I use the same model, grid and validation method as before but We need to specify weight column name so they can use it in training process.
# gradient boosted tree algorithm gbt_w = GBTClassifier().setWeightCol("weight") rf_w = RandomForestClassifier(weightCol="weight") # train validation split to search through all grid gbt_tvs_w = TrainValidationSplit(estimator=gbt_w, estimatorParamMaps=gbt_grid, e...
_____no_output_____
MIT
notebooks/4_training.ipynb
fahmiduldul/ds-sparkify
After training the model is using 20 trees and 7 tree depth
gbtw_model.bestModel.featureImportances
_____no_output_____
MIT
notebooks/4_training.ipynb
fahmiduldul/ds-sparkify
As seen above, the most influencing features are subscription duration, songs played per day, session count and number of cancellation confirmation page visited. The same as model before but with different value Evaluate Weighted Model
# predict using weighted model preds_gbt_w_df = gbt_model_w.transform(test_df) preds_rf_w_df = rf_model_w.transform(test_df) evaluate(preds_gbt_w_df) evaluate(preds_rf_w_df) # confusion matrix c_mat_gbt_w = confusion_matrix(preds_gbt_w_df.select("label").toPandas(), preds_gbt_w_df.select("prediction").t...
_____no_output_____
MIT
notebooks/4_training.ipynb
fahmiduldul/ds-sparkify
PyCitySChools Solution* Submitted by: Farshad Esnaashari * Data Analytics Bootcap * M-W session
# Dependencies and Setup import pandas as pd # File to Load (Remember to Change These) school_data_to_load = "Resources/schools_complete.csv" student_data_to_load = "Resources/students_complete.csv" # Read School and Student Data File and store into Pandas Data Frames school_data = pd.read_csv(school_data_to_load) st...
_____no_output_____
ADSL
PyCitySchools/PyCitySchools_Solution.ipynb
esnaaf1/Trends-in-standard-Tests
District Summary* Calculate the total number of schools* Calculate the total number of students* Calculate the total budget* Calculate the average math score * Calculate the average reading score* Calculate the overall passing rate (overall average score), i.e. (avg. math score + avg. reading score)/2* Calculate the p...
#Calculate total student in the school_data total_schools=school_data["school_name"].count() #Calculate total number of students (use size column) in the school_data total_students= school_data["size"].sum() #calculate total budget (use budget in the school_data) total_budget = school_data["budget"].sum() #calculate...
_____no_output_____
ADSL
PyCitySchools/PyCitySchools_Solution.ipynb
esnaaf1/Trends-in-standard-Tests
School Summary * Create an overview table that summarizes key metrics about each school, including: * School Name * School Type * Total Students * Total School Budget * Per Student Budget * Average Math Score * Average Reading Score * % Passing Math * % Passing Reading * Overall Passing Rate (Average of the ...
# (Note: I used the new groupby aggregation function with relabeling that is already available # in my current PythonData installation. # To create the school summary, I create dataframes in 4 steps: #step 1: create school_df_1 for average math and reading scores school_df_1 = school_data_complete.groupby('school_n...
_____no_output_____
ADSL
PyCitySchools/PyCitySchools_Solution.ipynb
esnaaf1/Trends-in-standard-Tests
Top Performing Schools (By Passing Rate) * Sort and display the top five schools in overall passing rate
#sort the school_summary dataframe on overall_passing_rate in descening order top_5_schools = school_summary.sort_values("% Overall Passing Rate", ascending=False) top_5_schools.set_index("school_name",inplace=True) top_5_schools.head()
_____no_output_____
ADSL
PyCitySchools/PyCitySchools_Solution.ipynb
esnaaf1/Trends-in-standard-Tests
Bottom Performing Schools (By Passing Rate) * Sort and display the five worst-performing schools
# sort the school_summary dataframe on overall_passing_rate in ascending order bottom_5_schools = school_summary.sort_values("% Overall Passing Rate") bottom_5_schools.set_index("school_name", inplace=True) bottom_5_schools.head()
_____no_output_____
ADSL
PyCitySchools/PyCitySchools_Solution.ipynb
esnaaf1/Trends-in-standard-Tests
Math Scores by Grade * Create a table that lists the average Reading Score for students of each grade level (9th, 10th, 11th, 12th) at each school. * Create a pandas series for each grade. Hint: use a conditional statement. * Group each series by school * Combine the series into a dataframe * Optional: give ...
# Use the "loc" function with conditional filtering to build 4 dataframes for grades 9 to 12 avergae scores nine_grade = school_data_complete.loc[school_data_complete["grade"] =="9th"].rename(columns={"math_score": "9th"}) ten_grade = school_data_complete.loc[school_data_complete["grade"] =="10th"].rename(columns={"ma...
_____no_output_____
ADSL
PyCitySchools/PyCitySchools_Solution.ipynb
esnaaf1/Trends-in-standard-Tests
Reading Score by Grade * Perform the same operations as above for reading scores
# build 4 dataframes for average scores in grades 9 to 12 nine_grade = school_data_complete.loc[school_data_complete["grade"] =="9th"].rename(columns={"reading_score": "9th"}) ten_grade = school_data_complete.loc[school_data_complete["grade"] =="10th"].rename(columns={"reading_score": "10th"}) eleven_grade = school_dat...
_____no_output_____
ADSL
PyCitySchools/PyCitySchools_Solution.ipynb
esnaaf1/Trends-in-standard-Tests
Scores by School Spending * Create a table that breaks down school performances based on average Spending Ranges (Per Student). Use 4 reasonable bins to group school spending. Include in the table each of the following: * Average Math Score * Average Reading Score * % Passing Math * % Passing Reading * Overall Pa...
# Set bins and group names for ranges of per student spending spending_bins = [0, 585, 615, 645, 675] group_names = ["<$585", "$585-615", "$615-645", "$645-675"] # create dataframe with subset of columns from the school summary using the loc function summary_by_spending=school_summary.loc[:,["Per Student Budget", "Ave...
_____no_output_____
ADSL
PyCitySchools/PyCitySchools_Solution.ipynb
esnaaf1/Trends-in-standard-Tests
Scores by School Size * Perform the same operations as above, based on school size.
# create lists for size ranges and group_names size_bins = [0, 1000, 2000, 5000] group_names = ["Small (<1000)", "Medium (1000-2000)", "Large (2000-5000)"] # create a subset dataframe from the school summary summary_by_size=school_summary.loc[:,["Total Students", "Average Math Score", "A...
_____no_output_____
ADSL
PyCitySchools/PyCitySchools_Solution.ipynb
esnaaf1/Trends-in-standard-Tests
Scores by School Type * Perform the same operations as above, based on school type.
# create a dataframe with subset of columns from the school summary summary_by_type=school_summary.loc[:,["School Type", "Average Math Score", "Average Reading Score", "% Passing Math", "% Passing Reading", "% Overall Passing Rate" ]] # gr...
_____no_output_____
ADSL
PyCitySchools/PyCitySchools_Solution.ipynb
esnaaf1/Trends-in-standard-Tests
Zasymuluj wahadlo matematyczne rozwiazując numerycznie rownanie różniczkowe je opisujace(rownież dla dużych wychyleń). $$\frac{d^2x}{dt^2} + \frac{g}{l} sin(x) = 0$$
g = 9.81 l = 1 def pendulum(initial_theta, time, initial_omega=0, time_step=0.01, g=g, l=l): theta = initial_theta omega = initial_omega t = 0 while(t < time): a = -(g / l) * np.sin(theta) omega += a * time_step theta += omega * time_step + a * (time_step ** 2) /2 t += ti...
_____no_output_____
MIT
lab9/lab9.ipynb
mprzewie/MOwNiT_2
Zasymuluj układ grawitacyjny : gwiazda i przylatujace cialo niebieskie z pewna (zadawanaprzez uzytkownika) prędkością poczatkową. $$g = G\frac{M}{r^2}$$
@np.vectorize def g(r, G=1, M=1, r_max=1): return (G * M) / r**2 if r > r_max else ((G * M) / r_max**2) * (r / r_max) def gravity(time, initial_pos, M=0, initial_v=0, time_step=0.1, r_max=1): t = 0 x = initial_pos v = initial_v r = np.abs(x) a = - g(r, M=M, r_max=r_max) * (x / r) X = [x] ...
_____no_output_____
MIT
lab9/lab9.ipynb
mprzewie/MOwNiT_2
**Instructions:** replace the string in the second cell, and execute each cell (to execute a cell, hit `Shift+Enter`)
import numpy as np %matplotlib notebook # or `%matplotlib inline` for non-interactive plots # or `%matplotlib widget` when using JupyterLab (github.com/matplotlib/jupyter-matplotlib) import matplotlib.pyplot as plt from openpmd_viewer import OpenPMDTimeSeries # Replace the string below, to point to your data ts = OpenP...
_____no_output_____
BSD-3-Clause-LBNL
openpmd_viewer/notebook_starter/Template_notebook.ipynb
AlexanderSinn/openPMD-viewer
基本程序设计- 一切代码输入,请使用英文输入法
print('joker is bad man')
joker is bad man
Apache-2.0
7.16.ipynb
hzh029/hzh1
编写一个简单的程序- 圆公式面积: area = radius \* radius \* 3.1415 在Python里面不需要定义数据的类型
radius = 100 # 定义变量 area = radius * radius * 3.14 # 普通代码,* 代表乘法 print(area) # 最后打印出结果
31400.0
Apache-2.0
7.16.ipynb
hzh029/hzh1
控制台的读取与输入- input 输入进去的是字符串- eval - 在jupyter用shift + tab 键可以跳出解释文档
variable = input('请输入一个数字') print(variable)
请输入一个数字1000 1000
Apache-2.0
7.16.ipynb
hzh029/hzh1
变量命名的规范- 由字母、数字、下划线构成- 不能以数字开头 \*- 标识符不能是关键词(实际上是可以强制改变的,但是对于代码规范而言是极其不适合)- 可以是任意长度- 驼峰式命名
print(12) import os def go(num): os.system('echo hahah') print = go print(12)
_____no_output_____
Apache-2.0
7.16.ipynb
hzh029/hzh1
变量、赋值语句和赋值表达式- 变量: 通俗理解为可以变化的量- x = 2 \* x + 1 在数学中是一个方程,而在语言中它是一个表达式- test = test + 1 \* 变量在赋值之前必须有值
x = 100 x = 2 * x + 1 # 赋值语句,在赋值之前,一定要有值 print(x) a = eval(input('数字')) print(type(a)) print(a * 3)
数字100 <class 'int'> 300
Apache-2.0
7.16.ipynb
hzh029/hzh1