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 |
|---|---|---|---|---|---|
Let's split the full training set into a validation set and a (smaller) training set. We also scale the pixel intensities down to the 0-1 range and convert them to floats, by dividing by 255. | X_valid, X_train = X_train_full[:5000] / 255., X_train_full[5000:] / 255.
y_valid, y_train = y_train_full[:5000], y_train_full[5000:]
X_test = X_test / 255. | _____no_output_____ | Apache-2.0 | 10_neural_nets_with_keras.ipynb | agniji/handson-ml2 |
You can plot an image using Matplotlib's `imshow()` function, with a `'binary'` color map: | plt.imshow(X_train[0], cmap="binary")
plt.axis('off')
plt.show() | _____no_output_____ | Apache-2.0 | 10_neural_nets_with_keras.ipynb | agniji/handson-ml2 |
The labels are the class IDs (represented as uint8), from 0 to 9: | y_train | _____no_output_____ | Apache-2.0 | 10_neural_nets_with_keras.ipynb | agniji/handson-ml2 |
Here are the corresponding class names: | class_names = ["T-shirt/top", "Trouser", "Pullover", "Dress", "Coat",
"Sandal", "Shirt", "Sneaker", "Bag", "Ankle boot"] | _____no_output_____ | Apache-2.0 | 10_neural_nets_with_keras.ipynb | agniji/handson-ml2 |
So the first image in the training set is a coat: | class_names[y_train[0]] | _____no_output_____ | Apache-2.0 | 10_neural_nets_with_keras.ipynb | agniji/handson-ml2 |
The validation set contains 5,000 images, and the test set contains 10,000 images: | X_valid.shape
X_test.shape | _____no_output_____ | Apache-2.0 | 10_neural_nets_with_keras.ipynb | agniji/handson-ml2 |
Let's take a look at a sample of the images in the dataset: | n_rows = 4
n_cols = 10
plt.figure(figsize=(n_cols * 1.2, n_rows * 1.2))
for row in range(n_rows):
for col in range(n_cols):
index = n_cols * row + col
plt.subplot(n_rows, n_cols, index + 1)
plt.imshow(X_train[index], cmap="binary", interpolation="nearest")
plt.axis('off')
plt... | _____no_output_____ | Apache-2.0 | 10_neural_nets_with_keras.ipynb | agniji/handson-ml2 |
This is equivalent to: ```pythonmodel.compile(loss=keras.losses.sparse_categorical_crossentropy, optimizer=keras.optimizers.SGD(), metrics=[keras.metrics.sparse_categorical_accuracy])``` | history = model.fit(X_train, y_train, epochs=30,
validation_data=(X_valid, y_valid))
history.params
print(history.epoch)
history.history.keys()
import pandas as pd
pd.DataFrame(history.history).plot(figsize=(8, 5))
plt.grid(True)
plt.gca().set_ylim(0, 1)
save_fig("keras_learning_curves_plot")
plt.s... | _____no_output_____ | Apache-2.0 | 10_neural_nets_with_keras.ipynb | agniji/handson-ml2 |
Regression MLP Let's load, split and scale the California housing dataset (the original one, not the modified one as in chapter 2): | from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
housing = fetch_california_housing()
X_train_full, X_test, y_train_full, y_test = train_test_split(housing.data, housing.target, random_state=42)
X_train, X_valid... | _____no_output_____ | Apache-2.0 | 10_neural_nets_with_keras.ipynb | agniji/handson-ml2 |
Functional API Not all neural network models are simply sequential. Some may have complex topologies. Some may have multiple inputs and/or multiple outputs. For example, a Wide & Deep neural network (see [paper](https://ai.google/research/pubs/pub45413)) connects all or part of the inputs directly to the output layer. | np.random.seed(42)
tf.random.set_seed(42)
input_ = keras.layers.Input(shape=X_train.shape[1:])
hidden1 = keras.layers.Dense(30, activation="relu")(input_)
hidden2 = keras.layers.Dense(30, activation="relu")(hidden1)
concat = keras.layers.concatenate([input_, hidden2])
output = keras.layers.Dense(1)(concat)
model = kera... | Train on 11610 samples, validate on 3870 samples
Epoch 1/20
11610/11610 [==============================] - 0s 43us/sample - loss: 1.2544 - val_loss: 2.9415
Epoch 2/20
11610/11610 [==============================] - 0s 32us/sample - loss: 0.6531 - val_loss: 0.8754
Epoch 3/20
11610/11610 [==============================] -... | Apache-2.0 | 10_neural_nets_with_keras.ipynb | agniji/handson-ml2 |
What if you want to send different subsets of input features through the wide or deep paths? We will send 5 features (features 0 to 4), and 6 through the deep path (features 2 to 7). Note that 3 features will go through both (features 2, 3 and 4). | np.random.seed(42)
tf.random.set_seed(42)
input_A = keras.layers.Input(shape=[5], name="wide_input")
input_B = keras.layers.Input(shape=[6], name="deep_input")
hidden1 = keras.layers.Dense(30, activation="relu")(input_B)
hidden2 = keras.layers.Dense(30, activation="relu")(hidden1)
concat = keras.layers.concatenate([inp... | Train on 11610 samples, validate on 3870 samples
Epoch 1/20
11610/11610 [==============================] - 1s 45us/sample - loss: 1.8070 - val_loss: 0.8422
Epoch 2/20
11610/11610 [==============================] - 0s 34us/sample - loss: 0.6752 - val_loss: 0.6426
Epoch 3/20
11610/11610 [==============================] -... | Apache-2.0 | 10_neural_nets_with_keras.ipynb | agniji/handson-ml2 |
Adding an auxiliary output for regularization: | np.random.seed(42)
tf.random.set_seed(42)
input_A = keras.layers.Input(shape=[5], name="wide_input")
input_B = keras.layers.Input(shape=[6], name="deep_input")
hidden1 = keras.layers.Dense(30, activation="relu")(input_B)
hidden2 = keras.layers.Dense(30, activation="relu")(hidden1)
concat = keras.layers.concatenate([inp... | 5160/5160 [==============================] - 0s 26us/sample - loss: 0.4661 - main_output_loss: 0.4167 - aux_output_loss: 0.9138
| Apache-2.0 | 10_neural_nets_with_keras.ipynb | agniji/handson-ml2 |
The subclassing API | class WideAndDeepModel(keras.models.Model):
def __init__(self, units=30, activation="relu", **kwargs):
super().__init__(**kwargs)
self.hidden1 = keras.layers.Dense(units, activation=activation)
self.hidden2 = keras.layers.Dense(units, activation=activation)
self.main_output = keras.l... | _____no_output_____ | Apache-2.0 | 10_neural_nets_with_keras.ipynb | agniji/handson-ml2 |
Saving and Restoring | np.random.seed(42)
tf.random.set_seed(42)
model = keras.models.Sequential([
keras.layers.Dense(30, activation="relu", input_shape=[8]),
keras.layers.Dense(30, activation="relu"),
keras.layers.Dense(1)
])
model.compile(loss="mse", optimizer=keras.optimizers.SGD(lr=1e-3))
history = model.fit(X_train, y_tr... | _____no_output_____ | Apache-2.0 | 10_neural_nets_with_keras.ipynb | agniji/handson-ml2 |
Using Callbacks during Training | keras.backend.clear_session()
np.random.seed(42)
tf.random.set_seed(42)
model = keras.models.Sequential([
keras.layers.Dense(30, activation="relu", input_shape=[8]),
keras.layers.Dense(30, activation="relu"),
keras.layers.Dense(1)
])
model.compile(loss="mse", optimizer=keras.optimizers.SGD(lr=1e-3))
che... | Train on 11610 samples, validate on 3870 samples
10144/11610 [=========================>....] - ETA: 0s - loss: 0.3427
val/train: 0.98
11610/11610 [==============================] - 0s 32us/sample - loss: 0.3467 - val_loss: 0.3384
| Apache-2.0 | 10_neural_nets_with_keras.ipynb | agniji/handson-ml2 |
TensorBoard | root_logdir = os.path.join(os.curdir, "my_logs")
def get_run_logdir():
import time
run_id = time.strftime("run_%Y_%m_%d-%H_%M_%S")
return os.path.join(root_logdir, run_id)
run_logdir = get_run_logdir()
run_logdir
keras.backend.clear_session()
np.random.seed(42)
tf.random.set_seed(42)
model = keras.models.S... | Train on 11610 samples, validate on 3870 samples
Epoch 1/30
11610/11610 [==============================] - 1s 45us/sample - loss: 1.8807 - val_loss: 0.7701
Epoch 2/30
11610/11610 [==============================] - 0s 33us/sample - loss: 0.6570 - val_loss: 0.7268
Epoch 3/30
11610/11610 [==============================] -... | Apache-2.0 | 10_neural_nets_with_keras.ipynb | agniji/handson-ml2 |
To start the TensorBoard server, one option is to open a terminal, if needed activate the virtualenv where you installed TensorBoard, go to this notebook's directory, then type:```bash$ tensorboard --logdir=./my_logs --port=6006```You can then open your web browser to [localhost:6006](http://localhost:6006) and use Ten... | %load_ext tensorboard
%tensorboard --logdir=./my_logs --port=6006
run_logdir2 = get_run_logdir()
run_logdir2
keras.backend.clear_session()
np.random.seed(42)
tf.random.set_seed(42)
model = keras.models.Sequential([
keras.layers.Dense(30, activation="relu", input_shape=[8]),
keras.layers.Dense(30, activation="re... | Train on 11610 samples, validate on 3870 samples
Epoch 1/30
11610/11610 [==============================] - 1s 43us/sample - loss: 0.5259 - val_loss: 0.4834
Epoch 2/30
11610/11610 [==============================] - 0s 33us/sample - loss: 0.4069 - val_loss: 0.3912
Epoch 3/30
11610/11610 [==============================] -... | Apache-2.0 | 10_neural_nets_with_keras.ipynb | agniji/handson-ml2 |
Notice how TensorBoard now sees two runs, and you can compare the learning curves. Check out the other available logging options: | help(keras.callbacks.TensorBoard.__init__) | Help on function __init__ in module tensorflow.python.keras.callbacks:
__init__(self, log_dir='logs', histogram_freq=0, write_graph=True, write_images=False, update_freq='epoch', profile_batch=2, embeddings_freq=0, embeddings_metadata=None, **kwargs)
Initialize self. See help(type(self)) for accurate signature.
| Apache-2.0 | 10_neural_nets_with_keras.ipynb | agniji/handson-ml2 |
Hyperparameter Tuning | keras.backend.clear_session()
np.random.seed(42)
tf.random.set_seed(42)
def build_model(n_hidden=1, n_neurons=30, learning_rate=3e-3, input_shape=[8]):
model = keras.models.Sequential()
model.add(keras.layers.InputLayer(input_shape=input_shape))
for layer in range(n_hidden):
model.add(keras.layers.D... | 5160/5160==============================] - 0s 22us/sample - loss: 0.3252
| Apache-2.0 | 10_neural_nets_with_keras.ipynb | agniji/handson-ml2 |
Notebook to concatenate all partial csv files for the dataset into a single file. Only the essential columns are kept. | import pandas as pd
import os
data_dir = "data/"
selected_fields = ['seed_ref', 'seed_ref_id', 'ref', 'ref_id', 'TRUE']
dfs = []
partials_dir = os.path.join(data_dir, 'partials')
for file in os.listdir(partials_dir):
if ".tsv" in file:
#print(file)
tmp_df = pd.read_csv(os.path.join(partials_dir, fi... | _____no_output_____ | MIT | concatenate-csv-partials.ipynb | kiem-group/GT-reference-clustering |
title | (define (constant value connector)
(define (me request)
(error "Unknow request -- CONSTANT" request))
(connect connector me)
(set-value! connector value me)
me)
(define (probe name connector)
(define (print-probe value)
(newline)
(display "Probe: ")
(display name)
(display " = ")
(dis... | _____no_output_____ | MIT | cn/.ipynb_checkpoints/sicp-3-34-checkpoint.ipynb | DamonDeng/sicp_exercise |
Dateien Eine Textdatei lesen und ihren Inhalt ausgeben | # Wir öffnen die Datei lesen.txt zum Lesen ("r") und speichern ihren Inhalt in die Variable file
file = open("lesen.txt", "r")
# Wir gehen alle Zeilen nacheinander durch
# In der txt-Datei stehen für uns nicht sichtbare Zeilenumbruchszeichen, durch die jeweils das Ende einer Zeile markiert ist
for line in file:
# ... | Das ist eine Kopie von Jürg
| MIT | 04 Python Teil 2/05 Dateien.ipynb | JonnyGrafico/00_Git_Projekte |
In eine Textdatei schreiben | # Wir öffnen eine Datei zum Schreiben ("w": write)
file = open("schreiben.txt", "w")
students = ["Max", "Monika", "Erik", "Franziska", "Juerg", "Peter"]
# Wir loopen mit einer for-Schleife durch die Liste students
for student in students:
# Mit der write-Methode schreiben wir den aktuellen String student und eine... | _____no_output_____ | MIT | 04 Python Teil 2/05 Dateien.ipynb | JonnyGrafico/00_Git_Projekte |
Dateien öffnen mit withWenn wir Dateien mit einer with-Konstruktion öffnen, dann brauchen wir sie nicht mehr explizit mit der close()-Methode schließen. | with open("lesen.txt", "r") as file:
for line in file:
print(line)
with open("lesen.txt", "r") as file:
for line in file:
print(line)
| _____no_output_____ | MIT | 04 Python Teil 2/05 Dateien.ipynb | JonnyGrafico/00_Git_Projekte |
CSV-Datei lesencsv steht für comma separated values. Auch solche csv-Dateien können wir mit Python auslesen. | with open("datei.csv") as file:
for line in file:
data = line.strip().split(";")
print(data[0] + ": " + data[1]) | Muenchen: 1800000
Berlin: 3000000
Budapest: 2000000
| MIT | 04 Python Teil 2/05 Dateien.ipynb | JonnyGrafico/00_Git_Projekte |
CSV-Datei lesen (und Daten überspringen)In dieser Lektion lernst du:- Wie du eine CSV-Datei einliest, und Zeilen überspringen kannst. | with open("datei.csv") as file:
for line in file:
data = line.strip().split(";")
if (data[0]) == "Aaron":
print(data[0])
if data[2] == "BUD":
continue
print(data)
#if data[2] == "BER" or data[2] == "BUD":
# ... | 1800000 MUC
3000000 BER
2000000 BUD
| MIT | 04 Python Teil 2/05 Dateien.ipynb | JonnyGrafico/00_Git_Projekte |
Übung- Besorgt euch die datei https://data.stadt-zuerich.ch/dataset/pd-stapo-hundenamen/resource/8bf2127d-c354-4834-8590-9666cbd6e160- Ihr findet sie auch im Ordner 20151001_hundenamen.csv- Findet heraus wie oft der Hundename "Aaron" zwischen 2000 - 2012 gebraucht wurde. | n = "1975"
print(int(n) < 1990)
jahre = ["Year", "1990", "1992"]
for jahr in jahre:
if jahr == "Year":
continue
print(int(jahr))
### Euer code hier | _____no_output_____ | MIT | 04 Python Teil 2/05 Dateien.ipynb | JonnyGrafico/00_Git_Projekte |
Lambda School Data Science*Unit 2, Sprint 3, Module 3*--- Permutation & Boosting- Get **permutation importances** for model interpretation and feature selection- Use xgboost for **gradient boosting** SetupRun the code cell below. You can work locally (follow the [local setup instructions](https://lambdaschool.github.... | %%capture
import sys
# If you're on Colab:
if 'google.colab' in sys.modules:
DATA_PATH = 'https://raw.githubusercontent.com/LambdaSchool/DS-Unit-2-Applied-Modeling/master/data/'
!pip install category_encoders==2.*
!pip install eli5
# If you're working locally:
else:
DATA_PATH = '../data/' | _____no_output_____ | MIT | module3-permutation-boosting/LS_DS_233.ipynb | ilEnzio/DS-Unit-2-Applied-Modeling |
We'll go back to Tanzania Waterpumps for this lesson. | import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
# Merge train_features.csv & train_labels.csv
train = pd.merge(pd.read_csv(DATA_PATH+'waterpumps/train_features.csv'),
pd.read_csv(DATA_PATH+'waterpumps/train_labels.csv'))
# Read test_features.csv & sample_s... | _____no_output_____ | MIT | module3-permutation-boosting/LS_DS_233.ipynb | ilEnzio/DS-Unit-2-Applied-Modeling |
Get permutation importances for model interpretation and feature selection Overview Default Feature Importances are fast, but Permutation Importances may be more accurate.These links go deeper with explanations and examples:- Permutation Importances - [Kaggle / Dan Becker: Machine Learning Explainability](https://ww... | # Get feature importances
rf = pipeline.named_steps['randomforestclassifier']
importances = pd.Series(rf.feature_importances_, X_train.columns)
# Plot feature importances
%matplotlib inline
import matplotlib.pyplot as plt
n = 20
plt.figure(figsize=(10,n/2))
plt.title(f'Top {n} features')
importances.sort_values()[-n:... | _____no_output_____ | MIT | module3-permutation-boosting/LS_DS_233.ipynb | ilEnzio/DS-Unit-2-Applied-Modeling |
2. Drop-Column ImportanceThe best in theory, but too slow in practice | column = 'quantity'
# Fit without column
pipeline = make_pipeline(
ce.OrdinalEncoder(),
SimpleImputer(strategy='median'),
RandomForestClassifier(n_estimators=100, random_state=42, n_jobs=-1)
)
pipeline.fit(X_train.drop(columns=column), y_train)
score_without = pipeline.score(X_val.drop(columns=column), ... | _____no_output_____ | MIT | module3-permutation-boosting/LS_DS_233.ipynb | ilEnzio/DS-Unit-2-Applied-Modeling |
3. Permutation ImportancePermutation Importance is a good compromise between Feature Importance based on impurity reduction (which is the fastest) and Drop Column Importance (which is the "best.")[The ELI5 library documentation explains,](https://eli5.readthedocs.io/en/latest/blackbox/permutation_importance.html)> Imp... | # Ignore warnings
| _____no_output_____ | MIT | module3-permutation-boosting/LS_DS_233.ipynb | ilEnzio/DS-Unit-2-Applied-Modeling |
Import Libraries | import numpy as np
import pandas as pd | _____no_output_____ | Apache-2.0 | Credit Risk Modeling/Credit Risk Modeling - LGD and EAD Models - With Comments - 12-1.ipynb | autodidact-m/Projects |
Import Data | # Import data.
loan_data_preprocessed_backup = pd.read_csv('loan_data_2007_2014_preprocessed.csv') | _____no_output_____ | Apache-2.0 | Credit Risk Modeling/Credit Risk Modeling - LGD and EAD Models - With Comments - 12-1.ipynb | autodidact-m/Projects |
Explore Data | loan_data_preprocessed = loan_data_preprocessed_backup.copy()
loan_data_preprocessed.columns.values
# Displays all column names.
loan_data_preprocessed.head()
loan_data_preprocessed.tail()
loan_data_defaults = loan_data_preprocessed[loan_data_preprocessed['loan_status'].isin(['Charged Off','Does not meet the credit pol... | _____no_output_____ | Apache-2.0 | Credit Risk Modeling/Credit Risk Modeling - LGD and EAD Models - With Comments - 12-1.ipynb | autodidact-m/Projects |
Independent Variables | loan_data_defaults['mths_since_last_delinq'].fillna(0, inplace = True)
# We fill the missing values with zeroes.
#loan_data_defaults['mths_since_last_delinq'].fillna(loan_data_defaults['mths_since_last_delinq'].max() + 12, inplace=True)
loan_data_defaults['mths_since_last_record'].fillna(0, inplace=True)
# We fill the ... | _____no_output_____ | Apache-2.0 | Credit Risk Modeling/Credit Risk Modeling - LGD and EAD Models - With Comments - 12-1.ipynb | autodidact-m/Projects |
Dependent Variables | loan_data_defaults['recovery_rate'] = loan_data_defaults['recoveries'] / loan_data_defaults['funded_amnt']
# We calculate the dependent variable for the LGD model: recovery rate.
# It is the ratio of recoveries and funded amount.
loan_data_defaults['recovery_rate'].describe()
# Shows some descriptive statisics for the ... | _____no_output_____ | Apache-2.0 | Credit Risk Modeling/Credit Risk Modeling - LGD and EAD Models - With Comments - 12-1.ipynb | autodidact-m/Projects |
Explore Dependent Variables | import matplotlib.pyplot as plt
import seaborn as sns
sns.set()
plt.hist(loan_data_defaults['recovery_rate'], bins = 100)
# We plot a histogram of a variable with 100 bins.
plt.hist(loan_data_defaults['recovery_rate'], bins = 50)
# We plot a histogram of a variable with 50 bins.
plt.hist(loan_data_defaults['CCF'], bins... | _____no_output_____ | Apache-2.0 | Credit Risk Modeling/Credit Risk Modeling - LGD and EAD Models - With Comments - 12-1.ipynb | autodidact-m/Projects |
LGD Model Splitting Data | from sklearn.model_selection import train_test_split
# LGD model stage 1 datasets: recovery rate 0 or greater than 0.
lgd_inputs_stage_1_train, lgd_inputs_stage_1_test, lgd_targets_stage_1_train, lgd_targets_stage_1_test = train_test_split(loan_data_defaults.drop(['good_bad', 'recovery_rate','recovery_rate_0_1', 'CCF']... | _____no_output_____ | Apache-2.0 | Credit Risk Modeling/Credit Risk Modeling - LGD and EAD Models - With Comments - 12-1.ipynb | autodidact-m/Projects |
Preparing the Inputs | features_all = ['grade:A',
'grade:B',
'grade:C',
'grade:D',
'grade:E',
'grade:F',
'grade:G',
'home_ownership:MORTGAGE',
'home_ownership:NONE',
'home_ownership:OTHER',
'home_ownership:OWN',
'home_ownership:RENT',
'verification_status:Not Verified',
'verification_status:Source Verified',
'verification_status:Verified',
'... | _____no_output_____ | Apache-2.0 | Credit Risk Modeling/Credit Risk Modeling - LGD and EAD Models - With Comments - 12-1.ipynb | autodidact-m/Projects |
Estimating the Model | # P values for sklearn logistic regression.
# Class to display p-values for logistic regression in sklearn.
from sklearn import linear_model
import scipy.stats as stat
class LogisticRegression_with_p_values:
def __init__(self,*args,**kwargs):#,**kwargs):
self.model = linear_model.LogisticRegression(... | _____no_output_____ | Apache-2.0 | Credit Risk Modeling/Credit Risk Modeling - LGD and EAD Models - With Comments - 12-1.ipynb | autodidact-m/Projects |
Testing the Model | lgd_inputs_stage_1_test = lgd_inputs_stage_1_test[features_all]
# Here we keep only the variables we need for the model.
lgd_inputs_stage_1_test = lgd_inputs_stage_1_test.drop(features_reference_cat, axis = 1)
# Here we remove the dummy variable reference categories.
y_hat_test_lgd_stage_1 = reg_lgd_st_1.model.predict(... | _____no_output_____ | Apache-2.0 | Credit Risk Modeling/Credit Risk Modeling - LGD and EAD Models - With Comments - 12-1.ipynb | autodidact-m/Projects |
Estimating the Аccuracy of the Мodel | tr = 0.5
# We create a new column with an indicator,
# where every observation that has predicted probability greater than the threshold has a value of 1,
# and every observation that has predicted probability lower than the threshold has a value of 0.
df_actual_predicted_probs['y_hat_test_lgd_stage_1'] = np.where(df_a... | _____no_output_____ | Apache-2.0 | Credit Risk Modeling/Credit Risk Modeling - LGD and EAD Models - With Comments - 12-1.ipynb | autodidact-m/Projects |
Saving the Model | import pickle
pickle.dump(reg_lgd_st_1, open('lgd_model_stage_1.sav', 'wb'))
# Here we export our model to a 'SAV' file with file name 'lgd_model_stage_1.sav'. | _____no_output_____ | Apache-2.0 | Credit Risk Modeling/Credit Risk Modeling - LGD and EAD Models - With Comments - 12-1.ipynb | autodidact-m/Projects |
Stage 2 – Linear Regression | lgd_stage_2_data = loan_data_defaults[loan_data_defaults['recovery_rate_0_1'] == 1]
# Here we take only rows where the original recovery rate variable is greater than one,
# i.e. where the indicator variable we created is equal to 1.
# LGD model stage 2 datasets: how much more than 0 is the recovery rate
lgd_inputs_sta... | _____no_output_____ | Apache-2.0 | Credit Risk Modeling/Credit Risk Modeling - LGD and EAD Models - With Comments - 12-1.ipynb | autodidact-m/Projects |
Stage 2 – Linear Regression Evaluation | lgd_inputs_stage_2_test = lgd_inputs_stage_2_test[features_all]
# Here we keep only the variables we need for the model.
lgd_inputs_stage_2_test = lgd_inputs_stage_2_test.drop(features_reference_cat, axis = 1)
# Here we remove the dummy variable reference categories.
lgd_inputs_stage_2_test.columns.values
# Calculates ... | _____no_output_____ | Apache-2.0 | Credit Risk Modeling/Credit Risk Modeling - LGD and EAD Models - With Comments - 12-1.ipynb | autodidact-m/Projects |
Combining Stage 1 and Stage 2 | y_hat_test_lgd_stage_2_all = reg_lgd_st_2.predict(lgd_inputs_stage_1_test)
y_hat_test_lgd_stage_2_all
y_hat_test_lgd = y_hat_test_lgd_stage_1 * y_hat_test_lgd_stage_2_all
# Here we combine the predictions of the models from the two stages.
pd.DataFrame(y_hat_test_lgd).describe()
# Shows some descriptive statisics for t... | _____no_output_____ | Apache-2.0 | Credit Risk Modeling/Credit Risk Modeling - LGD and EAD Models - With Comments - 12-1.ipynb | autodidact-m/Projects |
EAD Model Estimation and Interpretation | # EAD model datasets
ead_inputs_train, ead_inputs_test, ead_targets_train, ead_targets_test = train_test_split(loan_data_defaults.drop(['good_bad', 'recovery_rate','recovery_rate_0_1', 'CCF'], axis = 1), loan_data_defaults['CCF'], test_size = 0.2, random_state = 42)
# Takes a set of inputs and a set of targets as argum... | _____no_output_____ | Apache-2.0 | Credit Risk Modeling/Credit Risk Modeling - LGD and EAD Models - With Comments - 12-1.ipynb | autodidact-m/Projects |
Rhizotron lab experiment | # We first need to load the pyCATHY package
# pyCATHY is calling fortran codes via python subroutines and ease the process
#!pip install -i https://test.pypi.org/simple/ pycathy-v001==0.0.1
!pip install git+https://github.com/BenjMy/pycathy_wrapper.git
#!git clone https://github.com/BenjMy/pycathy_wrapper.git
import os... | _____no_output_____ | BSD-3-Clause | examples/.ipynb_checkpoints/maryetal_visu-checkpoint.ipynb | BenjMy/pycathy_wrapper |
We initiate a CATHY object; if the the CATHY src files are not included within the 'path2prj', they are automatically fetched from the gitbucket (If the notebook is initiate locally with an internet connection) | path2prj ='notebooks'
prj = 'rhizo_prj2'
#os.chdir(path2prj)
simu = cathy_tools.CATHY(dirName=path2prj,prjName=prj,notebook=True)
simu # show the CATHY object
simu.workdir | _____no_output_____ | BSD-3-Clause | examples/.ipynb_checkpoints/maryetal_visu-checkpoint.ipynb | BenjMy/pycathy_wrapper |
Rhizotron DEM Build the grid 3d with arbitrary values Run preprocessor Simulation inputs 1- Initial conditions 2- Irrigation schedule 3- Boundary conditions 4- Soil and roots inputs run processor Explore outputs | step = 1
cplt.showvtk(unit='pressure',timeStep=1,notebook=True, path='./' + prj + '/vtk/')
cplt.showvtk(unit='pressure',timeStep=2,notebook=True, path='./' + prj + '/vtk/')
cplt.showvtk(unit='pressure',timeStep=3,notebook=True, path='./' + prj + '/vtk/')
cplt.showvtk(unit='pressure',timeStep=4,notebook=True, path='./' ... | _____no_output_____ | BSD-3-Clause | examples/.ipynb_checkpoints/maryetal_visu-checkpoint.ipynb | BenjMy/pycathy_wrapper |
We run the preprocessor with the default files inputs (weill et al example). This step create all the prepro files required for the processor later on. | simu.run_preprocessor(verbose=True)
# survey.hap_in # hap.in parameters are saved in a dict
# survey.hap_in['Ncells'] # access and check the number of cell from the CATHY object | _____no_output_____ | BSD-3-Clause | examples/.ipynb_checkpoints/maryetal_visu-checkpoint.ipynb | BenjMy/pycathy_wrapper |
We run the processor with the default files inputs (weill et al example) | simu.run_processor(verbose=True) | recompile
| BSD-3-Clause | examples/.ipynb_checkpoints/maryetal_visu-checkpoint.ipynb | BenjMy/pycathy_wrapper |
Plot results | cplt.showvtk(unit='pressure',timeStep=1,notebook=True, path='./' + prj + '/vtk/')
| plot pressure
| BSD-3-Clause | examples/.ipynb_checkpoints/maryetal_visu-checkpoint.ipynb | BenjMy/pycathy_wrapper |
Comparison operators: < less than > greater than <= less than or equal >= greater than or equal == equal - this is **not** the same as the = (assignment) operator != not equal | 1 != 2
1 = 2
1 == 2
number = 5
number < 10 and number > 3
3 < number < 10 < 12 > 0
number < 10 and > 3
number < 10 or number > 3
not True
print(number)
not (number < 3 and number > 10) | 5
| CC-BY-4.0 | Day5LoopingOverTasks.ipynb | pvanheus/python-novice-gapminder |
The logical operators and True if both sides are True or True if either side is true not flip True to False or False to True | sillyval = print("returns None")
print(sillyval is None)
print(sillyval is not None)
number = 1
if number > 3:
print("the number is > 3")
number = 5
if number > 0:
print("the number is positive")
else:
print("the number is not positive")
number = 5
if number > 0:
print("the number is positive")
elif num... | africa income is low: 1252.57
asia income is moderate: 5195.48
americas income is moderate: 4079.06
oceania income is high: 10298.09
europe income is moderate: 5661.06
| CC-BY-4.0 | Day5LoopingOverTasks.ipynb | pvanheus/python-novice-gapminder |
Principal Component Analysis (PCA) in Python Killian McKee Overview 1. [What is PCA?](section1)2. [Key Terms](section2) 3. [Pros and Cons of PCA](section3)4. [When to use PCA](section4)5. [Key Parameters](section5)6. [Walkthrough: PCA for data visualization](section6)7. [Walkthrough: PCA w/ Random Forest](section7)7... | # import the necessary packages
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from sklearn import decomposition
from sklearn import datasets
#specify graph parameters for iris and load the dataset
centers = [[1, 1], [-1, -1], [1, -1]]
iris = datasets.load_iris()
# se... | _____no_output_____ | MIT | principal_component_analysis/principal_component_analysis.ipynb | kcmckee/reference_guides |
Walkthrough: PCA w/ Random Forest In this tutorial we will be walking through the typical workflow to improve model speed with PCA, then fitting a random forest. We will be working with the iris dataset again, but we will load it into a pandas dataframe | # import necessary packages
import numpy as np
import pandas as pd
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics impor... | [[11 0 0]
[ 0 10 3]
[ 0 2 4]]
Accuracy 0.8333333333333334
| MIT | principal_component_analysis/principal_component_analysis.ipynb | kcmckee/reference_guides |
Exploratory Data Analysis Don Irwin U.C. Berkeley MIDS W209 - Spring 2022 Thursday 4 P.M. Background:MIDS students taking W209, Data Visualization, are expected to demonstrate an ability to source datasets, analyze datasets, and present visualizations in the form of web-based applications, to convey insights from tho... | my_altair.get_import_export_balance_top_five("World")
#my_altair.get_altaire_bar_top5_partners("World") | _____no_output_____ | Apache-2.0 | .ipynb_checkpoints/w209_final_project_eda_don_irwin-checkpoint.ipynb | tuneman7/w209_spring_2022_thu_4_pm_team_4_web |
What is informative about this view:The view above shows the top 5 trading nations or blocks in the world with a slider for the years between 2014 and 2020.Utilizing the slider, a user can see that for each of the years the European Union is consistently the top trading block.While not directly related to the hypothes... | indo = my_altair.get_altaire_bar_top5_partners_for_matrix("Indonesia")
indo
saudi = my_altair.get_altaire_bar_top5_partners_for_matrix("Saudi Arabia")
saudi
iran = my_altair.get_altaire_bar_top5_partners_for_matrix("Iran")
iran
sk = my_altair.get_altaire_bar_top5_partners_for_matrix("South Korea")
sk
jap = my_altair.ge... | _____no_output_____ | Apache-2.0 | .ipynb_checkpoints/w209_final_project_eda_don_irwin-checkpoint.ipynb | tuneman7/w209_spring_2022_thu_4_pm_team_4_web |
What is informative about this view:The view above shows 6 nations in Asia, from the Middle East, to the Far East, and it provides a slider to compare different years. We see, that for almost all of these nations, for almost all years in the visualization, China is the top trading partner. In the case of India and... | sk = my_altair.get_altaire_line_chart_county_trade_for_matrix("South Korea","Iran")
spain = my_altair.get_altaire_line_chart_county_trade_for_matrix("Spain","Iran")
usa = my_altair.get_altaire_line_chart_county_trade_for_matrix("United States","Iran")
jap = my_altair.get_altaire_line_chart_county_trade_for_matrix("Indo... | _____no_output_____ | Apache-2.0 | .ipynb_checkpoints/w209_final_project_eda_don_irwin-checkpoint.ipynb | tuneman7/w209_spring_2022_thu_4_pm_team_4_web |
Face GenerationIn this project, you'll define and train a DCGAN on a dataset of faces. Your goal is to get a generator network to generate *new* images of faces that look as realistic as possible!The project will be broken down into a series of tasks from **loading in data to defining and training adversarial networks... | # can comment out after executing
# !unzip processed_celeba_small.zip
import os
thedir = './processed_celeba_small/celeba/'
# [ name for name in os.listdir(thedir) if os.path.isdir(os.path.join(thedir, name)) ]
print (len([name for name in os.listdir(thedir) if os.path.isfile(os.path.join(thedir, name))]))
data_dir = '... | _____no_output_____ | MIT | final_dlnd_face_generation.ipynb | LKona/Generate-Faces-Using-GANs |
Visualize the CelebA DataThe [CelebA](http://mmlab.ie.cuhk.edu.hk/projects/CelebA.html) dataset contains over 200,000 celebrity images with annotations. Since you're going to be generating faces, you won't need the annotations, you'll only need the images. Note that these are color images with [3 color channels (RGB)]... | # necessary imports
import torch
import os
from torchvision import datasets
from torchvision import transforms
from torch.utils.data import DataLoader
# import shutil
# import os
# image_path = './' + data_dir
# source = os.path.join(image_path,'celeba/New Folder With Items/')
# print(source)
# # source = './processe... | _____no_output_____ | MIT | final_dlnd_face_generation.ipynb | LKona/Generate-Faces-Using-GANs |
Create a DataLoader Exercise: Create a DataLoader `celeba_train_loader` with appropriate hyperparameters.Call the above function and create a dataloader to view images. * You can decide on any reasonable `batch_size` parameter* Your `image_size` **must be** `32`. Resizing the data to a smaller size will make for faste... | # Define function hyperparameters
batch_size = 128
img_size = 32
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
# Call your function and get a dataloader
celeba_train_loader = get_dataloader(batch_size, img_size)
print(len(celeba_train_loader.dataset))
| ./processed_celeba_small/
89931
| MIT | final_dlnd_face_generation.ipynb | LKona/Generate-Faces-Using-GANs |
Next, you can view some images! You should seen square images of somewhat-centered faces.Note: You'll need to convert the Tensor images into a NumPy type and transpose the dimensions to correctly display an image, suggested `imshow` code is below, but it may not be perfect. | # helper display function
def imshow(img):
npimg = img.numpy()
plt.imshow(np.transpose(npimg, (1, 2, 0)))
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
# obtain one batch of training images
dataiter = iter(celeba_train_loader)
images, _ = dataiter.next() # _ for no labels
# plot the image... | _____no_output_____ | MIT | final_dlnd_face_generation.ipynb | LKona/Generate-Faces-Using-GANs |
Exercise: Pre-process your image data and scale it to a pixel range of -1 to 1You need to do a bit of pre-processing; you know that the output of a `tanh` activated generator will contain pixel values in a range from -1 to 1, and so, we need to rescale our training images to a range of -1 to 1. (Right now, they are in... | # TODO: Complete the scale function
def scale(x, feature_range=(-1, 1)):
''' Scale takes in an image x and returns that image, scaled
with a feature_range of pixel values from -1 to 1.
This function assumes that the input x is already scaled from 0-1.'''
# assume x is scaled to (0, 1)
# scale... | Min: tensor(-0.9922)
Max: tensor(0.8275)
| MIT | final_dlnd_face_generation.ipynb | LKona/Generate-Faces-Using-GANs |
--- Define the ModelA GAN is comprised of two adversarial networks, a discriminator and a generator. DiscriminatorYour first task will be to define the discriminator. This is a convolutional classifier like you've built before, only without any maxpooling layers. To deal with this complex data, it's suggested you use a... | import torch.nn as nn
import torch.nn.functional as F
# helper conv function
def conv(in_channels, out_channels, kernel_size, stride=2, padding=1, batch_norm=True):
"""Creates a convolutional layer, with optional batch normalization.
"""
layers = []
conv_layer = nn.Conv2d(in_channels, out_channels,
... | Tests Passed
| MIT | final_dlnd_face_generation.ipynb | LKona/Generate-Faces-Using-GANs |
GeneratorThe generator should upsample an input and generate a *new* image of the same size as our training data `32x32x3`. This should be mostly transpose convolutional layers with normalization applied to the outputs. Exercise: Complete the Generator class* The inputs to the generator are vectors of some length `z_s... | def deconv(in_channels, out_channels, kernel_size, stride=2, padding=1, batch_norm=True):
"""Creates a transposed-convolutional layer, with optional batch normalization.
"""
# create a sequence of transpose + optional batch norm layers
layers = []
transpose_conv_layer = nn.ConvTranspose2d(in_channel... | Tests Passed
| MIT | final_dlnd_face_generation.ipynb | LKona/Generate-Faces-Using-GANs |
Initialize the weights of your networksTo help your models converge, you should initialize the weights of the convolutional and linear layers in your model. From reading the [original DCGAN paper](https://arxiv.org/pdf/1511.06434.pdf), they say:> All weights were initialized from a zero-centered Normal distribution wi... | from torch.nn import init
def weights_init_normal(m):
"""
Applies initial weights to certain layers in a model .
The weights are taken from a normal distribution
with mean = 0, std dev = 0.02.
:param m: A module or layer in a network
"""
# classname will be something like:
# `Conv`... | _____no_output_____ | MIT | final_dlnd_face_generation.ipynb | LKona/Generate-Faces-Using-GANs |
Build complete networkDefine your models' hyperparameters and instantiate the discriminator and generator from the classes defined above. Make sure you've passed in the correct input arguments. | """
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
def build_network(d_conv_dim, g_conv_dim, z_size):
# define discriminator and generator
D = Discriminator(d_conv_dim)
G = Generator(z_size=z_size, conv_dim=g_conv_dim)
# initialize model weights
D.apply(weights_init_normal)
G.ap... | _____no_output_____ | MIT | final_dlnd_face_generation.ipynb | LKona/Generate-Faces-Using-GANs |
Exercise: Define model hyperparameters | # Define model hyperparams
d_conv_dim = 32
g_conv_dim = 32
z_size = 200
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
D, G = build_network(d_conv_dim, g_conv_dim, z_size) | Discriminator(
(conv1): Sequential(
(0): Conv2d(3, 32, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)
)
(conv2): Sequential(
(0): Conv2d(32, 64, kernel_size=(4, 4), stride=(2, 2), padding=(1, 1), bias=False)
(1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats... | MIT | final_dlnd_face_generation.ipynb | LKona/Generate-Faces-Using-GANs |
Training on GPUCheck if you can train on GPU. Here, we'll set this as a boolean variable `train_on_gpu`. Later, you'll be responsible for making sure that >* Models,* Model inputs, and* Loss function argumentsAre moved to GPU, where appropriate. | """
DON'T MODIFY ANYTHING IN THIS CELL
"""
import torch
# Check for a GPU
train_on_gpu = torch.cuda.is_available()
if not train_on_gpu:
print('No GPU found. Please use a GPU to train your neural network.')
else:
print('Training on GPU!') | Training on GPU!
| MIT | final_dlnd_face_generation.ipynb | LKona/Generate-Faces-Using-GANs |
--- Discriminator and Generator LossesNow we need to calculate the losses for both types of adversarial networks. Discriminator Losses> * For the discriminator, the total loss is the sum of the losses for real and fake images, `d_loss = d_real_loss + d_fake_loss`. * Remember that we want the discriminator to output 1 f... | def real_loss(D_out, smooth=False):
'''Calculates how close discriminator outputs are to being real.
param, D_out: discriminator logits
return: real loss'''
batch_size = D_out.size(0)
# label smoothing
if smooth:
# smooth, real labels = 0.9
labels = torch.ones(batch_size)*0... | _____no_output_____ | MIT | final_dlnd_face_generation.ipynb | LKona/Generate-Faces-Using-GANs |
Optimizers Exercise: Define optimizers for your Discriminator (D) and Generator (G)Define optimizers for your models with appropriate hyperparameters. | import torch.optim as optim
# params
lr = 0.0002
beta1=0.5
beta2=0.999 # default value
# Create optimizers for the discriminator D and generator G
d_optimizer = optim.Adam(D.parameters(), lr, [beta1, beta2])
g_optimizer = optim.Adam(G.parameters(), lr, [beta1, beta2]) | _____no_output_____ | MIT | final_dlnd_face_generation.ipynb | LKona/Generate-Faces-Using-GANs |
--- TrainingTraining will involve alternating between training the discriminator and the generator. You'll use your functions `real_loss` and `fake_loss` to help you calculate the discriminator losses.* You should train the discriminator by alternating on real and fake images* Then the generator, which tries to trick t... | def train(D, G, n_epochs, print_every=50):
'''Trains adversarial networks for some number of epochs
param, D: the discriminator network
param, G: the generator network
param, n_epochs: number of epochs to train for
param, print_every: when to print and record the models' losses
re... | _____no_output_____ | MIT | final_dlnd_face_generation.ipynb | LKona/Generate-Faces-Using-GANs |
Set your number of training epochs and train your GAN! | # set number of epochs
n_epochs = 30
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
# call training function
losses = train(D, G, n_epochs=n_epochs) | Epoch [ 1/ 30] | d_loss: 1.4314 | g_loss: 0.9460
Epoch [ 1/ 30] | d_loss: 0.1727 | g_loss: 3.4594
Epoch [ 1/ 30] | d_loss: 0.2041 | g_loss: 4.0258
Epoch [ 1/ 30] | d_loss: 0.2896 | g_loss: 3.3163
Epoch [ 1/ 30] | d_loss: 0.1577 | g_loss: 3.8655
Epoch [ 1/ 30] | d_loss: 1.1076 | g_loss: 6.7... | MIT | final_dlnd_face_generation.ipynb | LKona/Generate-Faces-Using-GANs |
Training lossPlot the training losses for the generator and discriminator, recorded after each epoch. | fig, ax = plt.subplots()
losses = np.array(losses)
plt.plot(losses.T[0], label='Discriminator', alpha=0.5)
plt.plot(losses.T[1], label='Generator', alpha=0.5)
plt.title("Training Losses")
plt.legend() | _____no_output_____ | MIT | final_dlnd_face_generation.ipynb | LKona/Generate-Faces-Using-GANs |
Generator samples from trainingView samples of images from the generator, and answer a question about the strengths and weaknesses of your trained models. | # helper function for viewing a list of passed in sample images
def view_samples(epoch, samples):
fig, axes = plt.subplots(figsize=(16,4), nrows=2, ncols=8, sharey=True, sharex=True)
for ax, img in zip(axes.flatten(), samples[epoch]):
img = img.detach().cpu().numpy()
img = np.transpose(img, (1, ... | _____no_output_____ | MIT | final_dlnd_face_generation.ipynb | LKona/Generate-Faces-Using-GANs |
Copyright 2021 DeepMind Technologies LimitedLicensed under the Apache License, Version 2.0 (the "License");you may not use this file except in compliance with the License.You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0Unless required by applicable law or agreed to in writing, soft... | #@title Set CUDA version for PyTorch
import subprocess
CUDA_version = [s for s in subprocess.check_output(["nvcc", "--version"]
).decode("UTF-8").split(", ")
if s.startswith("release")][0].split(" ")[-1]
print("CUDA version:", CUDA_version)
if CUDA_v... | _____no_output_____ | Apache-2.0 | arnheim_1.ipynb | TotoArt/arnheim |
Neural Visual Grammar Drawing primitives | def to_homogeneous(p):
r, c = p
return np.stack((r, c, np.ones_like(p[0])), axis=0)
def from_homogeneous(p):
p = p / p.T[:, 2]
return p[0].astype("int32"), p[1].astype("int32")
def apply_scale(scale, lineh):
return np.stack([lineh[0, :] * scale,
lineh[1, :] * scale,
lin... | _____no_output_____ | Apache-2.0 | arnheim_1.ipynb | TotoArt/arnheim |
Hierarchical stroke painting functions | # PaintingCommand
# origin_top: Origin of line defined by top level LSTM
# angle_top: Angle of line defined by top level LSTM
# scale_top: Scale for line defined by top level LSTM
# origin_bottom: Origin of line defined by bottom level LSTM
# angle_bottom: Angle of line defined by bottom level LSTM
# scale_... | _____no_output_____ | Apache-2.0 | arnheim_1.ipynb | TotoArt/arnheim |
Recurrent Neural Network Layer Generator | # DrawingLSTMSpec - parameters defining the LSTM architecture
# input_spec_size: Size if sequence elements
# num_lstms: Number of LSTMs at each layer
# net_lstm_hiddens: Number of hidden LSTM units
# net_mlp_hiddens: Number of hidden units in MLP layer
DrawingLSTMSpec = collections.namedtuple("DrawingLSTMSpec",... | _____no_output_____ | Apache-2.0 | arnheim_1.ipynb | TotoArt/arnheim |
DrawingLSTM - A Drawing Recurrent Neural Network | Genotype = collections.namedtuple("Genotype",
["top_lstm",
"bottom_lstm",
"input_sequence",
"initial_img"])
class DrawingLSTM:
"""LSTM for processing input sequences and generati... | _____no_output_____ | Apache-2.0 | arnheim_1.ipynb | TotoArt/arnheim |
DrawingGenerator | class DrawingGenerator:
"""Creates a drawing using a DrawingLSTM."""
def __init__(self, image_size, drawing_lstm_spec,
allow_strokes_beyond_image_edges):
self.primitives = ["c", "r", "l", "b", "p", "j"]
self.pop = []
self.size = image_size
self.fitnesses = np.zeros(1)
self.noise ... | _____no_output_____ | Apache-2.0 | arnheim_1.ipynb | TotoArt/arnheim |
Evaluator | class Evaluator:
"""Evaluator for a drawing."""
def __init__(self, image_size, drawing_lstm_spec,
allow_strokes_beyond_image_edges):
self.drawing_generator = DrawingGenerator(image_size, drawing_lstm_spec,
allow_strokes_beyond_image_edges)
self.c... | _____no_output_____ | Apache-2.0 | arnheim_1.ipynb | TotoArt/arnheim |
Evolution Fitness calculation, tournament, and crossover | IMAGE_MEAN = torch.tensor([0.48145466, 0.4578275, 0.40821073]).cuda()
IMAGE_STD = torch.tensor([0.26862954, 0.26130258, 0.27577711]).cuda()
def get_fitness(pictures, use_projective_transform,
projective_transform_coefficient):
"""Run CLIP on a batch of `pictures` and return `fitnesses`.
Args:
... | _____no_output_____ | Apache-2.0 | arnheim_1.ipynb | TotoArt/arnheim |
Remote workers | VERBOSE_DURATION = False
@ray.remote
class Worker(object):
"""Takes a pickled dna and evaluates it, returning result."""
def __init__(self, image_size, drawing_lstm_spec,
allow_strokes_beyond_image_edges):
self.evaluator = Evaluator(image_size, drawing_lstm_spec,
... | _____no_output_____ | Apache-2.0 | arnheim_1.ipynb | TotoArt/arnheim |
Plotting | def plot_training_res(batch_drawings, fitness_history, idx=None):
"""Plot fitnesses and timings.
Args:
batch_drawings: Drawings
fitness_history: History of fitnesses
idx: Index of drawing to show, default is highest fitness
"""
_, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 5))
if idx is None:
... | _____no_output_____ | Apache-2.0 | arnheim_1.ipynb | TotoArt/arnheim |
Population and evolution main loop | def make_population(pop_size, evaluator, image_size, input_spec_size,
sequence_length):
"""Make initial population.
Args:
pop_size: number of genotypes in population.
evaluator: An Evaluator class instance for generating initial genotype.
image_size: Size of initial image for genoty... | _____no_output_____ | Apache-2.0 | arnheim_1.ipynb | TotoArt/arnheim |
Configure and Generate | #@title Hyperparameters
#@markdown Evolution parameters: population size and number of generations.
POPULATION_SIZE = 10 #@param {type:"slider", min:4, max:100, step:2}
NUM_GENERATIONS = 5000 #@param {type:"integer", min:100}
#@markdown Number of workers working in parallel (should be equal to or smaller than the po... | _____no_output_____ | Apache-2.0 | arnheim_1.ipynb | TotoArt/arnheim |
Running the original evolutionary algorithmThis is the original inefficient version of Arnheim which uses a genetic algorithm to optimize the picture. It takes at least 12 hours to produce an image using 50 workers. In our paper we used 500-1000 GPUs which speeded things up considerably. Refer to Arnheim 2 for a far mo... | # @title Get text input and run evolution
PROMPT = "an apple" #@param {type:"string"}
# Tokenize prompts and coompute CLIP features.
text_input = clip.tokenize(PROMPT).to(device)
with torch.no_grad():
text_features = model.encode_text(text_input)
ray.shutdown()
ray.init()
drawing_lstm_arch = DrawingLSTMSpec(INPUT... | _____no_output_____ | Apache-2.0 | arnheim_1.ipynb | TotoArt/arnheim |
Coverage of MultiPLIER LVThe goal of this notebook is to examine why genes were found to be generic. Specifically, this notebook is trying to answer the question: Are generic genes found in more multiplier latent variables compared to specific genes?The PLIER model performs a matrix factorization of gene expression da... | %load_ext autoreload
%autoreload 2
import os
import random
import textwrap
import scipy
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
import rpy2.robjects as ro
from rpy2.robjects import pandas2ri
from rpy2.robjects.conversion import localconv... | _____no_output_____ | BSD-3-Clause | LV_analysis/1_get_multiplier_LV_coverage.ipynb | jjc2718/generic-expression-patterns |
Load data | # Get gene summary file
summary_data_filename = os.path.join(data_dir, f"generic_gene_summary_{project_id}.tsv")
# Load gene summary data
data = pd.read_csv(summary_data_filename, sep="\t", index_col=0, header=0)
# Check that genes are unique since we will be using them as dictionary keys below
assert data.shape[0] ==... | _____no_output_____ | BSD-3-Clause | LV_analysis/1_get_multiplier_LV_coverage.ipynb | jjc2718/generic-expression-patterns |
Get gene dataDefine generic genes based on simulated gene ranking. Refer to [figure](https://github.com/greenelab/generic-expression-patterns/blob/master/human_general_analysis/gene_ranking_log2FoldChange.svg) as a guide.**Definitions:*** Generic genes: `Percentile (simulated) >= 60`(Having a high rank indicates that ... | generic_threshold = 60
dict_genes = lv.get_generic_specific_genes(data, generic_threshold)
# Check overlap between multiplier genes and our genes
multiplier_genes = list(multiplier_model_z.index)
our_genes = list(data.index)
shared_genes = set(our_genes).intersection(multiplier_genes)
print(len(our_genes))
print(len(s... | _____no_output_____ | BSD-3-Clause | LV_analysis/1_get_multiplier_LV_coverage.ipynb | jjc2718/generic-expression-patterns |
Get coverage of LVsFor each gene (generic or other) we want to find:1. The number of LVs that gene is present2. The number of LVs that the gene contributes a lot to (i.e. the gene is highly weighted within that LV) Nonzero LV coverage | dict_nonzero_coverage = lv.get_nonzero_LV_coverage(
processed_dict_genes, multiplier_model_z
)
# Check genes mapped correctly
assert processed_dict_genes["generic"][0] in dict_nonzero_coverage["generic"].index
assert len(dict_nonzero_coverage["generic"]) == len(processed_dict_genes["generic"])
assert len(dict_nonze... | _____no_output_____ | BSD-3-Clause | LV_analysis/1_get_multiplier_LV_coverage.ipynb | jjc2718/generic-expression-patterns |
High weight LV coverage | # Quick look at the distribution of gene weights per LV
sns.distplot(multiplier_model_z["LV3"], kde=False)
plt.yscale("log")
dict_highweight_coverage = lv.get_highweight_LV_coverage(
processed_dict_genes, multiplier_model_z, quantile_threshold
)
# Check genes mapped correctly
assert processed_dict_genes["generic"][... | _____no_output_____ | BSD-3-Clause | LV_analysis/1_get_multiplier_LV_coverage.ipynb | jjc2718/generic-expression-patterns |
Assemble LV coverage and plot | all_coverage = []
for gene_label in dict_genes.keys():
merged_df = pd.DataFrame(
dict_nonzero_coverage[gene_label], columns=["nonzero LV coverage"]
).merge(
pd.DataFrame(
dict_highweight_coverage[gene_label], columns=["highweight LV coverage"]
),
left_index=True,
... | _____no_output_____ | BSD-3-Clause | LV_analysis/1_get_multiplier_LV_coverage.ipynb | jjc2718/generic-expression-patterns |
Calculate statistics* Is the reduction in generic coverage significant?* Is the difference between generic versus other genes signficant? | # Test: mean number of LVs generic genes present in vs mean number of LVs that generic gene is high weight in
# (compare two blue boxes between plots)
generic_nonzero = all_coverage_df[all_coverage_df["gene type"] == "generic"][
"nonzero LV coverage"
].values
generic_highweight = all_coverage_df[all_coverage_df["ge... | 0.23947472582519233
| BSD-3-Clause | LV_analysis/1_get_multiplier_LV_coverage.ipynb | jjc2718/generic-expression-patterns |
Get LVs that generic genes are highly weighted inSince we are using quantiles to get high weight genes per LV, each LV has the same number of high weight genes. For each set of high weight genes, we will get the proportion of generic vs other genes. We will select the LVs that have a high proportion of generic genes t... | # Get proportion of generic genes per LV
prop_highweight_generic_dict = lv.get_prop_highweight_generic_genes(
processed_dict_genes, multiplier_model_z, quantile_threshold
)
# Return selected rows from summary matrix
multiplier_model_summary = pd.read_csv(
"multiplier_model_summary.tsv", sep="\t", index_col=0, h... | 0 6.540359
1 6.527677
2 2.738563
3 1.470443
4 1.272303
5 0.982001
6 0.842076
7 0.715623
8 0.714085
9 0.615867
10 0.567222
11 0.535279
12 0.532891
13 0.525537
14 0.522841
15 0.483024
16 0.475159
17 0.469341
18 0.462943
19 0.439901
Name: LV61, dtype: f... | BSD-3-Clause | LV_analysis/1_get_multiplier_LV_coverage.ipynb | jjc2718/generic-expression-patterns |
Save | # Save plot
nonzero_fig.figure.savefig(
nonzero_figure_filename,
format="svg",
bbox_inches="tight",
transparent=True,
pad_inches=0,
dpi=300,
)
# Save plot
highweight_fig.figure.savefig(
highweight_figure_filename,
format="svg",
bbox_inches="tight",
transparent=True,
pad_inch... | _____no_output_____ | BSD-3-Clause | LV_analysis/1_get_multiplier_LV_coverage.ipynb | jjc2718/generic-expression-patterns |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.