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
Now, you can send new scoring records (new data) for which you would like to get predictions. To do that, execute the following sample code:
fields = ["CheckingStatus", "LoanDuration", "CreditHistory", "LoanPurpose", "LoanAmount", "ExistingSavings", "EmploymentDuration", "InstallmentPercent", "Sex", "OthersOnLoan", "CurrentResidenceDuration", "OwnsProperty", "Age", "InstallmentPlans", "Housing", "ExistingCreditsCount", "J...
_____no_output_____
Apache-2.0
cpd3.5/notebooks/python_sdk/deployments/spark/Use Spark to predict credit risk.ipynb
kwright15/watson-machine-learning-samples
D - Optimizing diameter model 1D. Extra Trees
# This is a grid search for three parameters in the Extra Trees algorithm. # Parameters are: random_state, n_estimators, max_features. # This gives the best combination of the three parameters for the smallest mean squared error. min_mae = 99999 min_i, min_j, min_k = 0, 0, 0 for i in tqdm(range(1, 25)): for j in...
Outputs R2 Mean absolute error Mean squared error Root mean squared error --------- -------- --------------------- -------------------- ------------------------- Diameter 0.928258 0.175193 0.066874 0.2586
MIT
CdSe/5. Single-output.ipynb
Cossairt-Lab/Indium-Phosphide
2D. Decision Tree
# This is a grid search for three parameters in the Decision Trees algorithm. # Parameters are: max_depth, max_features, random_state. # This gives the best combination of the three parameters for the smallest mean squared error. min_mae = 99999 min_i, min_j, min_k = 0, 0, 0 for i in tqdm(range(1, 30)): for j ...
Outputs R2 Mean absolute error Mean squared error Root mean squared error --------- -------- --------------------- -------------------- ------------------------- Diameter 0.920359 0.214379 0.0742371 0.272465
MIT
CdSe/5. Single-output.ipynb
Cossairt-Lab/Indium-Phosphide
3D. Random Forest
# This is a grid search for three parameters in the Random Forest algorithm. # Parameters are: max_depth, n_estimators, max_features. # Random_state is set to 45. # This gives the best combination of the three parameters for the smallest mean squared error. min_mae = 99999 min_i, min_j, min_k = 0, 0, 0 for i in tqdm(...
100%|██████████| 20/20 [05:10<00:00, 15.54s/it]
MIT
CdSe/5. Single-output.ipynb
Cossairt-Lab/Indium-Phosphide
4D. K Neighbors
min_mae = 99999 min_i, min_j = 0, 0 for i in tqdm(range(1, 40)): for j in range(1, 40): KNN_reg_d = KNeighborsRegressor(n_neighbors=i, p=j).fit(X_train_d, np.ravel(Y_train_d)) KNN_Y_pred_d = KNN_reg_d.predict(X_test_d) mae = mean_absolute_error(Y_te...
100%|██████████| 39/39 [00:16<00:00, 2.31it/s]
MIT
CdSe/5. Single-output.ipynb
Cossairt-Lab/Indium-Phosphide
Saving Decision Tree model
ET_regr_d = ExtraTreesRegressor(n_estimators=2, max_features=23, random_state=20) ET_regr_d.fit(X_train_d, np.ravel(Y_train_d)) ET_Y_pred_d = pd.DataFrame(ET_regr.predict(X_test_d)) joblib.dump(ET_regr_d, "./model_CdS...
_____no_output_____
MIT
CdSe/5. Single-output.ipynb
Cossairt-Lab/Indium-Phosphide
E - Optimizing emission model 1E. Extra Trees
# This is a grid search for three parameters in the Extra Trees algorithm. # Parameters are: random_state, n_estimators, max_features. # This gives the best combination of the three parameters for the smallest mean squared error. min_mae = 99999 min_i, min_j, min_k = 0, 0, 0 for i in tqdm(range(1, 25)): for j in...
Outputs R2 Mean absolute error Mean squared error Root mean squared error --------- -------- --------------------- -------------------- ------------------------- Diameter 0.712964 11.9488 459.214 21.4293
MIT
CdSe/5. Single-output.ipynb
Cossairt-Lab/Indium-Phosphide
2E. Decision Trees
# This is a grid search for three parameters in the Decision Trees algorithm. # This gives the best combination of the three parameters for the smallest mean squared error. min_mae = 99999 min_i, min_j, min_k = 0, 0, 0 for i in tqdm(range(1, 30)): for j in range(1, 30): for k in range(4, 70, 2): ...
Outputs R2 Mean absolute error Mean squared error Root mean squared error --------- -------- --------------------- -------------------- ------------------------- Diameter 0.912234 8.37353 140.412 11.8496
MIT
CdSe/5. Single-output.ipynb
Cossairt-Lab/Indium-Phosphide
3E. Random Forest
min_mae = 99999 min_i, min_j, min_k = 0, 0, 0 for i in tqdm(range(1, 21)): for j in range(1, 21): for k in range(2, 30, 1): RF_regr_e = RandomForestRegressor(max_depth=i, n_estimators=j, max_features=k, ...
100%|██████████| 20/20 [03:02<00:00, 9.12s/it]
MIT
CdSe/5. Single-output.ipynb
Cossairt-Lab/Indium-Phosphide
4E. K Neighbors
min_mae = 99999 min_i, min_j = 0, 0 for i in tqdm(range(1, 40)): for j in range(1, 40): KNN_reg_e = KNeighborsRegressor(n_neighbors=i, p=j).fit(X_train_e, np.ravel(Y_train_e)) KNN_Y_pred_e = KNN_reg_e.predict(X_test_e) mae = mean_absolute_error(Y_te...
100%|██████████| 39/39 [00:15<00:00, 2.47it/s]
MIT
CdSe/5. Single-output.ipynb
Cossairt-Lab/Indium-Phosphide
Saving Extra Trees model
DT_regr_e = DecisionTreeRegressor(max_depth=13, max_features=5, random_state=32) DT_regr_e.fit(X_train_e, np.ravel(Y_train_e)) DT_Y_pred_e = pd.DataFrame(DT_regr_e.predict(X_test_e)) joblib.dump(ET_regr_e, "./model_CdSe_SO_emission_DecisionTree.joblib")
_____no_output_____
MIT
CdSe/5. Single-output.ipynb
Cossairt-Lab/Indium-Phosphide
A - Optimizing absorption model 1A: Extra Trees
# This is a grid search for three parameters in the Extra Trees algorithm. # Parameters are: random_state, n_estimators, max_features. # This gives the best combination of the three parameters for the smallest mean squared error. min_mae = 99999 min_i, min_j, min_k = 0, 0, 0 for i in tqdm(range(1, 30)): for j in...
Outputs R2 Mean absolute error Mean squared error Root mean squared error --------- -------- --------------------- -------------------- ------------------------- Diameter 0.872221 15.0212 448.564 21.1793
MIT
CdSe/5. Single-output.ipynb
Cossairt-Lab/Indium-Phosphide
2A. Decision Trees
# This is a grid search for three parameters in the Decision Trees algorithm. # This gives the best combination of the three parameters for the smallest mean squared error. min_mae = 99999 min_i, min_j, min_k = 0, 0, 0 for i in tqdm(range(1, 30)): for j in range(1, 30): for k in range(4, 60, 2): ...
Outputs R2 Mean absolute error Mean squared error Root mean squared error --------- -------- --------------------- -------------------- ------------------------- Diameter 0.888377 14.6697 391.85 19.7952
MIT
CdSe/5. Single-output.ipynb
Cossairt-Lab/Indium-Phosphide
3A. Random Forest
min_mae = 99999 min_i, min_j, min_k = 0, 0, 0 for i in tqdm(range(1, 21)): for j in range(1, 21): for k in range(2, 31, 1): RF_regr_a = RandomForestRegressor(max_depth=i, n_estimators=j, max_features=k, ...
100%|██████████| 20/20 [03:44<00:00, 11.25s/it]
MIT
CdSe/5. Single-output.ipynb
Cossairt-Lab/Indium-Phosphide
4A. K Neighbors
min_mae = 99999 min_i, min_j = 0, 0 for i in tqdm(range(1, 40)): for j in range(1, 40): KNN_reg_a = KNeighborsRegressor(n_neighbors=i, p=j).fit(X_train_a, np.ravel(Y_train_a)) KNN_Y_pred_a = KNN_reg_a.predict(X_test_a) mae = mean_absolute_error(Y_te...
100%|██████████| 39/39 [00:13<00:00, 2.84it/s]
MIT
CdSe/5. Single-output.ipynb
Cossairt-Lab/Indium-Phosphide
Saving model
DT_regr_a = DecisionTreeRegressor(max_depth=11, max_features=11, random_state=38) DT_regr_a.fit(X_train_a, np.ravel(Y_train_a)) DT_Y_pred_a = pd.DataFrame(DT_regr_a.predict(X_test_a)) joblib.dump(DT_regr_a, "./model_CdSe_SO_abs_DecisionTree.joblib")
_____no_output_____
MIT
CdSe/5. Single-output.ipynb
Cossairt-Lab/Indium-Phosphide
Analyzing
## Diameter ET_regr_d = ExtraTreesRegressor(n_estimators=2, max_features=23, random_state=20) ET_regr_d.fit(X_train_d, np.ravel(Y_train_d)) ET_Y_pred_d = pd.DataFrame(ET_regr_d.predict(X_test_d)) D_mae = mean_absolut...
_____no_output_____
MIT
CdSe/5. Single-output.ipynb
Cossairt-Lab/Indium-Phosphide
Feature importance For diameter prediction
importance_dict_d = dict() for i in range(0,48): importance_dict_d[input_col[i]] = ET_regr_d.feature_importances_[i] sorted_importance_d = sorted(importance_dict_d.items(), key=lambda x: x[1], reverse=True) sorted_importance_d top7_d = DataFrame(sorted_importance_d[0:7], columns=['features', 'importance score'])...
_____no_output_____
MIT
CdSe/5. Single-output.ipynb
Cossairt-Lab/Indium-Phosphide
Emission prediction
importance_dict_e = dict() for i in range(0,48): importance_dict_e[input_col[i]] = DT_regr_e.feature_importances_[i] sorted_importance_e = sorted(importance_dict_e.items(), key=lambda x: x[1], reverse=True) sorted_importance_e top7_e = DataFrame(sorted_importance_e[0:7], columns=['features', 'importance score']...
_____no_output_____
MIT
CdSe/5. Single-output.ipynb
Cossairt-Lab/Indium-Phosphide
Absorption prediction
importance_dict_a = dict() for i in range(0,48): importance_dict_a[input_col[i]] = DT_regr_a.feature_importances_[i] sorted_importance_a = sorted(importance_dict_a.items(), key=lambda x: x[1], reverse=True) sorted_importance_a top7_a = DataFrame(sorted_importance_a[0:7], columns=['features', 'importance score']) ...
_____no_output_____
MIT
CdSe/5. Single-output.ipynb
Cossairt-Lab/Indium-Phosphide
Combine
sorted_a = sorted(importance_dict_a.items(), key=lambda x: x[0], reverse=False) sorted_d = sorted(importance_dict_d.items(), key=lambda x: x[0], reverse=False) sorted_e = sorted(importance_dict_e.items(), key=lambda x: x[0], reverse=False) sorted_d combined_importance = dict() for i in range(0,48): combined_impor...
_____no_output_____
MIT
CdSe/5. Single-output.ipynb
Cossairt-Lab/Indium-Phosphide
繁衍计算
program = calcu_program() graphviz.Source(draw_program(program)) def get_subtree(program): probs = np.array([0.9 if node in function_sets else 0.1 for node in program]) probs = np.cumsum(probs / probs.sum()) start = np.searchsorted(probs, np.random.uniform(0, 1)) stack = 1 end = start while stac...
_____no_output_____
Apache-2.0
example/Example 3 - Genetic/Tree-GP.ipynb
wangjiehui11235/ultron
交叉计算
copy_program = program donor_program = calcu_program() start, end = get_subtree(copy_program) removed = range(start, end) donor_start, donor_end = get_subtree(donor_program) donor_removed = list(set(range(len(donor_program))) - set(range(donor_start, donor_end))) crossover_program = copy_p...
_____no_output_____
Apache-2.0
example/Example 3 - Genetic/Tree-GP.ipynb
wangjiehui11235/ultron
变异计算 树突变 - 等同于交叉计算
copy_program = program chicken_program = calcu_program() start, end = get_subtree(copy_program) removed = range(start, end) chicken_start, chicken_end = get_subtree(chicken_program) chicken_removed = list(set(range(len(chicken_program))) - set(range(chicken_start, chicken_end))) crossover_...
_____no_output_____
Apache-2.0
example/Example 3 - Genetic/Tree-GP.ipynb
wangjiehui11235/ultron
提升突变
copy_program = program start, end = get_subtree(copy_program) subtree = program[start:end] sub_start, sub_end = get_subtree(subtree) hoist = subtree[sub_start:sub_end] hosit_program = copy_program[:start] + hoist + copy_program[end:] graphviz.Source(draw_program(hosit_program))
_____no_output_____
Apache-2.0
example/Example 3 - Genetic/Tree-GP.ipynb
wangjiehui11235/ultron
节点突变
copy_program = copy(program) mutate = np.where(np.random.uniform(size=len(copy_program)) < 0.5)[0] for node in mutate: if copy_program[node] in function_sets: activy = copy_program[node]['activy'] #找到参数个数替换 if activy == 1: replace_node = mutated_sets[np.random.randint(0,len(mutat...
_____no_output_____
Apache-2.0
example/Example 3 - Genetic/Tree-GP.ipynb
wangjiehui11235/ultron
计算因子值
def create_formual(apply_formual): function = apply_formual[0] formula = function['function'].__name__ formula +='(' for i in range(0,function['activy']): if i != 0: formula += ',' if apply_formual[i+1] in facotr_sets: formula += '\'' + apply_formual[i+1] + '\'' ...
_____no_output_____
Apache-2.0
example/Example 3 - Genetic/Tree-GP.ipynb
wangjiehui11235/ultron
import numpy as np import matplotlib.pyplot as plt import h5py from PIL import Image from scipy import ndimage with h5py.File('train_signs.h5', 'r') as hdf: ls = list(hdf.keys()) print(ls) train_set_x = np.array(hdf.get('train_set_x')) train_set_y = np.array(hdf.get('train_set_y')) print(train_set_x.sh...
_____no_output_____
Apache-2.0
SESSION_20_(Decision_trees_and_Random_Forests).ipynb
madhavjk/DataScience-ML_and_DL
[Making a Predictive Keyboard using Recurrent Neural Networks](https://medium.com/@curiousily/making-a-predictive-keyboard-using-recurrent-neural-networks-tensorflow-for-hackers-part-v-3f238d824218) Recurrent Neural NetworksIn short, `RNN` models provide a way to not only examine the current input but the one that wa...
# Mounting Google Drive to Load Data from google.colab import drive drive.mount('/content/drive') import numpy as np np.random.seed(42) import tensorflow as tf tf.set_random_seed(42) from keras.models import Sequential, load_model from keras.layers import Dense, Activation from keras.layers import LSTM, Dropout, CuDNNL...
_____no_output_____
MIT
word_completion_prediction.ipynb
Shahid1993/colab-notebooks
Loading the data
#path = 'nietzsche.txt' path = "./drive/My Drive/ML/data/nietzsche.txt" #path = "./drive/My Drive/ML/data/1-billion-word-language-modeling-benchmark-r13output/training-monolingual.tokenized.shuffled/news.en-00001-of-00100" text = open(path).read().lower() print('corpus length:', len(text))
corpus length: 600902
MIT
word_completion_prediction.ipynb
Shahid1993/colab-notebooks
PreprocessingLet’s find all unique chars in the corpus and create char to index and index to char maps:
chars = sorted(list(set(text))) char_indices = dict((c, i) for i, c in enumerate(chars)) indices_char = dict((i, c) for i, c in enumerate(chars)) print(f'unique chars: {len(chars)}') print(chars) print(''.join(map(str, chars))) # def clean_special_chars(text, punct): # for p in punct: # text = text.repla...
unique chars: 50 [' ', '!', '"', "'", '(', ')', ',', '-', '.', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '?', '_', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '¦'] !"'(),-.0123456789:;?_abcdefghijklmnopqrstuvwxyz¦ c...
MIT
word_completion_prediction.ipynb
Shahid1993/colab-notebooks
Next, let’s cut the corpus into chunks of `40` characters, spacing the sequences by `3` characters. Additionally, we will store the next character (the one we need to predict) for every sequence:
SEQUENCE_LENGTH = 40 step = 3 sentences = [] next_chars = [] for i in range(0, len(text) - SEQUENCE_LENGTH, step): sentences.append(text[i: i + SEQUENCE_LENGTH]) next_chars.append(text[i + SEQUENCE_LENGTH]) print(f'num training examples: {len(sentences)}')
num training examples: 196817
MIT
word_completion_prediction.ipynb
Shahid1993/colab-notebooks
It is time for generating our features and labels. We will use the previously generated sequences and characters that need to be predicted to create one-hot encoded vectors using the `char_indices` map:
X = np.zeros((len(sentences), SEQUENCE_LENGTH, len(chars)), dtype=np.bool) y = np.zeros((len(sentences), len(chars)), dtype=np.bool) for i, sentence in enumerate(sentences): for t, char in enumerate(sentence): X[i, t, char_indices[char]] = 1 y[i, char_indices[next_chars[i]]] = 1
_____no_output_____
MIT
word_completion_prediction.ipynb
Shahid1993/colab-notebooks
Let’s have a look at a single training sequence:
sentences[1091]
_____no_output_____
MIT
word_completion_prediction.ipynb
Shahid1993/colab-notebooks
The character that needs to be predicted for it is:
next_chars[1091]
_____no_output_____
MIT
word_completion_prediction.ipynb
Shahid1993/colab-notebooks
The encoded (one-hot) data looks like this:
X[0] y[0]
_____no_output_____
MIT
word_completion_prediction.ipynb
Shahid1993/colab-notebooks
And for the dimensions:
X.shape y.shape
_____no_output_____
MIT
word_completion_prediction.ipynb
Shahid1993/colab-notebooks
We have `200285` training examples, each sequence has length of `40` with `57` unique chars. Building the modelThe model we’re going to train is pretty straight forward. Single `LSTM` layer with `128` neurons which accepts input of shape (`40` — the length of a sequence, `57` — the number of unique characters in our da...
model = Sequential() #model.add(LSTM(128, input_shape=(SEQUENCE_LENGTH, len(chars)))) #model.add(CuDNNLSTM(128, input_shape=(None, len(chars)))) model.add(CuDNNLSTM(128, input_shape=(None, len(chars)), return_sequences=True)) model.add(CuDNNLSTM(128, return_sequences=True)) model.add(CuDNNLSTM(128)) #Dropout added t...
Model: "sequential_2" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= cu_dnnlstm_4 (CuDNNLSTM) (None, None, 128) 92160 __________________________________...
MIT
word_completion_prediction.ipynb
Shahid1993/colab-notebooks
TrainingOur model is trained for `20` epochs using `RMSProp` optimizer and uses `5%` of the data for validation:
#optimizer = RMSprop(lr=0.01) model.compile(loss='categorical_crossentropy', optimizer=optimizer, metrics=['accuracy']) history = model.fit(X, y, validation_split=0.05, batch_size=128, epochs=15, shuffle=True).history
Train on 186976 samples, validate on 9841 samples Epoch 1/15 186976/186976 [==============================] - 46s 247us/step - loss: 2.5242 - acc: 0.2785 - val_loss: 2.1670 - val_acc: 0.3651 Epoch 2/15 186976/186976 [==============================] - 45s 242us/step - loss: 2.0713 - acc: 0.4002 - val_loss: 1.9043 - val_...
MIT
word_completion_prediction.ipynb
Shahid1993/colab-notebooks
Saving
model.save('predictive_keyboard_keras_model.h5') pickle.dump(history, open("predictive_keyboard_history.p", "wb"))
_____no_output_____
MIT
word_completion_prediction.ipynb
Shahid1993/colab-notebooks
And load it back, just to make sure it works:
model = load_model('predictive_keyboard_keras_model.h5') history = pickle.load(open("predictive_keyboard_history.p", "rb"))
_____no_output_____
MIT
word_completion_prediction.ipynb
Shahid1993/colab-notebooks
EvaluationLet’s have a look at how our accuracy and loss change over training epochs:
plt.plot(history['acc']) plt.plot(history['val_acc']) plt.title('model accuracy') plt.ylabel('accuracy') plt.xlabel('epoch') plt.legend(['train', 'test'], loc='upper left'); plt.plot(history['loss']) plt.plot(history['val_loss']) plt.title('model loss') plt.ylabel('loss') plt.xlabel('epoch') plt.legend(['train', 'test'...
_____no_output_____
MIT
word_completion_prediction.ipynb
Shahid1993/colab-notebooks
Let’s put our model to the test
# def prepare_input(text): # x = np.zeros((1, SEQUENCE_LENGTH, len(chars))) # for t, char in enumerate(text): # x[0, t, char_indices[char]] = 1. # return x def prepare_input(text): x = np.zeros((1, len(text), len(chars))) for t, char in enumerate(text): x[0, t, char_indic...
_____no_output_____
MIT
word_completion_prediction.ipynb
Shahid1993/colab-notebooks
Remember that our sequences must be `40` characters long. So we make a tensor with shape `(1, 40, 59)`, initialized with zeros. Then, a value of 1 is placed for each character in the passed text. We must not forget to use the lowercase version of the text:
prepare_input("This is an example of input for our LSTM".lower()) #prepare_input("Tests".lower())
_____no_output_____
MIT
word_completion_prediction.ipynb
Shahid1993/colab-notebooks
Next up, the sample function:This function allows us to ask our model what are the next `n` most probable characters.
def sample(preds, top_n=3): preds = np.asarray(preds).astype('float64') preds = np.log(preds) exp_preds = np.exp(preds) preds = exp_preds / np.sum(exp_preds) return heapq.nlargest(top_n, range(len(preds)), preds.take)
_____no_output_____
MIT
word_completion_prediction.ipynb
Shahid1993/colab-notebooks
Now for the **prediction functions** themselves:This function predicts next character until space is predicted (you can extend that to punctuation symbols, right?). It does so by repeatedly preparing input, asking our model for predictions and sampling from them.
def predict_completion(text): original_text = text generated = text completion = '' while True: x = prepare_input(text) preds = model.predict(x, verbose=0)[0] next_index = sample(preds, top_n=1)[0] next_char = indices_char[next_index] text = text[1:] + next_char ...
_____no_output_____
MIT
word_completion_prediction.ipynb
Shahid1993/colab-notebooks
The final piece of the puzzle — `predict_completions` wraps everything and allow us to predict multiple completions:
def predict_completions(text, n=3): x = prepare_input(text) preds = model.predict(x, verbose=0)[0] next_indices = sample(preds, n) return [indices_char[idx] + predict_completion(text[1:] + indices_char[idx]) for idx in next_indices]
_____no_output_____
MIT
word_completion_prediction.ipynb
Shahid1993/colab-notebooks
Let’s use sequences of 40 characters that we will use as seed for our completions. All of these are quotes from Friedrich Nietzsche himself:
# actual_text = [ # "It is not a lack of love, but a lack of friendship that makes unhappy marriages.", # "That which does not kill us makes us stronger.", # "I'm not upset that you lied to me, I'm upset that from now on I can't believe you.", # "And those who were seen dancing were thought to be insane...
it is not a lack of lov ['e ', 'ical ', 'ality ', 'oure ', 'uling '] that which does not kill us makes us stro ['ng ', 'dger ', 've ', 'gget ', 'w '] i'm not upset that you lied to me, i'm upset that from now on i can't bel ['ieve ', 'ong ', 'aes ', 'ess ', 'low '] and those who were seen dan ['gerous ', 'king ', 'd...
MIT
word_completion_prediction.ipynb
Shahid1993/colab-notebooks
Apart from the fact that the completions look like proper words (remember, we are training our model on characters, not words), they look pretty reasonable as well! Perhaps better model and/or more training will provide even better results? ConclusionWe’ve built a model using just a few lines of code in `Keras` that p...
# Mounting Google Drive to Load Data from google.colab import drive drive.mount('/content/drive') model = load_model('./drive/My Drive/ML/Models/word_completion_prediction/word_completion_prediction_keras_model.h5') history = pickle.load(open("./drive/My Drive/ML/Models/word_completion_prediction/word_completion_predic...
_____no_output_____
MIT
word_completion_prediction.ipynb
Shahid1993/colab-notebooks
Загрузка Pandas и очистка данных
import pandas as pd df = pd.read_csv('main_task.csv') # Ваш код по очистке данных и генерации новых признаков # При необходимости добавьте ячейки # df.Restaurant_id = df.Restaurant_id.apply(lambda x: int(x[3:])) df.info() newdf = df.drop(columns=['Restaurant_id','City','Cuisine Style','Price Range','Reviews','URL_TA','...
<class 'pandas.core.frame.DataFrame'> RangeIndex: 40000 entries, 0 to 39999 Data columns (total 4 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 Restaurant_id 40000 non-null object 1 Ranking 40000 non-null float64 2 Rating ...
MIT
module_3/your_first_model.ipynb
stuit/I-am-data-scientist
Разбиваем датафрейм на части, необходимые для обучения и тестирования модели
# Х - данные с информацией о ресторанах, у - целевая переменная (рейтинги ресторанов) X = df.drop(['Restaurant_id', 'Rating'], axis = 1) y = df['Rating'] # Загружаем специальный инструмент для разбивки: from sklearn.model_selection import train_test_split # Наборы данных с меткой "train" будут использоваться для обучен...
_____no_output_____
MIT
module_3/your_first_model.ipynb
stuit/I-am-data-scientist
Создаём, обучаем и тестируем модель
# Импортируем необходимые библиотеки: from sklearn.ensemble import RandomForestRegressor # инструмент для создания и обучения модели from sklearn import metrics # инструменты для оценки точности модели # Создаём модель regr = RandomForestRegressor(n_estimators=100) # Обучаем модель на тестовом наборе данных regr.fit(X...
MAE: 0.43638770734126986
MIT
module_3/your_first_model.ipynb
stuit/I-am-data-scientist
Extract barrier island metrics along transectsAuthor: Emily Sturdivant, esturdivant@usgs.gov***Extract barrier island metrics along transects for Barrier Island Geomorphology Bayesian Network. See the project [README](https://github.com/esturdivant-usgs/BI-geomorph-extraction/blob/master/README.md) and the Methods Rep...
import os import sys import pandas as pd import numpy as np import io import arcpy import pyproj import datetime import matplotlib.pyplot as plt import matplotlib matplotlib.style.use('ggplot') import core.functions_warcpy as fwa import core.functions as fun print("Date: {}".format(datetime.date.today())) # print(os.__...
Date: 2019-06-28 pandas version: 0.20.1 numpy version: 1.11.2 matplotlib version: 1.5.3 pyproj version: 1.9.5.1
CC0-1.0
vol2/extractor_met14.ipynb
esturdivant-usgs/geomorph-working-files
Initialize variablesThis cell prompts you for the site, year, and project directory path. `setvars.py` retrieves the pre-determined values for that site in that year from `configmap.py`. The project directory will be used to set up your workspace. It's hidden for security – sorry! I recommend that you type the path so...
from core.setvars import *
site (options: Assawoman, Fisherman, Cedar, RhodeIsland, FireIsland, Parramore, Cobb, Monomoy, Smith, CoastGuard, Metompkin, Forsythe, Assateague, CapeLookout, CapeHatteras, Rockaway, ParkerRiver): Metompkin year (options: 2010, 2012, 2014): 2014 Path to project directory (e.g. \\Mac olume\dir\FireIsland2014): ·····...
CC0-1.0
vol2/extractor_met14.ipynb
esturdivant-usgs/geomorph-working-files
Change the filename variables to match your local files. They should be in an Esri file geodatabase named site+year.gdb in your project directory, which you input above and is the value of the variable `home`.
# Extended transects: NASC transects extended and sorted, ready to be the base geometry for processing extendedTrans = os.path.join(home, 'Monomoy2014_extTrans_null') # Tidied transects: Extended transects without overlapping transects extTrans_tidy = os.path.join(home, 'Monomoy_tidyTrans') # Geomorphology points: p...
_____no_output_____
CC0-1.0
vol2/extractor_met14.ipynb
esturdivant-usgs/geomorph-working-files
Transect-averaged valuesWe work with the shapefile/feature class as a pandas DataFrame as much as possible to speed processing and minimize reliance on the ArcGIS GUI display.1. Add the bearing of each transect line to the attribute table from the LINE_BEARING geometry attribute.1. Create a pandas dataframe from the t...
# Add BEARING field to extendedTrans feature class arcpy.AddGeometryAttributes_management (extendedTrans, 'LINE_BEARING') print("Adding line bearing field to transects.") # Copy feature class to dataframe. trans_df = fwa.FCtoDF(extendedTrans, id_fld=tID_fld, extra_fields=extra_fields) trans_df['DD_ID'] = trans_df[tID_...
['StartX', 'StartY', 'ORIG_FID', 'Autogen', 'ProcTime', 'SHAPE_Leng', 'OBJECTID_1', 'Shape_Length', 'EndX', 'EndY', 'BaselineID', 'OBJECTID', 'orig_oid', 'TransOrder_1', 'lr2', 'lse', 'lci90', 'STARTX', 'STARTY', 'ORIG_FID', 'AUTOGEN', 'PROCTIME', 'SHAPE_LENG', 'OBJECTID_1', 'SHAPE_LENGTH', 'ENDX', 'ENDY', 'BASELINEID'...
CC0-1.0
vol2/extractor_met14.ipynb
esturdivant-usgs/geomorph-working-files
Get XY and Z/slope from SL, DH, DL points within 25 m of transectsAdd to each transect row the positions of the nearest pre-created beach geomorphic features (shoreline, dune toe, and dune crest). If needed, convert morphology points stored locally to feature classes for use.After which, view the new feature classes i...
if "morphdata_prefix" in locals(): csvpath = os.path.join(proj_dir, 'Input_Data', '{}_morphology'.format(morphdata_prefix), '{}_morphology.csv'.format(morphdata_prefix)) dt_fc, dc_fc, sl_fc = fwa.MorphologyCSV_to_FCsByFeature(csvpath, state, proj_code, ...
_____no_output_____
CC0-1.0
vol2/extractor_met14.ipynb
esturdivant-usgs/geomorph-working-files
ShorelineThe MHW shoreline easting and northing (__SL_x__, __SL_y__) are the coordinates of the intersection of the oceanside shoreline with the transect. Each transect is assigned the foreshore slope (__Bslope__) from the nearest shoreline point within 25 m. These values are populated for each transect as follows: 1....
if not arcpy.Exists(inletLines): # manually create lines that correspond to end of land and cross the MHW line (refer to shoreline polygon) arcpy.CreateFeatureclass_management(home, os.path.basename(inletLines), 'POLYLINE', spatial_reference=utmSR) print("OUTPUT: {}. Interrupt execution to manually create l...
...converting feature class to array... ...converting array to dataframe... Number of points in dataset: (967, 13) OBJECTID_______________________________1 | 970_________________ No fills_________No nulls Shape............... nan state............... 12 seg___________________________________74 | 77__________________...
CC0-1.0
vol2/extractor_met14.ipynb
esturdivant-usgs/geomorph-working-files
Dune positions along transects__DL_x__, __DL_y__, and __DL_z__ are the easting, northing, and elevation, respectively, of the nearest dune toe point within 25 meters of the transect. __DH_x__, __DH_y__, and __DH_z__ are the easting, northing, and elevation, respectively, of the nearest dune crest point within 25 meter...
# Create dataframe for both dune crest and dune toe positions dune2trans_df, dhPts, dlPts = fwa.find_ClosestPt2Trans_snap(extendedTrans, dhPts, dlPts, trans_df, tID_fld, proximity=pt2trans_disttolerance) # Save and print sample dune2trans_df.to_pickle(os.path.join(scratch_dir...
...converting feature class to array... ...converting array to dataframe... Number of points in dataset: (913, 14) OBJECTID_______________________________2 | 914_________________ No fills_________No nulls Shape............... nan state............... 12 seg___________________________________74 | 77__________________...
CC0-1.0
vol2/extractor_met14.ipynb
esturdivant-usgs/geomorph-working-files
Armoring__Arm_x__, __Arm_y__, and __Arm_z__ are the easting, northing, and elevation, respectively, where an artificial structure crosses the transect in the vicinity of the beach. These features are meant to supplement the dune toe data set by providing an upper limit to the beach in areas where dune toe extraction w...
# Create elevation raster at 5-m resolution if not already elevGrid = fwa.ProcessDEM_2(elevGrid, utmSR) # Armoring line if not arcpy.Exists(armorLines): arcpy.CreateFeatureclass_management(home, os.path.basename(armorLines), 'POLYLINE', spatial_reference=utmSR) print("{} created. If shorefront armoring exists,...
OUTPUT: Metompkin2014_dem_5m at 5x5 resolution. Armoring file either missing or empty so we will proceed without armoring data. If shorefront tampering is present at this site, cancel the operations to digitize.
CC0-1.0
vol2/extractor_met14.ipynb
esturdivant-usgs/geomorph-working-files
Add all the positions to the trans_dfJoin the new dataframes to the transect dataframe. Before it performs the join, `join_columns_id_check()` checks the index and the ID field for potential errors such as whether they are the equal and whether there are duplicated IDs or null values in either.
# Load saved dataframes trans_df = pd.read_pickle(os.path.join(scratch_dir, 'trans_df.pkl')) sl2trans_df = pd.read_pickle(os.path.join(scratch_dir, 'sl2trans.pkl')) dune2trans_df = pd.read_pickle(os.path.join(scratch_dir, 'dune2trans.pkl')) arm2trans_df = pd.read_pickle(os.path.join(scratch_dir, 'arm2trans.pkl')) # Joi...
_____no_output_____
CC0-1.0
vol2/extractor_met14.ipynb
esturdivant-usgs/geomorph-working-files
Check for errors*Optional*Display summary stats / histograms and create feature classes. The feature classes display the locations that will be used to calculate beach width. Review the output feature classes in a GIS to validate.
plots = trans_df.hist(['DH_z', 'DL_z', 'Arm_z']) # Subplot Labels plots[0][0].set_xlabel("Elevation (m in NAVD88)") plots[0][0].set_ylabel("Frequency") plots[0][1].set_xlabel("Elevation (m in NAVD88)") plots[0][1].set_ylabel("Frequency") try: plots[0][2].set_xlabel("Elevation (m in NAVD88)") plots[0][2].set_yl...
... converting dataframe to array... ... converting array to feature class... OUTPUT: pts2trans_SL in designated scratch geodatabase. ... converting dataframe to array... ... converting array to feature class... OUTPUT: ptSnap2trans_DH in designated scratch geodatabase. ... converting dataframe to array... ... c...
CC0-1.0
vol2/extractor_met14.ipynb
esturdivant-usgs/geomorph-working-files
Calculate upper beach width and heightUpper beach width (__uBW__) and upper beach height (__uBH__) are calculated based on the difference in position between two points: the position of MHW along the transect (__SL_x__, __SL_y__) and the dune toe position or equivalent (usually __DL_snapX__, __DL_snapY__). In some ca...
# Load saved dataframe trans_df = pd.read_pickle(os.path.join(scratch_dir, 'trans_df_beachmetrics.pkl')) # Calculate distances from shore to dunes, etc. trans_df = fwa.calc_BeachWidth_fill(extendedTrans, trans_df, maxDH, tID_fld, sitevals['MHW'], fill, skip_missing_z=True)
Fields uBW and uBH populated with beach width and beach height.
CC0-1.0
vol2/extractor_met14.ipynb
esturdivant-usgs/geomorph-working-files
Dist2InletDistance to nearest tidal inlet (__Dist2Inlet__) is computed as alongshore distance of each sampling transect from the nearest tidal inlet. This distance includes changes in the path of the shoreline instead of simply a Euclidean distance and reflects sediment transport pathways. It is measured using the oce...
# Calc Dist2Inlet in new dataframe dist_df = fwa.measure_Dist2Inlet(shoreline, extendedTrans, inletLines, tID_fld) # Join to transects trans_df = fun.join_columns_id_check(trans_df, pd.DataFrame(dist_df.Dist2Inlet), tID_fld, fill=fill) # Save and view last 10 rows dist_df.to_pickle(os.path.join(scratch_dir, 'dist2in...
Duration: 0:0:3.4 seconds
CC0-1.0
vol2/extractor_met14.ipynb
esturdivant-usgs/geomorph-working-files
Clip transects, get barrier widthsCalculates __WidthLand__, __WidthFull__, and __WidthPart__, which measure different flavors of the cross-shore width of the barrier island. __WidthLand__ is the above-water distance between the back-barrier and seaward MHW shorelines. __WidthLand__ only includes regions of the barrier...
# Clip transects, get barrier widths widths_df = fwa.calc_IslandWidths(extendedTrans, barrierBoundary, tID_fld=tID_fld) # # Save widths_df.to_pickle(os.path.join(scratch_dir, 'widths_df.pkl')) # Join trans_df = fun.join_columns_id_check(trans_df, widths_df, tID_fld, fill=fill) # Save trans_df.to_pickle(os.path.join(...
Clipping the transects to the barrier island boundaries ('clip2island')... Getting the width along each transect of the oceanside land (WidthPart)... ...converting feature class to array... ...converting array to dataframe... Getting the width along each transect of the entire barrier (WidthFull)... Converting feature ...
CC0-1.0
vol2/extractor_met14.ipynb
esturdivant-usgs/geomorph-working-files
5-m PointsThe point dataset samples the land every 5 m along each shore-normal transect. Split transects into points at 5-m intervals. The point dataset is created from the tidied transects (tidyTrans, created during pre-processing) as follows: 1. Clip the tidied transects (tidyTrans) to the shoreline polygon (bndpol...
pts_df, pts_presort = fwa.TransectsToPointsDF(extTrans_tidy, barrierBoundary, fc_out=pts_presort) print("OUTPUT: '{}' in scratch geodatabase.".format(os.path.basename(pts_presort))) # Save pts_df.to_pickle(os.path.join(scratch_dir, 'pts_presort.pkl'))
Clipping transects to within the shoreline bounds ('tidytrans_clipped')... Getting points every 5m along each transect and saving in new dataframe... Converting dataframe to feature class ('transPts_unsorted')... ... converting dataframe to array... ... converting array to feature class... Duration: 0:1:4.1 seconds ...
CC0-1.0
vol2/extractor_met14.ipynb
esturdivant-usgs/geomorph-working-files
Add Elevation and Slope to points__ptZ__ (later __ptZmhw__) and __ptSlp__ are the elevation and slope at the 5-m cell corresponding to the point. 1. Create the slope and DEM rasters if they don't already exist. We use the 5-m DEM to generate a slope surface (Slope tool in 3D Analyst). 2. Use Extract Multi Values to Po...
# Create slope raster from DEM if not arcpy.Exists(slopeGrid): arcpy.Slope_3d(elevGrid, slopeGrid, 'PERCENT_RISE') print("OUTPUT: slope file in designated home geodatabase.") # Add elevation and slope values at points. arcpy.sa.ExtractMultiValuesToPoints(pts_presort, [[elevGrid, 'ptZ'], [slopeGrid, 'ptSlp'...
_____no_output_____
CC0-1.0
vol2/extractor_met14.ipynb
esturdivant-usgs/geomorph-working-files
Calculate distances and sort points__SplitSort__ is a unique numeric identifier of the 5-m points at the study site, sorted by order along shoreline and by distance from oceanside. __SplitSort__ values are populated by sorting the points by __sort_ID__ and __Dist_Seg__ (see below). __Dist_Seg__ is the Euclidean distan...
# Load saved dataframes pts_df = pd.read_pickle(os.path.join(scratch_dir, 'pts_extractedvalues_presort.pkl')) trans_df = pd.read_pickle(os.path.join(scratch_dir, trans_name+'_null_prePts.pkl')) print(sorted_pt_flds) # Calculate DistSeg, Dist_MHWbay, DistSegDH, DistSegDL, DistSegArm, and sort points (SplitSort) pts_df =...
_____no_output_____
CC0-1.0
vol2/extractor_met14.ipynb
esturdivant-usgs/geomorph-working-files
Recode the values for CSV output and model running
# Recode pts_df4csv = pts_df.replace({'SubType': {7777:'{1111, 2222}', 1000:'{1111, 3333}'}, 'VegType': {77:'{11, 22}', 88:'{22, 33}', 99:'{33, 44}'}, 'VegDens': {666: '{111, 222}', 777: '{222, 333}', 888: '{333, 444...
_____no_output_____
CC0-1.0
vol2/extractor_met14.ipynb
esturdivant-usgs/geomorph-working-files
Quality checkingLook at extracted profiles from around the island. Enter the transect ID within the available range when prompted. Evaluate the plots for consistency among variables. Repeat various times until you can be satisfied that the variables are consistent with each other and appear to represent reality. View ...
desccols = ['DL_zmhw', 'DH_zmhw', 'Arm_zmhw', 'uBW', 'uBH', 'Dist2Inlet', 'WidthPart', 'WidthLand', 'WidthFull', 'mean_Zmhw', 'max_Zmhw'] # Histograms trans_df.hist(desccols, sharey=True, figsize=[15, 10], bins=20) plt.show() plt.close('all') flds_dist = ['SplitSort', 'Dist_Seg', 'Dist_MHWbay', 'DistSegDH...
Transect ID ("sort_ID" 1-209): 123
CC0-1.0
vol2/extractor_met14.ipynb
esturdivant-usgs/geomorph-working-files
Report field values
# Load dataframe pts_df4csv = pd.read_pickle(os.path.join(scratch_dir, pts_name+'_csv.pkl')) xmlfile = os.path.join(scratch_dir, pts_name+'_eainfo.xml') fun.report_fc_values(pts_df4csv, field_defs, xmlfile)
Number of points in dataset: (23116, 57) SplitSort______________________________0 | 23115_______________ No fills_________No nulls seg_x_________________448084.80402533617 | 452803.0445057908___ Fills present____No nulls seg_y__________________4171861.443778258 | 4181033.861208152___ Fills present____No nulls se...
CC0-1.0
vol2/extractor_met14.ipynb
esturdivant-usgs/geomorph-working-files
Outputs Transect-averagedOutput the transect-averaged metrics in the following formats:- transects, unpopulated except for ID values, as gdb feature class- transects, unpopulated except for ID values, as shapefile- populated transects with fill values as gdb feature class- populated transects with null values as gdb f...
# Load the dataframe trans_df = pd.read_pickle(os.path.join(scratch_dir, trans_name+'_null.pkl')) trans_df['Construction'] = 111 trans_df['Nourishment'] = 111 trans_df['Development'] = 111
_____no_output_____
CC0-1.0
vol2/extractor_met14.ipynb
esturdivant-usgs/geomorph-working-files
Vector format
# Create transect file with only ID values and geometry to publish. trans_flds = ['TRANSECTID', 'TRANSORDER', 'DD_ID'] for i, f in enumerate(trans_flds): for c in trans_df.columns: if f.lower() == c.lower(): trans_flds[i] = c trans_4pub = fwa.JoinDFtoFC(trans_df.loc[:,trans_flds], e...
Created met14_trans_fill from input dataframe and extTrans file. OUTPUT: met14_trans_null OUTPUT: met14_trans_shp.shp in specified scratch_dir.
CC0-1.0
vol2/extractor_met14.ipynb
esturdivant-usgs/geomorph-working-files
Raster - beach widthIt may be necessary to close any Arc sessions you have open.
# Create a template raster corresponding to the transects. if not arcpy.Exists(rst_transID): print("{} was not found so we will create the base raster.".format(os.path.basename(rst_transID))) outEucAll = arcpy.sa.EucAllocation(extTrans_tidy, maximum_distance=50, cell_size=cell_size, source_field=tID_fld) o...
OUTPUT: met14_ubw. Field "Value" is ID and "uBW" is beachwidth.
CC0-1.0
vol2/extractor_met14.ipynb
esturdivant-usgs/geomorph-working-files
5-m pointsOutput the point metrics in the following formats:- tabular, in CSV- populated points with fill values as gdb feature class- populated points with null values as gdb feature class- populated points with fill values as shapefile
# Load the saved dataframes pts_df4csv = pd.read_pickle(os.path.join(scratch_dir, pts_name+'_csv.pkl')) pts_df = pd.read_pickle(os.path.join(scratch_dir, pts_name+'_null.pkl')) pts_df4csv['Construction'] = 111 pts_df4csv['Nourishment'] = 111 pts_df4csv['Development'] = 111 pts_df['Construction'] = 111 pts_df['Nourishm...
_____no_output_____
CC0-1.0
vol2/extractor_met14.ipynb
esturdivant-usgs/geomorph-working-files
Tabular format
# Save CSV in scratch_dir csv_fname = os.path.join(scratch_dir, pts_name +'.csv') pts_df4csv.to_csv(csv_fname, na_rep=fill, index=False) sz_mb = os.stat(csv_fname).st_size/(1024.0 * 1024.0) print("OUTPUT: {} [{} MB] in specified scratch_dir. ".format(os.path.basename(csv_fname), sz_mb))
OUTPUT: met14_pts.csv [16.93202495574951 MB] in specified scratch_dir.
CC0-1.0
vol2/extractor_met14.ipynb
esturdivant-usgs/geomorph-working-files
Vector format
# Convert pts_df to FC - automatically converts NaNs to fills (default fill is -99999) pts_fc = fwa.DFtoFC_large(pts_df, out_fc=os.path.join(arcpy.env.workspace, pts_name+'_fill'), spatial_ref=utmSR, df_id=pID_fld, xy=["seg_x", "seg_y"]) # Save final FCs with null values fwa.CopyFCandReplace...
Converting points DF to FC... ... converting dataframe to array... ... converting array to feature class... OUTPUT: met14_pts_fill Duration: 0:2:46.2 seconds OUTPUT: met14_pts_null OUTPUT: met14_pts_shp.shp in specified scratch_dir.
CC0-1.0
vol2/extractor_met14.ipynb
esturdivant-usgs/geomorph-working-files
MOwNiT – arytmetyka komputerowa ![Content.png](attachment:Content.png)
import numpy as np import matplotlib.pyplot as plt x1 = 4 n = 30 def visualize(points): plt.figure(figsize=(12,6)) plt.axhline(y=3.14159, color='r', linestyle='--') plt.xlabel("Xi") plt.ylabel("points") plt.plot(points, marker="o", markersize=10) plt.show()
_____no_output_____
MIT
Lab_1/Lab_1_code.ipynb
Szymon-Budziak/MOwNiT
Informacje o używanych typach danych:
print(np.finfo(np.float32)) print(np.finfo(np.double)) print(np.finfo(np.longdouble))
Machine parameters for float128 --------------------------------------------------------------- precision = 18 resolution = 1e-18 machep = -63 eps = 1.084202172485504434e-19 negep = -64 epsneg = 5.42101086242752217e-20 minexp = -16382 tiny = 3.3621031431120935063e-4932 maxexp = 16384 ...
MIT
Lab_1/Lab_1_code.ipynb
Szymon-Budziak/MOwNiT
Rozwiązanie dla liczb typu float:
def float_32_sequence_default(): res = [np.float32(0) for _ in range(n)] res[0] = np.float32(x1) for k in range(n-1): calc_sqrt = np.sqrt(1 + (res[k]**2 / 2**(2*(k+2)))) new_xk = 2**(2*(k+2)+1) * ((calc_sqrt - 1)/res[k]) res[k+1] = np.float32(new_xk) return res def float_32_seque...
_____no_output_____
MIT
Lab_1/Lab_1_code.ipynb
Szymon-Budziak/MOwNiT
Porównanie wyników oraz ich wizualizacja: **Dla nieprzekształconego wzoru:**
f32_def_res = float_32_sequence_default() f32_def_res f32_def_res[-1] visualize(f32_def_res)
_____no_output_____
MIT
Lab_1/Lab_1_code.ipynb
Szymon-Budziak/MOwNiT
**Dla przekształconego wzoru:**
f32_resh_res = float_32_sequence_reshaped() f32_resh_res f32_resh_res[-1] visualize(f32_resh_res)
_____no_output_____
MIT
Lab_1/Lab_1_code.ipynb
Szymon-Budziak/MOwNiT
Rozwiązanie dla liczb typu double:
def double_sequence_default(): res = [np.double(0) for _ in range(n)] res[0] = np.double(x1) for k in range(n-1): calc_sqrt = np.sqrt(1 + (res[k]**2 / 2**(2*(k+2)))) new_xk = 2**(2*(k+2)+1) * ((calc_sqrt - 1)/res[k]) res[k+1] = np.double(new_xk) return res def double_sequence_res...
_____no_output_____
MIT
Lab_1/Lab_1_code.ipynb
Szymon-Budziak/MOwNiT
Porównanie wyników: **Dla nieprzekształconego wzoru:**
doub_def_res = double_sequence_default() doub_def_res doub_def_res[-1] visualize(doub_def_res)
_____no_output_____
MIT
Lab_1/Lab_1_code.ipynb
Szymon-Budziak/MOwNiT
**Dla przekształconego wzoru:**
doub_resh_res = double_sequence_reshaped() doub_resh_res doub_resh_res[-1] visualize(doub_resh_res)
_____no_output_____
MIT
Lab_1/Lab_1_code.ipynb
Szymon-Budziak/MOwNiT
Rozwiązanie dla liczb typu long double:
def longdouble_sequence_default(): res = [np.longdouble(0) for _ in range(n)] res[0] = np.longdouble(x1) for k in range(n-1): calc_sqrt = np.sqrt(1 + (res[k]**2 / 2**(2*(k+2)))) new_xk = 2**(2*(k+2)+1) * ((calc_sqrt - 1)/res[k]) res[k+1] = np.longdouble(new_xk) return res def lon...
_____no_output_____
MIT
Lab_1/Lab_1_code.ipynb
Szymon-Budziak/MOwNiT
Porównanie wyników: **Dla nieprzekształconego wzoru:**
l_doub_def_res = longdouble_sequence_default() l_doub_def_res l_doub_def_res[-1] visualize(l_doub_def_res)
_____no_output_____
MIT
Lab_1/Lab_1_code.ipynb
Szymon-Budziak/MOwNiT
**Dla przekształconego wzoru:**
l_doub_resh_res = longdouble_sequence_reshaped() l_doub_resh_res l_doub_resh_res[-1] visualize(l_doub_resh_res)
_____no_output_____
MIT
Lab_1/Lab_1_code.ipynb
Szymon-Budziak/MOwNiT
Create Planet object and stellar evolutionary track Example planet 1.1 - V1298Tau c with 5 Eearth mass core and measured radius (var. step)
# (David et al. 2019, Chandra observation) L_bol, mass_star, radius_star = 0.934, 1.101, 1.345 # solar units age_star = 23. # Myr Lx_age = Lx_chandra = 1.3e30 # erg/s in energy band: (0.1-2.4 keV) Lx_age_error = 1.4e29 # use dictionary to store star-parameters star_V1298Tau = {'star_id': 'V1298Tau', 'mass': mass_star...
_____no_output_____
MIT
examples/Evolve_one_planet.ipynb
soumitrahazra/platypos
Example planet 1.1.1 - V1298Tau c with 5 Eearth mass core and measured radius (fixed step)
pl = Planet_LoFo14_PAPER(star_V1298Tau, planet)
_____no_output_____
MIT
examples/Evolve_one_planet.ipynb
soumitrahazra/platypos
Example planet 1.2 - V1298Tau c with mass estimate from Otegi et al. (2020) and measured radius (var step)
pl = Planet_Ot20(star_V1298Tau, planet) pl.__dict__
_____no_output_____
MIT
examples/Evolve_one_planet.ipynb
soumitrahazra/platypos
Example planet 1.2.1 - V1298Tau c with mass estimate from Otegi et al. (2020) and measured radius (fixed step)
pl = Planet_Ot20_PAPER(star_V1298Tau, planet) pl.__dict__
_____no_output_____
MIT
examples/Evolve_one_planet.ipynb
soumitrahazra/platypos
Example planet 2 - artificial planet with specified core mass and envelope mass fraction
Lx_1Gyr, Lx_5Gyr = 2.10*10**28, 1.65*10**27 dict_star = {'star_id': 'star_age1.0_mass0.89', 'mass': 0.8879632311581124, 'radius': None, 'age': 1.0, 'L_bol': 1.9992811847525246e+33/const.L_sun.cgs.value, 'Lx_age': 1.298868513129789e+30} dict_pl = {'distance': 0.12248611607793611, 'metallicity': 'solarZ', 'fenv':...
_____no_output_____
MIT
examples/Evolve_one_planet.ipynb
soumitrahazra/platypos
Evolve & create outputs
%%time folder_id = "dummy" path_save = os.getcwd() + "/" + folder_id +"/" if not os.path.exists(path_save): os.makedirs(path_save) else: os.system("rm -r " + path_save[:-1]) os.makedirs(path_save) t_final = 5007. pl.evolve_forward_and_create_full_output(t_final, 0.1, 0.1, "yes", "yes", track_high, path_sa...
CPU times: user 14.8 s, sys: 11.8 ms, total: 14.8 s Wall time: 14.8 s
MIT
examples/Evolve_one_planet.ipynb
soumitrahazra/platypos
Read in results and plot
df_pl = pl.read_results(path_save) df_pl.head() df_pl.tail() # fig, ax = plt.subplots(figsize=(10,5)) # ax.plot(df_pl["Time"], df_pl["Lx"]) # ax.loglog() # plt.show() fig, ax = plt.subplots(figsize=(10,5)) age_arr = np.logspace(np.log10(pl.age), np.log10(t_final), 100) if (type(pl) == platypos.planet_LoFo14.Planet_LoF...
_____no_output_____
MIT
examples/Evolve_one_planet.ipynb
soumitrahazra/platypos
Prepare the Dataset for Building a Predictive ModelAs a first step we will build a graph convolution model predict ERK2 activity. We will train the model to distinguish a set of ERK2 active compounds from a set of decoy compounds. The active and decoy compounds are derived from the DUD-E database. In order to genera...
from rdkit import Chem from rdkit.Chem import Draw from rdkit.Chem.Draw import IPythonConsole import pandas as pd from rdkit.Chem import PandasTools from rdkit.Chem import Descriptors from rdkit.Chem import rdmolops import seaborn as sns
_____no_output_____
MIT
Chapter11/chapter_11_01_preparing_to_build_a_predictive_models.ipynb
peastman/DeepLearningLifeSciences
Now we can read a SMILES file into a Pandas dataframe and add an RDKit molecule to the dataframe.
active_df = pd.read_csv("mk01/actives_final.ism",header=None,sep=" ") active_rows,active_cols = active_df.shape active_df.columns = ["SMILES","ID","ChEMBL_ID"] active_df["label"] = ["Active"]*active_rows PandasTools.AddMoleculeColumnToFrame(active_df,"SMILES","Mol")
_____no_output_____
MIT
Chapter11/chapter_11_01_preparing_to_build_a_predictive_models.ipynb
peastman/DeepLearningLifeSciences
Let's define a function to add caculated properties to a dataframe
def add_property_columns_to_df(df_in): df_in["mw"] = [Descriptors.MolWt(mol) for mol in df_in.Mol] df_in["logP"] = [Descriptors.MolLogP(mol) for mol in df_in.Mol] df_in["charge"] = [rdmolops.GetFormalCharge(mol) for mol in df_in.Mol]
_____no_output_____
MIT
Chapter11/chapter_11_01_preparing_to_build_a_predictive_models.ipynb
peastman/DeepLearningLifeSciences
With this function in hand, we can calculate the molecular weight, LogP and formal charge of the molecules. Once we have these properties we can compare the distributions for the active and decoy sets.
add_property_columns_to_df(active_df)
_____no_output_____
MIT
Chapter11/chapter_11_01_preparing_to_build_a_predictive_models.ipynb
peastman/DeepLearningLifeSciences
Let's look at the frist few rows of our dataframe to ensure that it makes sense.
active_df.head()
_____no_output_____
MIT
Chapter11/chapter_11_01_preparing_to_build_a_predictive_models.ipynb
peastman/DeepLearningLifeSciences