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
Design 2A
sid='../Data/Design2a/design2a_11k_test5/' rp_sessionDes2 = ra.Session(stype='radical.pilot',src=sid) unitsDes2 = rp_sessionDes2.filter(etype='unit', inplace=False) execUnits = unitsDes2.filter(uid=['unit.000002','unit.000003','unit.000004','unit.000001'],inplace=False) exec_units_setup_des2 = execUnits.duration(event=...
_____no_output_____
MIT
Geolocation/Notebooks/Des1Des2OverheadComp.ipynb
radical-experiments/iceberg_escience
Running, Debugging, Testing & Packaging
!code ./1-helloconnectedworld
_____no_output_____
MIT
1_RunExtension.ipynb
kevcunnane/msbuild_ads_demo
NetworksIn this last exercise, you will start to put into practice some of the concepts learned in class. Start by importing the libraries that you will need.
import networkx as nx import matplotlib.pyplot as plt %matplotlib inline
_____no_output_____
MIT
ix-1-lab-intro/4-networks.ipynb
emlg/Internet-Analytics
We give you the network of the 34 members of [karate clubs](https://en.wikipedia.org/wiki/Zachary's_karate_club) on the campus. Each node is a member of one of two clubs ("Mr. Hi" or "Officer") and there is an edge between two nodes if the two are friends outside of the club.
karate_club = nx.karate_club_graph()
_____no_output_____
MIT
ix-1-lab-intro/4-networks.ipynb
emlg/Internet-Analytics
Visualization1. Visualize the network by - painting every 'Mr. Hi' member in **blue** and every 'Officer' member in **red**, and - drawing the label corresponding to the member index (between 1 and 34) on each node.2. What can you tell about the nodes and their connections? Do you see some nodes with more/less l...
# Your code goes here color_map = [] for i in range(0, karate_club.order()): if karate_club.node[i]['club'] == "Mr. Hi": color_map.append('blue') else: color_map.append('red') nx.draw_networkx(karate_club, node_color = color_map, with_labels = True) plt.axis('off');
_____no_output_____
MIT
ix-1-lab-intro/4-networks.ipynb
emlg/Internet-Analytics
Degree Distribution1. Plot the degree distribution of the network.2. Does it confirm your answer to the previous question?
# Your code goes here degre = list() for v in karate_club: degre.append(karate_club.degree(v)) plt.plot(degre, '*') plt.show()
_____no_output_____
MIT
ix-1-lab-intro/4-networks.ipynb
emlg/Internet-Analytics
Convolutional AutoencoderSticking with the MNIST dataset, let's improve our autoencoder's performance using convolutional layers. Again, loading modules and the data.
%matplotlib inline import numpy as np import tensorflow as tf import matplotlib.pyplot as plt from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('MNIST_data', validation_size=0) img = mnist.train.images[2] plt.imshow(img.reshape((28, 28)), cmap='Greys_r')
_____no_output_____
MIT
autoencoder/Convolutional_Autoencoder_Solution.ipynb
vinidixit/deep-learning-repo
Network ArchitectureThe encoder part of the network will be a typical convolutional pyramid. Each convolutional layer will be followed by a max-pooling layer to reduce the dimensions of the layers. The decoder though might be something new to you. The decoder needs to convert from a narrow representation to a wide rec...
inputs_ = tf.placeholder(tf.float32, (None, 28, 28, 1), name='inputs') targets_ = tf.placeholder(tf.float32, (None, 28, 28, 1), name='targets') ### Encoder conv1 = tf.layers.conv2d(inputs_, 16, (3,3), padding='same', activation=tf.nn.relu) # Now 28x28x16 maxpool1 = tf.layers.max_pooling2d(conv1, (2,2), (2,2), padding=...
_____no_output_____
MIT
autoencoder/Convolutional_Autoencoder_Solution.ipynb
vinidixit/deep-learning-repo
TrainingAs before, here wi'll train the network. Instead of flattening the images though, we can pass them in as 28x28x1 arrays.
sess = tf.Session() epochs = 1 batch_size = 200 sess.run(tf.global_variables_initializer()) for e in range(epochs): for ii in range(mnist.train.num_examples//batch_size): batch = mnist.train.next_batch(batch_size) imgs = batch[0].reshape((-1, 28, 28, 1)) batch_cost, _ = sess.run([cost, opt],...
_____no_output_____
MIT
autoencoder/Convolutional_Autoencoder_Solution.ipynb
vinidixit/deep-learning-repo
DenoisingAs I've mentioned before, autoencoders like the ones you've built so far aren't too useful in practive. However, they can be used to denoise images quite successfully just by training the network on noisy images. We can create the noisy images ourselves by adding Gaussian noise to the training images, then cl...
inputs_ = tf.placeholder(tf.float32, (None, 28, 28, 1), name='inputs') targets_ = tf.placeholder(tf.float32, (None, 28, 28, 1), name='targets') ### Encoder conv1 = tf.layers.conv2d(inputs_, 32, (3,3), padding='same', activation=tf.nn.relu) # Now 28x28x32 maxpool1 = tf.layers.max_pooling2d(conv1, (2,2), (2,2), padding=...
_____no_output_____
MIT
autoencoder/Convolutional_Autoencoder_Solution.ipynb
vinidixit/deep-learning-repo
Checking out the performanceHere I'm adding noise to the test images and passing them through the autoencoder. It does a suprising great job of removing the noise, even though it's sometimes difficult to tell what the original number is.
fig, axes = plt.subplots(nrows=2, ncols=10, sharex=True, sharey=True, figsize=(20,4)) in_imgs = mnist.test.images[:10] noisy_imgs = in_imgs + noise_factor * np.random.randn(*in_imgs.shape) noisy_imgs = np.clip(noisy_imgs, 0., 1.) reconstructed = sess.run(decoded, feed_dict={inputs_: noisy_imgs.reshape((10, 28, 28, 1))...
_____no_output_____
MIT
autoencoder/Convolutional_Autoencoder_Solution.ipynb
vinidixit/deep-learning-repo
1.1. Create_Data_Augmentation_With_Augmentorhttps://github.com/mdbloice/Augmentor
# install the package # !pip install Augmentor import Augmentor label = '200_frente' path_img = 'data_augmentation/source/' + label + '/' sample_per_configurator = 50 # random distortion + rotate p1 = Augmentor.Pipeline(path_img) p1.rotate(probability=1.0, max_left_rotation=20, max_right_rotation=20) p1.random_distorti...
Executing Pipeline: 0%| | 0/25 [00:00<?, ? Samples/s]
MIT
1.1. Create_Data_Augmentation_With_Augmentor.ipynb
christianquicano/tflite_classification_banknotes
Practice geospatial aggregations in geopandas before writing them to .py files
%load_ext autoreload %autoreload 2 import sys sys.path.append('../utils') import wd_management wd_management.set_wd_root() import geopandas as gp import pandas as pd import requests res = requests.get('https://services5.arcgis.com/GfwWNkhOj9bNBqoJ/arcgis/rest/services/NYC_Public_Use_Microdata_Areas_PUMAs_2010/FeatureS...
_____no_output_____
MIT
notebooks/Area_within_Historic_District_Exploratory.ipynb
NYCPlanning/db-equitable-development-tool
Ok looks good. Load in historic districts. [This stackoverflow post](https://gis.stackexchange.com/questions/327197/typeerror-input-geometry-column-must-contain-valid-geometry-objects) was helpful
from shapely import wkt hd= gp.read_file('.library/lpc_historic_district_areas.csv') hd['the_geom'] = hd['the_geom'].apply(wkt.loads) hd.set_geometry(col='the_geom', inplace=True, crs='EPSG:4326') hd= hd.explode(column='the_geom') hd.set_geometry('the_geom',inplace=True) hd = hd.to_crs('EPSG:2263') hd = hd.reset_index(...
/var/folders/tg/01b257jj0dzg5fzzc3p3gj0w0000gq/T/ipykernel_26102/3499734924.py:1: FutureWarning: Currently, index_parts defaults to True, but in the future, it will default to False to be consistent with Pandas. Use `index_parts=True` to keep the current behavior and True/False to silence the warning. hd= hd.explode(...
MIT
notebooks/Area_within_Historic_District_Exploratory.ipynb
NYCPlanning/db-equitable-development-tool
Ok great next do some geospatial analysis. Start only with PUMA 3807 as it has a lot of historic area
def fraction_area_historic(PUMA, hd): try: gdf = gp.GeoDataFrame(geometry = [PUMA.geometry], crs = 'EPSG:4326') gdf = gdf.to_crs('EPSG:2263') overlay = gp.overlay(hd, gdf, 'intersection') if overlay.empty: return 0, 0 else: fraction = overlay.area.sum...
_____no_output_____
MIT
notebooks/Area_within_Historic_District_Exploratory.ipynb
NYCPlanning/db-equitable-development-tool
Superimpose PUMA 3801's historic districts on it to see if 38% looks right
def visualize_overlay(PUMA): test_PUMA = NYC_PUMAs.loc[[PUMA]].to_crs('EPSG:2263') base = test_PUMA.plot(color='green', edgecolor='black') overlay = gp.overlay(hd, test_PUMA, 'intersection') overlay.plot(ax=base, color='red'); visualize_overlay('3810')
_____no_output_____
MIT
notebooks/Area_within_Historic_District_Exploratory.ipynb
NYCPlanning/db-equitable-development-tool
Ok great that looks like about a third to me From eyeballing map, more than 20% of PUMA 3806 on UWS looks to be historic
visualize_overlay('3806')
_____no_output_____
MIT
notebooks/Area_within_Historic_District_Exploratory.ipynb
NYCPlanning/db-equitable-development-tool
Ah ok the PUMA geography from includes central park. Worth flagging Question from Renae:Renae points out that description of historic districts says "including items that may have been denied designation or overturned."Look at dataset to see if columns point to this clearly
hd.head(5) hd.groupby('status_of_').size() hd.groupby('current_').size() hd.groupby('last_actio').size()
_____no_output_____
MIT
notebooks/Area_within_Historic_District_Exploratory.ipynb
NYCPlanning/db-equitable-development-tool
Install Transformers Library
!pip install transformers import numpy as np import pandas as pd import torch import torch.nn as nn from sklearn.model_selection import train_test_split from sklearn.metrics import classification_report import transformers from transformers import AutoModel, BertTokenizerFast # specify GPU device = torch.device("cuda"...
_____no_output_____
Apache-2.0
Fine_Tuning_BERT_for_Spam_Classification.ipynb
lamiathu/Fine-Tuning-BERT
Load Dataset
df = pd.read_csv("spamdata_v2.csv") df.head() df.shape # check class distribution df['label'].value_counts(normalize = True)
_____no_output_____
Apache-2.0
Fine_Tuning_BERT_for_Spam_Classification.ipynb
lamiathu/Fine-Tuning-BERT
Split train dataset into train, validation and test sets
train_text, temp_text, train_labels, temp_labels = train_test_split(df['text'], df['label'], random_state=2018, test_size=0.3, ...
_____no_output_____
Apache-2.0
Fine_Tuning_BERT_for_Spam_Classification.ipynb
lamiathu/Fine-Tuning-BERT
Import BERT Model and BERT Tokenizer
# import BERT-base pretrained model bert = AutoModel.from_pretrained('bert-base-uncased') # Load the BERT tokenizer tokenizer = BertTokenizerFast.from_pretrained('bert-base-uncased') # sample data text = ["this is a bert model tutorial", "we will fine-tune a bert model"] # encode text sent_id = tokenizer.batch_encode...
{'input_ids': [[101, 2023, 2003, 1037, 14324, 2944, 14924, 4818, 102, 0], [101, 2057, 2097, 2986, 1011, 8694, 1037, 14324, 2944, 102]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]}
Apache-2.0
Fine_Tuning_BERT_for_Spam_Classification.ipynb
lamiathu/Fine-Tuning-BERT
Tokenization
# get length of all the messages in the train set seq_len = [len(i.split()) for i in train_text] pd.Series(seq_len).hist(bins = 30) max_seq_len = 25 # tokenize and encode sequences in the training set tokens_train = tokenizer.batch_encode_plus( train_text.tolist(), max_length = max_seq_len, pad_to_max_leng...
_____no_output_____
Apache-2.0
Fine_Tuning_BERT_for_Spam_Classification.ipynb
lamiathu/Fine-Tuning-BERT
Convert Integer Sequences to Tensors
# for train set train_seq = torch.tensor(tokens_train['input_ids']) train_mask = torch.tensor(tokens_train['attention_mask']) train_y = torch.tensor(train_labels.tolist()) # for validation set val_seq = torch.tensor(tokens_val['input_ids']) val_mask = torch.tensor(tokens_val['attention_mask']) val_y = torch.tensor(val...
_____no_output_____
Apache-2.0
Fine_Tuning_BERT_for_Spam_Classification.ipynb
lamiathu/Fine-Tuning-BERT
Create DataLoaders
from torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler #define a batch size batch_size = 32 # wrap tensors train_data = TensorDataset(train_seq, train_mask, train_y) # sampler for sampling the data during training train_sampler = RandomSampler(train_data) # dataLoader for train set...
_____no_output_____
Apache-2.0
Fine_Tuning_BERT_for_Spam_Classification.ipynb
lamiathu/Fine-Tuning-BERT
Freeze BERT Parameters
# freeze all the parameters for param in bert.parameters(): param.requires_grad = False
_____no_output_____
Apache-2.0
Fine_Tuning_BERT_for_Spam_Classification.ipynb
lamiathu/Fine-Tuning-BERT
Define Model Architecture
class BERT_Arch(nn.Module): def __init__(self, bert): super(BERT_Arch, self).__init__() self.bert = bert # dropout layer self.dropout = nn.Dropout(0.1) # relu activation function self.relu = nn.ReLU() # dense layer 1 self.fc1 = nn.Linear(768,...
_____no_output_____
Apache-2.0
Fine_Tuning_BERT_for_Spam_Classification.ipynb
lamiathu/Fine-Tuning-BERT
Find Class Weights
from sklearn.utils.class_weight import compute_class_weight #compute the class weights class_wts = compute_class_weight('balanced', np.unique(train_labels), train_labels) print(class_wts) # convert class weights to tensor weights= torch.tensor(class_wts,dtype=torch.float) weights = weights.to(device) # loss function...
_____no_output_____
Apache-2.0
Fine_Tuning_BERT_for_Spam_Classification.ipynb
lamiathu/Fine-Tuning-BERT
Fine-Tune BERT
# function to train the model def train(): model.train() total_loss, total_accuracy = 0, 0 # empty list to save model predictions total_preds=[] # iterate over batches for step,batch in enumerate(train_dataloader): # progress update after every 50 batches. if step % 50 == 0 and not st...
_____no_output_____
Apache-2.0
Fine_Tuning_BERT_for_Spam_Classification.ipynb
lamiathu/Fine-Tuning-BERT
Start Model Training
# set initial loss to infinite best_valid_loss = float('inf') # empty lists to store training and validation loss of each epoch train_losses=[] valid_losses=[] #for each epoch for epoch in range(epochs): print('\n Epoch {:} / {:}'.format(epoch + 1, epochs)) #train model train_loss, _ = train() ...
Epoch 1 / 10 Batch 50 of 122. Batch 100 of 122. Evaluating... Training Loss: 0.526 Validation Loss: 0.656 Epoch 2 / 10 Batch 50 of 122. Batch 100 of 122. Evaluating... Training Loss: 0.345 Validation Loss: 0.231 Epoch 3 / 10 Batch 50 of 122. Batch 100 of 122....
Apache-2.0
Fine_Tuning_BERT_for_Spam_Classification.ipynb
lamiathu/Fine-Tuning-BERT
Load Saved Model
#load weights of best model path = 'saved_weights.pt' model.load_state_dict(torch.load(path))
_____no_output_____
Apache-2.0
Fine_Tuning_BERT_for_Spam_Classification.ipynb
lamiathu/Fine-Tuning-BERT
Get Predictions for Test Data
# get predictions for test data with torch.no_grad(): preds = model(test_seq.to(device), test_mask.to(device)) preds = preds.detach().cpu().numpy() # model's performance preds = np.argmax(preds, axis = 1) print(classification_report(test_y, preds)) # confusion matrix pd.crosstab(test_y, preds)
_____no_output_____
Apache-2.0
Fine_Tuning_BERT_for_Spam_Classification.ipynb
lamiathu/Fine-Tuning-BERT
WeatherPy---- Note* Instructions have been included for each segment. You do not have to follow them exactly, but they are included to help you think through the steps.
# Dependencies and Setup import matplotlib.pyplot as plt import pandas as pd import numpy as np import requests import time import random import json import scipy.stats as st from scipy.stats import linregress # Import API key from api_keys import weather_api_key from api_keys import g_key # Incorporated citipy to de...
_____no_output_____
ADSL
06-Python-APIs_HW/Instructions/starter_code/WeatherPy.ipynb
jmbruner37/6_python_api
Generate Cities List
# List for holding lat_lngs and cities lat_lngs = [] cities = [] # Create a set of random lat and lng combinations lats = np.random.uniform(lat_range[0], lat_range[1], size=1500) lngs = np.random.uniform(lng_range[0], lng_range[1], size=1500) lat_lngs = zip(lats, lngs) # Identify nearest city for each lat, lng combin...
_____no_output_____
ADSL
06-Python-APIs_HW/Instructions/starter_code/WeatherPy.ipynb
jmbruner37/6_python_api
Perform API Calls* Perform a weather check on each city using a series of successive API calls.* Include a print log of each city as it'sbeing processed (with the city number and city name).
print("Beginning Data Retrieval") print("-------------------------------") base_url = "http://api.openweathermap.org/data/2.5/weather?" units = "imperial" url = f"{base_url}appid={weather_api_key}&units={units}&q=" for index, city in enumerate(cities, start = 1): try: response = requests.get(url + city).j...
Beginning Data Retrieval ------------------------------- Processing Record 1 of Set 1 : albany Processing Record 2 of Set 1 : terney City not found. Skipping... Processing Record 3 of Set 1 : pedasi Processing Record 4 of Set 1 : wakkanai Processing Record 5 of Set 1 : talnakh City not found. Skipping... Processing Rec...
ADSL
06-Python-APIs_HW/Instructions/starter_code/WeatherPy.ipynb
jmbruner37/6_python_api
Convert Raw Data to DataFrame* Export the city data into a .csv.* Display the DataFrame
weather_df = pd.DataFrame({ "City" : city_names_ls, "Cloudiness" : cloudiness_ls, "Country" : country_ls, "Date" : date_ls, "Humidity" : humidity_ls, "Lat" : lat_ls, "Lng" : lng_ls, "Max Temp...
_____no_output_____
ADSL
06-Python-APIs_HW/Instructions/starter_code/WeatherPy.ipynb
jmbruner37/6_python_api
Inspect the data and remove the cities where the humidity > 100%.----Skip this step if there are no cities that have humidity > 100%.
# Get the indices of cities that have humidity over 100%. # Make a new DataFrame equal to the city data to drop all humidity outliers by index. # Passing "inplace=False" will make a copy of the city_data DataFrame, which we call "clean_city_data". # Extract relevant fields from the data frame # Export the City_Dat...
_____no_output_____
ADSL
06-Python-APIs_HW/Instructions/starter_code/WeatherPy.ipynb
jmbruner37/6_python_api
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
plt.scatter(weather_df["Lat"], weather_df["Max Temp"], facecolor = "darkblue", edgecolor = "darkgrey") plt.title("City Latitude vs. Max Temperature (07/13/20)") plt.ylabel("Max Temperature (F)") plt.xlabel("Latitude") plt.grid(True) plt.savefig("../Images/City Latitude vs Max Temperature.png") plt.show() print("Th...
_____no_output_____
ADSL
06-Python-APIs_HW/Instructions/starter_code/WeatherPy.ipynb
jmbruner37/6_python_api
Latitude vs. Humidity Plot
plt.scatter(weather_df["Lat"], weather_df["Humidity"], facecolor = "darkblue", edgecolor = "darkgrey") plt.title("City Latitude vs. Humidity (07/13/20)") plt.ylabel("Humidity (%)") plt.xlabel("Latitude") plt.grid(True) plt.savefig("../Images/City Latitude vs Humidity.png") plt.show() print("This plot shows that hu...
_____no_output_____
ADSL
06-Python-APIs_HW/Instructions/starter_code/WeatherPy.ipynb
jmbruner37/6_python_api
Latitude vs. Cloudiness Plot
plt.scatter(weather_df["Lat"], weather_df["Cloudiness"], facecolor = "darkblue", edgecolor = "darkgrey") plt.title("City Latitude vs. Cloudiness (07/13/20)") plt.ylabel("Cloudiness (%)") plt.xlabel("Latitude") plt.grid(True) plt.savefig("../Images/City Latitude vs Cloudiness.png") plt.show() print("This plot shows...
_____no_output_____
ADSL
06-Python-APIs_HW/Instructions/starter_code/WeatherPy.ipynb
jmbruner37/6_python_api
Latitude vs. Wind Speed Plot
plt.scatter(weather_df["Lat"], weather_df["Wind Speed"], facecolor = "darkblue", edgecolor = "darkgrey") plt.title("City Latitude vs. Windspeed (07/13/20)") plt.ylabel("Windspeed (mph)") plt.xlabel("Latitude") plt.grid(True) plt.savefig("../Images/City Latitude vs Windspeed.png") plt.show() print("This plot shows ...
_____no_output_____
ADSL
06-Python-APIs_HW/Instructions/starter_code/WeatherPy.ipynb
jmbruner37/6_python_api
Linear Regression
# OPTIONAL: Create a function to create Linear Regression plots nor_hemi = weather_df.loc[weather_df["Lat"] >= 0] sou_hemi = weather_df.loc[weather_df["Lat"] < 0] def linear_agression(x,y): print(f"The r-squared is : {round(st.pearsonr(x, y)[0],2)}") (slope, intercept, rvalue, pvalue, stderr) = linregress(x, y)...
_____no_output_____
ADSL
06-Python-APIs_HW/Instructions/starter_code/WeatherPy.ipynb
jmbruner37/6_python_api
Northern Hemisphere - Max Temp vs. Latitude Linear Regression
equation = linear_agression(nor_hemi["Lat"], nor_hemi["Max Temp"]) annotate(equation, 10, 40) plt.ylabel("Max Temp (F)") plt.xlabel("Latitude") plt.savefig("../Images/NorHemi Max Temp vs. Latitude Linear Regression.png") print("This linear regression shows that cities gets hotter as get closer to equator in northe...
The r-squared is : -0.65 This linear regression shows that cities gets hotter as get closer to equator in northern hemisphere
ADSL
06-Python-APIs_HW/Instructions/starter_code/WeatherPy.ipynb
jmbruner37/6_python_api
Southern Hemisphere - Max Temp vs. Latitude Linear Regression
equation = linear_agression(sou_hemi["Lat"], sou_hemi["Max Temp"]) annotate(equation, -50, 80) plt.ylabel("Max Temperature (F)") plt.xlabel("Latitude") plt.savefig("../Images/SouHemi Max Temp vs. Latitude Linear Regression.png") print("This linear regression shows that cities gets colder as get away to equator in so...
The r-squared is : 0.74
ADSL
06-Python-APIs_HW/Instructions/starter_code/WeatherPy.ipynb
jmbruner37/6_python_api
Northern Hemisphere - Humidity (%) vs. Latitude Linear Regression
equation = linear_agression(nor_hemi["Lat"], nor_hemi["Humidity"]) annotate(equation, 1, 5) plt.ylabel("Humidity") plt.xlabel("Latitude") plt.savefig("../Images/NorHemi Humidity vs. Latitude Linear Regression.png") print("This linear regression shows that cities' humidity doesn't change much as get closer to equa...
The r-squared is : -0.08
ADSL
06-Python-APIs_HW/Instructions/starter_code/WeatherPy.ipynb
jmbruner37/6_python_api
Southern Hemisphere - Humidity (%) vs. Latitude Linear Regression
equation = linear_agression(sou_hemi["Lat"], sou_hemi["Humidity"]) annotate(equation, -50, 20) plt.ylabel("Humidity") plt.xlabel("Latitude") plt.savefig("../Images/SouHemi Humidity vs. Latitude Linear Regression.png") print("This linear regression shows that cities' humidity doesn't change much as get closer to equa...
The r-squared is : 0.09
ADSL
06-Python-APIs_HW/Instructions/starter_code/WeatherPy.ipynb
jmbruner37/6_python_api
Northern Hemisphere - Cloudiness (%) vs. Latitude Linear Regression
equation = linear_agression(nor_hemi["Lat"], nor_hemi["Cloudiness"]) annotate(equation, 0, 0) plt.ylabel("Cloudiness") plt.xlabel("Latitude") plt.savefig("../Images/NorHemi Cloudiness vs. Latitude Linear Regression.png") print("This linear regression shows that cities' cloudiness doesn't change much as get closer...
The r-squared is : -0.01
ADSL
06-Python-APIs_HW/Instructions/starter_code/WeatherPy.ipynb
jmbruner37/6_python_api
Southern Hemisphere - Cloudiness (%) vs. Latitude Linear Regression
equation = linear_agression(sou_hemi["Lat"], sou_hemi["Cloudiness"]) annotate(equation, -50, 50) plt.ylabel("Cloudiness") plt.xlabel("Latitude") plt.savefig("../Images/SouHemi Cloudiness vs. Latitude Linear Regression.png") print("This linear regression shows that cities' cloudiness doesn't change much as get closer...
The r-squared is : 0.1
ADSL
06-Python-APIs_HW/Instructions/starter_code/WeatherPy.ipynb
jmbruner37/6_python_api
Northern Hemisphere - Wind Speed (mph) vs. Latitude Linear Regression
equation = linear_agression(nor_hemi["Lat"], nor_hemi["Wind Speed"]) annotate(equation, 40, 25) plt.ylabel("Wind Speed") plt.xlabel("Latitude") plt.savefig("../Images/NorHemi Wind Speed vs. Latitude Linear Regression.png") print("This linear regression shows that cities' windiness doesn't change much as get close...
The r-squared is : -0.0
ADSL
06-Python-APIs_HW/Instructions/starter_code/WeatherPy.ipynb
jmbruner37/6_python_api
Southern Hemisphere - Wind Speed (mph) vs. Latitude Linear Regression
equation = linear_agression(sou_hemi["Lat"], sou_hemi["Wind Speed"]) annotate(equation, -50, 25) plt.ylabel("Wind Speed") plt.xlabel("Latitude") plt.savefig("../Images/SouHemi Wind Speed vs. Latitude Linear Regression.png") print("This linear regression shows that cities' windiness doesn't change much as get closer ...
_____no_output_____
ADSL
06-Python-APIs_HW/Instructions/starter_code/WeatherPy.ipynb
jmbruner37/6_python_api
""" Array2D """ class Array2D: def __init__(self,rows, cols, value): self.__cols = cols self.__rows = rows self.__array=[[value for x in range(self.__cols)] for y in range(self.__rows)] def to_string(self): [print("---",end="") for x in range(self.__cols)] print("") ...
7 7 [6, 2] ['1,1,1,1,1,1,1\n', '1,1,1,1,1,1,1\n', '1,1,1,1,1,1,1\n', '1,1,1,1,1,1,1\n', '1,0,0,0,0,0,S\n', '1,1,0,1,1,1,1\n', '1,1,E,1,1,1,1'] --------------------- ['1', '1', '1', '1', '1', '1', '1'] ['1', '1', '1', '1', '1', '1', '1'] ['1', '1', '1', '1', '1', '1', '1'] ['1', '1', '1', '1', '1', '1', '1'] ['1', '0', ...
MIT
4_diciembre1358.ipynb
jorge23amury/daa_2021_1
Run hacked AlphaFold2 on the designed bound states Imports
%load_ext lab_black # Python standard library from glob import glob import os import socket import sys # 3rd party library imports import dask import matplotlib.pyplot as plt import pandas as pd import pyrosetta import numpy as np import scipy import seaborn as sns from tqdm.auto import tqdm # jupyter compatible prog...
running in directory: /mnt/home/pleung/projects/crispy_shifty/projects/crispy_shifties running on node: dig154
MIT
projects/crispy_shifties/03_fold_bound_states.ipynb
proleu/crispy_shifty
Set working directory to the root of the crispy_shifty repoTODO set to projects dir
os.chdir("/home/pleung/projects/crispy_shifty") # os.chdir("/projects/crispy_shifty")
_____no_output_____
MIT
projects/crispy_shifties/03_fold_bound_states.ipynb
proleu/crispy_shifty
Run AF2 on the designed bound statesTODO
from crispy_shifty.utils.io import gen_array_tasks simulation_name = "03_fold_bound_states" design_list_file = os.path.join( os.getcwd(), "projects/crispy_shifties/02_mpnn_bound_states/test_mpnn_states.pair", # TODO ) output_path = os.path.join(os.getcwd(), f"projects/crispy_shifties/{simulation_name}") opti...
_____no_output_____
MIT
projects/crispy_shifties/03_fold_bound_states.ipynb
proleu/crispy_shifty
Collect scorefiles of designed bound states and concatenateTODO change to projects dir
sys.path.insert(0, "~/projects/crispy_shifty") # TODO from crispy_shifty.utils.io import collect_score_file simulation_name = "03_fold_bound_states" output_path = os.path.join(os.getcwd(), f"projects/crispy_shifties/{simulation_name}") if not os.path.exists(os.path.join(output_path, "scores.json")): collect_scor...
/projects/crispy_shifty/envs/crispy/lib/python3.8/site-packages/dask_jobqueue/core.py:20: FutureWarning: tmpfile is deprecated and will be removed in a future release. Please use dask.utils.tmpfile instead. from distributed.utils import tmpfile
MIT
projects/crispy_shifties/03_fold_bound_states.ipynb
proleu/crispy_shifty
Load resulting concatenated scorefileTODO change to projects dir
sys.path.insert(0, "~/projects/crispy_shifty") # TODO from crispy_shifty.utils.io import parse_scorefile_linear output_path = os.path.join(os.getcwd(), f"projects/crispy_shifties/{simulation_name}") scores_df = parse_scorefile_linear(os.path.join(output_path, "scores.json")) scores_df = scores_df.convert_dtypes()
_____no_output_____
MIT
projects/crispy_shifties/03_fold_bound_states.ipynb
proleu/crispy_shifty
Setup for plotting
sns.set( context="talk", font_scale=1, # make the font larger; default is pretty small style="ticks", # make the background white with black lines palette="colorblind", # a color palette that is colorblind friendly! )
_____no_output_____
MIT
projects/crispy_shifties/03_fold_bound_states.ipynb
proleu/crispy_shifty
Data explorationGonna remove the Rosetta sfxn scoreterms for now
from crispy_shifty.protocols.design import beta_nov16_terms scores_df = scores_df[ [term for term in scores_df.columns if term not in beta_nov16_terms] ] print(len(scores_df)) j = 0 for i, r in scores_df.iterrows(): if (r["designed_by"]) == "rosetta": j += 1 print(j)
10
MIT
projects/crispy_shifties/03_fold_bound_states.ipynb
proleu/crispy_shifty
Save a list of outputs
# simulation_name = "03_fold_bound_states" # output_path = os.path.join(os.getcwd(), f"projects/crispy_shifties/{simulation_name}") # with open(os.path.join(output_path, "folded_states.list"), "w") as f: # for path in tqdm(scores_df.index): # print(path, file=f)
_____no_output_____
MIT
projects/crispy_shifties/03_fold_bound_states.ipynb
proleu/crispy_shifty
Prototyping blocks test `fold_bound_state`
%%time from operator import gt, lt import pyrosetta filter_dict = { "mean_plddt": (gt, 85.0), "rmsd_to_reference": (lt, 2.2), "mean_pae_interaction": (lt, 10.0), } rank_on = "mean_plddt" prefix = "mpnn_seq" pyrosetta.init() sys.path.insert(0, "~/projects/crispy_shifty/") # TODO projects from crispy_sh...
_____no_output_____
MIT
projects/crispy_shifties/03_fold_bound_states.ipynb
proleu/crispy_shifty
test `generate_decoys_from_pose`
from operator import gt, lt from crispy_shifty.protocols.folding import generate_decoys_from_pose filter_dict = { "mean_plddt": (gt, 85.0), "rmsd_to_reference": (lt, 2.2), "mean_pae_interaction": (lt, 10.0), } rank_on = "mean_plddt" prefix = "mpnn_seq" tpose = tppose.pose.clone() genr = generate_decoys_...
_____no_output_____
MIT
projects/crispy_shifties/03_fold_bound_states.ipynb
proleu/crispy_shifty
Segmentation of Road from Satellite imagery Importing Libraries
import warnings warnings.filterwarnings('ignore') import os import cv2 #from google.colab.patches import cv2_imshow import numpy as np import tensorflow as tf import pandas as pd from keras.models import Model, load_model from skimage.morphology import label import pickle from keras import backend as K from matplotli...
Drive already mounted at /content/gdrive/; to attempt to forcibly remount, call drive.mount("/content/gdrive/", force_remount=True). /content/gdrive/My Drive/MapSegClean
MIT
Train_and_Test_Notebooks/ResNet101_RoadTest.ipynb
parshwa1999/Map-Segmentation
Defining Custom Loss functions and accuracy Metric.
#Source: https://towardsdatascience.com/metrics-to-evaluate-your-semantic-segmentation-model-6bcb99639aa2 from keras import backend as K def iou_coef(y_true, y_pred, smooth=1): intersection = K.sum(K.abs(y_true * y_pred), axis=[1,2,3]) union = K.sum(y_true,[1,2,3])+K.sum(y_pred,[1,2,3])-intersection iou = K.mean(...
_____no_output_____
MIT
Train_and_Test_Notebooks/ResNet101_RoadTest.ipynb
parshwa1999/Map-Segmentation
Defining Our Model
pip install -U segmentation-models from keras.models import Model, load_model import tensorflow as tf from keras.layers import Input from keras.layers.core import Dropout, Lambda from keras.layers.convolutional import Conv2D, Conv2DTranspose from keras.layers.pooling import MaxPooling2D from keras.layers.merge import c...
WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/keras/backend/tensorflow_backend.py:541: The name tf.placeholder is deprecated. Please use tf.compat.v1.placeholder instead. WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/keras/backend/tensorflow_backend.py:66: The name tf.get_default_grap...
MIT
Train_and_Test_Notebooks/ResNet101_RoadTest.ipynb
parshwa1999/Map-Segmentation
HYPER_PARAMETERS
LEARNING_RATE = 0.0001
_____no_output_____
MIT
Train_and_Test_Notebooks/ResNet101_RoadTest.ipynb
parshwa1999/Map-Segmentation
Initializing Callbacks
#from tensorboardcolab import TensorBoardColab, TensorBoardColabCallback from keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau from datetime import datetime model_path = "./Models/Resnet_road_weights.h5" checkpointer = ModelCheckpoint(model_path, monitor="val_loss", ...
_____no_output_____
MIT
Train_and_Test_Notebooks/ResNet101_RoadTest.ipynb
parshwa1999/Map-Segmentation
Compiling the model
opt = keras.optimizers.adam(LEARNING_RATE) model.compile( optimizer=opt, loss=soft_dice_loss, metrics=[iou_coef])
WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/keras/optimizers.py:793: The name tf.train.Optimizer is deprecated. Please use tf.compat.v1.train.Optimizer instead.
MIT
Train_and_Test_Notebooks/ResNet101_RoadTest.ipynb
parshwa1999/Map-Segmentation
Testing our Model On Test Images
model.load_weights("Models/Resnet_road_weights.h5") import cv2 import glob import numpy as np import h5py #test_images = np.array([cv2.imread(file) for file in glob.glob("/home/bisag/Desktop/Road-Segmentation/I/")]) #test_masks = np.array([cv2.imread(file) for file in glob.glob("/home/bisag/Desktop/Road-Segmentation/M...
_____no_output_____
MIT
Train_and_Test_Notebooks/ResNet101_RoadTest.ipynb
parshwa1999/Map-Segmentation
Just Test
"""Test""" import cv2 import glob import numpy as np import h5py #test_images = np.array([cv2.imread(file) for file in glob.glob("/home/bisag/Desktop/Road-Segmentation/I/")]) #test_masks = np.array([cv2.imread(file) for file in glob.glob("/home/bisag/Desktop/Road-Segmentation/M/")]) test_images = [] files = glob.glob...
_____no_output_____
MIT
Train_and_Test_Notebooks/ResNet101_RoadTest.ipynb
parshwa1999/Map-Segmentation
Seaborn (Working on the diabetes dataset)
import seaborn as sns import matplotlib.pyplot as plt import pandas as pd df = pd.read_csv('diabetes.csv') sns.lmplot(x='Age', y='BloodPressure', data=df) plt.show() sns.lmplot(x='Age', y='Glucose', data=df, fit_reg=False, # No regression line hue='Outcome' # color by evaluation stage )...
_____no_output_____
MIT
Session_2_ and_3_Seaborn.ipynb
reeha-parkar/applied-statistics
Homework 4Today we'll start by reproducing the DQN and then try improving it with the tricks we learned on the lecture:* Target networks* Double q-learning* Prioritized experience replay* Dueling DQN* Bootstrap DQN
import matplotlib.pyplot as plt import numpy as np %matplotlib inline # If you are running on a server, launch xvfb to record game videos # Please make sure you have xvfb installed import os if type(os.environ.get("DISPLAY")) is not str or len(os.environ.get("DISPLAY")) == 0: !bash ../xvfb start os.environ['D...
_____no_output_____
Unlicense
week04_approx_rl/homework_lasagne.ipynb
Kirili4ik/Practical_RL
Processing game image (2 pts)Raw Atari images are large, 210x160x3 by default. However, we don't need that level of detail in order to learn them.We can thus save a lot of time by preprocessing game image, including* Resizing to a smaller shape* Converting to grayscale* Cropping irrelevant image parts
from gym.core import ObservationWrapper from gym.spaces import Box from scipy.misc import imresize class PreprocessAtari(ObservationWrapper): def __init__(self, env): """A gym wrapper that crops, scales image into the desired shapes and optionally grayscales it.""" ObservationWrapper.__init__(sel...
_____no_output_____
Unlicense
week04_approx_rl/homework_lasagne.ipynb
Kirili4ik/Practical_RL
Building a DQN (2 pts)Here we define a simple agent that maps game images into Qvalues using simple convolutional neural network.![scheme](https://s18.postimg.cc/gbmsq6gmx/dqn_scheme.png)
# setup theano/lasagne. Prefer GPU. Fallback to CPU (will print warning) %env THEANO_FLAGS = floatX = float32 import theano import lasagne from lasagne.layers import * from theano import tensor as T # observation observation_layer = InputLayer( (None,)+observation_shape) # game image, [batch,64,64] # 4-tick windo...
_____no_output_____
Unlicense
week04_approx_rl/homework_lasagne.ipynb
Kirili4ik/Practical_RL
Define agentHere you will need to declare how your agent works* `observation_layers` and `action_layers` are the input and output of agent in MDP.* `policy_estimators` must contain whatever you need for training * In our case, that's `qvalues_layer`, but you'll need to add more when implementing target network.* agent...
from agentnet.agent import Agent # agent agent = Agent(observation_layers=<YOUR CODE>, policy_estimators=<YOUR CODE>, action_layers=<YOUR CODE>, agent_states={new_wnd: prev_wnd},)
_____no_output_____
Unlicense
week04_approx_rl/homework_lasagne.ipynb
Kirili4ik/Practical_RL
Create and manage a pool of Atari sessions to play with* To make training more stable, we shall have an entire batch of game sessions each happening independent of others* Why several parallel agents help training: http://arxiv.org/pdf/1602.01783v1.pdf* Alternative approach: store more sessions: https://www.cs.toronto...
from agentnet.experiments.openai_gym.pool import EnvPool pool = EnvPool(agent, make_env, n_games=16) # 16 parallel game sessions %%time # interact for 7 ticks _, action_log, reward_log, _, _, _ = pool.interact(5) print('actions:') print(action_log[0]) print("rewards") print(reward_log[0]) # load first sessions (this...
_____no_output_____
Unlicense
week04_approx_rl/homework_lasagne.ipynb
Kirili4ik/Practical_RL
Q-learningWe train our agent based on sessions it has played in `pool.update(SEQ_LENGTH)`To do so, we first obtain sequences of observations, rewards, actions, q-values, etc.Actions and rewards have shape `[n_games,seq_length]`, q-values are `[n_games,seq_length,n_actions]`
# get agent's Qvalues obtained via experience replay replay = pool.experience_replay actions, rewards, is_alive = replay.actions[0], replay.rewards, replay.is_alive _, _, _, _, qvalues = agent.get_sessions( replay, session_length=SEQ_LENGTH, experience_replay=True, ) assert actions.ndim == rewards.ndim =...
_____no_output_____
Unlicense
week04_approx_rl/homework_lasagne.ipynb
Kirili4ik/Practical_RL
Demo runas usual...
action_layer.epsilon.set_value(0.05) untrained_reward = np.mean(pool.evaluate(save_path="./records", record_video=True)) # show video from IPython.display import HTML import os video_names = list( filter(lambda s: s.endswith(".mp4"), os.listdir("./records/"))) HTML(""" <vi...
_____no_output_____
Unlicense
week04_approx_rl/homework_lasagne.ipynb
Kirili4ik/Practical_RL
Training loop
# starting epoch epoch_counter = 1 # full game rewards rewards = {} loss, reward_per_tick, reward = 0, 0, 0 from tqdm import trange from IPython.display import clear_output for i in trange(150000): # update agent's epsilon (in e-greedy policy) current_epsilon = 0.05 + 0.45*np.exp(-epoch_counter/20000.) ...
_____no_output_____
Unlicense
week04_approx_rl/homework_lasagne.ipynb
Kirili4ik/Practical_RL
Evaluating results * Here we plot learning curves and sample testimonials
import pandas as pd plt.plot(*zip(*sorted(rewards.items(), key=lambda k: k[0]))) from agentnet.utils.persistence import save, load save(action_layer, "pacman.pcl") action_layer.epsilon.set_value(0.05) rw = pool.evaluate(n_games=20, save_path="./records", record_video=False) print("mean session score=%f.5" % np.mean(rw)...
_____no_output_____
Unlicense
week04_approx_rl/homework_lasagne.ipynb
Kirili4ik/Practical_RL
Assignment part I (5 pts)We'll start by implementing target network to stabilize training.There are two ways to do so: __1)__ Manually write lasagne network, or clone it via [one of those methods](https://github.com/Lasagne/Lasagne/issues/720).You will need to implement loading weights from original network to target ...
from lasagne.layers import * class DuelingQvaluesLayer(MergeLayer): def get_output_for(self, inputs, **tags): V, A = inputs return <YOUR CODE: add them up :)> def get_output_shape_for(self, input_shapes, **tags): V_shape, A_shape=input_shapes assert len( V_shape) =...
_____no_output_____
Unlicense
week04_approx_rl/homework_lasagne.ipynb
Kirili4ik/Practical_RL
__mlmachine - GroupbyImputer, KFoldEncoder, and Skew Correction__Welcome to Example Notebook 2. If you're new to mlmachine, check out [Example Notebook 1](https://github.com/petersontylerd/mlmachine/blob/master/notebooks/mlmachine_part_1.ipynb).Check out the [GitHub repository](https://github.com/petersontylerd/mlmachi...
# import libraries import numpy as np import pandas as pd # import mlmachine tools import mlmachine as mlm from mlmachine.data import titanic # use titanic() function to create DataFrames for training and validation datasets df_train, df_valid = titanic() # ordinal encoding hierarchy ordinal_encodings = {"Pclass": [...
~/.pyenv/versions/main37/lib/python3.7/site-packages/sklearn/externals/joblib/__init__.py:15: FutureWarning: sklearn.externals.joblib is deprecated in 0.21 and will be removed in 0.23. Please import this functionality directly from joblib, which can be installed with: pip install joblib. If this warning is raised when ...
MIT
notebooks/mlmachine_part_2.ipynb
klahrich/mlmachine
--- Assessment---Each `Machine()` object contains a method for summarizing missingness in tabular form and in graphical form:
# generate missingness summary for training data mlmachine_titanic_train.eda_missing_summary(display_df=True)
_____no_output_____
MIT
notebooks/mlmachine_part_2.ipynb
klahrich/mlmachine
---By default, this method acts on the `data` attribute associated with `mlmachine_train`. Let's do the same for the validation dataset:
# generate missingness summary for validation data mlmachine_titanic_valid.eda_missing_summary(display_df=True)
_____no_output_____
MIT
notebooks/mlmachine_part_2.ipynb
klahrich/mlmachine
---Next, we need to determine if there are features with missing values in the training data, but not the validation data, and vice versa. This informs how we should set up our transformation pipeline. For example, if a feature has missing values in the validation dataset, but not the training dataset, we will still wa...
# generate missingness comparison summary mlmachine_titanic_train.missing_column_compare( validation_data=mlmachine_titanic_valid.data, )
Feature has missing values in validation data, not training data. {'Fare'} Feature has missing values in training data, not validation data. {'Embarked'}
MIT
notebooks/mlmachine_part_2.ipynb
klahrich/mlmachine
---The key observation here is that "Fare" is fully populated in the training data, but not the validation data. We need to make sure our pipeline learns how to impute these missing values based on the training data, despite the fact that the training data is not missing any values in this feature. --- GroupbyImputer--...
# import mlmachine tools from mlmachine.features.preprocessing import GroupbyImputer # instantiate GroupbyImputer to fill "Age" mean, grouped by "SibSp" impute = GroupbyImputer(null_column="Age", groupby_column="SibSp", strategy="mean") impute.fit_transform(mlmachine_titanic_train.data[["Age","SibSp"]]) display(impute...
_____no_output_____
MIT
notebooks/mlmachine_part_2.ipynb
klahrich/mlmachine
---In the code snippet above, we mean impute "Age", grouped by "SibSp". We pass "Age" to the `null_column` parameter to indicate which column contains the nulls, and pass "SibSp" to the `groupby_column` parameter. The strategy parameter receives the same instructions as Scikit-learn's `SimpleImputer()` - "mean", "media...
# import libraries from sklearn.impute import SimpleImputer from sklearn.pipeline import make_pipeline # import mlmachine tools from mlmachine.features.preprocessing import ( DataFrameSelector, PandasTransformer, PandasFeatureUnion, ) # create imputation PandasFeatureUnion pipeline impute_pipe = PandasFea...
_____no_output_____
MIT
notebooks/mlmachine_part_2.ipynb
klahrich/mlmachine
---`GroupbyImputer()` makes two appearances in this `PandasFeatureUnion()` operation. On line 4, we groupby the feature "SibSp" to impute the mean "Age" value, and on line 8 we groupby the feature "Pclass" to impute the mean "Fare" value. Imputations for "Embarked" and "Cabin" are completed in straightforward fashion -...
# import libraries from sklearn.preprocessing import KBinsDiscretizer # create simple encoding PandasFeatureUnion pipeline encode_pipe = PandasFeatureUnion([ ("bin", make_pipeline( DataFrameSelector(include_columns=["Age"]), PandasTransformer(KBinsDiscretizer(encode="ordinal")) )), ("select...
_____no_output_____
MIT
notebooks/mlmachine_part_2.ipynb
klahrich/mlmachine
---This operation returns a binned version of "Age", as well as the original "Age" and "Pclass" features.
mlmachine_titanic_train.data[:10]
_____no_output_____
MIT
notebooks/mlmachine_part_2.ipynb
klahrich/mlmachine
---Next, we target encode both "Pclass" and "Age_binned_5" using mean encoding, CatBoost encoding and Weight of Evidence encoding as provided by the package category_encoders. 
# import libraries from sklearn.model_selection import KFold from category_encoders import WOEEncoder, TargetEncoder, CatBoostEncoder # import mlmachine tools from mlmachine.features.preprocessing import KFoldEncoder # create KFold encoding PandasFeatureUnion pipeline target_encode_pipe = PandasFeatureUnion([ ("t...
_____no_output_____
MIT
notebooks/mlmachine_part_2.ipynb
klahrich/mlmachine
---Let's review the key `KFoldEncoder()` parameters:- `target`: the target attribute of our mlmachine_titanic_train object- `cv`: a cross-validation object- `encoder`: a target encoder class`KFoldEncoder()` learns the encoded values on the training data, and applies the values to the out-of-fold observations. On the va...
# generate skewness summary mlmachine_titanic_train.skew_summary()
_____no_output_____
MIT
notebooks/mlmachine_part_2.ipynb
klahrich/mlmachine
---The `skew_summary()` method returns a `DataFrame` that summarizes the skew for each feature, along with a "Percent zero" column, which informs us of the percentage of values in the feature that are zero. --- Skew correction---mlmachine contains a class called `DualTransformer()`, which, by default, applies both Yeo-...
# import mlmachine tools from mlmachine.features.preprocessing import DualTransformer # create skew correction PandasFeatureUnion pipeline skew_pipe = PandasFeatureUnion([ ("skew", make_pipeline( DataFrameSelector(include_columns=["Age"]), DualTransformer(), )), ]) # fit and transform trai...
_____no_output_____
MIT
notebooks/mlmachine_part_2.ipynb
klahrich/mlmachine
---`DualTransformer()` adds the features "Age_BoxCox" and "Age_YeoJohnson". Let's execute `skew_summary()` again to see if `DualTransformer()` addressed the skew in our original feature:"Age_BoxCox" and "Age_YeoJohnson" have a skew of 0.0286 and 0.0483, respectively.
# generate skewness summary mlmachine_titanic_train.skew_summary()
_____no_output_____
MIT
notebooks/mlmachine_part_2.ipynb
klahrich/mlmachine
Tools to analyze the results of Gate simulations
#hide from nbdev.showdoc import *
_____no_output_____
Apache-2.0
nbs/01_analysis.ipynb
dmitryhits/ProtonBeamTherapy
Dependencies
#export import pandas as pd import uproot as rt import awkward as ak from scipy.stats import moyal import matplotlib.pyplot as plt import numpy as np import math from scipy import stats from scipy.stats import rv_continuous # import pylandau from matplotlib.pyplot import hist2d import matplotlib.colors as mcolors impo...
_____no_output_____
Apache-2.0
nbs/01_analysis.ipynb
dmitryhits/ProtonBeamTherapy
ph0 = get_phasespace_df('2021May03_141349', 0)ph5 = get_phasespace_df('2021May03_141349', 5)ph10 = get_phasespace_df('2021May03_141349', 10)ph15 = get_phasespace_df('2021May03_141349', 15)ph19 = get_phasespace_df('2021May03_141349', 19)
get_Ekin(ph0).hist(bins=50) get_Ekin(ph19).hist(bins=50) print(round(stats.tstd(get_Ekin(ph0), (175, 200)), 2), 'MeV') print(round(stats.tstd(get_Ekin(ph19), (55, 90)), 2), 'MeV') from matplotlib import colors x0 = ph19[(ph19["ParticleName"]=='proton') & (ph19['CreatorProcess'] == 0) & (ph19['NuclearProcess'] == 0)]['...
_____no_output_____
Apache-2.0
nbs/01_analysis.ipynb
dmitryhits/ProtonBeamTherapy
Lateral positions of protons in the last phantom layer. On the left are all protons, on the right are only the primary protons that did not experience nuclear scattering.
x0 = ph19[(ph19["ParticleName"]=='proton') & (ph19['CreatorProcess'] == 0) & (ph19['NuclearProcess'] == 0)]['X'] ekin0 = ph19[(ph19["ParticleName"]=='proton') & (ph19['CreatorProcess'] == 0) & (ph19['NuclearProcess'] == 0)]['Ekine'] x1 = ph19[(ph19["ParticleName"]=='proton')]['X'] ekin1 = ph19[(ph19["ParticleName"]...
_____no_output_____
Apache-2.0
nbs/01_analysis.ipynb
dmitryhits/ProtonBeamTherapy
Kinetic energy deposited by particle versus the position of the hit (left) all protons (right) protons from the primary beam that did not experience nuclear scattering
ph = pd.merge(ph0, ph5, on="EventID", suffixes=("", "_5")) ph = pd.merge(ph, ph10, on="EventID", suffixes=("", "_10")) ph = pd.merge(ph, ph15, on="EventID", suffixes=("", "_15")) ph = pd.merge(ph, ph19, on="EventID", suffixes=("", "_19")) def select(ph): result = (ph[f"CreatorProcess"] == 0) & (ph[f"ParticleName"] ...
_____no_output_____
Apache-2.0
nbs/01_analysis.ipynb
dmitryhits/ProtonBeamTherapy
Example showing energy deposition with 3 sensors
df2 = get_df_subentry2('results/TrackerHits.root') edep = get_edep_data(df2, sensor=0) _ = plt.hist(edep, bins=100, range=(0,1000)) _ = plt.hist(get_edep_data(df2, sensor=1), bins=100, range=(0,1000)) _ = plt.hist(get_edep_data(df2, sensor=2), bins=100, range=(0,1000)) null_columns = [col for col in df2.columns if df2[...
_____no_output_____
Apache-2.0
nbs/01_analysis.ipynb
dmitryhits/ProtonBeamTherapy
序列到序列学习(seq2seq)在`seq2seq`中,特定的“&lt;eos&gt;”表示序列结束词元。一旦输出序列生成此词元,模型就会停止预测。在循环神经网络解码器的初始化时间步,有两个特定的设计决定:首先,特定的“&lt;bos&gt;”表示序列开始词元,它是解码器的输入序列的第一个词元。其次,使用循环神经网络编码器最终的隐状态来初始化解码器的隐状态。这种设计将输入序列的编码信息送入到解码器中来生成输出序列的。在其他一些设计中 :cite:`Cho.Van-Merrienboer.Gulcehre.ea.2014`,编码器最终的隐状态在每一个时间步都作为解码器的输入序列的一部分。类似于 :`language_model`中...
import collections import math import tensorflow as tf from d2l import tensorflow as d2l
_____no_output_____
MIT
09_recurrent_neural_networks/tf_seq2seq.ipynb
JiaheXu/Machine-Learning-Codebase
编码器从技术上讲,编码器将长度可变的输入序列转换成形状固定的上下文变量$\mathbf{c}$,并且将输入序列的信息在该上下文变量中进行编码。如 :numref:`fig_seq2seq`所示,可以使用循环神经网络来设计编码器。考虑由一个序列组成的样本(批量大小是$1$)。假设输入序列是$x_1, \ldots, x_T$,其中$x_t$是输入文本序列中的第$t$个词元。在时间步$t$,循环神经网络将词元$x_t$的输入特征向量$\mathbf{x}_t$和$\mathbf{h} _{t-1}$(即上一时间步的隐状态)转换为$\mathbf{h}_t$(即当前步的隐状态)。使用一个函数$f$来描述循环神经网络的循环层所做的变换:$...
class Encoder(tf.keras.layers.Layer): """编码器-解码器架构的基本编码器接口""" def __init__(self, **kwargs): super(Encoder, self).__init__(**kwargs) def call(self, X, *args, **kwargs): raise NotImplementedError #@save class Seq2SeqEncoder(d2l.Encoder): """用于序列到序列学习的循环神经网络编码器""" def __init__(self, vo...
_____no_output_____
MIT
09_recurrent_neural_networks/tf_seq2seq.ipynb
JiaheXu/Machine-Learning-Codebase