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 |
|---|---|---|---|---|---|
Discriminator | #!L
class Discriminator(nn.Module):
def __init__(self, in_dim, hidden_dim=100):
super(Discriminator, self).__init__()
self.fc1 = nn.Linear(in_dim, hidden_dim)
nn.init.xavier_normal_(self.fc1.weight)
nn.init.constant_(self.fc1.bias, 0.0)
self.fc2 = nn.Linear(... | _____no_output_____ | MIT | homework03/homework03_part3_gan_basic.ipynb | VendettaPrime/Practical_DL |
Define updates and losses | #!L
generator = Generator(NOISE_DIM, out_dim = 2)
discriminator = Discriminator(in_dim = 2)
lr = 0.001
g_optimizer = optim.Adam(generator.parameters(), lr=lr, betas=(0.5, 0.999))
d_optimizer = optim.Adam(discriminator.parameters(), lr=lr, betas=(0.5, 0.999)) | _____no_output_____ | MIT | homework03/homework03_part3_gan_basic.ipynb | VendettaPrime/Practical_DL |
Notice we are using ADAM optimizer with `beta1=0.5` for both discriminator and discriminator. This is a common practice and works well. Motivation: models should be flexible and adapt itself rapidly to the distributions. You can try different optimizers and parameters. | #!L
################################
# IMPLEMENT HERE
# Define the g_loss and d_loss here
# these are the only lines of code you need to change to implement GAN game
def g_loss():
# if TASK == 1:
# do something
return # TODO
def d_loss():
# if TASK == 1:
# do something
return # ... | _____no_output_____ | MIT | homework03/homework03_part3_gan_basic.ipynb | VendettaPrime/Practical_DL |
Get real data | #!L
data = sample_true(100000)
def iterate_minibatches(X, batchsize, y=None):
perm = np.random.permutation(X.shape[0])
for start in range(0, X.shape[0], batchsize):
end = min(start + batchsize, X.shape[0])
if y is None:
yield X[perm[start:end]]
else:
yield X[... | _____no_output_____ | MIT | homework03/homework03_part3_gan_basic.ipynb | VendettaPrime/Practical_DL |
**Legend**:- Blue dots are generated samples. - Colored histogram at the back shows density of real data. - And with arrows we show gradients of the discriminator -- they are the directions that discriminator pushes generator's samples. Train the model | #!L
from IPython import display
plt.xlim(lims)
plt.ylim(lims)
num_epochs = 100
batch_size = 64
# ===========================
# IMPORTANT PARAMETER:
# Number of D updates per G update
# ===========================
k_d, k_g = 4, 1
accs = []
try:
for epoch in range(num_epochs):
for input_data in iterate_m... | _____no_output_____ | MIT | homework03/homework03_part3_gan_basic.ipynb | VendettaPrime/Practical_DL |
> **Copyright (c) 2020 Skymind Holdings Berhad**> **Copyright (c) 2021 Skymind Education Group Sdn. Bhd.**Licensed 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 http://www.apache.org/licenses/LICENSE-2.0/Un... | """
install torch(PyTorch) and transformers
to install them type in your terminal:
pip install torch
pip install transformers
"""
# import the necessary library
from transformers import pipeline
# write your context (where model seeks the answer for the question)
context = """
You can add your own context here. Try to... | _____no_output_____ | Apache-2.0 | nlp-labs/Day_09/QnA_Model/QnA_Handson.ipynb | skymind-talent/nlp-traininglabs |
1. Import libraries | #----------------------------Reproducible----------------------------------------------------------------------------------------
import numpy as np
import tensorflow as tf
import random as rn
import os
seed=0
os.environ['PYTHONHASHSEED'] = str(seed)
np.random.seed(seed)
rn.seed(seed)
#session_conf = tf.ConfigProto(i... | _____no_output_____ | MIT | Python/AbsoluteAndOtherAlgorithms/8ProstateGE/AEFS_64.ipynb | xinxingwu-uk/UFS |
2. Loading data | data_path="./Dataset/Prostate_GE.mat"
Data = scipy.io.loadmat(data_path)
data_arr=Data['X']
label_arr=Data['Y'][:, 0]-1
Data=MinMaxScaler(feature_range=(0,1)).fit_transform(data_arr)
C_train_x,C_test_x,C_train_y,C_test_y= train_test_split(Data,label_arr,test_size=0.2,random_state=seed)
print('Shape of C_train_x: ' ... | _____no_output_____ | MIT | Python/AbsoluteAndOtherAlgorithms/8ProstateGE/AEFS_64.ipynb | xinxingwu-uk/UFS |
3. Model | train=(C_train_x,C_train_x)
test=(C_test_x,C_test_x)
start = time.clock()
C_train_selected_x, C_test_selected_x = AEFS((train[0], train[0]), (test[0], test[0]), key_feture_number)
time_cost=time.clock() - start
write_to_csv(np.array([time_cost]),"./log/AEFS_time"+str(key_feture_number)+".csv") | y_train.shape (72, 5966)
alpha 0.001
WARNING:tensorflow:From /usr/local/lib/python3.7/site-packages/tensorflow/python/ops/init_ops.py:1251: calling VarianceScaling.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.
Instructions for updating:
Call initializer... | MIT | Python/AbsoluteAndOtherAlgorithms/8ProstateGE/AEFS_64.ipynb | xinxingwu-uk/UFS |
4. Classifying Extra Trees | train_feature=C_train_x
train_label=C_train_y
test_feature=C_test_x
test_label=C_test_y
print('Shape of train_feature: ' + str(train_feature.shape))
print('Shape of train_label: ' + str(train_label.shape))
print('Shape of test_feature: ' + str(test_feature.shape))
print('Shape of test_label: ' + str(test_label.shap... | Shape of train_feature: (81, 64)
Shape of train_label: (81,)
Shape of test_feature: (21, 64)
Shape of test_label: (21,)
Training accuracy: 1.0
Training accuracy: 1.0
Testing accuracy: 0.8571428571428571
Testing accuracy: 0.8571428571428571
| MIT | Python/AbsoluteAndOtherAlgorithms/8ProstateGE/AEFS_64.ipynb | xinxingwu-uk/UFS |
6. Reconstruction loss | from sklearn.linear_model import LinearRegression
def mse_check(train, test):
LR = LinearRegression(n_jobs = -1)
LR.fit(train[0], train[1])
MSELR = ((LR.predict(test[0]) - test[1]) ** 2).mean()
return MSELR
train_feature_tuple=(C_train_selected_x,C_train_x)
test_feature_tuple=(C_test_selected_x,C_test_... | 0.27951798104721787
| MIT | Python/AbsoluteAndOtherAlgorithms/8ProstateGE/AEFS_64.ipynb | xinxingwu-uk/UFS |
Deprecated - Connecting Brain region through BAMS informationThis script connects brain regions through BAMS conenctivity informtation.However, at this level the connectivity information has no reference to the original, and that is not ok. Thereby do **not** use this. | ### DEPRECATED
import pandas as pd
import re
import itertools
from difflib import SequenceMatcher
root = "Data/csvs/basal_ganglia/regions"
sim_csv_loc = "/region_similarity.csv"
def similar(a, b):
return SequenceMatcher(None, a, b).ratio()
## Prepare regions and regions_other csvs
df_all_regions = pd.read_cs... | Added 6124 relationships of type EQUALS
| CC-BY-4.0 | 1. Extending the dataset with data from other sources/X - Deprecated - Connecting the regions through BAMS information.ipynb | marenpg/jupyter_basal_ganglia |
Tile Coding---Tile coding is an innovative way of discretizing a continuous space that enables better generalization compared to a single grid-based approach. The fundamental idea is to create several overlapping grids or _tilings_; then for any given sample value, you need only check which tiles it lies in. You can t... | # Import common libraries
import sys
import gym
import numpy as np
import matplotlib.pyplot as plt
# Set plotting options
%matplotlib inline
plt.style.use('ggplot')
np.set_printoptions(precision=3, linewidth=120) | _____no_output_____ | MIT | tile-coding/Tile_Coding.ipynb | kw90/deep-reinforcement-learning |
2. Specify the Environment, and Explore the State and Action SpacesWe'll use [OpenAI Gym](https://gym.openai.com/) environments to test and develop our algorithms. These simulate a variety of classic as well as contemporary reinforcement learning tasks. Let's begin with an environment that has a continuous state spac... | # Create an environment
env = gym.make('Acrobot-v1')
env.seed(505);
# Explore state (observation) space
print("State space:", env.observation_space)
print("- low:", env.observation_space.low)
print("- high:", env.observation_space.high)
# Explore action space
print("Action space:", env.action_space) | [33mWARN: gym.spaces.Box autodetected dtype as <class 'numpy.float32'>. Please provide explicit dtype.[0m
State space: Box(6,)
- low: [ -1. -1. -1. -1. -12.566 -28.274]
- high: [ 1. 1. 1. 1. 12.566 28.274]
Action space: Discrete(3)
| MIT | tile-coding/Tile_Coding.ipynb | kw90/deep-reinforcement-learning |
Note that the state space is multi-dimensional, with most dimensions ranging from -1 to 1 (positions of the two joints), while the final two dimensions have a larger range. How do we discretize such a space using tiles? 3. TilingLet's first design a way to create a single tiling for a given state space. This is very si... | def float_range(start: float, stop: float, step_size: float):
count: int = 0
while True:
temp = start + count * step_size
if step_size > 0 and temp >= stop:
break
if step_size < 0 and temp <= stop:
break
yield temp
count += 1
def create_tiling_grid... | _____no_output_____ | MIT | tile-coding/Tile_Coding.ipynb | kw90/deep-reinforcement-learning |
You can now use this function to define a set of tilings that are a little offset from each other. | def create_tilings(low, high, tiling_specs):
"""Define multiple tilings using the provided specifications.
Parameters
----------
low : array_like
Lower bounds for each dimension of the continuous space.
high : array_like
Upper bounds for each dimension of the continuous space.
t... | _____no_output_____ | MIT | tile-coding/Tile_Coding.ipynb | kw90/deep-reinforcement-learning |
It may be hard to gauge whether you are getting desired results or not. So let's try to visualize these tilings. | from matplotlib.lines import Line2D
def visualize_tilings(tilings):
"""Plot each tiling as a grid."""
prop_cycle = plt.rcParams['axes.prop_cycle']
colors = prop_cycle.by_key()['color']
linestyles = ['-', '--', ':']
legend_lines = []
fig, ax = plt.subplots(figsize=(10, 10))
for i, grid in e... | _____no_output_____ | MIT | tile-coding/Tile_Coding.ipynb | kw90/deep-reinforcement-learning |
Great! Now that we have a way to generate these tilings, we can next write our encoding function that will convert any given continuous state value to a discrete vector. 4. Tile EncodingImplement the following to produce a vector that contains the indices for each tile that the input state value belongs to. The shape o... | def discretize(sample, grid):
"""Discretize a sample as per given grid.
Parameters
----------
sample : array_like
A single sample from the (original) continuous space.
grid : list of array_like
A list of arrays containing split points for each dimension.
Returns
---... |
Samples:
[(-1.2, -5.1), (-0.75, 3.25), (-0.5, 0.0), (0.25, -1.9), (0.15, -1.75), (0.75, 2.5), (0.7, -3.7), (1.0, 5.0)]
Encoded samples:
[[(0, 0), (0, 0), (0, 0)], [(1, 8), (1, 8), (0, 7)], [(2, 5), (2, 5), (2, 4)], [(6, 3), (6, 3), (5, 2)], [(6, 3), (5, 3), (5, 2)], [(9, 7), (8, 7), (8, 7)], [(8, 1), (8, 1), (8, 0)],... | MIT | tile-coding/Tile_Coding.ipynb | kw90/deep-reinforcement-learning |
Note that we did not flatten the encoding above, which is why each sample's representation is a pair of indices for each tiling. This makes it easy to visualize it using the tilings. | from matplotlib.patches import Rectangle
def visualize_encoded_samples(samples, encoded_samples, tilings, low=None, high=None):
"""Visualize samples by activating the respective tiles."""
samples = np.array(samples) # for ease of indexing
# Show tiling grids
ax = visualize_tilings(tilings)
#... | _____no_output_____ | MIT | tile-coding/Tile_Coding.ipynb | kw90/deep-reinforcement-learning |
Inspect the results and make sure you understand how the corresponding tiles are being chosen. Note that some samples may have one or more tiles in common. 5. Q-Table with Tile CodingThe next step is to design a special Q-table that is able to utilize this tile coding scheme. It should have the same kind of interface a... | class QTable:
"""Simple Q-table."""
def __init__(self, state_size, action_size):
"""Initialize Q-table.
Parameters
----------
state_size : tuple
Number of discrete values along each dimension of state space.
action_size : int
Number of di... | QTable(): size = (10, 10, 2)
QTable(): size = (10, 10, 2)
QTable(): size = (10, 10, 2)
TiledQTable(): no. of internal tables = 3
[GET] Q((0.25, -1.9), 0) = 0.0
[UPDATE] Q((0.15, -1.75), 0) = 1.0
[GET] Q((0.25, -1.9), 0) = 0.06666666666666667
| MIT | tile-coding/Tile_Coding.ipynb | kw90/deep-reinforcement-learning |
If you update the q-value for a particular state (say, `(0.25, -1.91)`) and action (say, `0`), then you should notice the q-value of a nearby state (e.g. `(0.15, -1.75)` and same action) has changed as well! This is how tile-coding is able to generalize values across the state space better than a single uniform grid. ... | class QLearningAgentTileCoding:
"""Q-Learning agent that can act on a continuous state space by discretizing it."""
def __init__(self, env, tiled_q_table, alpha=0.02, gamma=0.99,
epsilon=1.0, epsilon_decay_rate=0.9995, min_epsilon=.01, seed=123):
"""Initialize variables, create grid fo... | _____no_output_____ | MIT | tile-coding/Tile_Coding.ipynb | kw90/deep-reinforcement-learning |
Importando biblioteca Pandas | import pandas as pd | _____no_output_____ | MIT | aulas/aula2.ipynb | artuguen28/Do_Zero_Ao_DS |
Carregando o dataset na variável data | data = pd.read_csv('datasets\kc_house_data.csv')
| _____no_output_____ | MIT | aulas/aula2.ipynb | artuguen28/Do_Zero_Ao_DS |
Selecionando pelos nomes | print(data[['id', 'date', 'price']]) | _____no_output_____ | MIT | aulas/aula2.ipynb | artuguen28/Do_Zero_Ao_DS |
Selecionando pelos índices | print(data.iloc[0:10, 1:4]) | date price bedrooms
0 20141013T000000 221900.0 3
1 20141209T000000 538000.0 3
2 20150225T000000 180000.0 2
3 20141209T000000 604000.0 4
4 20150218T000000 510000.0 3
5 20140512T000000 1225000.0 4
6 20140627T000000 257500.0 3
... | MIT | aulas/aula2.ipynb | artuguen28/Do_Zero_Ao_DS |
Respondendo as perguntas de negócio Data do imóvel mais antigo | data['date'] = pd.to_datetime(data['date'])
data.sort_values('date', ascending=True) | _____no_output_____ | MIT | aulas/aula2.ipynb | artuguen28/Do_Zero_Ao_DS |
Determinar o maior numero de andares e contar quantos temos por andar | data['floors'].unique()
print(data.loc[data['floors'] == 3.5].shape) | (8, 21)
| MIT | aulas/aula2.ipynb | artuguen28/Do_Zero_Ao_DS |
Criando classificação | data['level'] = 'standard'
data.loc[data['price'] > 540000, 'level'] = 'high_level'
data.loc[data['price'] < 540000, 'level'] = 'low_level'
data.head()
| _____no_output_____ | MIT | aulas/aula2.ipynb | artuguen28/Do_Zero_Ao_DS |
Relatório ordenado pelo preço | report = data[['id', 'date', 'price', 'bedrooms', 'sqft_lot', 'level']].sort_values('price', ascending=False)
report.to_csv('datasets/report_aula02.csv', index=False) | _____no_output_____ | MIT | aulas/aula2.ipynb | artuguen28/Do_Zero_Ao_DS |
Sorting 1. Bubble: $O(n^2)$repeatedly swapping the adjacent elements if they are in wrong order 2. Selection: $O(n^2)$find largest number and place it in the correct order 3. Insertion: $O(n^2)$ 4. Shell: $O(n^2)$ 5. Merge: $O(n \log n)$ 6. Quick: $O(n \log n)$it is important to select proper pivot 7. Counting: $O(n)$... | def bubble(arr):
n = len(arr)
for i in range(n):
# (n-1)-(i): 뒤에서부터 i+1 번째 idx
# 0번째 -> 커서가 n-1까지 움직임
# 1번째 -> 커서가 n-1-1
for j in range(0, (n-1)-i):
print(j)
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
def bubble(arr):
n =... | _____no_output_____ | MIT | 01.Algorithm/algorithm.ipynb | HenryPaik1/Study |
Selection Sorting | def Selection(arr):
n = len(arr)
for i in range(n-1, 0, -1):
positionOfMax=0
for loc in range(1, i+1):
if arr[loc] > arr[positionOfMax]:
positionOfMax = loc
arr[i], arr[loc] = arr[loc], arr[i]
# test code
arr = [54,26,93,17,77,31,44,55,20]
Selection(... | [54, 26, 93, 17, 77, 31, 44, 55, 20]
| MIT | 01.Algorithm/algorithm.ipynb | HenryPaik1/Study |
Quick | # partition은 cur가 앞에서부터 high까지 순회하면서
def partition(arr, low, high):
i = low - 1
pivot = arr[high]
for cur in range(low, high):
print(cur, i)
if arr[cur] <= pivot:
i += 1
arr[i], arr[cur] = arr[cur], arr[i]
arr[i+1], arr[high] = arr[high], arr[i+1]
r... | 0 -1
1 -1
2 -1
3 -1
4 -1
2 1
3 1
4 1
3 2
4 2
4 3
1
5
7
8
9
10
| MIT | 01.Algorithm/algorithm.ipynb | HenryPaik1/Study |
Quick2 | def partition(arr, start, end):
povot = arr[start]
i = start + 1
j = end -1
while True:
# i: traverse from begin
# j: traverse from end
# if arr[i](left side of pivot) smaller than pivot, then pass
while (i <= j and arr[i] <= pivot):
i += 1
... | _____no_output_____ | MIT | 01.Algorithm/algorithm.ipynb | HenryPaik1/Study |
계수정렬 Counting Sort- reference: https://www.geeksforgeeks.org/radix-sort/- count_arr: count how many each of 0,1,2,...,n is in arr- iter 0, 1, ..., n- fill ans with 0, 1, ..., n | # 핵심은 counting arr생성
# 갯수만큼 itter
def counting_sort(arr, max_val):
count_arr = [0 for _ in range(max_val)]
for num in arr:
count_arr[num] += 1
i = 0
for num in range(max_val):
iter_n = count_arr[num]
for _ in range(iter_n):
arr[i] = num
i += 1
ret... | _____no_output_____ | MIT | 01.Algorithm/algorithm.ipynb | HenryPaik1/Study |
기수정렬 Radix Sort 핵심- `숫자 //` 원하는 `digit`(첫쨰 자리: 1, 둘째 자리: 10, ...) `% 10`- `// 10^(digit-1)`: 끝자리가 내가 원하는 digit의 숫자가 됨 - eg. 25948의 끝에서 셋째 자리 9를 끝자리로 만드려면, 25948 // 10^(3-1) = 259- `%10`: 마지막 끝자리만 남김 | 4378 // 10**(4-1) % 10
def SortingByDigit(arr, exp):
n = len(arr)
output = [0 for _ in range(n)]
count = [0 for _ in range(10)]
for num in arr:
last_digit = num // exp % 10
count[last_digit] += 1
i = 1
while i < max_:
count[i] += count[i-1]
i += 1
print('dig... | 5145 1
digit: 1.0
[1, 1, 2, 2, 3, 6, 6, 6, 6, 6]
[0, 1, 1, 2, 2, 3, 6, 6, 6, 6]
[170, 802, 24, 5145, 3145, 2145]
5145 10
digit: 2.0
[1, 1, 2, 2, 5, 5, 5, 6, 6, 6]
[0, 1, 1, 2, 2, 5, 5, 5, 6, 6]
[802, 24, 5145, 3145, 2145, 170]
5145 100
digit: 3.0
[1, 5, 5, 5, 5, 5, 5, 5, 6, 6]
[0, 1, 5, 5, 5, 5, 5, 5, 5, 6]
[24, 5145... | MIT | 01.Algorithm/algorithm.ipynb | HenryPaik1/Study |
Airtable - Get data **Tags:** airtable database productivity spreadsheet naas_drivers operations snippet dataframe **Author:** [Jeremy Ravenel](https://www.linkedin.com/in/ACoAAAJHE7sB5OxuKHuzguZ9L6lfDHqw--cdnJg/) Input Import library | from naas_drivers import airtable | _____no_output_____ | BSD-3-Clause | Airtable/Airtable_Get_data.ipynb | techthiyanes/awesome-notebooks |
Variables | API_KEY = 'API_KEY'
BASE_KEY = 'BASE_KEY'
TABLE_NAME = 'TABLE_NAME' | _____no_output_____ | BSD-3-Clause | Airtable/Airtable_Get_data.ipynb | techthiyanes/awesome-notebooks |
Model Connect to airtable and get data | df = naas_drivers.airtable.connect(API_KEY,
BASE_KEY,
TABLE_NAME).get(view='All opportunities',
maxRecords=20) | _____no_output_____ | BSD-3-Clause | Airtable/Airtable_Get_data.ipynb | techthiyanes/awesome-notebooks |
Output Display result | df | _____no_output_____ | BSD-3-Clause | Airtable/Airtable_Get_data.ipynb | techthiyanes/awesome-notebooks |
Physically labeled data: pyfocs single-ended examplesFinally, after all of that (probably confusing) work we can map the data to physical coordinates. | import xarray as xr
import pyfocs
import os | /Users/karllapo/anaconda3/lib/python3.7/typing.py:847: FutureWarning: xarray subclass DataStore should explicitly define __slots__
super().__init_subclass__(*args, **kwargs)
| MIT | notebooks/pyfocs_ex3_finalcheck.ipynb | klapo/btmm_process |
1. Load data 1.1 Configuration filesAs in the previous example we will load and prepare the configuration files. This time we will load all the configuration files.Physically labeled data is triggered by setting the below flag within the configuration file.```pythonfinal_flag = True``` | dir_example = os.path.join('../tests/data/')
# Grab a configuration file for the twisted pair pvc fiber and for the stainless steel fiber
config_names = [
'example_configuration_steelfiber.yml',
'example_twistedpair_bothwls.yml',
'example_twistedpair_p1wls.yml',
'example_twistedpair_p2wls.yml',
]
cfg_... | _____no_output_____ | MIT | notebooks/pyfocs_ex3_finalcheck.ipynb | klapo/btmm_process |
1.2 Data- In this case we only use a single twisted pair, p1, since it is closer to the DTS device in LAF space yielding a less noisy signal.- Additionally, we will load the paired heated-unheated stainless steel fiber that has been interpolated to a common spatial index. | ds_p1 = xr.open_dataset(os.path.join(dir_example, 'multifiledemo', 'final', 'multifiledemo_final_20190722-0000_p1-wls_unheated.nc'))
ds_p2 = xr.open_dataset(os.path.join(dir_example, 'multifiledemo', 'final', 'multifiledemo_final_20190722-0000_p2-wls_unheated.nc'))
ds_cold = xr.open_dataset(os.path.join(dir_example, 'm... | =================
Unheated fibers - Twisted PVC fiber, pair 1
<xarray.Dataset>
Dimensions: (time: 60, xyz: 1612)
Coordinates:
* time (time) datetime64[ns] 2019-07-22T00:00:05 ... 2019-07-22T00:05:00
LAF (xyz) float64 ...
unheated (xyz) object ...
x (xyz) float64 ...
y (xy... | MIT | notebooks/pyfocs_ex3_finalcheck.ipynb | klapo/btmm_process |
Here we see that all datasets now have `x`, `y`, and `z` coordinates which are labeled using the `xyz` multiindex. Other quantities have been dropped.The netcdf files are also now labeled differently. Channel information has been excluded and there is now a label on the location type at the end of the file name. 2. Ca... | import numpy as np
power_loc = {
'1': [1892.5, 2063.5],
'2': [2063.5, 2205.5],
'3': [2207.0, 2361.],
'4': [2361., 2524.]}
power_vals = {
'1': 6.1,
'2': 6.4,
'3': 4.7,
'4': 5.4,}
ds_heat['power'] = ('LAF', np.zeros_like(ds_heat.LAF))
for p in power_vals:
laf_mask = ((ds_heat.LAF ... | _____no_output_____ | MIT | notebooks/pyfocs_ex3_finalcheck.ipynb | klapo/btmm_process |
2.2 Calculate wind speed | wind_speed = pyfocs.wind_speed.calculate(ds_heat.cal_temp, ds_cold.cal_temp, ds_heat.power)
| Converted air temperature from Celsius to Kelvin.
Converted air temperature from Celsius to Kelvin.
Converted air temperature from Celsius to Kelvin.
Converted air temperature from Celsius to Kelvin.
| MIT | notebooks/pyfocs_ex3_finalcheck.ipynb | klapo/btmm_process |
2.3 Split up wind speed basedWind speed is most efficiently measured in the direction orthogonal to the fiber. Since we have fibers that are orthogonal to each other that means we effectively measured wind in two different directions. We represent that here by combining sections that are parallel to each other. | cross_valley_components = ['OR_SE', 'OR_NW']
logic = [wind_speed.unheated == l for l in cross_valley_components]
logic = xr.concat(logic, dim='locations').any(dim='locations')
wind_speed_cross_valley = wind_speed.where(logic, drop=True)
along_valley_components = ['OR_SW2', 'OR_SW1', 'OR_NE1', 'OR_NE2']
logic = [wind_s... | _____no_output_____ | MIT | notebooks/pyfocs_ex3_finalcheck.ipynb | klapo/btmm_process |
2.4 Create a Dataset that contains all unheated data | unheated = xr.concat([ds_cold, ds_p1], dim='xyz', coords='different') | _____no_output_____ | MIT | notebooks/pyfocs_ex3_finalcheck.ipynb | klapo/btmm_process |
3. Plot your Fiber Optic Distributed Sensing data 3.1 Wind speed and temperature | import matplotlib.pyplot as plt
fig = plt.figure(figsize=(12, 6),)
spec = fig.add_gridspec(ncols=4,
nrows=2,
width_ratios=[1, 0.08, 0.04, 0.08],
hspace=0.18, wspace=0.25,
)
ax_ew_cbar = fig.add_subplot(spec[0, 3])
ax_ns_c... | _____no_output_____ | MIT | notebooks/pyfocs_ex3_finalcheck.ipynb | klapo/btmm_process |
3.2 Biases in space | ds_p2 = ds_p2.interp_like(ds_p1)
fig = plt.figure(figsize=(8, 6),)
spec = fig.add_gridspec(ncols=2,
nrows=1,
width_ratios=[1, 0.1],
hspace=0.18, wspace=0.25,
)
ax_t_cbar = fig.add_subplot(spec[:, 1])
ax_temp = fig.add_subp... | _____no_output_____ | MIT | notebooks/pyfocs_ex3_finalcheck.ipynb | klapo/btmm_process |
Machine Translation English-German Example Using SageMaker Seq2Seq1. [Introduction](Introduction)2. [Setup](Setup)3. [Download dataset and preprocess](Download-dataset-and-preprocess)3. [Training the Machine Translation model](Training-the-Machine-Translation-model)4. [Inference](Inference) IntroductionWelcome to our... | # S3 bucket and prefix
bucket = '<your_s3_bucket_name_here>'
prefix = 'sagemaker/<your_s3_prefix_here>' # E.g.'sagemaker/seq2seq/eng-german'
import boto3
import re
from sagemaker import get_execution_role
role = get_execution_role() | _____no_output_____ | Apache-2.0 | introduction_to_amazon_algorithms/seq2seq_translation_en-de/SageMaker-Seq2Seq-Translation-English-German.ipynb | karim7262/amazon-sagemaker-examples |
Next, we'll import the Python libraries we'll need for the remainder of the exercise. | from time import gmtime, strftime
import time
import numpy as np
import os
import json
# For plotting attention matrix later on
import matplotlib
%matplotlib inline
import matplotlib.pyplot as plt | _____no_output_____ | Apache-2.0 | introduction_to_amazon_algorithms/seq2seq_translation_en-de/SageMaker-Seq2Seq-Translation-English-German.ipynb | karim7262/amazon-sagemaker-examples |
Download dataset and preprocess In this notebook, we will train a English to German translation model on a dataset from the[Conference on Machine Translation (WMT) 2017](http://www.statmt.org/wmt17/). | %%bash
wget http://data.statmt.org/wmt17/translation-task/preprocessed/de-en/corpus.tc.de.gz & \
wget http://data.statmt.org/wmt17/translation-task/preprocessed/de-en/corpus.tc.en.gz & wait
gunzip corpus.tc.de.gz & \
gunzip corpus.tc.en.gz & wait
mkdir validation
curl http://data.statmt.org/wmt17/translation-task/prepr... | _____no_output_____ | Apache-2.0 | introduction_to_amazon_algorithms/seq2seq_translation_en-de/SageMaker-Seq2Seq-Translation-English-German.ipynb | karim7262/amazon-sagemaker-examples |
Please note that it is a common practise to split words into subwords using Byte Pair Encoding (BPE). Please refer to [this](https://github.com/awslabs/sockeye/tree/master/tutorials/wmt) tutorial if you are interested in performing BPE. Since training on the whole dataset might take several hours/days, for this demo, l... | !head -n 10000 corpus.tc.en > corpus.tc.en.small
!head -n 10000 corpus.tc.de > corpus.tc.de.small | _____no_output_____ | Apache-2.0 | introduction_to_amazon_algorithms/seq2seq_translation_en-de/SageMaker-Seq2Seq-Translation-English-German.ipynb | karim7262/amazon-sagemaker-examples |
Now, let's use the preprocessing script `create_vocab_proto.py` (provided with this notebook) to create vocabulary mappings (strings to integers) and convert these files to x-recordio-protobuf as required for training by SageMaker Seq2Seq. Uncomment the cell below and run to see check the arguments this script expects... | %%bash
# python3 create_vocab_proto.py -h | _____no_output_____ | Apache-2.0 | introduction_to_amazon_algorithms/seq2seq_translation_en-de/SageMaker-Seq2Seq-Translation-English-German.ipynb | karim7262/amazon-sagemaker-examples |
The cell below does the preprocessing. If you are using the complete dataset, the script might take around 10-15 min on an m4.xlarge notebook instance. Remove ".small" from the file names for training on full datasets. | %%time
%%bash
python3 create_vocab_proto.py \
--train-source corpus.tc.en.small \
--train-target corpus.tc.de.small \
--val-source validation/newstest2014.tc.en \
--val-target validation/newstest2014.tc.de | _____no_output_____ | Apache-2.0 | introduction_to_amazon_algorithms/seq2seq_translation_en-de/SageMaker-Seq2Seq-Translation-English-German.ipynb | karim7262/amazon-sagemaker-examples |
The script will output 4 files, namely:- train.rec : Contains source and target sentences for training in protobuf format- val.rec : Contains source and target sentences for validation in protobuf format- vocab.src.json : Vocabulary mapping (string to int) for source language (English in this example)- vocab.trg.json :... | def upload_to_s3(bucket, prefix, channel, file):
s3 = boto3.resource('s3')
data = open(file, "rb")
key = prefix + "/" + channel + '/' + file
s3.Bucket(bucket).put_object(Key=key, Body=data)
upload_to_s3(bucket, prefix, 'train', 'train.rec')
upload_to_s3(bucket, prefix, 'validation', 'val.rec')
upload_t... | _____no_output_____ | Apache-2.0 | introduction_to_amazon_algorithms/seq2seq_translation_en-de/SageMaker-Seq2Seq-Translation-English-German.ipynb | karim7262/amazon-sagemaker-examples |
Training the Machine Translation model | job_name = 'seq2seq-en-de-p2-xlarge-' + strftime("%Y-%m-%d-%H", gmtime())
print("Training job", job_name)
create_training_params = \
{
"AlgorithmSpecification": {
"TrainingImage": container,
"TrainingInputMode": "File"
},
"RoleArn": role,
"OutputDataConfig": {
"S3OutputPath": "s... | _____no_output_____ | Apache-2.0 | introduction_to_amazon_algorithms/seq2seq_translation_en-de/SageMaker-Seq2Seq-Translation-English-German.ipynb | karim7262/amazon-sagemaker-examples |
> Now wait for the training job to complete and proceed to the next step after you see model artifacts in your S3 bucket. You can jump to [Use a pretrained model](Use-a-pretrained-model) as training might take some time. InferenceA trained model does nothing on its own. We now want to use the model to perform inferenc... | use_pretrained_model = False | _____no_output_____ | Apache-2.0 | introduction_to_amazon_algorithms/seq2seq_translation_en-de/SageMaker-Seq2Seq-Translation-English-German.ipynb | karim7262/amazon-sagemaker-examples |
Use a pretrained model Please uncomment and run the cell below if you want to use a pretrained model, as training might take several hours/days to complete. | # use_pretrained_model = True
# model_name = "pretrained-en-de-model"
# !curl https://s3-us-west-2.amazonaws.com/gsaur-seq2seq-data/seq2seq/eng-german/full-nb-translation-eng-german-p2-16x-2017-11-24-22-25-53/output/model.tar.gz > model.tar.gz
# !curl https://s3-us-west-2.amazonaws.com/gsaur-seq2seq-data/seq2seq/eng-ge... | _____no_output_____ | Apache-2.0 | introduction_to_amazon_algorithms/seq2seq_translation_en-de/SageMaker-Seq2Seq-Translation-English-German.ipynb | karim7262/amazon-sagemaker-examples |
Create endpoint configurationUse the model to create an endpoint configuration. The endpoint configuration also contains information about the type and number of EC2 instances to use when hosting the model.Since SageMaker Seq2Seq is based on Neural Nets, we could use an ml.p2.xlarge (GPU) instance, but for this exampl... | from time import gmtime, strftime
endpoint_config_name = 'Seq2SeqEndpointConfig-' + strftime("%Y-%m-%d-%H-%M-%S", gmtime())
print(endpoint_config_name)
create_endpoint_config_response = sage.create_endpoint_config(
EndpointConfigName = endpoint_config_name,
ProductionVariants=[{
'InstanceType':'ml.m4.x... | _____no_output_____ | Apache-2.0 | introduction_to_amazon_algorithms/seq2seq_translation_en-de/SageMaker-Seq2Seq-Translation-English-German.ipynb | karim7262/amazon-sagemaker-examples |
Create endpointLastly, we create the endpoint that serves up model, through specifying the name and configuration defined above. The end result is an endpoint that can be validated and incorporated into production applications. This takes 10-15 minutes to complete. | %%time
import time
endpoint_name = 'Seq2SeqEndpoint-' + strftime("%Y-%m-%d-%H-%M-%S", gmtime())
print(endpoint_name)
create_endpoint_response = sage.create_endpoint(
EndpointName=endpoint_name,
EndpointConfigName=endpoint_config_name)
print(create_endpoint_response['EndpointArn'])
resp = sage.describe_endpoin... | _____no_output_____ | Apache-2.0 | introduction_to_amazon_algorithms/seq2seq_translation_en-de/SageMaker-Seq2Seq-Translation-English-German.ipynb | karim7262/amazon-sagemaker-examples |
If you see the message,> Endpoint creation ended with EndpointStatus = InServicethen congratulations! You now have a functioning inference endpoint. You can confirm the endpoint configuration and status by navigating to the "Endpoints" tab in the AWS SageMaker console. We will finally create a runtime object from whic... | runtime = boto3.client(service_name='runtime.sagemaker') | _____no_output_____ | Apache-2.0 | introduction_to_amazon_algorithms/seq2seq_translation_en-de/SageMaker-Seq2Seq-Translation-English-German.ipynb | karim7262/amazon-sagemaker-examples |
Perform Inference Using JSON format for inference (Suggested for a single or small number of data instances) Note that you don't have to convert string to text using the vocabulary mapping for inference using JSON mode | sentences = ["you are so good !",
"can you drive a car ?",
"i want to watch a movie ."
]
payload = {"instances" : []}
for sent in sentences:
payload["instances"].append({"data" : sent})
response = runtime.invoke_endpoint(EndpointName=endpoint_name,
... | _____no_output_____ | Apache-2.0 | introduction_to_amazon_algorithms/seq2seq_translation_en-de/SageMaker-Seq2Seq-Translation-English-German.ipynb | karim7262/amazon-sagemaker-examples |
Retrieving the Attention Matrix Passing `"attention_matrix":"true"` in `configuration` of the data instance will return the attention matrix. | sentence = 'can you drive a car ?'
payload = {"instances" : [{
"data" : sentence,
"configuration" : {"attention_matrix":"true"}
}
]}
response = runtime.invoke_endpoint(EndpointName=endpoint_name,
... | _____no_output_____ | Apache-2.0 | introduction_to_amazon_algorithms/seq2seq_translation_en-de/SageMaker-Seq2Seq-Translation-English-German.ipynb | karim7262/amazon-sagemaker-examples |
Using Protobuf format for inference (Suggested for efficient bulk inference) Reading the vocabulary mappings as this mode of inference accepts list of integers and returns list of integers. | import io
import tempfile
from record_pb2 import Record
from create_vocab_proto import vocab_from_json, reverse_vocab, write_recordio, list_to_record_bytes, read_next
source = vocab_from_json("vocab.src.json")
target = vocab_from_json("vocab.trg.json")
source_rev = reverse_vocab(source)
target_rev = reverse_vocab(tar... | _____no_output_____ | Apache-2.0 | introduction_to_amazon_algorithms/seq2seq_translation_en-de/SageMaker-Seq2Seq-Translation-English-German.ipynb | karim7262/amazon-sagemaker-examples |
Converting the string to integers, followed by protobuf encoding: | # Convert strings to integers using source vocab mapping. Out-of-vocabulary strings are mapped to 1 - the mapping for <unk>
sentences = [[source.get(token, 1) for token in sentence.split()] for sentence in sentences]
f = io.BytesIO()
for sentence in sentences:
record = list_to_record_bytes(sentence, [])
write_r... | _____no_output_____ | Apache-2.0 | introduction_to_amazon_algorithms/seq2seq_translation_en-de/SageMaker-Seq2Seq-Translation-English-German.ipynb | karim7262/amazon-sagemaker-examples |
Now, parse the protobuf response and convert list of integers back to strings | def _parse_proto_response(received_bytes):
output_file = tempfile.NamedTemporaryFile()
output_file.write(received_bytes)
output_file.flush()
target_sentences = []
with open(output_file.name, 'rb') as datum:
next_record = True
while next_record:
next_record = read_next(dat... | _____no_output_____ | Apache-2.0 | introduction_to_amazon_algorithms/seq2seq_translation_en-de/SageMaker-Seq2Seq-Translation-English-German.ipynb | karim7262/amazon-sagemaker-examples |
Stop / Close the Endpoint (Optional)Finally, we should delete the endpoint before we close the notebook. | sage.delete_endpoint(EndpointName=endpoint_name) | _____no_output_____ | Apache-2.0 | introduction_to_amazon_algorithms/seq2seq_translation_en-de/SageMaker-Seq2Seq-Translation-English-German.ipynb | karim7262/amazon-sagemaker-examples |
from google.colab import drive
drive.mount('/content/drive')
import numpy as np
import csv | _____no_output_____ | MIT | B_DS2.ipynb | eunyul24/eunyul24.github.io | |
header = []
userId = []
movieId = []
ratings = []
test = []
rownum = -1
with open('/content/drive/My Drive/Colab Notebooks/ml-20m/ratings.csv','r') as f:
data = csv.reader(f)
for row in data:
rownum += 1
if rownum == 0:
header = row
continue
if int(row[3]) < 1388... | 19152913
847350
| MIT | B_DS2.ipynb | eunyul24/eunyul24.github.io | |
userIdx = dict()
for i, uid in enumerate(np.unique(userId)):
userIdx[uid] = i
movieIdx = dict()
for i, mid in enumerate(np.unique(movieId)):
movieIdx[mid] = i
X = np.zeros((len(ratings),2), dtype=int)
for i in range(len(userId)):
X[i] = [userIdx[userId[i]], movieIdx[movieId[i]]] | _____no_output_____ | MIT | B_DS2.ipynb | eunyul24/eunyul24.github.io | |
class MatrixFactorization():
def __init__(self, ratings, X, k = 10, learning_rate = 0.01, reg_param = 0.1, epochs = 20):
"""
param R: ratings
param X: userId, movieId
param k: latent parameter
param learning_rate: alpha on weight update
param reg_param: beta on weight... | _____no_output_____ | MIT | B_DS2.ipynb | eunyul24/eunyul24.github.io | |
MF = MatrixFactorization(ratings, X)
training_process = MF.fit()
print("train RMSE:", MF.rmse())
f = open('/content/drive/My Drive/Colab Notebooks/ml-20m/B_results_DS2.csv', 'w', encoding='utf-8')
header[2] = 'predected rating'
wr = csv.writer(f)
wr.writerow(header)
error = 0
for uId, mId, rating, time in test:
... | _____no_output_____ | MIT | B_DS2.ipynb | eunyul24/eunyul24.github.io | |
911 Calls Capstone Project - Solutions For this capstone project we will be analyzing some 911 call data from [Kaggle](https://www.kaggle.com/mchirico/montcoalert). The data contains the following fields:* lat : String variable, Latitude* lng: String variable, Longitude* desc: String variable, Description of the Emerg... | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns | _____no_output_____ | BSD-2-Clause | Exercises - Qasim/Python. Pandas, Viz/Capstone Project 1/911 Calls - o .ipynb | k21k/Python-Notes |
* Import visualization libraries and set %matplotlib inline. | df = pd.read_csv('911.csv') | _____no_output_____ | BSD-2-Clause | Exercises - Qasim/Python. Pandas, Viz/Capstone Project 1/911 Calls - o .ipynb | k21k/Python-Notes |
* Read in the csv file as a dataframe called df | df.dtypes
df.info()
df.head(3) | _____no_output_____ | BSD-2-Clause | Exercises - Qasim/Python. Pandas, Viz/Capstone Project 1/911 Calls - o .ipynb | k21k/Python-Notes |
Short Questions* What are the bottom 5 zipcodes for 911 calls? | df['zip'].value_counts().tail(5)
df.head() | _____no_output_____ | BSD-2-Clause | Exercises - Qasim/Python. Pandas, Viz/Capstone Project 1/911 Calls - o .ipynb | k21k/Python-Notes |
* What are the top 5 townships (twp) for 911 calls? | df['twp'].value_counts().head(5) | _____no_output_____ | BSD-2-Clause | Exercises - Qasim/Python. Pandas, Viz/Capstone Project 1/911 Calls - o .ipynb | k21k/Python-Notes |
* Take a look at the 'title' column, how many unique title codes are there? | df['title'].nunique() | _____no_output_____ | BSD-2-Clause | Exercises - Qasim/Python. Pandas, Viz/Capstone Project 1/911 Calls - o .ipynb | k21k/Python-Notes |
Adding New Features* In the titles column there are "Reasons/Departments" specified before the title code. These are EMS, Fire, and Traffic. Use .apply() with a custom lambda expression to create a new column called "Reason" that contains this string value.* *For example, if the title column value is EMS: BACK PAINS/I... | df['Reason'] = df['title'].apply(lambda title: title.split(':')[0])
df.head() | _____no_output_____ | BSD-2-Clause | Exercises - Qasim/Python. Pandas, Viz/Capstone Project 1/911 Calls - o .ipynb | k21k/Python-Notes |
* Most common Reason for a 911 call based off of this new column? | # df3 = df2.value_counts()
# df3.columns= 'count'
df['Reason'].value_counts()
sns.countplot(x='Reason',data=df,palette='viridis') | _____no_output_____ | BSD-2-Clause | Exercises - Qasim/Python. Pandas, Viz/Capstone Project 1/911 Calls - o .ipynb | k21k/Python-Notes |
___* Now let us begin to focus on time information. What is the data type of the objects in the timeStamp column? | # Convert it to DateTime object
df['timeStamp'] = pd.to_datetime(df['timeStamp'])
df['Hour'] = df['timeStamp'].apply(lambda time: time.hour)
df['Month'] = df['timeStamp'].apply(lambda time: time.month)
df['Day of Week'] = df['timeStamp'].apply(lambda time: time.dayofweek)
# map Day of week column according to the days ... | _____no_output_____ | BSD-2-Clause | Exercises - Qasim/Python. Pandas, Viz/Capstone Project 1/911 Calls - o .ipynb | k21k/Python-Notes |
* You should have noticed it was missing some Months, let's see if we can maybe fill in this information by plotting the information in another way, possibly a simple line plot that fills in the missing months, in order to do this, we'll need to do some work with pandas... * Now create a gropuby object called byMonth, ... | byMonth = df.groupby('Month').count()
byMonth.head()
# Simple line plot of any column of byMonth
byMonth['twp'].plot()
# Now see if you can use seaborn's lmplot() to create a linear fit
# on the number of calls per month. Keep in mind you
# may need to reset the index to a column.
sns.lmplot(x='Month',y='twp',data=byMo... | _____no_output_____ | BSD-2-Clause | Exercises - Qasim/Python. Pandas, Viz/Capstone Project 1/911 Calls - o .ipynb | k21k/Python-Notes |
* Now groupby this Date column with the count() aggregate and create a plot of counts of 911 calls. | # use .plot()
df.groupby('Date').count()['twp'].plot()
plt.tight_layout() | _____no_output_____ | BSD-2-Clause | Exercises - Qasim/Python. Pandas, Viz/Capstone Project 1/911 Calls - o .ipynb | k21k/Python-Notes |
* Now recreate this plot but create 3 separate plots with each plot representing a Reason for the 911 call | # Traffic
df[df['Reason']=='Traffic'].groupby('Date').count()['twp'].plot()
plt.title('Traffic')
plt.tight_layout()
# Fire
df[df['Reason']=='Fire'].groupby('Date').count()['twp'].plot()
plt.title('Fire')
plt.tight_layout()
# EMS
df[df['Reason']=='EMS'].groupby('Date').count()['twp'].plot()
plt.title('EMS')
plt.tight_la... | _____no_output_____ | BSD-2-Clause | Exercises - Qasim/Python. Pandas, Viz/Capstone Project 1/911 Calls - o .ipynb | k21k/Python-Notes |
* Now let's move on to creating heatmaps with seaborn and our data. We'll first need to restructure the dataframe so that the columns become the Hours and the Index becomes the Day of the Week. There are lots of ways to do this, but I would recommend trying to combine groupby with an [unstack](http://pandas.pydata.org... | dayHour = df.groupby(by=['Day of Week','Hour']).count()['Reason'].unstack()
dayHour.head()
dayHour.head()
plt.figure(figsize=(12,6))
sns.heatmap(dayHour)
sns.clustermap(dayHour) | _____no_output_____ | BSD-2-Clause | Exercises - Qasim/Python. Pandas, Viz/Capstone Project 1/911 Calls - o .ipynb | k21k/Python-Notes |
* Now repeat these same plots and operations, for a DataFrame that shows the Month as the column. | dayMonth = df.groupby(by=['Day of Week','Month']).count()['Reason'].unstack()
dayMonth.head()
plt.figure(figsize=(12,6))
sns.heatmap(dayMonth)
sns.clustermap(dayMonth) | _____no_output_____ | BSD-2-Clause | Exercises - Qasim/Python. Pandas, Viz/Capstone Project 1/911 Calls - o .ipynb | k21k/Python-Notes |
Let's Grow your Own Inner Core! Choose a model in the list: - geodyn_trg.TranslationGrowthRotation() - geodyn_static.Hemispheres() Choose a proxy type: - age - position - phi - theta - growth rate set the parameters for the model : geodynModel.set_parameters(parameters) set the units : geodynMod... | %matplotlib inline
# import statements
import numpy as np
import matplotlib.pyplot as plt #for figures
from mpl_toolkits.basemap import Basemap #to render maps
import math
import json #to write dict with parameters
from GrowYourIC import positions, geodyn, geodyn_trg, geodyn_static, plot_data, data
plt.rcParams['fig... | /Users/marine/.python-eggs/GrowYourIC-0.5-py3.5.egg-tmp/GrowYourIC/data/CM2008_data.mat
| MIT | notebooks/sandbox-grow.ipynb | MarineLasbleis/GrowYourIC |
Define the geodynamical model Un-comment one of the model | ## un-comment one of them
geodynModel = geodyn_trg.TranslationGrowthRotation() #can do all the models presented in the paper
# geodynModel = geodyn_static.Hemispheres() #this is a static model, only hemispheres. | _____no_output_____ | MIT | notebooks/sandbox-grow.ipynb | MarineLasbleis/GrowYourIC |
Change the values of the parameters to get the model you want (here, parameters for .TranslationGrowthRotation()) | age_ic_dim = 1e9 #in years
rICB_dim = 1221. #in km
v_g_dim = rICB_dim/age_ic_dim # in km/years #growth rate
print("Growth rate is {:.2e} km/years".format(v_g_dim))
v_g_dim_seconds = v_g_dim*1e3/(np.pi*1e7)
translation_velocity_dim = 0.8*v_g_dim_seconds#4e-10 #0.8*v_g_dim_seconds#4e-10 #m.s, value for today's Earth wit... | Growth rate is 1.22e-06 km/years
The translation recycles the inner core material in 2.50e+03 million years
Translation velocity is 9.77e-07 km/years
Rotation rate is 0.00e+00
1.221e-06 0.7999999999999999 0.0
| MIT | notebooks/sandbox-grow.ipynb | MarineLasbleis/GrowYourIC |
Define a proxy type, and a proxy name (to be used in the figures to annotate the axes)You can re-define it later if you want (or define another proxy_type2 if needed) | proxy_type = "age"#"growth rate"
proxy_name = "age (Myears)" #growth rate (km/Myears)"
proxy_lim = [0, maxAge] #or None
#proxy_lim = None
fig_name = "figures/test_" #to name the figures
print(rICB, age_ic, velocity_amplitude, omega, exponent_growth, proxy_type)
print(velocity) | 1.0 1.0 0.7999999999999999 0.0 1.0 age
[ -1.38918542e-01 7.87846202e-01 4.89858720e-17]
| MIT | notebooks/sandbox-grow.ipynb | MarineLasbleis/GrowYourIC |
Parameters for the geodynamical modelThis will input the different parameters in the model. | parameters = dict({'units': units,
'rICB': rICB,
'tau_ic':age_ic,
'vt': velocity,
'exponent_growth': exponent_growth,
'omega': omega,
'proxy_type': proxy_type})
geodynModel.set_parameters(parameters)
geodynModel.define_units()
param =... | {'exponent_growth': 1.0, 'vt': [-0.13891854213354424, 0.7878462024097663, 4.8985871965894125e-17], 'proxy_type': 'age', 'omega': 0.0, 'tau_ic': 1.0, 'units': None, 'rICB': 1.0}
| MIT | notebooks/sandbox-grow.ipynb | MarineLasbleis/GrowYourIC |
Different data set and visualisations Perfect sampling at the equator (to visualise the flow lines)You can add more points to get a better precision. | npoints = 10 #number of points in the x direction for the data set.
data_set = data.PerfectSamplingEquator(npoints, rICB = 1.)
data_set.method = "bt_point"
proxy = geodyn.evaluate_proxy(data_set, geodynModel, proxy_type="age", verbose = False)
data_set.plot_c_vec(geodynModel, proxy=proxy, cm=cm, nameproxy="age (Myears... | ===
== Evaluate value of proxy for all points of the data set
= Geodynamic model is Translation, Rotation and Growth
= Proxy is age
= Data set is Perfect sampling in the equatorial plane
= Proxy is evaluated for bt_point
= Number of points to examine: 60
===
| MIT | notebooks/sandbox-grow.ipynb | MarineLasbleis/GrowYourIC |
Perfect sampling in the first 100km (to visualise the depth evolution) | data_meshgrid = data.Equator_upperpart(10,10)
data_meshgrid.method = "bt_point"
proxy_meshgrid = geodyn.evaluate_proxy(data_meshgrid, geodynModel, proxy_type=proxy_type, verbose = False)
#r, t, p = data_meshgrid.extract_rtp("bottom_turning_point")
fig3, ax3 = plt.subplots(figsize=(8, 2))
X, Y, Z = data_meshgrid.mesh_... | ===
== Evaluate value of proxy for all points of the data set
= Geodynamic model is Translation, Rotation and Growth
= Proxy is age
= Data set is Perfect sampling at the surface
= Proxy is evaluated for bt_point
= Number of points to examine: 400
===
| MIT | notebooks/sandbox-grow.ipynb | MarineLasbleis/GrowYourIC |
Random data set, in the first 100km - bottom turning point only Calculate the data | # random data set
data_set_random = data.RandomData(300)
data_set_random.method = "bt_point"
proxy_random = geodyn.evaluate_proxy(data_set_random, geodynModel, proxy_type=proxy_type, verbose=False)
data_path = "../GrowYourIC/data/"
geodynModel.data_path = data_path
if proxy_type == "age":
# ## domain size and Vp
... | _____no_output_____ | MIT | notebooks/sandbox-grow.ipynb | MarineLasbleis/GrowYourIC |
Real Data set from Waszek paper | ## real data set
data_set = data.SeismicFromFile("../GrowYourIC/data/WD11.dat")
data_set.method = "bt_point"
proxy2 = geodyn.evaluate_proxy(data_set, geodynModel, proxy_type=proxy_type, verbose=False)
if proxy_type == "age":
## domain size and DV/V
proxy_size = geodyn.evaluate_proxy(data_set, geodynModel, proxy_... | _____no_output_____ | MIT | notebooks/sandbox-grow.ipynb | MarineLasbleis/GrowYourIC |
Запуск SEO бота Screaming Frog SEO spider в облаке через Google Colab ------------- > *Protip: под задачу для крупного сайта лучше всего подходят High RAM (25GB) инстансы без GPU/TPU, доступные в PRO подписке* Косметическое улучшение: добавляем перенос строки для длинных однострочных команд | from IPython.display import HTML, display
def set_css():
display(HTML('''
<style>
pre {
white-space: pre-wrap;
}
</style>
'''))
get_ipython().events.register('pre_run_cell', set_css) | _____no_output_____ | MIT | Running_screamingfrog_SEO_spider_in_Colab_notebook.ipynb | danzerzine/seospider-colab |
Подключаем Google Drive в котором хранятся конфиги бота и куда будут сохраняться результаты обхода | from google.colab import drive
drive.mount('/content/drive') | _____no_output_____ | MIT | Running_screamingfrog_SEO_spider_in_Colab_notebook.ipynb | danzerzine/seospider-colab |
Узнаем внешний IP инстанса чтобы затем ручками добавить его в исключения файерволла cloudflare -- иначе очень быстро упремся в rate limit и нам начнут показывать страницу с проверкой на человекообразность | !wget -qO- http://ipecho.net/plain | xargs echo && wget -qO - icanhazip.com | _____no_output_____ | MIT | Running_screamingfrog_SEO_spider_in_Colab_notebook.ipynb | danzerzine/seospider-colab |
Устанавливаем последнюю версию seo spider, делаем мелкие дела по хозяйству* Обновляем установленные linux пакеты * Копируем настройки с десктопной версии SEO spider в локальную папку инстанса (это нужно чтобы передать токены авторизации к google search console, GA и так далее) | #@title Settings directory on GDrive { vertical-output: true, display-mode: "both" }
settings_path = "" #@param {type:"string"}
!wget https://download.screamingfrog.co.uk/products/seo-spider/screamingfrogseospider_16.3_all.deb
!apt-get install screamingfrogseospider_16.3_all.deb
!sudo apt-get update && sudo apt-get upg... | _____no_output_____ | MIT | Running_screamingfrog_SEO_spider_in_Colab_notebook.ipynb | danzerzine/seospider-colab |
Запускаем bash скрипт для донастройки инстанса и бота Он добавит виртуальный дисплей для вывода из JAVA, переключит бота в режим сохранения результатов на диске вместо RAM и т.д. | !wget https://raw.githubusercontent.com/fili/screaming-frog-on-google-compute-engine/master/gce-sf.sh -O install.sh && chmod +x install.sh && source ./install.sh | _____no_output_____ | MIT | Running_screamingfrog_SEO_spider_in_Colab_notebook.ipynb | danzerzine/seospider-colab |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.