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 |
|---|---|---|---|---|---|
Plotting the Data* Use proper labeling of the plots using plot titles (including date of analysis) and axes labels.* Save the plotted figures as .pngs. Latitude vs. Temperature Plot | #Make plot
temp = city_df["Max Temp"]
lat = city_df["Lat"]
plt.scatter(lat, temp, marker="o", facecolors="blue", edgecolors="black", alpha=0.75)
# Set y lim based on max and min temp
plt.ylim(min(temp) - 5, max(temp) + 5)
# Set the x lim based on max and min lat
plt.xlim(min(lat) - 5, max(lat) + 5)
# Create a title... | _____no_output_____ | MIT | WeatherPy/WeatherPy.ipynb | ball4410/python-api-challenge |
Latitude vs. Humidity Plot | #Make plot
humid = city_df["Humidity"]
lat = city_df["Lat"]
plt.scatter(lat, humid, marker="o", facecolors="blue", edgecolors="black", alpha=0.75)
# Set y lim based on max and min humudity
plt.ylim(min(humid) - 5, max(humid) + 5)
# Set the x lim based on max and min lat
plt.xlim(min(lat) - 5, max(lat) + 5)
# Create... | _____no_output_____ | MIT | WeatherPy/WeatherPy.ipynb | ball4410/python-api-challenge |
Latitude vs. Cloudiness Plot | #Make plot
cloud = city_df["Cloudiness"]
lat = city_df["Lat"]
plt.scatter(lat, cloud, marker="o", facecolors="blue", edgecolors="black", alpha=0.75)
# Set y lim based on max and min cloudiness
plt.ylim(min(cloud) - 5, max(cloud) + 5)
# Set the x lim based on max and min lat
plt.xlim(min(lat) - 5, max(lat) + 5)
# Cr... | _____no_output_____ | MIT | WeatherPy/WeatherPy.ipynb | ball4410/python-api-challenge |
Latitude vs. Wind Speed Plot | #Make plot
wind = city_df["Wind Speed"]
lat = city_df["Lat"]
plt.scatter(lat, wind, marker="o", facecolors="blue", edgecolors="black", alpha=0.75)
# Set y lim based on max and min cloudiness
plt.ylim(-0.75, max(wind) + 5)
# Set the x lim based on max and min lat
plt.xlim(min(lat) - 5, max(lat) + 5)
# Create a title... | _____no_output_____ | MIT | WeatherPy/WeatherPy.ipynb | ball4410/python-api-challenge |
Linear Regression | #Separate our data frame into different hemispheres
city_df.head()
nor_hem_df = city_df.loc[city_df["Lat"] >= 0]
so_hem_df = city_df.loc[city_df["Lat"] <= 0] | _____no_output_____ | MIT | WeatherPy/WeatherPy.ipynb | ball4410/python-api-challenge |
Northern Hemisphere - Max Temp vs. Latitude Linear Regression | #Make plot
temp = nor_hem_df["Max Temp"]
lat = nor_hem_df["Lat"]
plt.scatter(lat, temp, marker="o", facecolors="blue", edgecolors="black", alpha=0.75)
# Set y lim based on max and min temp
plt.ylim(min(temp) - 5, max(temp) + 5)
# Set the x lim based on max and min lat
plt.xlim(min(lat) - 5, max(lat) + 5)
# Create a... | _____no_output_____ | MIT | WeatherPy/WeatherPy.ipynb | ball4410/python-api-challenge |
Southern Hemisphere - Max Temp vs. Latitude Linear Regression | #Make plot
temp = so_hem_df["Max Temp"]
lat = so_hem_df["Lat"]
plt.scatter(lat, temp, marker="o", facecolors="blue", edgecolors="black", alpha=0.75)
# Set y lim based on max and min temp
plt.ylim(min(temp) - 5, max(temp) + 5)
# Set the x lim based on max and min lat
plt.xlim(min(lat) - 2, max(lat) + 2)
# Create a t... | _____no_output_____ | MIT | WeatherPy/WeatherPy.ipynb | ball4410/python-api-challenge |
Northern Hemisphere - Humidity (%) vs. Latitude Linear Regression | #Make plot
humid = nor_hem_df["Humidity"]
lat = nor_hem_df["Lat"]
plt.scatter(lat, humid, marker="o", facecolors="blue", edgecolors="black", alpha=0.75)
# Set y lim based on max and min humudity
plt.ylim(min(humid) - 5, max(humid) + 5)
# Set the x lim based on max and min lat
plt.xlim(min(lat) - 5, max(lat) + 5)
# ... | _____no_output_____ | MIT | WeatherPy/WeatherPy.ipynb | ball4410/python-api-challenge |
Southern Hemisphere - Humidity (%) vs. Latitude Linear Regression | #Make plot
humid = so_hem_df["Humidity"]
lat = so_hem_df["Lat"]
plt.scatter(lat, humid, marker="o", facecolors="blue", edgecolors="black", alpha=0.75)
# Set y lim based on max and min humudity
plt.ylim(min(humid) - 5, max(humid) + 5)
# Set the x lim based on max and min lat
plt.xlim(min(lat) - 5, max(lat) + 5)
# Cr... | _____no_output_____ | MIT | WeatherPy/WeatherPy.ipynb | ball4410/python-api-challenge |
Northern Hemisphere - Cloudiness (%) vs. Latitude Linear Regression | #Make plot
cloud = nor_hem_df["Cloudiness"]
lat = nor_hem_df["Lat"]
plt.scatter(lat, cloud, marker="o", facecolors="blue", edgecolors="black", alpha=0.75)
# Set y lim based on max and min humudity
plt.ylim(min(cloud) - 5, max(cloud) + 5)
# Set the x lim based on max and min lat
plt.xlim(min(lat) - 5, max(lat) + 5)
... | _____no_output_____ | MIT | WeatherPy/WeatherPy.ipynb | ball4410/python-api-challenge |
Southern Hemisphere - Cloudiness (%) vs. Latitude Linear Regression | #Make plot
cloud = so_hem_df["Cloudiness"]
lat = so_hem_df["Lat"]
plt.scatter(lat, cloud, marker="o", facecolors="blue", edgecolors="black", alpha=0.75)
# Set y lim based on max and min humudity
plt.ylim(min(cloud) - 5, max(cloud) + 5)
# Set the x lim based on max and min lat
plt.xlim(min(lat) - 5, max(lat) + 5)
# ... | _____no_output_____ | MIT | WeatherPy/WeatherPy.ipynb | ball4410/python-api-challenge |
Northern Hemisphere - Wind Speed (mph) vs. Latitude Linear Regression | #Make plot
wind = nor_hem_df["Wind Speed"]
lat = nor_hem_df["Lat"]
plt.scatter(lat, wind, marker="o", facecolors="blue", edgecolors="black", alpha=0.75)
# Set y lim based on max and min humudity
plt.ylim(min(wind) - 5, max(wind) + 5)
# Set the x lim based on max and min lat
plt.xlim(min(lat) - 5, max(lat) + 5)
# Cr... | _____no_output_____ | MIT | WeatherPy/WeatherPy.ipynb | ball4410/python-api-challenge |
Southern Hemisphere - Wind Speed (mph) vs. Latitude Linear Regression | #Make plot
wind = so_hem_df["Wind Speed"]
lat = so_hem_df["Lat"]
plt.scatter(lat, wind, marker="o", facecolors="blue", edgecolors="black", alpha=0.75)
# Set y lim based on max and min humudity
plt.ylim(min(wind) - 5, max(wind) + 5)
# Set the x lim based on max and min lat
plt.xlim(min(lat) - 5, max(lat) + 5)
# Crea... | _____no_output_____ | MIT | WeatherPy/WeatherPy.ipynb | ball4410/python-api-challenge |
Exact Equation | x, p = np.cos(t - np.pi), -np.sin(t - np.pi)
fig = plt.figure(figsize=(5, 5))
for i in range(0, len(t), 1):
plt.plot(x[i:i+2], p[i:i+2], color='black', markersize=0) | _____no_output_____ | MIT | hmc/example4-leapfrog.ipynb | bjlkeng/sandbox |
Euler's Method Equation Euler's Method | # x' = p/m = p
# p' = -kx + mg = -x
# x = x + \eps * p' = x + \eps*(p)
# p = p + \eps * x' = p - \eps*(x)
fig = plt.figure(figsize=(5, 5))
plt.title("Euler's Method (eps=0.1)")
plt.xlabel("position (q)")
plt.ylabel("momentum (p)")
for i in range(0, len(t), 1):
plt.plot(x[i:i+2], p[i:i+2], color='black', markersize=... | _____no_output_____ | MIT | hmc/example4-leapfrog.ipynb | bjlkeng/sandbox |
Modified Euler's Method | # x' = p/m = p
# p' = -kx + mg = -x
# x = x + \eps * p' = x + \eps*(p)
# p = p + \eps * x' = p - \eps*(x)
fig = plt.figure(figsize=(5, 5))
plt.title("Modified Euler's Method (eps=0.2)")
plt.xlabel("position (q)")
plt.ylabel("momentum (p)")
for i in range(0, len(t), 1):
plt.plot(x[i:i+2], p[i:i+2], color='black', ma... | _____no_output_____ | MIT | hmc/example4-leapfrog.ipynb | bjlkeng/sandbox |
Leapfrog Method | # x' = p/m = p
# p' = -kx + mg = -x
# x = x + \eps * p' = x + \eps*(p)
# p = p + \eps * x' = p - \eps*(x)
fig = plt.figure(figsize=(5, 5))
plt.title("Leapfrog Method (eps=0.2)")
plt.xlabel("position (q)")
plt.ylabel("momentum (p)")
for i in range(0, len(t), 1):
plt.plot(x[i:i+2], p[i:i+2], color='black', markersize... | _____no_output_____ | MIT | hmc/example4-leapfrog.ipynb | bjlkeng/sandbox |
Combined Figure | fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(15,15))
# subplot1
ax1.set_title("Euler's Method (eps=0.1)")
ax1.set_xlabel("position (q)")
ax1.set_ylabel("momentum (p)")
for i in range(0, len(t), 1):
ax1.plot(x[i:i+2], p[i:i+2], color='black', markersize=0)
x_prev = 0
p_prev = 1
eps = 0.1
steps = 100... | _____no_output_____ | MIT | hmc/example4-leapfrog.ipynb | bjlkeng/sandbox |
Combined Figure - Square | fig, ((ax1, ax2)) = plt.subplots(1, 2, figsize=(15, 7.5))
# subplot1
ax1.set_title("Euler's Method (eps=0.2)")
ax1.set_xlabel("position (q)")
ax1.set_ylabel("momentum (p)")
for i in range(0, len(t), 1):
ax1.plot(x[i:i+2], p[i:i+2], color='black', markersize=0)
def draw_square(ax, x, p, **args):
assert len... | _____no_output_____ | MIT | hmc/example4-leapfrog.ipynb | bjlkeng/sandbox |
Import and settings | import numpy as np
import matplotlib.pyplot as plt
from matplotlib.path import Path
import matplotlib.patches as patches
from snaptools import manipulate as man
from snaptools import snapio
from snaptools import plot_tools
from snaptools import utils
from scipy.stats import binned_statistic
from mpl_toolkits.axes_grid1... | _____no_output_____ | MIT | Measure_velocities.ipynb | stephenpardy/Offsets_Notebooks |
Snapshot | settings = plot_tools.make_defaults(first_only=True, com=True, xlen=20, ylen=20, in_min=0)
snap = io.load_snap('/usr/users/spardy/coors2/hpc_backup/working/Gas/Dehnen_LMC/collision/output_Dehnen_smc_45deg/snap_007.hdf5')
velfield = snap.to_velfield(parttype='gas', write=False, first_only=True, com=True)
centDict = snap... | 255.248
| MIT | Measure_velocities.ipynb | stephenpardy/Offsets_Notebooks |
Measure Velocities from Velfield | # Now try with the velfield
settings = plot_tools.make_defaults(first_only=True, com=True, xlen=20, ylen=20, in_min=0)
binDict = snap.bin_snap(settings)
Z2 = binDict['Z2']
measurements = man.fit_contours(Z2, settings, plot=True)
#measurementsV2 = man.fit_contours(~np.isnan(velfield), settingsV, plot=True, numcontours=1... | Astro715_HW3.ipynb Illustris.ipynb plottingtest.ipynb
Data Impact_parameter.ipynb PythonNotebooks
Dehnen_Burkert_fit.ipynb isima_notebooks Stream_Notebooks
Ellipse_Stuff.ipynb llustrisPlots.ipynb test.out
GalCoords.ipynb Mathematica_Notebooks TestPotential.ipynb
Haro11.ipynb Offsets_Noteboo... | MIT | Measure_velocities.ipynb | stephenpardy/Offsets_Notebooks |
Plot 2d velocities vs. disk fit | names = [r'$\theta = 45$', r'$\theta = 90$',
r'$\theta = 0$', r'$\theta = 0$ - Retrograde']
fig = plt.figure(figsize=(15, 10))
colors = ['#332288', '#CC6677', '#6699CC', '#117733']
grid = Grid(fig, 111,
nrows_ncols=(2, 2),
axes_pad=0.0,
label_mode="L",
share_all... | _____no_output_____ | MIT | Measure_velocities.ipynb | stephenpardy/Offsets_Notebooks |
OLD STUFF | theta = np.radians(20)
r = 0
x = r*np.sin(theta)
y = r*np.cos(theta)
verts = [
[length*np.cos(theta)-thick*np.sin(theta)-x,
length*np.sin(theta)+thick*np.cos(theta)+y],
[length*np.cos(theta)+thick*np.sin(theta)-x,
length*np.sin(theta)-thick*np.cos(theta)+y],
[-length*np.co... | _____no_output_____ | MIT | Measure_velocities.ipynb | stephenpardy/Offsets_Notebooks |
A CASE STUDY OF FACTORS AFFECTING LOAN APPROVAL 1. Defining the question a) Specifying the analysis questionIs there a relationship between gender, credit history and the area one lives and loan status? b) Defining the metric for successBe able to obtain and run statistically correct hypothesis tests, and come to ... | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from scipy.stats import f_oneway
from scipy.stats import ttest_ind
import scipy.stats as stats
from sklearn.decomposition import PCA | _____no_output_____ | MIT | THE_LOAN_APPROVAL_PROJECT.ipynb | Ciiku-Kihara/LOAN-APPROVAL-PROJECT |
3. Loading and checking the data | # Loading our dataset
loans_df = pd.read_csv('loans.csv')
# Getting a preview of the first 10 rows
loans_df.head(10)
# Determining the number of rows and columns in the dataset
loans_df.shape
# Determining the names of the columns present in the dataset
loans_df.columns
# Description of the quantitative columns
l... | <class 'pandas.core.frame.DataFrame'>
RangeIndex: 614 entries, 0 to 613
Data columns (total 13 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 Loan_ID 614 non-null object
1 Gender 601 non-null object
2 Married ... | MIT | THE_LOAN_APPROVAL_PROJECT.ipynb | Ciiku-Kihara/LOAN-APPROVAL-PROJECT |
4. External data source validation > We validated our dataset using information from the following link:> http://calcnet.mth.cmich.edu/org/spss/prj_loan_data.htm 5. Data cleaning Uniformity | # Changing all column names to lowercase, stripping white spaces
# and removing all underscores
loans_df.columns = loans_df.columns.str.lower().str.strip().str.replace("_","")
# Confirming the changes made
loans_df.head(5) | _____no_output_____ | MIT | THE_LOAN_APPROVAL_PROJECT.ipynb | Ciiku-Kihara/LOAN-APPROVAL-PROJECT |
Data Completeness | # Determining the number of null values in each column
loans_df.isnull().sum()
#Imputing Loan Amount with mean
loans_df['loanamount'] = loans_df['loanamount'].fillna(loans_df['loanamount'].mean())
#FowardFill For LoanTerm
loans_df['loanamountterm'] = loans_df['loanamountterm'].fillna(method = "ffill")
#Assuming Mis... | _____no_output_____ | MIT | THE_LOAN_APPROVAL_PROJECT.ipynb | Ciiku-Kihara/LOAN-APPROVAL-PROJECT |
Data Consistency | # Checking if there are any duplicated rows
loans_df.duplicated().sum()
# Checking for any anomalies in the qualitative variables
qcol = ['gender', 'married', 'dependents', 'education',
'selfemployed','credithistory', 'propertyarea', 'loanstatus']
for col in qcol:
print(col, ':', loans_df[col].unique())
#C... | _____no_output_____ | MIT | THE_LOAN_APPROVAL_PROJECT.ipynb | Ciiku-Kihara/LOAN-APPROVAL-PROJECT |
6. Exploratory Data Analysis a) Univariate Analysis | # Previewing the dataset
loans_df.head(4)
# Loan Status
Yes = loans_df[loans_df["loanstatus"] == 'Y'].shape[0]
No = loans_df[loans_df["loanstatus"] == 'N'].shape[0]
print(f"Yes = {Yes}")
print(f"No = {No}")
print(' ')
print(f"Proportion of Yes = {(Yes / len(loans_df['loanstatus'])) * 100:.2f}%")
print(f"Proportion of... | _____no_output_____ | MIT | THE_LOAN_APPROVAL_PROJECT.ipynb | Ciiku-Kihara/LOAN-APPROVAL-PROJECT |
b) Bivariate Analysis | # Preview of dataset
loans_df.head(3)
# Comparison of Self employment Status and Loan Status
table=pd.crosstab(loans_df['selfemployed'],loans_df['loanstatus'])
table.div(table.sum(1).astype(float), axis=0).plot(kind='bar', figsize= (10,8), stacked=False)
plt.title('Stacked Bar Chart of Self Employed to Loan Status',... | _____no_output_____ | MIT | THE_LOAN_APPROVAL_PROJECT.ipynb | Ciiku-Kihara/LOAN-APPROVAL-PROJECT |
c) Multivariate Analysis | # Analysis of Loan Status, Applicant income and Loan Amount
plt.figure(figsize=(10,8))
sns.scatterplot(x= loans_df['loanamount'], y=loans_df['applicantincome'], hue= loans_df['loanstatus'])
plt.title('Loan Amount vs Applicant Income vs Loan Status', fontsize = 16)
plt.xlabel('Loan Amount', fontsize = 14)
plt.ylabel('A... | _____no_output_____ | MIT | THE_LOAN_APPROVAL_PROJECT.ipynb | Ciiku-Kihara/LOAN-APPROVAL-PROJECT |
7. Hypothesis testing - The Chi-square test will be used for all hypothesis tests in our analysis.- The level of significance to be used in all tests below will be 0.05 or 5% **Hypothesis 1:**Ho : There is no relationship between credit history and the loan statusHa : There is a relationship between credit history an... | # Creating a crosstab
tab = pd.crosstab(loans_df['loanstatus'], loans_df['credithistory'])
tab
# Obtaining the observed values
observed_values = tab.values
print('Observed values: -\n', observed_values)
# Creating the chi square contingency table
val = stats.chi2_contingency(tab)
val
# Obtaining the expected values
... | Reject Null Hypothesis
| MIT | THE_LOAN_APPROVAL_PROJECT.ipynb | Ciiku-Kihara/LOAN-APPROVAL-PROJECT |
The chi-square statistic is greater than the critical value hence we reject the null hypothesis that there is no relationship between credit history and loan statusAt 5% level of significance, there is enough evidence to conclude that there is a relationship between credit history and loan status **Hypothesis 2 :**Ho :... | # Creating a crosstab
tab = pd.crosstab(loans_df['loanstatus'], loans_df['propertyarea'])
tab
# Obtaining the observed values
observed_values = tab.values
print('Observed values: -\n', observed_values)
# Creating the chi square contingency table
val = stats.chi2_contingency(tab)
val
# Obtaining the expected values
... | Reject Null Hypothesis
| MIT | THE_LOAN_APPROVAL_PROJECT.ipynb | Ciiku-Kihara/LOAN-APPROVAL-PROJECT |
The chi-square statistic is greater than the critical value hence we reject the null hypothesis that there is no relationship between area and loan statusAt 5% level of significance, there is enough evidence to conclude that there is a relationship between credit area and loan status **Hypothesis 3 :**Ho : There is no ... | # Creating a crosstab
tab = pd.crosstab(loans_df['loanstatus'], loans_df['gender'])
tab
# Obtaining the observed values
observed_values = tab.values
print('Observed values: -\n', observed_values)
# Creating the chi square contingency table
val = stats.chi2_contingency(tab)
val
# Obtaining the expected values
expect... | Do not Reject Null Hypothesis
| MIT | THE_LOAN_APPROVAL_PROJECT.ipynb | Ciiku-Kihara/LOAN-APPROVAL-PROJECT |
The chi-square statistic is less than the critical value hence we do not reject the null hypothesis that there is no relationship between area and loan statusAt 5% level of significance, there is not enough evidence to conclude that there is a relationship between credit area and loan status 8. Dimensionality reductio... | # PCA analysis with One Hot Encoding
dummy_Gender = pd.get_dummies(loans_df['gender'], prefix = 'Gender')
dummy_Married = pd.get_dummies(loans_df['married'], prefix = "Married")
dummy_Education = pd.get_dummies(loans_df['education'], prefix = "Education")
dummy_Self_Employed = pd.get_dummies(loans_df['selfemployed'], ... | [[ 0 33]
[ 0 90]]
Accuracy 0.7317073170731707
| MIT | THE_LOAN_APPROVAL_PROJECT.ipynb | Ciiku-Kihara/LOAN-APPROVAL-PROJECT |
Dependencies | import os
import random
import warnings
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.utils import class_weight
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix, cohen_kappa_score
from keras import backend as K
... | Using TensorFlow backend.
| MIT | Model backlog/ResNet50/23 - ResNet50 - Data augmentation fill constant.ipynb | ThinkBricks/APTOS2019BlindnessDetection |
Load data | train = pd.read_csv('../input/aptos2019-blindness-detection/train.csv')
test = pd.read_csv('../input/aptos2019-blindness-detection/test.csv')
print('Number of train samples: ', train.shape[0])
print('Number of test samples: ', test.shape[0])
# Preprocecss data
train["id_code"] = train["id_code"].apply(lambda x: x + ".... | Number of train samples: 3662
Number of test samples: 1928
| MIT | Model backlog/ResNet50/23 - ResNet50 - Data augmentation fill constant.ipynb | ThinkBricks/APTOS2019BlindnessDetection |
Model parameters | # Model parameters
BATCH_SIZE = 8
EPOCHS = 30
WARMUP_EPOCHS = 2
LEARNING_RATE = 1e-4
WARMUP_LEARNING_RATE = 1e-3
HEIGHT = 512
WIDTH = 512
CANAL = 3
N_CLASSES = train['diagnosis'].nunique()
ES_PATIENCE = 5
RLROP_PATIENCE = 3
DECAY_DROP = 0.5
def kappa(y_true, y_pred, n_classes=5):
y_trues = K.cast(K.argmax(y_true), ... | _____no_output_____ | MIT | Model backlog/ResNet50/23 - ResNet50 - Data augmentation fill constant.ipynb | ThinkBricks/APTOS2019BlindnessDetection |
Train test split | X_train, X_val = train_test_split(train, test_size=0.25, random_state=0) | _____no_output_____ | MIT | Model backlog/ResNet50/23 - ResNet50 - Data augmentation fill constant.ipynb | ThinkBricks/APTOS2019BlindnessDetection |
Data generator | train_datagen=ImageDataGenerator(rescale=1./255,
rotation_range=360,
brightness_range=[0.5, 1.5],
zoom_range=[1, 1.2],
zca_whitening=True,
horizontal_flip... | Found 2746 validated image filenames belonging to 5 classes.
Found 916 validated image filenames belonging to 5 classes.
Found 1928 validated image filenames.
| MIT | Model backlog/ResNet50/23 - ResNet50 - Data augmentation fill constant.ipynb | ThinkBricks/APTOS2019BlindnessDetection |
Model | def create_model(input_shape, n_out):
input_tensor = Input(shape=input_shape)
base_model = applications.ResNet50(weights=None,
include_top=False,
input_tensor=input_tensor)
base_model.load_weights('../input/resnet50/resnet50_weig... | __________________________________________________________________________________________________
Layer (type) Output Shape Param # Connected to
==================================================================================================
input_1 (InputLayer) ... | MIT | Model backlog/ResNet50/23 - ResNet50 - Data augmentation fill constant.ipynb | ThinkBricks/APTOS2019BlindnessDetection |
Train top layers | STEP_SIZE_TRAIN = train_generator.n//train_generator.batch_size
STEP_SIZE_VALID = valid_generator.n//valid_generator.batch_size
history_warmup = model.fit_generator(generator=train_generator,
steps_per_epoch=STEP_SIZE_TRAIN,
validation_data=vali... | Epoch 1/2
343/343 [==============================] - 564s 2s/step - loss: 1.3429 - acc: 0.6112 - kappa: 0.7074 - val_loss: 1.8074 - val_acc: 0.4890 - val_kappa: 0.2442
Epoch 2/2
343/343 [==============================] - 532s 2s/step - loss: 0.8423 - acc: 0.7008 - kappa: 0.8523 - val_loss: 2.3498 - val_acc: 0.4890 - va... | MIT | Model backlog/ResNet50/23 - ResNet50 - Data augmentation fill constant.ipynb | ThinkBricks/APTOS2019BlindnessDetection |
Fine-tune the complete model | for layer in model.layers:
layer.trainable = True
es = EarlyStopping(monitor='val_loss', mode='min', patience=ES_PATIENCE, restore_best_weights=True, verbose=1)
rlrop = ReduceLROnPlateau(monitor='val_loss', mode='min', patience=RLROP_PATIENCE, factor=DECAY_DROP, min_lr=1e-6, verbose=1)
callback_list = [es, rlrop]... | Epoch 1/30
343/343 [==============================] - 567s 2s/step - loss: 0.7127 - acc: 0.7340 - kappa: 0.8797 - val_loss: 0.9326 - val_acc: 0.6927 - val_kappa: 0.8542
Epoch 2/30
343/343 [==============================] - 549s 2s/step - loss: 0.6119 - acc: 0.7693 - kappa: 0.9201 - val_loss: 0.4930 - val_acc: 0.8095 - ... | MIT | Model backlog/ResNet50/23 - ResNet50 - Data augmentation fill constant.ipynb | ThinkBricks/APTOS2019BlindnessDetection |
Model loss graph | history = {'loss': history_warmup['loss'] + history_finetunning['loss'],
'val_loss': history_warmup['val_loss'] + history_finetunning['val_loss'],
'acc': history_warmup['acc'] + history_finetunning['acc'],
'val_acc': history_warmup['val_acc'] + history_finetunning['val_acc'],
... | _____no_output_____ | MIT | Model backlog/ResNet50/23 - ResNet50 - Data augmentation fill constant.ipynb | ThinkBricks/APTOS2019BlindnessDetection |
Model Evaluation | lastFullTrainPred = np.empty((0, N_CLASSES))
lastFullTrainLabels = np.empty((0, N_CLASSES))
lastFullValPred = np.empty((0, N_CLASSES))
lastFullValLabels = np.empty((0, N_CLASSES))
for i in range(STEP_SIZE_TRAIN+1):
im, lbl = next(train_generator)
scores = model.predict(im, batch_size=train_generator.batch_size... | _____no_output_____ | MIT | Model backlog/ResNet50/23 - ResNet50 - Data augmentation fill constant.ipynb | ThinkBricks/APTOS2019BlindnessDetection |
Threshold optimization | def find_best_fixed_threshold(preds, targs, do_plot=True):
best_thr_list = [0 for i in range(preds.shape[1])]
for index in reversed(range(1, preds.shape[1])):
score = []
thrs = np.arange(0, 1, 0.01)
for thr in thrs:
preds_thr = [index if x[index] > thr else np.argmax(x) for x... | thr=0.390 F2=0.812
| MIT | Model backlog/ResNet50/23 - ResNet50 - Data augmentation fill constant.ipynb | ThinkBricks/APTOS2019BlindnessDetection |
Confusion Matrix | fig, (ax1, ax2) = plt.subplots(1, 2, sharex='col', figsize=(24, 7))
labels = ['0 - No DR', '1 - Mild', '2 - Moderate', '3 - Severe', '4 - Proliferative DR']
train_cnf_matrix = confusion_matrix(train_labels, train_preds)
validation_cnf_matrix = confusion_matrix(validation_labels, validation_preds)
train_cnf_matrix_norm... | _____no_output_____ | MIT | Model backlog/ResNet50/23 - ResNet50 - Data augmentation fill constant.ipynb | ThinkBricks/APTOS2019BlindnessDetection |
Quadratic Weighted Kappa | print("Train Cohen Kappa score: %.3f" % cohen_kappa_score(train_preds, train_labels, weights='quadratic'))
print("Validation Cohen Kappa score: %.3f" % cohen_kappa_score(validation_preds, validation_labels, weights='quadratic'))
print("Complete set Cohen Kappa score: %.3f" % cohen_kappa_score(train_preds+validation_pre... | Train Cohen Kappa score: 0.930
Validation Cohen Kappa score: 0.906
Complete set Cohen Kappa score: 0.924
Train optimized Cohen Kappa score: 0.915
Validation optimized Cohen Kappa score: 0.896
Complete optimized set Cohen Kappa score: 0.910
| MIT | Model backlog/ResNet50/23 - ResNet50 - Data augmentation fill constant.ipynb | ThinkBricks/APTOS2019BlindnessDetection |
Apply model to test set and output predictions | test_generator.reset()
STEP_SIZE_TEST = test_generator.n//test_generator.batch_size
preds = model.predict_generator(test_generator, steps=STEP_SIZE_TEST)
predictions = [np.argmax(pred) for pred in preds]
predictions_opt = [0 for i in range(preds.shape[0])]
for idx, thr in enumerate(threshold_list):
for idx2, pred ... | _____no_output_____ | MIT | Model backlog/ResNet50/23 - ResNet50 - Data augmentation fill constant.ipynb | ThinkBricks/APTOS2019BlindnessDetection |
Predictions class distribution | fig, (ax1, ax2) = plt.subplots(1, 2, sharex='col', figsize=(24, 8.7))
sns.countplot(x="diagnosis", data=results, palette="GnBu_d", ax=ax1)
sns.countplot(x="diagnosis", data=results_opt, palette="GnBu_d", ax=ax2)
sns.despine()
plt.show()
val_kappa = cohen_kappa_score(validation_preds, validation_labels, weights='quadra... | _____no_output_____ | MIT | Model backlog/ResNet50/23 - ResNet50 - Data augmentation fill constant.ipynb | ThinkBricks/APTOS2019BlindnessDetection |
Task: Predict User Item response under uniform exposure while learning from biased training dataMany current applications use recommendations in order to modify the natural user behavior, such as to increase the number of sales or the time spent on a website. This results in a gap between the final recommendation obj... | %%javascript
IPython.OutputArea.prototype._should_scroll = function(lines) {
return false;
}
import os
import string
import tempfile
import time
import numpy as np
import matplotlib.pyplot as plt
import csv
import random
import tensorflow as tf
from tensorflow.contrib.tensorboard.plugins import projector
from tens... | _____no_output_____ | MIT | application/part_3/CausalMF-questions.ipynb | vishalbelsare/intro-to-reco |
About Supervised Prod2vec - Class to define MF of the implicit feedback matrix (1/0/unk) of Users x Products- When called it creates the TF graph for the associated NN:Step1: self.create_placeholders() => Creates the input placeholdersStep2: self.build_graph() => Creates the 3 layers: - the user embedding layer ... | class SupervisedProd2vec():
def __init__(self, userid_size, productid_size, embedding_size, l2_pen, learning_rate):
self.userid_size = userid_size
self.productid_size = productid_size
self.embedding_size = embedding_size
self.l2_pen = l2_pen
self.learning_rate = learning_rat... | _____no_output_____ | MIT | application/part_3/CausalMF-questions.ipynb | vishalbelsare/intro-to-reco |
CausalProd2Vec2i - inherits from SupervisedProd2vec- Class to define the causal version of MF of the implicit feedback matrix (1/0/unk) of Users x Products- When called it creates the TF graph for the associated NN:**Step1: Changed: +regularizer placeholder** self.create_placeholders() => Creates the input placeholder... | class CausalProd2Vec2i(SupervisedProd2vec):
def __init__(self, userid_size, productid_size, embedding_size, l2_pen, learning_rate, cf_pen, cf='l1'):
self.userid_size = userid_size
self.productid_size = productid_size * 2 # Doubled to accommodate the treatment embeddings
self.embedding_size... | _____no_output_____ | MIT | application/part_3/CausalMF-questions.ipynb | vishalbelsare/intro-to-reco |
Create the TF Graph | # Create graph object
graph = tf.Graph()
with graph.as_default():
with tf.device('/cpu:0'):
# Load the required graph
### Number of products and users
productid_size = 1683
userid_size = 944
model = CausalProd2Vec2i(userid_size, productid_size+1, FLAGS.embedding_size, FLAG... | _____no_output_____ | MIT | application/part_3/CausalMF-questions.ipynb | vishalbelsare/intro-to-reco |
Launch the Session: Train the model | # Launch the Session
with tf.Session(graph=graph, config=tf.ConfigProto(allow_soft_placement=True, log_device_placement=False)) as sess:
# initialise all the TF variables
init_op = tf.global_variables_initializer()
sess.run(init_op)
# Setup tensorboard: tensorboard --logdir=/tmp/tensorboard
time_t... | _____no_output_____ | MIT | application/part_3/CausalMF-questions.ipynb | vishalbelsare/intro-to-reco |
 Basketball Shooting Practice[Watch on YouTube](https://www.youtube.com/watch?v=Tm2ruZQLcqE&list=PL-j7ku2URmjZYtWzMCS4AqFS5SXPXRHwf)When Nick shoots a basketball, he either sinks the shot or mis... | import pandas as pd
shots = 28
final_score = 0
shots_dataframe = pd.DataFrame(columns=['Sunk', 'Missed', 'Points'])
for sunk in range(0,shots+1):
missed = shots - sunk
points = sunk * 5 - missed * 2
shots_dataframe = shots_dataframe.append({'Sunk':sunk, 'Missed':missed, 'Points':points}, ignore_index=True)... | _____no_output_____ | CC-BY-4.0 | notebooks/basketball-shooting-practice.ipynb | callysto/interesting-problems |
Ray RLlib - Introduction to Reinforcement Learning© 2019-2021, Anyscale. All Rights Reserved_Reinforcement Learning_ is the category of machine learning that focuses on training one or more _agents_ to achieve maximal _rewards_ while operating in an environment. Th... | import gym
import numpy as np
import pandas as pd
import json | _____no_output_____ | Apache-2.0 | ray-rllib/01-Introduction-to-Reinforcement-Learning.ipynb | alexy/ray-qiskit-tutorial |
The code below illustrates how to create and manipulate MDPs in Python. An MDP can be created by calling `gym.make`. Gym environments are identified by names like `CartPole-v1`. A **catalog of built-in environments** can be found at https://gym.openai.com/envs. | env = gym.make("CartPole-v1")
print("Created env:", env) | _____no_output_____ | Apache-2.0 | ray-rllib/01-Introduction-to-Reinforcement-Learning.ipynb | alexy/ray-qiskit-tutorial |
Reset the state of the MDP by calling `env.reset()`. This call returns the initial state of the MDP. | state = env.reset()
print("The starting state is:", state) | _____no_output_____ | Apache-2.0 | ray-rllib/01-Introduction-to-Reinforcement-Learning.ipynb | alexy/ray-qiskit-tutorial |
Recall that the state is the position of the cart, its velocity, the angle of the pole, and the angular velocity of the pole. The `env.step` method takes an action. In the case of the `CartPole` environment, the appropriate actions are 0 or 1, for pushing the cart to the left or right, respectively. `env.step()` return... | action = 0
state, reward, done, info = env.step(action)
print(state, reward, done, info) | _____no_output_____ | Apache-2.0 | ray-rllib/01-Introduction-to-Reinforcement-Learning.ipynb | alexy/ray-qiskit-tutorial |
A **rollout** is a simulation of a policy in an environment. It is used both during training and when running simulations with a trained policy. The code below performs a rollout in a given environment. It takes **random actions** until the simulation has finished and returns the cumulative reward. | def random_rollout(env):
state = env.reset()
done = False
cumulative_reward = 0
# Keep looping as long as the simulation has not finished.
while not done:
# Choose a random action (either 0 or 1).
action = np.random.choice([0, 1])
# Take the action in the envir... | _____no_output_____ | Apache-2.0 | ray-rllib/01-Introduction-to-Reinforcement-Learning.ipynb | alexy/ray-qiskit-tutorial |
Try rerunning the following cell a few times. How much do the answers change? Note that the maximum possible reward for `CartPole-v1` is 500. You'll probably get numbers well under 500. | reward = random_rollout(env)
print(reward)
reward = random_rollout(env)
print(reward) | _____no_output_____ | Apache-2.0 | ray-rllib/01-Introduction-to-Reinforcement-Learning.ipynb | alexy/ray-qiskit-tutorial |
Exercise 1Choosing actions at random in `random_rollout` is not a very effective policy, as the previous results showed. Finish implementing the `rollout_policy` function below, which takes an environment *and* a policy. Recall that the *policy* is a function that takes in a *state* and returns an *action*. The main d... | def rollout_policy(env, policy):
state = env.reset()
done = False
cumulative_reward = 0
# EXERCISE: Fill out this function by copying the appropriate part of 'random_rollout'
# and modifying it to choose the action using the policy.
raise NotImplementedError
# Return the cumulative re... | _____no_output_____ | Apache-2.0 | ray-rllib/01-Introduction-to-Reinforcement-Learning.ipynb | alexy/ray-qiskit-tutorial |
We'll return to `CartPole` in lesson [01: Application Cart Pole](explore-rllib/01-Application-Cart-Pole.ipynb) in the `explore-rllib` section. RLlib Reinforcement Learning Example: Cart Pole with Proximal Policy OptimizationThis section demonstrates how to use the _proximal policy optimization_ (PPO) algorithm impleme... | import ray
from ray.rllib.agents.ppo import PPOTrainer, DEFAULT_CONFIG
from ray.tune.logger import pretty_print | _____no_output_____ | Apache-2.0 | ray-rllib/01-Introduction-to-Reinforcement-Learning.ipynb | alexy/ray-qiskit-tutorial |
Initialize Ray. If you are running these tutorials on your laptop, then a single-node Ray cluster will be started by the next cell. If you are running in the Anyscale platform, it will connect to the running Ray cluster. | info = ray.init(ignore_reinit_error=True, log_to_driver=False)
print(info) | _____no_output_____ | Apache-2.0 | ray-rllib/01-Introduction-to-Reinforcement-Learning.ipynb | alexy/ray-qiskit-tutorial |
> **Tip:** Having trouble starting Ray? See the [Troubleshooting](../reference/Troubleshooting-Tips-Tricks.ipynb) tips. The next cell prints the URL for the Ray Dashboard. **This is only correct if you are running this tutorial on a laptop.** Click the link to open the dashboard.If you are running on the Anyscale platf... | print("Dashboard URL: http://{}".format(info["webui_url"])) | _____no_output_____ | Apache-2.0 | ray-rllib/01-Introduction-to-Reinforcement-Learning.ipynb | alexy/ray-qiskit-tutorial |
Instantiate a PPOTrainer object. We pass in a config object that specifies how the network and training procedure should be configured. Some of the parameters are the following.- `num_workers` is the number of actors that the agent will create. This determines the degree of parallelism that will be used. In a cluster, ... | config = DEFAULT_CONFIG.copy()
config['num_workers'] = 1
config['num_sgd_iter'] = 30
config['sgd_minibatch_size'] = 128
config['model']['fcnet_hiddens'] = [100, 100]
config['num_cpus_per_worker'] = 0
agent = PPOTrainer(config, 'CartPole-v1') | _____no_output_____ | Apache-2.0 | ray-rllib/01-Introduction-to-Reinforcement-Learning.ipynb | alexy/ray-qiskit-tutorial |
Now let's train the policy on the `CartPole-v1` environment for `N` steps. The JSON object returned by each call to `agent.train()` contains a lot of information we'll inspect below. For now, we'll extract information we'll graph, such as `episode_reward_mean`. The _mean_ values are more useful for determining successf... | N = 10
results = []
episode_data = []
episode_json = []
for n in range(N):
result = agent.train()
results.append(result)
episode = {'n': n,
'episode_reward_min': result['episode_reward_min'],
'episode_reward_mean': result['episode_reward_mean'],
'episo... | _____no_output_____ | Apache-2.0 | ray-rllib/01-Introduction-to-Reinforcement-Learning.ipynb | alexy/ray-qiskit-tutorial |
Now let's convert the episode data to a Pandas `DataFrame` for easy manipulation. The results indicate how much reward the policy is receiving (`episode_reward_*`) and how many time steps of the environment the policy ran (`episode_len_mean`). The maximum possible reward for this problem is `500`. The reward mean and t... | df = pd.DataFrame(data=episode_data)
df
df.columns.tolist() | _____no_output_____ | Apache-2.0 | ray-rllib/01-Introduction-to-Reinforcement-Learning.ipynb | alexy/ray-qiskit-tutorial |
Let's plot the data. Since the length and reward means are equal, we'll only plot one line: | df.plot(x="n", y=["episode_reward_mean", "episode_reward_min", "episode_reward_max"], secondary_y=True) | _____no_output_____ | Apache-2.0 | ray-rllib/01-Introduction-to-Reinforcement-Learning.ipynb | alexy/ray-qiskit-tutorial |
The model is quickly able to hit the maximum value of 500, but the mean is what's most valuable. After 10 steps, we're more than half way there. FYI, here are two views of the whole value for one result. First, a "pretty print" output.> **Tip:** The output will be long. When this happens for a cell, right click and sel... | print(pretty_print(results[-1])) | _____no_output_____ | Apache-2.0 | ray-rllib/01-Introduction-to-Reinforcement-Learning.ipynb | alexy/ray-qiskit-tutorial |
We'll learn about more of these values as continue the tutorial.The whole, long JSON blob, which includes the historical stats about episode rewards and lengths: | results[-1] | _____no_output_____ | Apache-2.0 | ray-rllib/01-Introduction-to-Reinforcement-Learning.ipynb | alexy/ray-qiskit-tutorial |
Let's plot the `episode_reward` values: | episode_rewards = results[-1]['hist_stats']['episode_reward']
df_episode_rewards = pd.DataFrame(data={'episode':range(len(episode_rewards)), 'reward':episode_rewards})
df_episode_rewards.plot(x="episode", y="reward") | _____no_output_____ | Apache-2.0 | ray-rllib/01-Introduction-to-Reinforcement-Learning.ipynb | alexy/ray-qiskit-tutorial |
For a well-trained model, most runs do very well while occasional runs do poorly. Try plotting other results episodes by changing the array index in `results[-1]` to another number between `0` and `9`. (The length of `results` is `10`.) Exercise 2The current network and training configuration are too large and heavy-d... | # Make edits here:
config = DEFAULT_CONFIG.copy()
config['num_workers'] = 3
config['num_sgd_iter'] = 30
config['sgd_minibatch_size'] = 128
config['model']['fcnet_hiddens'] = [100, 100]
config['num_cpus_per_worker'] = 0
agent = PPOTrainer(config, 'CartPole-v1') | _____no_output_____ | Apache-2.0 | ray-rllib/01-Introduction-to-Reinforcement-Learning.ipynb | alexy/ray-qiskit-tutorial |
Train the agent and try to get a reward of 500. If it's training too slowly you may need to modify the config above to use fewer hidden units, a larger `sgd_minibatch_size`, a smaller `num_sgd_iter`, or a larger `num_workers`.This should take around `N` = 20 or 30 training iterations. | N = 5
results = []
episode_data = []
episode_json = []
for n in range(N):
result = agent.train()
results.append(result)
episode = {'n': n,
'episode_reward_mean': result['episode_reward_mean'],
'episode_reward_max': result['episode_reward_max'],
'episode... | _____no_output_____ | Apache-2.0 | ray-rllib/01-Introduction-to-Reinforcement-Learning.ipynb | alexy/ray-qiskit-tutorial |
Using CheckpointsYou checkpoint the current state of a trainer to save what it has learned. Checkpoints are used for subsequent _rollouts_ and also to continue training later from a known-good state. Calling `agent.save()` creates the checkpoint and returns the path to the checkpoint file, which can be used later to ... | checkpoint_path = agent.save()
print(checkpoint_path) | _____no_output_____ | Apache-2.0 | ray-rllib/01-Introduction-to-Reinforcement-Learning.ipynb | alexy/ray-qiskit-tutorial |
Now load the checkpoint in a new trainer: | trained_config = config.copy()
test_agent = PPOTrainer(trained_config, "CartPole-v1")
test_agent.restore(checkpoint_path) | _____no_output_____ | Apache-2.0 | ray-rllib/01-Introduction-to-Reinforcement-Learning.ipynb | alexy/ray-qiskit-tutorial |
Use the previously-trained policy to act in an environment. The key line is the call to `test_agent.compute_action(state)` which uses the trained policy to choose an action. This is an example of _rollout_, which we'll study in a subsequent lesson.Verify that the cumulative reward received roughly matches up with the r... | env = gym.make("CartPole-v1")
state = env.reset()
done = False
cumulative_reward = 0
while not done:
action = test_agent.compute_action(state) # key line; get the next action
state, reward, done, _ = env.step(action)
cumulative_reward += reward
print(cumulative_reward)
ray.shutdown() | _____no_output_____ | Apache-2.0 | ray-rllib/01-Introduction-to-Reinforcement-Learning.ipynb | alexy/ray-qiskit-tutorial |
Introduction- メトリックをちゃんと定義する- ref: > exploring-molecular-properties-data.ipynb Import everything I nead :) | import numpy as np
import matplotlib.pyplot
import pandas as pd
from sklearn.metrics import mean_absolute_error | _____no_output_____ | MIT | src/17_Metric.ipynb | fkubota/kaggle-Predicting-Molecular-Properties |
Metric - このコンペでは、以下のスコアを用いる- type ごとの平均$$score = \frac{1}{T} \sum_{t=1}^{T} \log \left ( \frac{1}{n_t} \sum_{i=1}^{n_i} |{y_i - \hat{y_i}|} \right)$$ | def metric(df, preds):
df["prediction"] = preds
maes = []
for t in df.type.unique():
y_true = df[df.type==t].scalar_coupling_constant.values
y_pred = df[df.type==t].prediction.values
mae = np.log(mean_absolute_error(y_true, y_pred))
maes.append(mae)
return np.mean(maes) | _____no_output_____ | MIT | src/17_Metric.ipynb | fkubota/kaggle-Predicting-Molecular-Properties |
T81-558: Applications of Deep Neural Networks**Module 5: Regularization and Dropout*** Instructor: [Jeff Heaton](https://sites.wustl.edu/jeffheaton/), McKelvey School of Engineering, [Washington University in St. Louis](https://engineering.wustl.edu/Programs/Pages/default.aspx)* For more information visit the [class ... | try:
%tensorflow_version 2.x
COLAB = True
print("Note: using Google CoLab")
except:
print("Note: not using Google CoLab")
COLAB = False | Note: not using Google CoLab
| Apache-2.0 | t81_558_class_05_2_kfold.ipynb | machevres6/t81_558_deep_learning |
Part 5.2: Using K-Fold Cross-validation with KerasCross-validation can be used for a variety of purposes in predictive modeling. These include:* Generating out-of-sample predictions from a neural network* Estimate a good number of epochs to train a neural network for (early stopping)* Evaluate the effectiveness of ce... | import pandas as pd
from scipy.stats import zscore
from sklearn.model_selection import train_test_split
# Read the data set
df = pd.read_csv(
"https://data.heatonresearch.com/data/t81-558/jh-simple-dataset.csv",
na_values=['NA','?'])
# Generate dummies for job
df = pd.concat([df,pd.get_dummies(df['job'],prefi... | _____no_output_____ | Apache-2.0 | t81_558_class_05_2_kfold.ipynb | machevres6/t81_558_deep_learning |
Now that the feature vector is created a 5-fold cross-validation can be performed to generate out of sample predictions. We will assume 500 epochs, and not use early stopping. Later we will see how we can estimate a more optimal epoch count. | import pandas as pd
import os
import numpy as np
from sklearn import metrics
from scipy.stats import zscore
from sklearn.model_selection import KFold
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Activation
# Cross-Validate
kf = KFold(5, shuffle=True, random_state=42) # Use f... | Fold #1
Fold score (RMSE): 0.6245484893737087
Fold #2
Fold score (RMSE): 0.5802295511082306
Fold #3
Fold score (RMSE): 0.6300965769274195
Fold #4
Fold score (RMSE): 0.4550931884841248
Fold #5
Fold score (RMSE): 1.0517027192572377
Final, out of sample score (RMSE): 0.6981314007708873
| Apache-2.0 | t81_558_class_05_2_kfold.ipynb | machevres6/t81_558_deep_learning |
As you can see, the above code also reports the average number of epochs needed. A common technique is to then train on the entire dataset for the average number of epochs needed. Classification with Stratified K-Fold Cross-ValidationThe following code trains and fits the jh-simple-dataset dataset with cross-validati... | import pandas as pd
from scipy.stats import zscore
# Read the data set
df = pd.read_csv(
"https://data.heatonresearch.com/data/t81-558/jh-simple-dataset.csv",
na_values=['NA','?'])
# Generate dummies for job
df = pd.concat([df,pd.get_dummies(df['job'],prefix="job")],axis=1)
df.drop('job', axis=1, inplace=True... | _____no_output_____ | Apache-2.0 | t81_558_class_05_2_kfold.ipynb | machevres6/t81_558_deep_learning |
We will assume 500 epochs, and not use early stopping. Later we will see how we can estimate a more optimal epoch count. | import pandas as pd
import os
import numpy as np
from sklearn import metrics
from sklearn.model_selection import StratifiedKFold
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Activation
# np.argmax(pred,axis=1)
# Cross-validate
# Use for StratifiedKFold classification
kf = S... | Fold #1
Fold score (accuracy): 0.6766169154228856
Fold #2
Fold score (accuracy): 0.6691542288557214
Fold #3
Fold score (accuracy): 0.6907730673316709
Fold #4
Fold score (accuracy): 0.6733668341708543
Fold #5
Fold score (accuracy): 0.654911838790932
Final score (accuracy): 0.673
| Apache-2.0 | t81_558_class_05_2_kfold.ipynb | machevres6/t81_558_deep_learning |
Training with both a Cross-Validation and a Holdout SetIf you have a considerable amount of data, it is always valuable to set aside a holdout set before you cross-validate. This hold out set will be the final evaluation before you make use of your model for its real-world use. Figure 5.HOLDOUT shows this division.**... | import pandas as pd
from scipy.stats import zscore
from sklearn.model_selection import train_test_split
# Read the data set
df = pd.read_csv(
"https://data.heatonresearch.com/data/t81-558/jh-simple-dataset.csv",
na_values=['NA','?'])
# Generate dummies for job
df = pd.concat([df,pd.get_dummies(df['job'],prefi... | Fold #1
Fold score (RMSE): 24.299626704604506
Fold #2
Fold score (RMSE): 0.6609159891625663
Fold #3
Fold score (RMSE): 0.4997884237817687
Fold #4
Fold score (RMSE): 1.1084218284103058
Fold #5
Fold score (RMSE): 0.614899992174395
Cross-validated score (RMSE): 10.888206072135832
Holdout score (RMSE): 0.6283593821273058
| Apache-2.0 | t81_558_class_05_2_kfold.ipynb | machevres6/t81_558_deep_learning |
HLCA Figure 2 Here we will generate the figures from the HLCA pre-print, figure 2. Figure 2d was generated separately in R, using code from integration benchmarking framework 'scIB'. import modules, set paths and parameters: | import scanpy as sc
import pandas as pd
import numpy as np
import sys
import os
from collections import Counter
sys.path.append("../../scripts/")
import reference_based_harmonizing
import celltype_composition_plotting
import plotting
import sankey
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib.... | _____no_output_____ | MIT | notebooks/1_building_and_annotating_the_atlas_core/11_figure_2_data_overview.ipynb | LungCellAtlas/HLCA_reproducibility |
for pretty code formatting (not needed to run notebook): | %load_ext lab_black | _____no_output_____ | MIT | notebooks/1_building_and_annotating_the_atlas_core/11_figure_2_data_overview.ipynb | LungCellAtlas/HLCA_reproducibility |
paths: | path_HLCA = "../../data/HLCA_core_h5ads/HLCA_v1.h5ad"
path_celltype_reference = "../../supporting_files/metadata_harmonization/HLCA_cell_type_reference_mapping_20211103.csv"
dir_figures = "../../figures" | _____no_output_____ | MIT | notebooks/1_building_and_annotating_the_atlas_core/11_figure_2_data_overview.ipynb | LungCellAtlas/HLCA_reproducibility |
Generate figures: initiate empty dictionary in which to store paper figures. | FIGURES = dict() | _____no_output_____ | MIT | notebooks/1_building_and_annotating_the_atlas_core/11_figure_2_data_overview.ipynb | LungCellAtlas/HLCA_reproducibility |
for automatic script updating and pretty coding (not necessary for code to run!) | adata = sc.read(path_HLCA) | _____no_output_____ | MIT | notebooks/1_building_and_annotating_the_atlas_core/11_figure_2_data_overview.ipynb | LungCellAtlas/HLCA_reproducibility |
Overview of stats (number of studies, cells, annotations etc.): Number of studies, datasets, subjects, samples, cells: | print("Number of studies:", len(set(adata.obs.study)))
print("Number of datasets:", len(set(adata.obs.dataset)))
print("Number of subjects:", len(set(adata.obs.subject_ID)))
print("Number of samples:", len(set(adata.obs["sample"])))
print("Number of cells:", adata.obs.shape[0]) | Number of studies: 11
Number of datasets: 14
Number of subjects: 107
Number of samples: 166
Number of cells: 584884
| MIT | notebooks/1_building_and_annotating_the_atlas_core/11_figure_2_data_overview.ipynb | LungCellAtlas/HLCA_reproducibility |
Proportions of cell compartments in the HLCA: | original_ann_lev_1_percs = np.round(
adata.obs.original_ann_level_1.value_counts() / adata.n_obs * 100, 1
)
print("Original annotation proportions (level 1):")
print(original_ann_lev_1_percs) | Original annotation proportions (level 1):
Epithelial 48.1
Immune 38.7
Endothelial 8.5
Stroma 4.3
Proliferating cells 0.3
Name: original_ann_level_1, dtype: float64
| MIT | notebooks/1_building_and_annotating_the_atlas_core/11_figure_2_data_overview.ipynb | LungCellAtlas/HLCA_reproducibility |
Perc. of cells annotated per level: | for level in range(1, 6):
n_unannotated = np.sum(
[
isnone or isnull
for isnone, isnull in zip(
adata.obs[f"original_ann_level_{level}_clean"].values == "None",
pd.isnull(adata.obs[f"original_ann_level_{level}_clean"].values),
)
]
... | Perc. originally annotated at level 1: 100.0
Perc. originally annotated at level 2: 98.8
Perc. originally annotated at level 3: 93.6
Perc. originally annotated at level 4: 65.7
Perc. originally annotated at level 5: 6.8
| MIT | notebooks/1_building_and_annotating_the_atlas_core/11_figure_2_data_overview.ipynb | LungCellAtlas/HLCA_reproducibility |
Distribution of demographics: | print(f"Min. and max. age: {adata.obs.age.min()}, {adata.obs.age.max()}")
adata.obs.sex.value_counts() / adata.n_obs * 100
adata.obs.ethnicity.value_counts() / adata.n_obs * 100
print(f"Min. and max. BMI: {adata.obs.BMI.min()}, {adata.obs.BMI.max()}")
adata.obs.smoking_status.value_counts() / adata.n_obs * 100 | _____no_output_____ | MIT | notebooks/1_building_and_annotating_the_atlas_core/11_figure_2_data_overview.ipynb | LungCellAtlas/HLCA_reproducibility |
figures: Overview of subjects, samples, and cells per study (not in the paper): | plotting.plot_dataset_statistics(adata, fontsize=8, figheightscale=3.5) | _____no_output_____ | MIT | notebooks/1_building_and_annotating_the_atlas_core/11_figure_2_data_overview.ipynb | LungCellAtlas/HLCA_reproducibility |
2a Subject/sample distributions Re-map ethnicities: | ethnicity_remapper = {
"asian": "asian",
"black": "black",
"latino": "latino",
"mixed": "mixed",
"nan": "nan",
"pacific islander": "other",
"white": "white",
}
adata.obs.ethnicity = adata.obs.ethnicity.map(ethnicity_remapper) | _____no_output_____ | MIT | notebooks/1_building_and_annotating_the_atlas_core/11_figure_2_data_overview.ipynb | LungCellAtlas/HLCA_reproducibility |
Plot subject demographic and sample anatomical location distributions: | FIGURES["2a_subject_and_sample_stats"] = plotting.plot_subject_and_sample_stats_incl_na(
adata, return_fig=True
) | age: 99% annotated
BMI: 70% annotated
sex: 100% annotated)
ethnicity 93% annotated
smoking_status: 92% annotated
| MIT | notebooks/1_building_and_annotating_the_atlas_core/11_figure_2_data_overview.ipynb | LungCellAtlas/HLCA_reproducibility |
2b Cell type composition sankey plot, level 1-3: First, generate a color mapping. We want to map cell types from the same compartment in the same shade (e.g. epithilial orange/red, endothelial purple), at all levels. We'll need to incorporate our hierarchical cell type reference for that, and then calculate the colors... | harmonizing_df = reference_based_harmonizing.load_harmonizing_table(
path_celltype_reference
)
consensus_df = reference_based_harmonizing.create_consensus_table(harmonizing_df)
max_level = 5
color_prop_df = celltype_composition_plotting.calculate_hierarchical_coloring_df(
adata,
consensus_df,
max_level,... | /home/icb/lisa.sikkema/miniconda3/envs/scRNAseq_analysis/lib/python3.7/site-packages/pandas/core/indexing.py:671: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame
See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#return... | MIT | notebooks/1_building_and_annotating_the_atlas_core/11_figure_2_data_overview.ipynb | LungCellAtlas/HLCA_reproducibility |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.