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 |
|---|---|---|---|---|---|
Task 2 Display 5 records where launch sites begin with the string 'CCA' | %sql SELECT * FROM SPACEXDATASET WHERE LAUNCH_SITE LIKE 'CCA%' LIMIT 5 | * ibm_db_sa://gmb99703:***@dashdb-txn-sbox-yp-dal09-04.services.dal.bluemix.net:50000/BLUDB
Done.
| MIT | Week 2 - SQL/jupyter-labs-eda-sql-coursera.ipynb | pFontanilla/ibm-applied-datascience-capstone |
Task 3 Display the total payload mass carried by boosters launched by NASA (CRS) | %sql SELECT SUM(PAYLOAD_MASS__KG_) FROM SPACEXDATASET WHERE PAYLOAD LIKE '%CRS%' | * ibm_db_sa://gmb99703:***@dashdb-txn-sbox-yp-dal09-04.services.dal.bluemix.net:50000/BLUDB
Done.
| MIT | Week 2 - SQL/jupyter-labs-eda-sql-coursera.ipynb | pFontanilla/ibm-applied-datascience-capstone |
Task 4 Display average payload mass carried by booster version F9 v1.1 | %sql SELECT AVG(PAYLOAD_MASS__KG_) FROM SPACEXDATASET WHERE booster_version LIKE '%F9 v1.1%' | * ibm_db_sa://gmb99703:***@dashdb-txn-sbox-yp-dal09-04.services.dal.bluemix.net:50000/BLUDB
Done.
| MIT | Week 2 - SQL/jupyter-labs-eda-sql-coursera.ipynb | pFontanilla/ibm-applied-datascience-capstone |
Task 5 List the date when the first successful landing outcome in ground pad was acheived.*Hint:Use min function* | %sql SELECT MIN(DATE) FROM SPACEXDATASET WHERE landing__outcome = 'Success (ground pad)' | * ibm_db_sa://gmb99703:***@dashdb-txn-sbox-yp-dal09-04.services.dal.bluemix.net:50000/BLUDB
Done.
| MIT | Week 2 - SQL/jupyter-labs-eda-sql-coursera.ipynb | pFontanilla/ibm-applied-datascience-capstone |
Task 6 List the names of the boosters which have success in drone ship and have payload mass greater than 4000 but less than 6000 | %sql SELECT BOOSTER_VERSION FROM SPACEXDATASET WHERE landing__outcome = 'Success (drone ship)' AND 4000 < PAYLOAD_MASS__KG_ < 6000 | * ibm_db_sa://gmb99703:***@dashdb-txn-sbox-yp-dal09-04.services.dal.bluemix.net:50000/BLUDB
Done.
| MIT | Week 2 - SQL/jupyter-labs-eda-sql-coursera.ipynb | pFontanilla/ibm-applied-datascience-capstone |
Task 7 List the total number of successful and failure mission outcomes | %sql SELECT MISSION_OUTCOME, COUNT(MISSION_OUTCOME) FROM SPACEXDATASET GROUP BY MISSION_OUTCOME | * ibm_db_sa://gmb99703:***@dashdb-txn-sbox-yp-dal09-04.services.dal.bluemix.net:50000/BLUDB
Done.
| MIT | Week 2 - SQL/jupyter-labs-eda-sql-coursera.ipynb | pFontanilla/ibm-applied-datascience-capstone |
Task 8 List the names of the booster_versions which have carried the maximum payload mass. Use a subquery | %sql SELECT UNIQUE BOOSTER_VERSION FROM SPACEXDATASET WHERE PAYLOAD_MASS__KG_ = (SELECT MAX(PAYLOAD_MASS__KG_) FROM SPACEXDATASET) | * ibm_db_sa://gmb99703:***@dashdb-txn-sbox-yp-dal09-04.services.dal.bluemix.net:50000/BLUDB
Done.
| MIT | Week 2 - SQL/jupyter-labs-eda-sql-coursera.ipynb | pFontanilla/ibm-applied-datascience-capstone |
Task 9 List the failed landing_outcomes in drone ship, their booster versions, and launch site names for in year 2015 | %sql SELECT BOOSTER_VERSION, launch_site, landing__outcome FROM SPACEXDATASET WHERE LANDING__OUTCOME = 'Failure (drone ship)' AND YEAR(DATE) = 2015 | * ibm_db_sa://gmb99703:***@dashdb-txn-sbox-yp-dal09-04.services.dal.bluemix.net:50000/BLUDB
Done.
| MIT | Week 2 - SQL/jupyter-labs-eda-sql-coursera.ipynb | pFontanilla/ibm-applied-datascience-capstone |
Task 10 Rank the count of landing outcomes (such as Failure (drone ship) or Success (ground pad)) between the date 2010-06-04 and 2017-03-20, in descending order | %sql SELECT LANDING__OUTCOME, COUNT(LANDING__OUTCOME) FROM SPACEXDATASET WHERE DATE BETWEEN '2010-06-04' AND '2017-03-20' GROUP BY LANDING__OUTCOME ORDER BY COUNT(LANDING__OUTCOME) DESC | * ibm_db_sa://gmb99703:***@dashdb-txn-sbox-yp-dal09-04.services.dal.bluemix.net:50000/BLUDB
Done.
| MIT | Week 2 - SQL/jupyter-labs-eda-sql-coursera.ipynb | pFontanilla/ibm-applied-datascience-capstone |
Highly divisible triangular number Problem 12The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be:1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...Let us list the factors of the first seven triangle numbers:... | def factors(n):
f = []
for i in range(1,n+1):
if (n%i) == 0:
f.append(i)
return f
len(factors(25200))
def triangle_number(n):
tri_num = 0
for i in range(1,n+1):
tri_num += i
return tri_num
triangle_number(125150)
def find_tri_num_div(n):
x = 1
while(1):
... | _____no_output_____ | MIT | solutions/S0012.ipynb | trabdlkarim/UrkelOs |
Load the data and perform EDA.https://www.kaggle.com/pavansubhasht/ibm-hr-analytics-attrition-dataset1. Evaluate missing values2. Assess target class distribution3. Assess information value of individual features (correlation analysis and pairlot). | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
ibm = pd.read_csv('WA_Fn-UseC_-HR-Employee-Attrition.csv',index_col=0)
# Evaluate missing values
ibm.isnull().sum()
ibm.describe().transpose()
# Change data types for categorical variables
# Dummy code categorical features
#... | _____no_output_____ | MIT | Notebook/Employee_Attrition_Prediction.ipynb | rjparkk/rjparkk.github.io |
4. Pre-process the dataset5. Split the data into training/test datasets (70/30)4 pts. | #Dropping variables
# ibm.drop(['Over18_Y'], axis=1, inplace=True)
# ibm.drop(['EmployeeCount'], axis=1, inplace=True)
# ibm.drop(['StandardHours'], axis=1, inplace=True)
# Preparing features and labels
X = ibm.drop('Attrition',axis=1).values
y = ibm['Attrition'].values
from sklearn.model_selection import train_tes... | _____no_output_____ | MIT | Notebook/Employee_Attrition_Prediction.ipynb | rjparkk/rjparkk.github.io |
6. Build a sequential neural network with the following parameters: 3 hidden dense layers - 100, 50, 25 nodes respectively, activation function = 'relu', dropout = 0.5 for each layer).7. Use early stopping callback to prevent overfitting. | import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense,Activation,Dropout
model = Sequential()
model.add(Dense(units=100,activation='relu'))
model.add(Dense(units=50,activation='relu'))
model.add(Dense(units=25,activation='relu'))
model.add(Dense(units=1,activa... | Epoch 1/100
9/9 [==============================] - 0s 12ms/step - loss: 0.6206 - val_loss: 0.5047
Epoch 2/100
9/9 [==============================] - 0s 3ms/step - loss: 0.4449 - val_loss: 0.4384
Epoch 3/100
9/9 [==============================] - 0s 3ms/step - loss: 0.4050 - val_loss: 0.4446
Epoch 4/100
9/9 [===========... | MIT | Notebook/Employee_Attrition_Prediction.ipynb | rjparkk/rjparkk.github.io |
8. Plot training and validation losses versus epochs.9. Print out model confusion matrix.10. Print out model classification report.11. Print out model ROC AUC. | model_loss = pd.DataFrame(model.history.history)
model_loss.plot()
# with Dropout
from tensorflow.keras.layers import Dropout
model = Sequential()
model.add(Dense(units=100,activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(units=50,activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(units=25,activ... | [[363 1]
[ 72 5]]
ROC AUC: 0.531093906093906
| MIT | Notebook/Employee_Attrition_Prediction.ipynb | rjparkk/rjparkk.github.io |
Raw Data visualisation and analysisThis notebook was designed to carry out the visualisation and analysis of the raw data--- - Author: Luis F Patino Velasquez - MA - Date: Jun 2020 - Version: 1.0 - Notes: ... | # Imports for xclim and xarray
import xclim as xc
import pandas as pd
import numpy as np
import xarray as xr
import functools
# from functools import reduce
# File handling libraries
import time
import tempfile
from pathlib import Path
# Geospatial libraries
import geopandas
import rioxarray
from shapely.geometry imp... | _____no_output_____ | MIT | py_notebooks/RawDataAnalysis.ipynb | GeoFelpave/MResDissertation_Aug2021 |
1. Reading the raw data 1.1. ERA5 | # Set directory to read and for outputs
fldr_src = Path('/mnt/d/MRes_dataset/search_data/era_copernicus_uk/')
# Create list with files
fls_lst = fldr_src.glob('**/era5_copernicus_DAY_prcp_*')
# Load multiple NetCDFs into a single xarray.Dataset
dataset_ERA = xr.open_mfdataset(paths=fls_lst, combine='by_coords', paral... | _____no_output_____ | MIT | py_notebooks/RawDataAnalysis.ipynb | GeoFelpave/MResDissertation_Aug2021 |
1.2. GPM-IMERG | # Set directory to read and for outputs
fldr_src = Path('/mnt/d/MRes_dataset/search_data/gpm_imerg_nasa_uk/')
# Create list with files
fls_lst = fldr_src.glob('**/*')
# Load multiple NetCDFs into a single xarray.Dataset
dataset_GPM = xr.open_mfdataset(paths=fls_lst, combine='by_coords', parallel=True)
dataset_GPM | _____no_output_____ | MIT | py_notebooks/RawDataAnalysis.ipynb | GeoFelpave/MResDissertation_Aug2021 |
1.3. HadUK-Grid | # Set directory to read and for outputs
fldr_src = Path('/mnt/d/MRes_dataset/search_data/haduk_cedac_uk/')
# Create list with files
fls_lst = fldr_src.glob('**/*')
# Load multiple NetCDFs into a single xarray.Dataset
dataset_HAD = xr.open_mfdataset(paths=fls_lst, combine='by_coords', parallel=True)
dataset_HAD | _____no_output_____ | MIT | py_notebooks/RawDataAnalysis.ipynb | GeoFelpave/MResDissertation_Aug2021 |
2. Data Analysis 2.1. Functions | def UK_clip(xarray_dataset, coord_lon_name, coord_lat_name, xarray_dataset_crs):
"""
Return xarray with data for the UK only
:xarray_dataset: xarray
:coord_lon_name: string
:coord_lat_name: string
:xarray_dataset_crs: dictionary
:return: xarray
"""
# Setting spatial dimmension in nc ... | _____no_output_____ | MIT | py_notebooks/RawDataAnalysis.ipynb | GeoFelpave/MResDissertation_Aug2021 |
2.2. Yearly Average AnalysisHere we are plotting the mean yearly value for each of the datasets for the whole UK | # Get annual value from daily data
arr_yearPrcp_ERA = dataset_ERA.groupby('time.year').sum(dim='time')
arr_yearPrcp_GPM = dataset_GPM.groupby('time.year').sum(dim='time')
arr_yearPrcp_HAD = dataset_HAD.groupby('time.year').sum(dim='time')
# only use mainland UK data
arr_yearPrcp_ERAUK = UK_clip(arr_yearPrcp_ERA, 'long... | _____no_output_____ | MIT | py_notebooks/RawDataAnalysis.ipynb | GeoFelpave/MResDissertation_Aug2021 |
* **Plotting the yearly average for the UK using all datasets** | # Create copy of dataframe
df_plot = df_final
# Rename columns
df_plot.rename(columns = {'tp':'prcp_ERA5', 'precipitationCal':'prcp_IMERG',
'rainfall':'prcp_HadGrid-UK'}, inplace = True)
# change year column to date format
df_plot['year'] = pd.to_datetime(df_plot['year'], format='%Y')
... | _____no_output_____ | MIT | py_notebooks/RawDataAnalysis.ipynb | GeoFelpave/MResDissertation_Aug2021 |
* **Creating climatology map for all datasets** | # Summ data by year
year_dataset = dataset_GPM.groupby('time.year').sum(dim='time')
# year_dataset_climat = UK_clip(year_dataset, 'longitude', 'latitude', "epsg:4326")
# year_dataset_climat = dataset_HAD.groupby('time.year').sum(dim='time')
# Change to pandas dataframe
df = year_dataset.to_dataframe().reset_index()
# G... | _____no_output_____ | MIT | py_notebooks/RawDataAnalysis.ipynb | GeoFelpave/MResDissertation_Aug2021 |
2.3. Data distributionHere we are plotting the distribution of the mean daily precipitation for each year - *The plotted dataset contains the daily mean value for each year at each grid cell* | # Get average value by season
ERA_season_mean = dataset_ERA.groupby('time.season').mean('time')
# Change to dataframe
df_era_season = ERA_season_mean.to_dataframe().reset_index()
test = df_era_season[(df_era_season["season"] == 'DJF')]
test2 = df_era_season[(df_era_season["season"] == 'MAM')]
test3 = df_era_season[(d... | _____no_output_____ | MIT | py_notebooks/RawDataAnalysis.ipynb | GeoFelpave/MResDissertation_Aug2021 |
2.3.1. Descriptive statisticsHere we get the individual tables showing the descriptive characteristics. | # Create dataframe using the data for each year - These data was used in the violin plots
dataset_lst_ERA
dataset_lst_GPM
dataset_lst_HAD
# Conver to pandas dataframe
ERA = pd.DataFrame(list(map(np.ravel, dataset_lst_ERA)))
GPM = pd.DataFrame(list(map(np.ravel, dataset_lst_GPM)))
HAD = pd.DataFrame(list(map(np.ravel, ... | _____no_output_____ | MIT | py_notebooks/RawDataAnalysis.ipynb | GeoFelpave/MResDissertation_Aug2021 |
The Dispersion RelationThe _dispersion relation_ is the function that relates the frequency $\omega$ and the wavevector $k$. It characterizes each wave type and leads to the labels for the various type. - CMA diagram - phase velocity vs normalized frequency - normalized or not - density - angle - field strength - tr... | def plasma_frequency(n, q, m):
'''
Returns the plasma angular frequency for a given species.
'''
omega_p = sqrt(n*q**2/(m*epsilon_0))
return omega_p
def cyclotron_frequency(q, m, B0):
'''
Returns the cyclotron angular frequency for a given species.
'''
omega_c = np.abs(q)*B0/m
r... | _____no_output_____ | MIT | notebooks/Fusion_Basics/Dispersion Relation.ipynb | Hash--/documents |
Let's define a convenient object: a particle species. | class Species:
def __init__(self, m, q, description=None):
self.m = m
self.q = q
self.description = description
def omega_p(self, n):
return plasma_frequency(n, self.q, self.m)
def omega_c(self, B0):
return cyclotron_frequency(self.q, self.m, B0)
def __repr__(self... | Specie:Electron. Mass:9.10938356e-31 kg, charge:-1.6021766208e-19 C
Specie:Deuterium. Mass:3.343583719e-27 kg, charge:1.6021766208e-19 C
| MIT | notebooks/Fusion_Basics/Dispersion Relation.ipynb | Hash--/documents |
The cold plasma tensorThe cold plasma tensor is given by:$$\mathbf{K} = \left(\begin{matrix}K_\perp & K_\times & 0 \\-K_\times & K_\perp & 0 \\0 & 0 & K_\parallel\end{matrix}\right)$$with$$\begin{array}{lcl}K_\perp = S &=& 1 - \displaystyle \sum_k \frac{\omega_{pk}^2}{\omega^2 - \omega_{ck}^2}\\i K_\times = D &=& \di... | def K_perp(species, n, B0, f):
K_perp = 1
omega = 2*np.pi*f
for k, specie in enumerate(species):
K_perp -= specie.omega_p(n[k])**2 / (omega**2 - specie.omega_c(B0)**2)
return K_perp
def K_parallel(species, n, f):
K_parallel = 1
omega = 2*np.pi*f
for k,specie in enumerate(sp... | _____no_output_____ | MIT | notebooks/Fusion_Basics/Dispersion Relation.ipynb | Hash--/documents |
Dogs vs Cats with Keras--- Import Libraries | %reload_ext autoreload
%autoreload 2
%matplotlib inline
PATH = "../data/dogscats/dogscats/"
sz=224
batch_size=64
import numpy as np
from keras.preprocessing.image import ImageDataGenerator
from keras.preprocessing import image
from keras.layers import Dropout, Flatten, Dense
from keras.applications import ResNet50
from... | _____no_output_____ | MIT | notebooks/keras_lesson1.ipynb | AmanDaVinci/DeepLabs |
Load Data | train_data_dir = f'{PATH}train'
validation_data_dir = f'{PATH}valid'
train_datagen = ImageDataGenerator(preprocessing_function=preprocess_input, shear_range=0.2, zoom_range=0.2, horizontal_flip=True)
test_datagen = ImageDataGenerator(preprocessing_function=preprocess_input)
train_generator = train_datagen.flow_from_di... | Found 23000 images belonging to 2 classes.
Found 2000 images belonging to 2 classes.
| MIT | notebooks/keras_lesson1.ipynb | AmanDaVinci/DeepLabs |
Build Model | base_model = ResNet50(weights='imagenet', include_top=False)
base_model.summary()
x = base_model.output
x = GlobalAveragePooling2D()(x)
x = Dense(1024, activation='relu')(x)
predictions = Dense(1, activation='sigmoid')(x)
model = Model(inputs=base_model.input, outputs=predictions)
for layer in base_model.layers: layer.... | _____no_output_____ | MIT | notebooks/keras_lesson1.ipynb | AmanDaVinci/DeepLabs |
Train Model | %%time
model.fit_generator(train_generator, train_generator.n // batch_size, epochs=3, workers=4,
validation_data=validation_generator, validation_steps=validation_generator.n // batch_size)
len(model.layers)
split_at = 140
for layer in model.layers[:split_at]: layer.trainable = False
for layer in model.layers[... | Epoch 1/1
359/359 [==============================] - 263s 733ms/step - loss: 0.0779 - acc: 0.9739 - val_loss: 0.2162 - val_acc: 0.9718
CPU times: user 9min 54s, sys: 38.2 s, total: 10min 33s
Wall time: 4min 25s
| MIT | notebooks/keras_lesson1.ipynb | AmanDaVinci/DeepLabs |
Model Evaluation | test_data_dir = f'{PATH}valid'
test_generator = test_datagen.flow_from_directory(test_data_dir, target_size=(sz,sz),
batch_size=batch_size, class_mode='binary')
test_generator.n
sample_x, sample_y = test_generator.next()
sample_x.shape, sample_y.shape
sample_pred = mod... | _____no_output_____ | MIT | notebooks/keras_lesson1.ipynb | AmanDaVinci/DeepLabs |
Brand ClassificationSource : https://www.dqlab.id/Typed by : Aulia Khalqillah Import Libraries | import datetime
import pandas as pd
import matplotlib.pyplot as plt | _____no_output_____ | MIT | top5brand_classification.ipynb | auliakhalqillah/top5brand-classification |
Load data | dataset = pd.read_csv('retail_raw_reduced.csv')
dataset | _____no_output_____ | MIT | top5brand_classification.ipynb | auliakhalqillah/top5brand-classification |
Info data | dataset.info() | <class 'pandas.core.frame.DataFrame'>
RangeIndex: 5000 entries, 0 to 4999
Data columns (total 9 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 order_id 5000 non-null int64
1 order_date 5000 non-null object
2 customer_id 5000 non-null int64
3 city... | MIT | top5brand_classification.ipynb | auliakhalqillah/top5brand-classification |
Exploratory Data Analysis Generate new columns of order_month and Gross Marchendise Volume (GMV) | dataset['order_month'] = dataset['order_date'].apply(lambda x: datetime.datetime.strptime(x, "%Y-%m-%d").strftime('%Y-%m'))
dataset['gmv'] = dataset['item_price']*dataset['quantity']
dataset | _____no_output_____ | MIT | top5brand_classification.ipynb | auliakhalqillah/top5brand-classification |
Select top 5 brands based on its total of quantity in December 2019 | top_brands = (dataset[dataset['order_month']=='2019-12'].groupby('brand')['quantity']
.sum()
.reset_index()
.sort_values(by='quantity',ascending=False)
.reset_index()
.drop('index',axis=1)
.head(5))
top_brands | _____no_output_____ | MIT | top5brand_classification.ipynb | auliakhalqillah/top5brand-classification |
Generate new dataframe for top 5 brands in December 2019 | dataset_top5brand_dec = dataset[
(dataset['order_month']=='2019-12') & (dataset['brand'].isin(top_brands['brand'].to_list()))
].reset_index().drop('index',axis=1)
dataset_top5brand_dec | _____no_output_____ | MIT | top5brand_classification.ipynb | auliakhalqillah/top5brand-classification |
High value | max_brand = dataset_top5brand_dec.groupby(['order_date','brand'])['quantity'].sum().unstack().idxmax().index
max_order_date = dataset_top5brand_dec.groupby(['order_date','brand'])['quantity'].sum().unstack().idxmax().values
max_quantity = dataset_top5brand_dec.groupby(['order_date','brand'])['quantity'].sum().unstack()... | _____no_output_____ | MIT | top5brand_classification.ipynb | auliakhalqillah/top5brand-classification |
A total of quantity of brands in December 2019 | dataset_top5brand_dec.groupby(['order_date','brand'])['quantity'].sum().unstack()
dataset_top5brand_dec.groupby(['order_date','brand'])['quantity'].sum().unstack().plot(marker='.', cmap='plasma', figsize=(10,5))
plt.title('Daily Sold Quantity Dec 2019 Breakdown by Brands',loc='center',pad=30, fontsize=15, color='blue')... | _____no_output_____ | MIT | top5brand_classification.ipynb | auliakhalqillah/top5brand-classification |
Plot number of sold products for each brand in December 2019 | dataset_top5brand_dec.groupby('brand')['product_id'].nunique().sort_values(ascending=False).plot(kind='bar', color='green', figsize=(10,5))
plt.title('Number of Sold Products per Brand, December 2019',loc='center',pad=30, fontsize=15, color='blue')
plt.xlabel('Brand', fontsize = 15)
plt.ylabel('Number of Products',font... | _____no_output_____ | MIT | top5brand_classification.ipynb | auliakhalqillah/top5brand-classification |
Generate new data frame of total of quantity for each product | dataset_top5brand_dec_per_product = dataset_top5brand_dec.groupby(['brand','product_id'])['quantity'].sum().reset_index()
dataset_top5brand_dec_per_product | _____no_output_____ | MIT | top5brand_classification.ipynb | auliakhalqillah/top5brand-classification |
Add a columns for quantity group (>=100 or < 100) | dataset_top5brand_dec_per_product['quantity_group'] = dataset_top5brand_dec_per_product['quantity'].apply(
lambda x: '>= 100' if x>=100 else '< 100'
)
dataset_top5brand_dec_per_product.sort_values('quantity',ascending=False,inplace=True)
dataset_top5brand_dec_per_product | _____no_output_____ | MIT | top5brand_classification.ipynb | auliakhalqillah/top5brand-classification |
How much products in each brand? | s_sort = dataset_top5brand_dec_per_product.groupby('brand')['product_id'].nunique().sort_values(ascending=False)
s_sort
dataset_top5brand_dec_per_product_by_quantity = dataset_top5brand_dec_per_product.groupby(['brand','quantity_group'])['product_id'].nunique().reindex(index=s_sort.index, level='brand').unstack()
datas... | _____no_output_____ | MIT | top5brand_classification.ipynb | auliakhalqillah/top5brand-classification |
6 products of Brand P were sold more than 100 pcs, which is the highest sales number compared others products and brands. Otherwise, the Brand C was sold less than 100 pcs. | plt.hist(dataset_top5brand_dec.groupby('product_id')['item_price'].median(), bins=20, stacked=True, range=(1,2000000), color='green', edgecolor='black')
plt.title('Distribution of Price Median per Product\nTop 5 Brands in Dec 2019', fontsize=15, color='blue')
plt.xlabel('Price Median (1000000)', fontsize = 12)
plt.ylab... | _____no_output_____ | MIT | top5brand_classification.ipynb | auliakhalqillah/top5brand-classification |
Based on median calculation, a lot of selling products has range of price from 250000 - 750000. That means, many products from various brands are purchased less than 1000000. Calculate total of quantity, total of GMV, and median of item price for each product. | data_per_product_top5brand_dec = dataset_top5brand_dec.groupby('product_id').agg({'quantity': 'sum', 'gmv':'sum', 'item_price':'median'}).reset_index()
data_per_product_top5brand_dec
plt.scatter(data_per_product_top5brand_dec['quantity'],data_per_product_top5brand_dec['gmv'], marker='+', color='red')
plt.title('Correla... | _____no_output_____ | MIT | top5brand_classification.ipynb | auliakhalqillah/top5brand-classification |
The correlation between quantity number of product was purchased and GMV from top 5 brands in December 2019, a lot of products were sold less than 50 pcs. It indicates the GMV is not high enough for each brand. However, there are some quantities of products were sold more than 50 pcs. | plt.scatter(data_per_product_top5brand_dec['item_price'],data_per_product_top5brand_dec['quantity'], marker='o', color='green')
plt.title('Correlation of Price Median and Quantity\nTop 5 Brands in December 2019',fontsize=15, color='blue')
plt.xlabel('Price Median (1000000)', fontsize = 12)
plt.ylabel('Quantity',fontsiz... | _____no_output_____ | MIT | top5brand_classification.ipynb | auliakhalqillah/top5brand-classification |
Bioenergy consumption for each fuelGross inland consumption from Eurostat energy balances | import pandas as pd
import os
import datetime
csv_input_dir = 'data'
csv_output_dir = datetime.datetime.today().strftime('%Y-%m-%d')
if not os.path.exists(csv_output_dir):
os.mkdir(csv_output_dir)
df = pd.read_csv(os.path.join(os.path.abspath(csv_input_dir), 'eurostat_2002_2018_tj.csv'), decimal=',')
df
for count... | _____no_output_____ | MIT | 2020/selection/fuels.ipynb | jandolezal/balances |
Combine trajectory data List of tasks accomplished in this Jupyter Notebook:- Output 4 dataframe combining all animal trajectories: Fed animals acclimation phase, Fed animals experiment phase, Starved animals acclimation phase, and Starved animals experiment phase | import numpy as np
import pandas as pd
import eleanor_constants as EL
df = pd.read_csv("./data/experiment_IDs/cleaned_static_data.csv")
for val in ["acclimate", "experiment"]:
for food, tag in EL.fed.items():
df_food = df[df['starved'] == tag]
master_df = pd.DataFrame()
for index, row in d... | --- All files finished ---
| MIT | 6_combine_trajectory_data_for_modeling.ipynb | riffelllab/Mosquito-larval-analyses-2 |
**問10 format()関数について** 複数の変数定義と、`format()`関数について学びましょう。以下のコードを実行してみましょう。`format()`関数も使用する組み込み関数の一つです。慣れておきましょう。とりあえず、プログラムを実行してみましょう。スクリプト名:training10.py | # 複数の変数を定義する方法
x_data, y_data = 100, 1000
print("x_data:", x_data, "y_data : ", y_data) | x_data: 100 y_data : 1000
| MIT | source/training10.ipynb | hskm07/pybeginner_training100 |
上記の例では、`変数1, 変数2, ... = 値1, 値2, ...`と定義すると、変数1には値1、変数2には値2、...という感じで値が代入されます。 | # 複数の変数を定義する方法
x_string, y_string, z_number = "python", "vba", 10*10
print("x_string:", x_string, "y_string : ", y_string, "z_number : ", z_number) | x_string: python y_string : vba z_number : 100
| MIT | source/training10.ipynb | hskm07/pybeginner_training100 |
****** format()関数の使い方 | # 練習1
msg = "私の年齢は{0}歳で、出身地は{1}です。趣味は{2}です。".format(29,"東京都","釣り")
print(msg) | 私の年齢は29歳で、出身地は東京都です。趣味は釣りです。
| MIT | source/training10.ipynb | hskm07/pybeginner_training100 |
***フォーマット関数 : `文字列{}.format(引数...)`***波カッコで囲まれた{}部分は、置換フィールドと呼ばれ、引数で{}の部分を置換します。上記の例は、"私の年齢は{0}歳で、出身地は{1}です。趣味は{2}です。".format(29,"東京都","釣り"){0} --> 引数1: 29{1} --> 引数2: "東京都"{2} --> 引数3: "釣り"という感じで値が置換されます。 | # 練習2
hello = "私は株式会社サンプルに{0}年に入社しました。職種は{1}です。得意なことは{2}と{3}です。".format(2020, "営業", "走ること", "Python")
print(hello) | 私は株式会社サンプルに2020年に入社しました。職種は営業です。得意なことは走ることとPythonです。
| MIT | source/training10.ipynb | hskm07/pybeginner_training100 |
****** for文を使って、文字を一文字ずつ取り出す | print("\"for文\"で文字を一文字ずつ取り出します")
# len()関数で変数msgの長さを取得
ln = len(msg)
for i in range(ln):
print("{0}番目の文字は、{1}です。".format(i, msg[i])) | "for文"で文字を一文字ずつ取り出します
0番目の文字は、私です。
1番目の文字は、のです。
2番目の文字は、年です。
3番目の文字は、齢です。
4番目の文字は、はです。
5番目の文字は、2です。
6番目の文字は、9です。
7番目の文字は、歳です。
8番目の文字は、でです。
9番目の文字は、、です。
10番目の文字は、出です。
11番目の文字は、身です。
12番目の文字は、地です。
13番目の文字は、はです。
14番目の文字は、東です。
15番目の文字は、京です。
16番目の文字は、都です。
17番目の文字は、でです。
18番目の文字は、すです。
19番目の文字は、。です。
20番目の文字は、趣です。
21番目の文字は、味です。
... | MIT | source/training10.ipynb | hskm07/pybeginner_training100 |
Data Science Unit 1 Sprint Challenge 2 Storytelling with DataIn this sprint challenge you'll work with a dataset from **FiveThirtyEight's article, [Every Guest Jon Stewart Ever Had On ‘The Daily Show’](https://fivethirtyeight.com/features/every-guest-jon-stewart-ever-had-on-the-daily-show/)**! Part 0 — Run this star... | %matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/fivethirtyeight/data/master/daily-show-guests/daily_show_guests.csv')
df.rename(columns={'YEAR': 'Year', 'Raw_Guest_List': 'Guest'}, inplace=True)
def get_occupation(group):
... | _____no_output_____ | MIT | DS_Unit_1_Sprint_Challenge_2.ipynb | aapte11/DS-Sprint-02-Storytelling-With-Data |
Part 1 — What's the breakdown of guests’ occupations per year?For example, in 1999, what percentage of guests were actors, comedians, or musicians? What percentage were in the media? What percentage were in politics? What percentage were from another occupation?Then, what about in 2000? In 2001? And so on, up through ... | df.head() | _____no_output_____ | MIT | DS_Unit_1_Sprint_Challenge_2.ipynb | aapte11/DS-Sprint-02-Storytelling-With-Data |
**PART 1: CROSSTAB** | cross = pd.crosstab(df.Year, df.Occupation, normalize = 'index')
cross
| _____no_output_____ | MIT | DS_Unit_1_Sprint_Challenge_2.ipynb | aapte11/DS-Sprint-02-Storytelling-With-Data |
Part 2 — Recreate this explanatory visualization: | from IPython.display import display, Image
url = 'https://fivethirtyeight.com/wp-content/uploads/2015/08/hickey-datalab-dailyshow.png'
example = Image(url, width=500)
display(example) | _____no_output_____ | MIT | DS_Unit_1_Sprint_Challenge_2.ipynb | aapte11/DS-Sprint-02-Storytelling-With-Data |
**Hint:** use the crosstab you calculated in part 1!**Expectations:** Your plot should include:- 3 lines visualizing "occupation of guests, by year." The shapes of the lines should look roughly identical to 538's example. Each line should be a different color. (But you don't need to use the _same_ colors as 538.)- Lege... | cross.index
import matplotlib.style as style
style.available
cross100 = 100*cross
fig, ax = plt.subplots(facecolor = 'white', figsize = (8,6))
style.use("fivethirtyeight") # Doesn't work
year = cross100.index
media = cross100['Media']
gov = cross100['Government and Politics']
entertainment = cross100['Acting, Come... | _____no_output_____ | MIT | DS_Unit_1_Sprint_Challenge_2.ipynb | aapte11/DS-Sprint-02-Storytelling-With-Data |
**plt.text and plt.style did not work in this case so I couldn't place text as needed. ** | !pip install --upgrade seaborn
import seaborn as sns
sns.__version__
import matplotlib.pyplot as plt
five_thirty_eight = [
"#30a2da",
"#fc4f30",
"#e5ae38",
"#6d904f",
"#8b8b8b",
]
sns.set_palette(five_thirty_eight)
sns.palplot(sns.color_palette())
plt.show() | _____no_output_____ | MIT | DS_Unit_1_Sprint_Challenge_2.ipynb | aapte11/DS-Sprint-02-Storytelling-With-Data |
**Attempting the problem in Seaborn****UPDATE: Same text issues with seaborn** | year = cross100.index
media = cross100['Media']
gov = cross100['Government and Politics']
entertainment = cross100['Acting, Comedy & Music']
ax1 = sns.lineplot(x=year, y=media, color = 'purple')
ax2 = sns.lineplot(x=year, y=gov, color = 'orangered')
ax3 = sns.lineplot(x=year, y=entertainment, color = 'dodgerblue')
ax... | _____no_output_____ | MIT | DS_Unit_1_Sprint_Challenge_2.ipynb | aapte11/DS-Sprint-02-Storytelling-With-Data |
Part 3 — Who were the top 10 guests on _The Daily Show_?**Make a plot** that shows their names and number of appearances.**Hint:** you can use the pandas `value_counts` method.**Expectations:** This can be a simple, quick plot: exploratory, not explanatory. If you want, you can add titles and change aesthetics, but it... | top_ten = df.Guest.value_counts()[0:10]
fig, ax = plt.subplots(facecolor = 'white', figsize = (8,6))
ax = top_ten.plot.bar(width = 0.9, color = 'limegreen')
ax.tick_params(axis = 'x', labelrotation = 90, colors = 'black', pad = 2, bottom = 'on')
ax.tick_params(axis = 'y', labelrotation = 0, colors = 'black')
y... | _____no_output_____ | MIT | DS_Unit_1_Sprint_Challenge_2.ipynb | aapte11/DS-Sprint-02-Storytelling-With-Data |
Introducción a SympyAdemais das variables numéricas existen as variables simbólicas que permiten calcularlímites, derivadas, integrais etc., como se fai habitualmente nas clases de matemáticas.Para poder facer estas operacións, habituais nun curso de Cálculo, é preciso ter instalada a libraría **Sympy**.Ao contrario q... | !pip -q install sympy | [33mYou are using pip version 19.3.1, however version 20.0.2 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.[0m
| MIT | practicas/introduccion-sympy.ipynb | maprieto/CalculoMultivariable |
Para dispoñer do módulo **Sympy** e importalo para o resto do guión de prácticas, usaremos: | import sympy as sp | _____no_output_____ | MIT | practicas/introduccion-sympy.ipynb | maprieto/CalculoMultivariable |
Variables simbólicasPara traballar en modo simbólico é necesario definir variables simbólicas e para faceristo usaremos o función `sp.Symbol`. Vexamos algúns exemplos do seu uso: | x = sp.Symbol('x') # define a variable simbólica x
y = sp.Symbol('y') # define a variable simbólica y
f = 3*x + 5*y # agora temos definida a expresion simbólica f
print(f)
a, b, c = sp.symbols('a:c') # define como simbólicas as variables a, b, c.
expresion = a**3 + b**2 + c
print(expresion) | 3*x + 5*y
a**3 + b**2 + c
| MIT | practicas/introduccion-sympy.ipynb | maprieto/CalculoMultivariable |
Por claridade na implementación e nos cálculos, será habitual que o nome da variable simbólica e o nome do obxecto **Sympy** no que se alamacena coincidan, pero isto non ter porque ser así: | a = sp.Symbol('x')
print(a)
a.name | x
| MIT | practicas/introduccion-sympy.ipynb | maprieto/CalculoMultivariable |
Debemos ter claso que agora as variables `x` ou `y` definidas antes non son números, nin tampouco pertencen aos obxectos definidos co módulo **Numpy** revisado na práctica anterior. Todas as variables simbólicas son obxectos da clase `sp.Symbol` e os seus atributos e métodos son completamente diferentes aos que aparecí... | print(type(x))
dir(x) | <class 'sympy.core.symbol.Symbol'>
| MIT | practicas/introduccion-sympy.ipynb | maprieto/CalculoMultivariable |
Con **Sympy** pódense definir constantes enteiras ou números racioanais (todas de forma simbólica) de xeito doado usando o comando `sp.Integer` ou `sp.Rational`. Por exemplo, podemos definir a constante simbólica $1/3$. Se fixeramos o mesmo con números representados por defecto en Python, obteríamos resultados moi dife... | a = sp.Rational('1/3')
b = sp.Integer('6')/sp.Integer('3')
c = 1/3
d = 1.0/3.0
print(a)
print(b)
print(c)
print(d)
print(type(a))
print(type(b))
print(type(c))
print(type(d))
print(a)
print(b) | 1/3
2
0
0.333333333333
<class 'sympy.core.numbers.Rational'>
<class 'sympy.core.numbers.Integer'>
<type 'int'>
<type 'float'>
1/3
2
| MIT | practicas/introduccion-sympy.ipynb | maprieto/CalculoMultivariable |
Outra forma sinxela de manexar valores constante mediante obxectos do módulo **Sympy** é usar a función `sp.S`. Unha vez feitos todos os cálculos simbólicos, se precisamos obter o valor numérico, empregaríase a función `sp.N` ou ben directamente `float`: | a = sp.S(2)
b = sp.S(6)
c = a/b
d = sp.N(c)
e = float(c)
print(type(a))
print(type(b))
print(type(c))
print(type(d))
print(type(e))
print(c)
print(d)
print('{0:.15f}'.format(e)) | <class 'sympy.core.numbers.Integer'>
<class 'sympy.core.numbers.Integer'>
<class 'sympy.core.numbers.Rational'>
<class 'sympy.core.numbers.Float'>
<type 'float'>
1/3
0.333333333333333
0.333333333333333
| MIT | practicas/introduccion-sympy.ipynb | maprieto/CalculoMultivariable |
Ao longo do curso usaremos asiduamente dous números reais que podes definir como constantes simbólicas: $\pi$ e o numéro $e$. Do mesmo xeito, para operar con variables ou constantes simbólicas, debemos empregar funcións que sexan capaces de manipular este tipo de obxectos, todas elas implementadas no módulo **Sympy** (... | import numpy as np
print(np.pi)
print(type(np.pi))
p=sp.pi # definición da constante pi
print(sp.cos(p))
e = sp.E # definición do número e
print(sp.log(e))
print(sp.N(sp.pi,1000))
print(type(sp.N(sp.pi,100))) | 3.14159265359
<type 'float'>
-1
1
3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214808651328230664709384460955058223172535940812848111745028410270193852110555964462294895493038196442881097566593344612847564823378678316527120190914564856692346034861045432664821339... | MIT | practicas/introduccion-sympy.ipynb | maprieto/CalculoMultivariable |
Suposicións sobre as variablesCando se define unha variable simbólica se lle pode asignar certa información adicional sobre o tipo de valores que pode acadar, ou as suposicións que se lle van a aplicar. Por exemplo, podemos decidir antes de facer calquera cálculo se a variable toma valores enteiros ou reais, se é posi... | x = sp.Symbol('x', nonnegative = True) # A raíz cadrada dun número non negativo é real
y = sp.sqrt(x)
print(y.is_real)
x = sp.Symbol('x', integer = True) # A potencia dun número enteiro é enteira
y = x**sp.S(2)
print(y.is_integer)
a = sp.Symbol('a')
b = sp.sqrt(a)
print(b.is_real)
a = sp.Symbol('a')
b = a**sp.S(2)
p... | True
True
None
None
| MIT | practicas/introduccion-sympy.ipynb | maprieto/CalculoMultivariable |
Posto que os cálculos simbólicos son consistentes en **Sympy**, se poden tamén facer comprobacións sobre se algunhas desigualdades son certas ou non, sempre e cando se teña coidado nas suposicións que se fagan ao definir as variables simbólicas | x = sp.Symbol('x', real = True)
p = sp.Symbol('p', positive = True)
q = sp.Symbol('q', real = True)
y = sp.Abs(x) + p # O valor absoluto
z = sp.Abs(x) + q
print(y > 0)
print(z > 0) | True
q + Abs(x) > 0
| MIT | practicas/introduccion-sympy.ipynb | maprieto/CalculoMultivariable |
Manipulación de expresións simbólicas Do mesmo xeito que o módulo **Sympy** nos permite definir variables simbólicas, tamén podemos definir expresións matemáticas a partir destas e manipulalas, factorizándoas, expandíndoas, simplificalas, ou mesmo imprimilas dun xeito similar a como o faríamos con lápiz e papel | x,y = sp.symbols('x,y', real=True)
expr = (x-3)*(x-3)**2*(y-2)
expr_long = sp.expand(expr) # Expandir expresión
print(expr_long) # Imprimir de forma estándar
sp.pprint(expr_long) # Imprimir de forma semellante a con lápiz e papel
expr_short = sp.factor(expr)
print(expr_short) # Factorizar expresión
expr = -3+(x**2-6... | x**3*y - 2*x**3 - 9*x**2*y + 18*x**2 + 27*x*y - 54*x - 27*y + 54
3 3 2 2
x ⋅y - 2⋅x - 9⋅x ⋅y + 18⋅x + 27⋅x⋅y - 54⋅x - 27⋅y + 54
(x - 3)**3*(y - 2)
2
x - 6⋅x + 9
-3 + ────────────
x - 3
x - 6
| MIT | practicas/introduccion-sympy.ipynb | maprieto/CalculoMultivariable |
Dada unha expresión en **Sympy** tamén se pode manipulala, substituindo unhas variables simbólica por outras ou mesmo reemprazando as variables simbólicas por constantes. Para facer este tipo de substitucións emprégase a función `subs` e os valores a utilizar na substitución veñen definidos por un diccionario de Python... | x,y = sp.symbols('x,y', real=True)
expr = x*x + x*y + y*x + y*y
res = expr.subs({x:1, y:2}) # Substitutición das variables simbólicas por constantes
print(res)
expr_sub = expr.subs({x:1-y}) # Subsitución de variable simbólica por unha expresión
sp.pprint(expr_sub)
print(sp.simplify(expr_sub)) | 9
2 2
y + 2⋅y⋅(-y + 1) + (-y + 1)
1
| MIT | practicas/introduccion-sympy.ipynb | maprieto/CalculoMultivariable |
**Exercicio 2.1** Define a expresión dada pola suma dos termos seguintes:$$a+a^2+a^3+\ldots+a^N,$$onde $a$ é unha variable real arbitraria e $N$ e un valor enteiro positivo. | # O TEU CÓDIGO AQUÍ | _____no_output_____ | MIT | practicas/introduccion-sympy.ipynb | maprieto/CalculoMultivariable |
**Exercicio 2.2** Cal é o valor exacto da anterior expresión cando $N=15$ e $a=5/6$? Cal é valor numérico en coma flotante? | # O TEU CÓDIGO AQUÍ | _____no_output_____ | MIT | practicas/introduccion-sympy.ipynb | maprieto/CalculoMultivariable |
Problem statementGiven a sorted array that may have duplicate values, use *binary search* to find the **first** and **last** indexes of a given value.For example, if you have the array `[0, 1, 2, 2, 3, 3, 3, 4, 5, 6]` and the given value is `3`, the answer will be `[4, 6]` (because the value `3` occurs first at index ... | def first_and_last_index(arr, number):
"""
Given a sorted array that may have duplicate values, use binary
search to find the first and last indexes of a given value.
Args:
arr(list): Sorted array (or Python list) that may have duplicate values
number(int): Value to search for in the a... | _____no_output_____ | MIT | Course/Data structures and algorithms/3.Basic algorithm/1.Basic algorithms/5.First and last index.ipynb | IulianOctavianPreda/Udacity |
Hide Solution | def first_and_last_index(arr, number):
# search first occurence
first_index = find_start_index(arr, number, 0, len(arr) - 1)
# search last occurence
last_index = find_end_index(arr, number, 0, len(arr) - 1)
return [first_index, last_index]
def find_start_index(arr, number, start_index, end_i... | _____no_output_____ | MIT | Course/Data structures and algorithms/3.Basic algorithm/1.Basic algorithms/5.First and last index.ipynb | IulianOctavianPreda/Udacity |
Below are several different test cases you can use to check your solution. | def test_function(test_case):
input_list = test_case[0]
number = test_case[1]
solution = test_case[2]
output = first_and_last_index(input_list, number)
if output == solution:
print("Pass")
else:
print("Fail")
input_list = [1]
number = 1
solution = [0, 0]
test_case_1 = [input_list... | _____no_output_____ | MIT | Course/Data structures and algorithms/3.Basic algorithm/1.Basic algorithms/5.First and last index.ipynb | IulianOctavianPreda/Udacity |
print("ssss213") | _____no_output_____ | MIT | Untitled2.ipynb | mohamadhayeri9/tensorflow_example | |
Project: Ventilation in the CCU EDA: Ventilator Mode in the CCU Cohort C.V. Cosgriff NYU CCU Data Science Group__Question:__ Can you guys please see how many of the 756 patients received receive SIMV or IMV as the mode of mechanical ventilation. A very interesting (and relatively simple) analysis would be to compare l... | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
sns.set()
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
import psycopg2
dbname = 'mimic'
schema_name = 'mimiciii'
db_schema = 'SET search_path TO {0};'.format(schema_name)
con = psycopg2.connect(database=d... | _____no_output_____ | MIT | ventilation/mode_analysis.ipynb | cosgriffc/mimic-ccu |
1 - CCU Cohort Extraction | query = db_schema + '''
SELECT ie.icustay_id, ie.hadm_id, ie.subject_id, ie.dbsource
, ie.first_careunit, ie.intime, ie.outtime, ie.los
, ied.admission_age, ied.gender, ied.ethnicity
, ied.first_icu_stay, oa.oasis AS oasis_score
, elix.elixhauser_vanwalraven AS elixhauser_score
, vd.s... | _____no_output_____ | MIT | ventilation/mode_analysis.ipynb | cosgriffc/mimic-ccu |
2 - Identify Ventilator Mode Items | query = db_schema + '''
SELECT itemid, label, dbsource, linksto
FROM d_items
WHERE LOWER(label) LIKE '%mode%'
AND dbsource='metavision';
'''
d_search = pd.read_sql_query(query, con)
display(d_search) | _____no_output_____ | MIT | ventilation/mode_analysis.ipynb | cosgriffc/mimic-ccu |
It appears the `itemid` is __223849__. 3 - Extract Ventilation Modes | query = db_schema + '''
WITH vent_mode_day1 AS (
SELECT ce.icustay_id, ce.charttime - ie.intime AS offset
, ce.value
FROM icustays ie
LEFT JOIN chartevents ce
ON ie.icustay_id = ce.icustay_id
WHERE ce.itemid = 223849
)
SELECT vm.icustay_id, vm.value AS vent_mode_24h
FROM vent_mode_day1 vm
WH... | _____no_output_____ | MIT | ventilation/mode_analysis.ipynb | cosgriffc/mimic-ccu |
Lets look at the distribution of different ventilation modes in this data. | vm_df.groupby(vm_df.vent_mode_24h).count().plot(kind='bar', figsize=(12,6)) | _____no_output_____ | MIT | ventilation/mode_analysis.ipynb | cosgriffc/mimic-ccu |
Format Data | def permute(image):
image = torch.Tensor(image)
image = image.permute(3,0,1,2).numpy()
return image
DATA_PATH = '../data/brats_dataset/raw_data/'
OUT_PATH = '../data/brats_dataset/processed_data_2d/'
TABLE_PATH = '../data/split_tables/brats_2d/'
os.makedirs(TABLE_PATH,exist_ok=True)
patient_list = [i for i ... | 93%|█████████▎| 342/369 [22:45<01:42, 3.78s/it] | BSD-2-Clause | notebooks/.ipynb_checkpoints/0_format_BRATS_data-checkpoint.ipynb | neurips2021vat/Variance-Aware-Training |
Prepare split tables | patient_list = [OUT_PATH[1:]+i for i in os.listdir(OUT_PATH) if i.find('.')==-1]
print(f'Total number of patients: {len(patient_list)}')
patient_arr = []
records = []
for patient in patient_list:
records += [patient+'/'+i for i in os.listdir('.'+patient) if i.find('voxels')!=-1]
patient_arr += [patient]*len([pa... | _____no_output_____ | BSD-2-Clause | notebooks/.ipynb_checkpoints/0_format_BRATS_data-checkpoint.ipynb | neurips2021vat/Variance-Aware-Training |
___ ___ Merging, Joining, and ConcatenatingThere are 3 main ways of combining DataFrames together: Merging, Joining and Concatenating. In this lecture we will discuss these 3 methods with examples.____ Example DataFrames | import pandas as pd
df1 = pd.DataFrame({'A': ['A0', 'A1', 'A2', 'A3'],
'B': ['B0', 'B1', 'B2', 'B3'],
'C': ['C0', 'C1', 'C2', 'C3'],
'D': ['D0', 'D1', 'D2', 'D3']},
index=[0, 1, 2, 3])
df2 = pd.DataFrame({'A': ['A4', 'A5', '... | _____no_output_____ | MIT | res/Python-for-Data-Analysis/Pandas/Merging, Joining, and Concatenating .ipynb | Calvibert/machine-learning-exercises |
ConcatenationConcatenation basically glues together DataFrames. Keep in mind that dimensions should match along the axis you are concatenating on. You can use **pd.concat** and pass in a list of DataFrames to concatenate together: | pd.concat([df1,df2,df3])
pd.concat([df1,df2,df3],axis=1) | _____no_output_____ | MIT | res/Python-for-Data-Analysis/Pandas/Merging, Joining, and Concatenating .ipynb | Calvibert/machine-learning-exercises |
_____ Example DataFrames | left = pd.DataFrame({'key': ['K0', 'K1', 'K2', 'K3'],
'A': ['A0', 'A1', 'A2', 'A3'],
'B': ['B0', 'B1', 'B2', 'B3']})
right = pd.DataFrame({'key': ['K0', 'K1', 'K2', 'K3'],
'C': ['C0', 'C1', 'C2', 'C3'],
'D': ['D0', 'D1', '... | _____no_output_____ | MIT | res/Python-for-Data-Analysis/Pandas/Merging, Joining, and Concatenating .ipynb | Calvibert/machine-learning-exercises |
___ MergingThe **merge** function allows you to merge DataFrames together using a similar logic as merging SQL Tables together. For example: | pd.merge(left,right,how='inner',on='key') | _____no_output_____ | MIT | res/Python-for-Data-Analysis/Pandas/Merging, Joining, and Concatenating .ipynb | Calvibert/machine-learning-exercises |
Or to show a more complicated example: | left = pd.DataFrame({'key1': ['K0', 'K0', 'K1', 'K2'],
'key2': ['K0', 'K1', 'K0', 'K1'],
'A': ['A0', 'A1', 'A2', 'A3'],
'B': ['B0', 'B1', 'B2', 'B3']})
right = pd.DataFrame({'key1': ['K0', 'K1', 'K1', 'K2'],
'key2':... | _____no_output_____ | MIT | res/Python-for-Data-Analysis/Pandas/Merging, Joining, and Concatenating .ipynb | Calvibert/machine-learning-exercises |
JoiningJoining is a convenient method for combining the columns of two potentially differently-indexed DataFrames into a single result DataFrame. | left = pd.DataFrame({'A': ['A0', 'A1', 'A2'],
'B': ['B0', 'B1', 'B2']},
index=['K0', 'K1', 'K2'])
right = pd.DataFrame({'C': ['C0', 'C2', 'C3'],
'D': ['D0', 'D2', 'D3']},
index=['K0', 'K2', 'K3'])
left.join(right)
left.join(right, ho... | _____no_output_____ | MIT | res/Python-for-Data-Analysis/Pandas/Merging, Joining, and Concatenating .ipynb | Calvibert/machine-learning-exercises |
Version 6.0ground truth using "denosing"find out the different pairs and only output those different things 1. Preparation | from google.colab import drive
drive.mount('/content/drive')
root = 'drive/MyDrive/LM/'
!pip install sentencepiece
!pip install transformers -q
!pip install wandb -q
# Importing stock libraries
import numpy as np
import pandas as pd
import time
from tqdm import tqdm
import os
import regex as re
import sys
sys.path.appe... | _____no_output_____ | MIT | huggingface_t5_6_3.ipynb | skywalker00001/Conterfactual-Reasoning-Project |
2. Load dataframe | #training df
small_path = root + '/TimeTravel/cleaned_small_2.0.xlsx'
small_df = pd.read_excel(small_path)
#small_df.head()
print(len(small_df))
small_df.head(3)
#valid df
large_path = root + '/TimeTravel/cleaned_large_2.0.xlsx'
large_df = pd.read_excel(large_path)
#large_df.head()
print(len(large_df))
small_ids = []
f... | _____no_output_____ | MIT | huggingface_t5_6_3.ipynb | skywalker00001/Conterfactual-Reasoning-Project |
3. Dataset and Dataloader | # Creating a custom dataset for reading the dataframe and loading it into the dataloader to pass it to the neural network at a later stage for finetuning the model and to prepare it for predictions
class CustomDataset(Dataset):
def __init__(self, dataframe, tokenizer, input_len, output_len):
self.tokenize... | _____no_output_____ | MIT | huggingface_t5_6_3.ipynb | skywalker00001/Conterfactual-Reasoning-Project |
4. Define train() and val() | def save_model(epoch, model, optimizer, loss, PATH):
torch.save({
'epoch': epoch,
'model_state_dict': model.state_dict(),
'optimizer_state_dict': optimizer.state_dict(),
'loss': loss
}, PATH)
def load_model(PATH):
checkpoint = torch.load(PATH)
mode... | _____no_output_____ | MIT | huggingface_t5_6_3.ipynb | skywalker00001/Conterfactual-Reasoning-Project |
5. main() | import time
# Helper function to print time between epochs
def epoch_time(start_time, end_time):
elapsed_time = end_time - start_time
elapsed_mins = int(elapsed_time / 60)
elapsed_secs = int(elapsed_time - (elapsed_mins * 60))
return elapsed_mins, elapsed_secs
# if need, load model
loss = 0
if (load_ve... | _____no_output_____ | MIT | huggingface_t5_6_3.ipynb | skywalker00001/Conterfactual-Reasoning-Project |
6. Inference | # # load model
# model, optimizer, initial_epoch, loss = load_model(config.LOAD_PATH)
# print(loss)
# Validation loop and saving the resulting file with predictions and acutals in a dataframe.
# Saving the dataframe as predictions.csv
print('Now inferecing:')
start_time = time.time()
raws, predictions, actuals,final_lo... | _____no_output_____ | MIT | huggingface_t5_6_3.ipynb | skywalker00001/Conterfactual-Reasoning-Project |
7. check the samples with same original ending and edited ending | # import pandas as pd
# import regex as re
result_df = pd.read_excel(root + 'results/' + 'output_beam1' + model_version + '.xlsx')
result_df.head()
print(len(result_df))
or_pat = re.compile(r'(original_ending: )(.*)$')
ed_pat = re.compile(r'(edited_ending: )(.*)$')
pipei = re.search(ed_pat, result_df.iloc[0].generat... | _____no_output_____ | MIT | huggingface_t5_6_3.ipynb | skywalker00001/Conterfactual-Reasoning-Project |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.