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 |
|---|---|---|---|---|---|
The above figure makes it clear: In terms of validation loss, on this problem, this careful initialization gives a clear advantage. Train the model | model = make_model()
model.load_weights(initial_weights)
baseline_history = model.fit(
train_features,
train_labels,
batch_size=BATCH_SIZE,
epochs=EPOCHS,
callbacks = [early_stopping],
validation_data=(val_features, val_labels)) | Train on 182276 samples, validate on 45569 samples
Epoch 1/100
182276/182276 [==============================] - 3s 16us/sample - loss: 0.0256 - tp: 64.0000 - fp: 745.0000 - tn: 181227.0000 - fn: 240.0000 - accuracy: 0.9946 - precision: 0.0791 - recall: 0.2105 - auc: 0.8031 - val_loss: 0.0079 - val_tp: 17.0000 - val_fp:... | Apache-2.0 | courses/machine_learning/deepdive2/introduction_to_tensorflow/solutions/adv_logistic_reg_TF2.0.ipynb | Best-Cloud-Practice-for-Data-Science/training-data-analyst |
Check training historyIn this section, you will produce plots of your model's accuracy and loss on the training and validation set. These are useful to check for overfitting, which you can learn more about in this [tutorial](https://www.tensorflow.org/tutorials/keras/overfit_and_underfit).Additionally, you can produce... | def plot_metrics(history):
metrics = ['loss', 'auc', 'precision', 'recall']
for n, metric in enumerate(metrics):
name = metric.replace("_"," ").capitalize()
plt.subplot(2,2,n+1)
plt.plot(history.epoch, history.history[metric], color=colors[0], label='Train')
plt.plot(history.epoch, history.history... | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive2/introduction_to_tensorflow/solutions/adv_logistic_reg_TF2.0.ipynb | Best-Cloud-Practice-for-Data-Science/training-data-analyst |
Note: That the validation curve generally performs better than the training curve. This is mainly caused by the fact that the dropout layer is not active when evaluating the model. Evaluate metricsYou can use a [confusion matrix](https://developers.google.com/machine-learning/glossary/confusion_matrix) to summarize th... | train_predictions_baseline = model.predict(train_features, batch_size=BATCH_SIZE)
test_predictions_baseline = model.predict(test_features, batch_size=BATCH_SIZE)
def plot_cm(labels, predictions, p=0.5):
cm = confusion_matrix(labels, predictions > p)
plt.figure(figsize=(5,5))
sns.heatmap(cm, annot=True, fmt="d")
... | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive2/introduction_to_tensorflow/solutions/adv_logistic_reg_TF2.0.ipynb | Best-Cloud-Practice-for-Data-Science/training-data-analyst |
Evaluate your model on the test dataset and display the results for the metrics you created above. | baseline_results = model.evaluate(test_features, test_labels,
batch_size=BATCH_SIZE, verbose=0)
for name, value in zip(model.metrics_names, baseline_results):
print(name, ': ', value)
print()
plot_cm(test_labels, test_predictions_baseline) | loss : 0.005941324691873794
tp : 55.0
fp : 12.0
tn : 56845.0
fn : 50.0
accuracy : 0.99891156
precision : 0.8208955
recall : 0.52380955
auc : 0.9390888
Legitimate Transactions Detected (True Negatives): 56845
Legitimate Transactions Incorrectly Detected (False Positives): 12
Fraudulent Transactions Missed (F... | Apache-2.0 | courses/machine_learning/deepdive2/introduction_to_tensorflow/solutions/adv_logistic_reg_TF2.0.ipynb | Best-Cloud-Practice-for-Data-Science/training-data-analyst |
If the model had predicted everything perfectly, this would be a [diagonal matrix](https://en.wikipedia.org/wiki/Diagonal_matrix) where values off the main diagonal, indicating incorrect predictions, would be zero. In this case the matrix shows that you have relatively few false positives, meaning that there were relat... | def plot_roc(name, labels, predictions, **kwargs):
fp, tp, _ = sklearn.metrics.roc_curve(labels, predictions)
plt.plot(100*fp, 100*tp, label=name, linewidth=2, **kwargs)
plt.xlabel('False positives [%]')
plt.ylabel('True positives [%]')
plt.xlim([-0.5,20])
plt.ylim([80,100.5])
plt.grid(True)
ax = plt.g... | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive2/introduction_to_tensorflow/solutions/adv_logistic_reg_TF2.0.ipynb | Best-Cloud-Practice-for-Data-Science/training-data-analyst |
It looks like the precision is relatively high, but the recall and the area under the ROC curve (AUC) aren't as high as you might like. Classifiers often face challenges when trying to maximize both precision and recall, which is especially true when working with imbalanced datasets. It is important to consider the cos... | # Scaling by total/2 helps keep the loss to a similar magnitude.
# The sum of the weights of all examples stays the same.
weight_for_0 = (1 / neg)*(total)/2.0
weight_for_1 = (1 / pos)*(total)/2.0
class_weight = {0: weight_for_0, 1: weight_for_1}
print('Weight for class 0: {:.2f}'.format(weight_for_0))
print('Weight ... | Weight for class 0: 0.50
Weight for class 1: 289.44
| Apache-2.0 | courses/machine_learning/deepdive2/introduction_to_tensorflow/solutions/adv_logistic_reg_TF2.0.ipynb | Best-Cloud-Practice-for-Data-Science/training-data-analyst |
Train a model with class weightsNow try re-training and evaluating the model with class weights to see how that affects the predictions.Note: Using `class_weights` changes the range of the loss. This may affect the stability of the training depending on the optimizer. Optimizers whose step size is dependent on the mag... | weighted_model = make_model()
weighted_model.load_weights(initial_weights)
weighted_history = weighted_model.fit(
train_features,
train_labels,
batch_size=BATCH_SIZE,
epochs=EPOCHS,
callbacks = [early_stopping],
validation_data=(val_features, val_labels),
# The class weights go here
cla... | WARNING:tensorflow:sample_weight modes were coerced from
...
to
['...']
WARNING:tensorflow:sample_weight modes were coerced from
...
to
['...']
Train on 182276 samples, validate on 45569 samples
Epoch 1/100
182276/182276 [==============================] - 3s 19us/sample - loss: 1.0524 - tp: 138.0000... | Apache-2.0 | courses/machine_learning/deepdive2/introduction_to_tensorflow/solutions/adv_logistic_reg_TF2.0.ipynb | Best-Cloud-Practice-for-Data-Science/training-data-analyst |
Check training history | plot_metrics(weighted_history) | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive2/introduction_to_tensorflow/solutions/adv_logistic_reg_TF2.0.ipynb | Best-Cloud-Practice-for-Data-Science/training-data-analyst |
Evaluate metrics | train_predictions_weighted = weighted_model.predict(train_features, batch_size=BATCH_SIZE)
test_predictions_weighted = weighted_model.predict(test_features, batch_size=BATCH_SIZE)
weighted_results = weighted_model.evaluate(test_features, test_labels,
batch_size=BATCH_SIZE, ver... | loss : 0.06950428275801711
tp : 94.0
fp : 905.0
tn : 55952.0
fn : 11.0
accuracy : 0.9839191
precision : 0.0940941
recall : 0.8952381
auc : 0.9844724
Legitimate Transactions Detected (True Negatives): 55952
Legitimate Transactions Incorrectly Detected (False Positives): 905
Fraudulent Transactions Missed (Fa... | Apache-2.0 | courses/machine_learning/deepdive2/introduction_to_tensorflow/solutions/adv_logistic_reg_TF2.0.ipynb | Best-Cloud-Practice-for-Data-Science/training-data-analyst |
Here you can see that with class weights the accuracy and precision are lower because there are more false positives, but conversely the recall and AUC are higher because the model also found more true positives. Despite having lower accuracy, this model has higher recall (and identifies more fraudulent transactions). ... | plot_roc("Train Baseline", train_labels, train_predictions_baseline, color=colors[0])
plot_roc("Test Baseline", test_labels, test_predictions_baseline, color=colors[0], linestyle='--')
plot_roc("Train Weighted", train_labels, train_predictions_weighted, color=colors[1])
plot_roc("Test Weighted", test_labels, test_pred... | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive2/introduction_to_tensorflow/solutions/adv_logistic_reg_TF2.0.ipynb | Best-Cloud-Practice-for-Data-Science/training-data-analyst |
Oversampling Oversample the minority classA related approach would be to resample the dataset by oversampling the minority class. | pos_features = train_features[bool_train_labels]
neg_features = train_features[~bool_train_labels]
pos_labels = train_labels[bool_train_labels]
neg_labels = train_labels[~bool_train_labels] | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive2/introduction_to_tensorflow/solutions/adv_logistic_reg_TF2.0.ipynb | Best-Cloud-Practice-for-Data-Science/training-data-analyst |
Using NumPyYou can balance the dataset manually by choosing the right number of random indices from the positive examples: | ids = np.arange(len(pos_features))
choices = np.random.choice(ids, len(neg_features))
res_pos_features = pos_features[choices]
res_pos_labels = pos_labels[choices]
res_pos_features.shape
resampled_features = np.concatenate([res_pos_features, neg_features], axis=0)
resampled_labels = np.concatenate([res_pos_labels, ne... | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive2/introduction_to_tensorflow/solutions/adv_logistic_reg_TF2.0.ipynb | Best-Cloud-Practice-for-Data-Science/training-data-analyst |
Using `tf.data` If you're using `tf.data` the easiest way to produce balanced examples is to start with a `positive` and a `negative` dataset, and merge them. See [the tf.data guide](../../guide/data.ipynb) for more examples. | BUFFER_SIZE = 100000
def make_ds(features, labels):
ds = tf.data.Dataset.from_tensor_slices((features, labels))#.cache()
ds = ds.shuffle(BUFFER_SIZE).repeat()
return ds
pos_ds = make_ds(pos_features, pos_labels)
neg_ds = make_ds(neg_features, neg_labels) | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive2/introduction_to_tensorflow/solutions/adv_logistic_reg_TF2.0.ipynb | Best-Cloud-Practice-for-Data-Science/training-data-analyst |
Each dataset provides `(feature, label)` pairs: | for features, label in pos_ds.take(1):
print("Features:\n", features.numpy())
print()
print("Label: ", label.numpy()) | Features:
[-2.46955933 3.42534191 -4.42937043 3.70651659 -3.17895499 -1.30458304
-5. 2.86676917 -4.9308611 -5. 3.58555137 -5.
1.51535494 -5. 0.01049775 -5. -5. -5.
2.02380731 0.36595419 1.61836304 -1.16743779 0.31324117 -0.35515978
-0.62579636 -0.55952005 0.51255... | Apache-2.0 | courses/machine_learning/deepdive2/introduction_to_tensorflow/solutions/adv_logistic_reg_TF2.0.ipynb | Best-Cloud-Practice-for-Data-Science/training-data-analyst |
Merge the two together using `experimental.sample_from_datasets`: | resampled_ds = tf.data.experimental.sample_from_datasets([pos_ds, neg_ds], weights=[0.5, 0.5])
resampled_ds = resampled_ds.batch(BATCH_SIZE).prefetch(2)
for features, label in resampled_ds.take(1):
print(label.numpy().mean()) | 0.48974609375
| Apache-2.0 | courses/machine_learning/deepdive2/introduction_to_tensorflow/solutions/adv_logistic_reg_TF2.0.ipynb | Best-Cloud-Practice-for-Data-Science/training-data-analyst |
To use this dataset, you'll need the number of steps per epoch.The definition of "epoch" in this case is less clear. Say it's the number of batches required to see each negative example once: | resampled_steps_per_epoch = np.ceil(2.0*neg/BATCH_SIZE)
resampled_steps_per_epoch | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive2/introduction_to_tensorflow/solutions/adv_logistic_reg_TF2.0.ipynb | Best-Cloud-Practice-for-Data-Science/training-data-analyst |
Train on the oversampled dataNow try training the model with the resampled data set instead of using class weights to see how these methods compare.Note: Because the data was balanced by replicating the positive examples, the total dataset size is larger, and each epoch runs for more training steps. | resampled_model = make_model()
resampled_model.load_weights(initial_weights)
# Reset the bias to zero, since this dataset is balanced.
output_layer = resampled_model.layers[-1]
output_layer.bias.assign([0])
val_ds = tf.data.Dataset.from_tensor_slices((val_features, val_labels)).cache()
val_ds = val_ds.batch(BATCH_SI... | Train for 278.0 steps, validate for 23 steps
Epoch 1/100
278/278 [==============================] - 13s 48ms/step - loss: 0.4624 - tp: 267186.0000 - fp: 124224.0000 - tn: 160439.0000 - fn: 17495.0000 - accuracy: 0.7511 - precision: 0.6826 - recall: 0.9385 - auc: 0.9268 - val_loss: 0.3299 - val_tp: 79.0000 - val_fp: 282... | Apache-2.0 | courses/machine_learning/deepdive2/introduction_to_tensorflow/solutions/adv_logistic_reg_TF2.0.ipynb | Best-Cloud-Practice-for-Data-Science/training-data-analyst |
If the training process were considering the whole dataset on each gradient update, this oversampling would be basically identical to the class weighting.But when training the model batch-wise, as you did here, the oversampled data provides a smoother gradient signal: Instead of each positive example being shown in one... | plot_metrics(resampled_history ) | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive2/introduction_to_tensorflow/solutions/adv_logistic_reg_TF2.0.ipynb | Best-Cloud-Practice-for-Data-Science/training-data-analyst |
Re-train Because training is easier on the balanced data, the above training procedure may overfit quickly. So break up the epochs to give the `callbacks.EarlyStopping` finer control over when to stop training. | resampled_model = make_model()
resampled_model.load_weights(initial_weights)
# Reset the bias to zero, since this dataset is balanced.
output_layer = resampled_model.layers[-1]
output_layer.bias.assign([0])
resampled_history = resampled_model.fit(
resampled_ds,
# These are not real epochs
steps_per_epoch... | Train for 20 steps, validate for 23 steps
Epoch 1/1000
20/20 [==============================] - 4s 181ms/step - loss: 0.8800 - tp: 18783.0000 - fp: 16378.0000 - tn: 4036.0000 - fn: 1763.0000 - accuracy: 0.5571 - precision: 0.5342 - recall: 0.9142 - auc: 0.7752 - val_loss: 1.3661 - val_tp: 83.0000 - val_fp: 40065.0000 -... | Apache-2.0 | courses/machine_learning/deepdive2/introduction_to_tensorflow/solutions/adv_logistic_reg_TF2.0.ipynb | Best-Cloud-Practice-for-Data-Science/training-data-analyst |
Re-check training history | plot_metrics(resampled_history) | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive2/introduction_to_tensorflow/solutions/adv_logistic_reg_TF2.0.ipynb | Best-Cloud-Practice-for-Data-Science/training-data-analyst |
Evaluate metrics | train_predictions_resampled = resampled_model.predict(train_features, batch_size=BATCH_SIZE)
test_predictions_resampled = resampled_model.predict(test_features, batch_size=BATCH_SIZE)
resampled_results = resampled_model.evaluate(test_features, test_labels,
batch_size=BATCH_S... | loss : 0.3960801533448772
tp : 99.0
fp : 5892.0
tn : 50965.0
fn : 6.0
accuracy : 0.8964573
precision : 0.016524788
recall : 0.94285715
auc : 0.9804354
Legitimate Transactions Detected (True Negatives): 50965
Legitimate Transactions Incorrectly Detected (False Positives): 5892
Fraudulent Transactions Missed ... | Apache-2.0 | courses/machine_learning/deepdive2/introduction_to_tensorflow/solutions/adv_logistic_reg_TF2.0.ipynb | Best-Cloud-Practice-for-Data-Science/training-data-analyst |
Plot the ROC | plot_roc("Train Baseline", train_labels, train_predictions_baseline, color=colors[0])
plot_roc("Test Baseline", test_labels, test_predictions_baseline, color=colors[0], linestyle='--')
plot_roc("Train Weighted", train_labels, train_predictions_weighted, color=colors[1])
plot_roc("Test Weighted", test_labels, test_pred... | _____no_output_____ | Apache-2.0 | courses/machine_learning/deepdive2/introduction_to_tensorflow/solutions/adv_logistic_reg_TF2.0.ipynb | Best-Cloud-Practice-for-Data-Science/training-data-analyst |
Assignment 01: Evaluate the FAA Dataset*The comments/sections provided are your cues to perform the assignment. You don't need to limit yourself to the number of rows/cells provided. You can add additional rows in each section to add more lines of code.**If at any point in time you need help on solving this assignment... | #Import necessary libraries
import pandas as pd
#Import the FAA (Federal Aviation Authority) dataset
df_faa_dataset = pd.read_csv("D:/COURSES/Artificial Intellegence Engineer/Data Analytics With Python/Analyse the Federal Aviation Authority Dataset using Pandas/WORK DONE/faa_ai_prelim.csv") | _____no_output_____ | MIT | Analyse the Federal Aviation Authority Dataset using Pandas/WORK DONE/Pandas - Assignment 01.ipynb | NeoWist/aiengineer-simplylearn-projects |
2: View and understand the dataset | #View the dataset shape
df_faa_dataset.shape
#View the first five observations
df_faa_dataset.head()
#View all the columns present in the dataset
df_faa_dataset.columns | _____no_output_____ | MIT | Analyse the Federal Aviation Authority Dataset using Pandas/WORK DONE/Pandas - Assignment 01.ipynb | NeoWist/aiengineer-simplylearn-projects |
3: Extract the following attributes from the dataset:1. Aircraft make name2. State name3. Aircraft model name4. Text information5. Flight phase6. Event description type7. Fatal flag | #Create a new dataframe with only the required columns
df_analyze_dataset = df_faa_dataset[['LOC_STATE_NAME', 'RMK_TEXT', 'EVENT_TYPE_DESC', 'ACFT_MAKE_NAME',
'ACFT_MODEL_NAME', 'FLT_PHASE', 'FATAL_FLAG']]
#View the type of the object
type(df_analyze_dataset)
#Check if the dataframe... | _____no_output_____ | MIT | Analyse the Federal Aviation Authority Dataset using Pandas/WORK DONE/Pandas - Assignment 01.ipynb | NeoWist/aiengineer-simplylearn-projects |
4. Clean the dataset and replace the fatal flag NaN with “No” | #Replace all Fatal Flag missing values with the required output
df_analyze_dataset['FATAL_FLAG'].fillna(value="No",inplace=True)
#Verify if the missing values are replaced
df_analyze_dataset.head()
#Check the number of observations
df_analyze_dataset.shape | _____no_output_____ | MIT | Analyse the Federal Aviation Authority Dataset using Pandas/WORK DONE/Pandas - Assignment 01.ipynb | NeoWist/aiengineer-simplylearn-projects |
5. Remove all the observations where aircraft names are not available | #Drop the unwanted values/observations from the dataset
df_final_dataset = df_analyze_dataset.dropna(subset=['ACFT_MAKE_NAME']) | _____no_output_____ | MIT | Analyse the Federal Aviation Authority Dataset using Pandas/WORK DONE/Pandas - Assignment 01.ipynb | NeoWist/aiengineer-simplylearn-projects |
6. Find the aircraft types and their occurrences in the dataset | #Check the number of observations now to compare it with the original dataset and see how many values have been dropped
df_final_dataset.shape
#Group the dataset by aircraft name
aircraftType = df_final_dataset.groupby('ACFT_MAKE_NAME')
#View the number of times each aircraft type appears in the dataset (Hint: use the ... | _____no_output_____ | MIT | Analyse the Federal Aviation Authority Dataset using Pandas/WORK DONE/Pandas - Assignment 01.ipynb | NeoWist/aiengineer-simplylearn-projects |
7: Display the observations where fatal flag is “Yes” | #Group the dataset by fatal flag
fatalAccedents = df_final_dataset.groupby('FATAL_FLAG')
#View the total number of fatal and non-fatal accidents
fatalAccedents.size()
#Create a new dataframe to view only the fatal accidents (Fatal Flag values = Yes)
accidents_with_fatality = fatalAccedents.get_group('Yes')
accidents_wi... | _____no_output_____ | MIT | Analyse the Federal Aviation Authority Dataset using Pandas/WORK DONE/Pandas - Assignment 01.ipynb | NeoWist/aiengineer-simplylearn-projects |
1D Numpy in PythonEstimated time needed: **30** minutes ObjectivesAfter completing this lab you will be able to:- Import and use `numpy` library- Perform operations with `numpy` Table of Contents Preparation What is Numpy? Type Assign Valu... | # Import the libraries
import time
import sys
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
# Plotting functions
def Plotvec1(u, z, v):
ax = plt.axes()
ax.arrow(0, 0, *u, head_width=0.05, color='r', head_length=0.1)
plt.text(*(u + 0.1), 'u')
ax.arrow(0, 0, *v, he... | _____no_output_____ | MIT | material/PY0101EN-5-1-Numpy1D.ipynb | sergiodealencar/courses |
Create a Python List as follows: | # Create a python list
a = ["0", 1, "two", "3", 4] | _____no_output_____ | MIT | material/PY0101EN-5-1-Numpy1D.ipynb | sergiodealencar/courses |
We can access the data via an index: We can access each element using a square bracket as follows: | # Print each element
print("a[0]:", a[0])
print("a[1]:", a[1])
print("a[2]:", a[2])
print("a[3]:", a[3])
print("a[4]:", a[4]) | a[0]: 0
a[1]: 1
a[2]: two
a[3]: 3
a[4]: 4
| MIT | material/PY0101EN-5-1-Numpy1D.ipynb | sergiodealencar/courses |
What is Numpy? A numpy array is similar to a list. It's usually fixed in size and each element is of the same type. We can cast a list to a numpy array by first importing numpy: | # import numpy library
import numpy as np | _____no_output_____ | MIT | material/PY0101EN-5-1-Numpy1D.ipynb | sergiodealencar/courses |
We then cast the list as follows: | # Create a numpy array
a = np.array([0, 1, 2, 3, 4])
a | _____no_output_____ | MIT | material/PY0101EN-5-1-Numpy1D.ipynb | sergiodealencar/courses |
Each element is of the same type, in this case integers: As with lists, we can access each element via a square bracket: | # Print each element
print("a[0]:", a[0])
print("a[1]:", a[1])
print("a[2]:", a[2])
print("a[3]:", a[3])
print("a[4]:", a[4]) | a[0]: 0
a[1]: 1
a[2]: 2
a[3]: 3
a[4]: 4
| MIT | material/PY0101EN-5-1-Numpy1D.ipynb | sergiodealencar/courses |
Type If we check the type of the array we get numpy.ndarray: | # Check the type of the array
type(a) | _____no_output_____ | MIT | material/PY0101EN-5-1-Numpy1D.ipynb | sergiodealencar/courses |
As numpy arrays contain data of the same type, we can use the attribute "dtype" to obtain the Data-type of the array’s elements. In this case a 64-bit integer: | # Check the type of the values stored in numpy array
a.dtype | _____no_output_____ | MIT | material/PY0101EN-5-1-Numpy1D.ipynb | sergiodealencar/courses |
We can create a numpy array with real numbers: | # Create a numpy array
b = np.array([3.1, 11.02, 6.2, 213.2, 5.2]) | _____no_output_____ | MIT | material/PY0101EN-5-1-Numpy1D.ipynb | sergiodealencar/courses |
When we check the type of the array we get numpy.ndarray: | # Check the type of array
type(b) | _____no_output_____ | MIT | material/PY0101EN-5-1-Numpy1D.ipynb | sergiodealencar/courses |
If we examine the attribute dtype we see float 64, as the elements are not integers: | # Check the value type
b.dtype | _____no_output_____ | MIT | material/PY0101EN-5-1-Numpy1D.ipynb | sergiodealencar/courses |
Assign value We can change the value of the array, consider the array c: | # Create numpy array
c = np.array([20, 1, 2, 3, 4])
c | _____no_output_____ | MIT | material/PY0101EN-5-1-Numpy1D.ipynb | sergiodealencar/courses |
We can change the first element of the array to 100 as follows: | # Assign the first element to 100
c[0] = 100
c | _____no_output_____ | MIT | material/PY0101EN-5-1-Numpy1D.ipynb | sergiodealencar/courses |
We can change the 5th element of the array to 0 as follows: | # Assign the 5th element to 0
c[4] = 0
c | _____no_output_____ | MIT | material/PY0101EN-5-1-Numpy1D.ipynb | sergiodealencar/courses |
Slicing Like lists, we can slice the numpy array, and we can select the elements from 1 to 3 and assign it to a new numpy array d as follows: | # Slicing the numpy array
d = c[1:4]
d | _____no_output_____ | MIT | material/PY0101EN-5-1-Numpy1D.ipynb | sergiodealencar/courses |
We can assign the corresponding indexes to new values as follows: | # Set the fourth element and fifth element to 300 and 400
c[3:5] = 300, 400
c | _____no_output_____ | MIT | material/PY0101EN-5-1-Numpy1D.ipynb | sergiodealencar/courses |
Assign Value with List Similarly, we can use a list to select a specific index.The list ' select ' contains several values: | # Create the index list
select = [0, 2, 3] | _____no_output_____ | MIT | material/PY0101EN-5-1-Numpy1D.ipynb | sergiodealencar/courses |
We can use the list as an argument in the brackets. The output is the elements corresponding to the particular index: | # Use List to select elements
d = c[select]
d | _____no_output_____ | MIT | material/PY0101EN-5-1-Numpy1D.ipynb | sergiodealencar/courses |
We can assign the specified elements to a new value. For example, we can assign the values to 100 000 as follows: | # Assign the specified elements to new value
c[select] = 100000
c | _____no_output_____ | MIT | material/PY0101EN-5-1-Numpy1D.ipynb | sergiodealencar/courses |
Other Attributes Let's review some basic array attributes using the array a: | # Create a numpy array
a = np.array([0, 1, 2, 3, 4])
a | _____no_output_____ | MIT | material/PY0101EN-5-1-Numpy1D.ipynb | sergiodealencar/courses |
The attribute size is the number of elements in the array: | # Get the size of numpy array
a.size | _____no_output_____ | MIT | material/PY0101EN-5-1-Numpy1D.ipynb | sergiodealencar/courses |
The next two attributes will make more sense when we get to higher dimensions but let's review them. The attribute ndim represents the number of array dimensions or the rank of the array, in this case, one: | # Get the number of dimensions of numpy array
a.ndim | _____no_output_____ | MIT | material/PY0101EN-5-1-Numpy1D.ipynb | sergiodealencar/courses |
The attribute shape is a tuple of integers indicating the size of the array in each dimension: | # Get the shape/size of numpy array
a.shape
# Create a numpy array
a = np.array([1, -1, 1, -1])
# Get the mean of numpy array
mean = a.mean()
mean
# Get the standard deviation of numpy array
standard_deviation=a.std()
standard_deviation
# Create a numpy array
b = np.array([-1, 2, 3, 4, 5])
b
# Get the biggest valu... | _____no_output_____ | MIT | material/PY0101EN-5-1-Numpy1D.ipynb | sergiodealencar/courses |
Numpy Array Operations Array Addition Consider the numpy array u: | u = np.array([1, 0])
u | _____no_output_____ | MIT | material/PY0101EN-5-1-Numpy1D.ipynb | sergiodealencar/courses |
Consider the numpy array v: | v = np.array([0, 1])
v | _____no_output_____ | MIT | material/PY0101EN-5-1-Numpy1D.ipynb | sergiodealencar/courses |
We can add the two arrays and assign it to z: | # Numpy Array Addition
z = u + v
z | _____no_output_____ | MIT | material/PY0101EN-5-1-Numpy1D.ipynb | sergiodealencar/courses |
The operation is equivalent to vector addition: | # Plot numpy arrays
Plotvec1(u, z, v) | _____no_output_____ | MIT | material/PY0101EN-5-1-Numpy1D.ipynb | sergiodealencar/courses |
Array Multiplication Consider the vector numpy array y: | # Create a numpy array
y = np.array([1, 2])
y | _____no_output_____ | MIT | material/PY0101EN-5-1-Numpy1D.ipynb | sergiodealencar/courses |
We can multiply every element in the array by 2: | # Numpy Array Multiplication
z = 2 * y
z | _____no_output_____ | MIT | material/PY0101EN-5-1-Numpy1D.ipynb | sergiodealencar/courses |
This is equivalent to multiplying a vector by a scaler: Product of Two Numpy Arrays Consider the following array u: | # Create a numpy array
u = np.array([1, 2])
u | _____no_output_____ | MIT | material/PY0101EN-5-1-Numpy1D.ipynb | sergiodealencar/courses |
Consider the following array v: | # Create a numpy array
v = np.array([3, 2])
v | _____no_output_____ | MIT | material/PY0101EN-5-1-Numpy1D.ipynb | sergiodealencar/courses |
The product of the two numpy arrays u and v is given by: | # Calculate the production of two numpy arrays
z = u * v
z | _____no_output_____ | MIT | material/PY0101EN-5-1-Numpy1D.ipynb | sergiodealencar/courses |
Dot Product The dot product of the two numpy arrays u and v is given by: | # Calculate the dot product
np.dot(u, v) | _____no_output_____ | MIT | material/PY0101EN-5-1-Numpy1D.ipynb | sergiodealencar/courses |
Adding Constant to a Numpy Array Consider the following array: | # Create a constant to numpy array
u = np.array([1, 2, 3, -1])
u | _____no_output_____ | MIT | material/PY0101EN-5-1-Numpy1D.ipynb | sergiodealencar/courses |
Adding the constant 1 to each element in the array: | # Add the constant to array
u + 1 | _____no_output_____ | MIT | material/PY0101EN-5-1-Numpy1D.ipynb | sergiodealencar/courses |
The process is summarised in the following animation: Mathematical Functions We can access the value of pi in numpy as follows : | # The value of pi
np.pi | _____no_output_____ | MIT | material/PY0101EN-5-1-Numpy1D.ipynb | sergiodealencar/courses |
We can create the following numpy array in Radians: | # Create the numpy array in radians
x = np.array([0, np.pi/2 , np.pi])
x | _____no_output_____ | MIT | material/PY0101EN-5-1-Numpy1D.ipynb | sergiodealencar/courses |
We can apply the function sin to the array x and assign the values to the array y; this applies the sine function to each element in the array: | # Calculate the sin of each elements
y = np.sin(x)
y | _____no_output_____ | MIT | material/PY0101EN-5-1-Numpy1D.ipynb | sergiodealencar/courses |
Linspace A useful function for plotting mathematical functions is linspace. Linspace returns evenly spaced numbers over a specified interval. We specify the starting point of the sequence and the ending point of the sequence. The parameter "num" indicates the Number of samples to generate, in this case 5: | # Makeup a numpy array within [-2, 2] and 5 elements
np.linspace(-2, 2, num=5) | _____no_output_____ | MIT | material/PY0101EN-5-1-Numpy1D.ipynb | sergiodealencar/courses |
If we change the parameter num to 9, we get 9 evenly spaced numbers over the interval from -2 to 2: | # Makeup a numpy array within [-2, 2] and 9 elements
np.linspace(-2, 2, num=9) | _____no_output_____ | MIT | material/PY0101EN-5-1-Numpy1D.ipynb | sergiodealencar/courses |
We can use the function linspace to generate 100 evenly spaced samples from the interval 0 to 2π: | # Makeup a numpy array within [0, 2π] and 100 elements
x = np.linspace(0, 2*np.pi, num=100) | _____no_output_____ | MIT | material/PY0101EN-5-1-Numpy1D.ipynb | sergiodealencar/courses |
We can apply the sine function to each element in the array x and assign it to the array y: | # Calculate the sine of x list
y = np.sin(x)
# Plot the result
plt.plot(x, y) | _____no_output_____ | MIT | material/PY0101EN-5-1-Numpy1D.ipynb | sergiodealencar/courses |
Quiz on 1D Numpy Array Implement the following vector subtraction in numpy: u-v | # Write your code below and press Shift+Enter to execute
u = np.array([1, 0])
v = np.array([0, 1])
u-v | _____no_output_____ | MIT | material/PY0101EN-5-1-Numpy1D.ipynb | sergiodealencar/courses |
Click here for the solution```pythonu - v``` Multiply the numpy array z with -2: | # Write your code below and press Shift+Enter to execute
z = np.array([2, 4])
-2*z | _____no_output_____ | MIT | material/PY0101EN-5-1-Numpy1D.ipynb | sergiodealencar/courses |
Click here for the solution```python-2 * z``` Consider the list [1, 2, 3, 4, 5] and [1, 0, 1, 0, 1], and cast both lists to a numpy array then multiply them together: | # Write your code below and press Shift+Enter to execute
a = np.array([1, 2, 3, 4, 5])
b = np.array([1, 0, 1, 0, 1])
a*b | _____no_output_____ | MIT | material/PY0101EN-5-1-Numpy1D.ipynb | sergiodealencar/courses |
Click here for the solution```pythona = np.array([1, 2, 3, 4, 5])b = np.array([1, 0, 1, 0, 1])a * b``` Convert the list [-1, 1] and [1, 1] to numpy arrays a and b. Then, plot the arrays as vectors using the fuction Plotvec2 and find the dot product: | # Write your code below and press Shift+Enter to execute
a = np.array([-1, 1])
b = np.array([1, 1])
Plotvec2(a, b)
print("The dot product is", np.dot(a,b)) | The dot product is 0
| MIT | material/PY0101EN-5-1-Numpy1D.ipynb | sergiodealencar/courses |
Click here for the solution```pythona = np.array([-1, 1])b = np.array([1, 1])Plotvec2(a, b)print("The dot product is", np.dot(a,b))``` Convert the list [1, 0] and [0, 1] to numpy arrays a and b. Then, plot the arrays as vectors using the function Plotvec2 and find the dot product: | # Write your code below and press Shift+Enter to execute
a = np.array([1, 0])
b = np.array([0, 1])
Plotvec2(a, b)
print("The dot product is", np.dot(a,b)) | The dot product is 0
| MIT | material/PY0101EN-5-1-Numpy1D.ipynb | sergiodealencar/courses |
Click here for the solution```pythona = np.array([1, 0])b = np.array([0, 1])Plotvec2(a, b)print("The dot product is", np.dot(a, b))``` Convert the list [1, 1] and [0, 1] to numpy arrays a and b. Then plot the arrays as vectors using the fuction Plotvec2 and find the dot product: | # Write your code below and press Shift+Enter to execute
a = np.array([1, 1])
b = np.array([0, 1])
Plotvec2(a, b)
print("The dot product is", np.dot(a,b)) | The dot product is 1
| MIT | material/PY0101EN-5-1-Numpy1D.ipynb | sergiodealencar/courses |
Click here for the solution```pythona = np.array([1, 1])b = np.array([0, 1])Plotvec2(a, b)print("The dot product is", np.dot(a, b))print("The dot product is", np.dot(a, b))``` Why are the results of the dot product for [-1, 1] and [1, 1] and the dot product for [1, 0] and [0, 1] zero, but not zero for the dot product... | # Write your code below and press Shift+Enter to execute
| _____no_output_____ | MIT | material/PY0101EN-5-1-Numpy1D.ipynb | sergiodealencar/courses |
Semi-Monocoque Theory: corrective solutions | from pint import UnitRegistry
import sympy
import networkx as nx
import numpy as np
import matplotlib.pyplot as plt
import sys
%matplotlib inline
from IPython.display import display | _____no_output_____ | MIT | 04_CorrectiveSolutions.ipynb | Ccaccia73/semimonocoque |
Import **Section** class, which contains all calculations | from Section import Section | _____no_output_____ | MIT | 04_CorrectiveSolutions.ipynb | Ccaccia73/semimonocoque |
Initialization of **sympy** symbolic tool and **pint** for dimension analysis (not really implemented rn as not directly compatible with sympy) | ureg = UnitRegistry()
sympy.init_printing() | _____no_output_____ | MIT | 04_CorrectiveSolutions.ipynb | Ccaccia73/semimonocoque |
Define **sympy** parameters used for geometric description of sections | A, A0, t, t0, a, b, h, L, E, G = sympy.symbols('A A_0 t t_0 a b h L E G', positive=True) | _____no_output_____ | MIT | 04_CorrectiveSolutions.ipynb | Ccaccia73/semimonocoque |
We also define numerical values for each **symbol** in order to plot scaled section and perform calculations | values = [(A, 150 * ureg.millimeter**2),(A0, 250 * ureg.millimeter**2),(a, 80 * ureg.millimeter), \
(b, 20 * ureg.millimeter),(h, 35 * ureg.millimeter),(L, 2000 * ureg.millimeter), \
(t, 0.8 *ureg.millimeter),(E, 72e3 * ureg.MPa), (G, 27e3 * ureg.MPa)]
datav = [(v[0],v[1].magnitude) for v in values... | _____no_output_____ | MIT | 04_CorrectiveSolutions.ipynb | Ccaccia73/semimonocoque |
First example: Simple rectangular symmetric section Define graph describing the section:1) **stringers** are **nodes** with parameters:- **x** coordinate- **y** coordinate- **Area**2) **panels** are **oriented edges** with parameters:- **thickness**- **lenght** which is automatically calculated | stringers = {1:[(2*a,h),A],
2:[(a,h),A],
3:[(sympy.Integer(0),h),A],
4:[(sympy.Integer(0),sympy.Integer(0)),A],
5:[(2*a,sympy.Integer(0)),A]}
#5:[(sympy.Rational(1,2)*a,h),A]}
panels = {(1,2):t,
(2,3):t,
(3,4):t,
(4,5):t,
... | _____no_output_____ | MIT | 04_CorrectiveSolutions.ipynb | Ccaccia73/semimonocoque |
Define section and perform first calculations | S1 = Section(stringers, panels)
S1.cycles | _____no_output_____ | MIT | 04_CorrectiveSolutions.ipynb | Ccaccia73/semimonocoque |
Plot of **S1** section in original reference frame Define a dictionary of coordinates used by **Networkx** to plot section as a Directed graph.Note that arrows are actually just thicker stubs | start_pos={ii: [float(S1.g.node[ii]['ip'][i].subs(datav)) for i in range(2)] for ii in S1.g.nodes() }
plt.figure(figsize=(12,8),dpi=300)
nx.draw(S1.g,with_labels=True, arrows= True, pos=start_pos)
plt.arrow(0,0,20,0)
plt.arrow(0,0,0,20)
#plt.text(0,0, 'CG', fontsize=24)
plt.axis('equal')
plt.title("Section in starting ... | _____no_output_____ | MIT | 04_CorrectiveSolutions.ipynb | Ccaccia73/semimonocoque |
Plot of **S1** section in inertial reference Frame Section is plotted wrt **center of gravity** and rotated (if necessary) so that *x* and *y* are principal axes.**Center of Gravity** and **Shear Center** are drawn | positions={ii: [float(S1.g.node[ii]['pos'][i].subs(datav)) for i in range(2)] for ii in S1.g.nodes() }
x_ct, y_ct = S1.ct.subs(datav)
plt.figure(figsize=(12,8),dpi=300)
nx.draw(S1.g,with_labels=True, pos=positions)
plt.plot([0],[0],'o',ms=12,label='CG')
plt.plot([x_ct],[y_ct],'^',ms=12, label='SC')
#plt.text(0,0, 'CG'... | _____no_output_____ | MIT | 04_CorrectiveSolutions.ipynb | Ccaccia73/semimonocoque |
Compute **L** matrix: with 5 nodes we expect 2 **dofs**, one with _symmetric load_ and one with _antisymmetric load_ | S1.compute_L()
S1.L | _____no_output_____ | MIT | 04_CorrectiveSolutions.ipynb | Ccaccia73/semimonocoque |
Compute **H** matrix | S1.compute_H()
S1.H | _____no_output_____ | MIT | 04_CorrectiveSolutions.ipynb | Ccaccia73/semimonocoque |
Compute $\tilde{K}$ and $\tilde{M}$ as:$$\tilde{K} = L^T \cdot \left[ \frac{A}{A_0} \right] \cdot L$$$$\tilde{M} = H^T \cdot \left[ \frac{l}{l_0}\frac{t_0}{t} \right] \cdot L$$ | S1.compute_KM(A,h,t)
S1.Ktilde
S1.Mtilde | _____no_output_____ | MIT | 04_CorrectiveSolutions.ipynb | Ccaccia73/semimonocoque |
Compute **eigenvalues** and **eigenvectors** as:$$\left| \mathbf{I} \cdot \beta^2 - \mathbf{\tilde{K}}^{-1} \cdot \mathbf{\tilde{M}} \right| = 0$$We substitute some numerical values to simplify the expressions | sol_data = (S1.Ktilde.inv()*(S1.Mtilde.subs(datav))).eigenvects() | _____no_output_____ | MIT | 04_CorrectiveSolutions.ipynb | Ccaccia73/semimonocoque |
**Eigenvalues** correspond to $\beta^2$ | β2 = [sol[0] for sol in sol_data]
β2 | _____no_output_____ | MIT | 04_CorrectiveSolutions.ipynb | Ccaccia73/semimonocoque |
**Eigenvectors** are orthogonal as expected | X = [sol[2][0] for sol in sol_data]
X | _____no_output_____ | MIT | 04_CorrectiveSolutions.ipynb | Ccaccia73/semimonocoque |
From $\beta_i^2$ we compute:$$\lambda_i = \sqrt{\frac{E A_0 l_0}{G t_0} \beta_i^2}$$substuting numerical values | λ = [sympy.N(sympy.sqrt(E*A*h/(G*t)*βi).subs(datav)) for βi in β2]
λ | _____no_output_____ | MIT | 04_CorrectiveSolutions.ipynb | Ccaccia73/semimonocoque |
Examining Total Category List | # restaurants categories in the dataset: all
print(sorted(set(', '.join(dataset.category_alias).split(', '))))
yelp_categories = pd.read_json("../../data/raw/categories.json")
# select only one parent categories
yelp_categories = yelp_categories[yelp_categories.parents.apply(lambda x: len(x) == 1) == True]
res_list = ... | _____no_output_____ | MIT | notebooks/eda/businesses.ipynb | metinsenturk/semantic-analysis |
Exploratory Data Analysis | print(dataset.loc[dataset.alias.isin(yelp_branches)].rating.sum())
print(dataset.loc[dataset.alias.isin(yelp_branches)].rating.mean())
len(dataset)
dataset.is_closed[dataset.is_closed == True].count()
dataset.price.value_counts()
print(f"sum : {dataset.review_count.sum()}")
print(f"mean: {dataset.review_count.mean()}")... | _____no_output_____ | MIT | notebooks/eda/businesses.ipynb | metinsenturk/semantic-analysis |
With additional features | models_path = "/home/soufiane.oualil/lustre/data_sec-um6p-st-sccs-6sevvl76uja/IDS/prod_ai_models/ML/full_binary_0/"
dataset = "UNSW-NB15"
dataset_path = f"/home/soufiane.oualil/lustre/data_sec-um6p-st-sccs-6sevvl76uja/IDS/preprocessed_datasets/{dataset}/flow_features/multi/"
data = pd.read_pickle(f'{dataset_path}/t... | ['Benign' 'Benign' 'Benign' 'Malign' 'Benign' 'Benign' 'Benign' 'Benign'
'Benign' 'Benign' 'Benign' 'Benign' 'Benign' 'Benign' 'Benign' 'Benign'
'Benign' 'Benign' 'Benign' 'Benign']
| BSD-3-Clause | Prod_ML_IDS_model.ipynb | sooualil/atlas-plugin-sample |
Without additional features | models_path = "/home/abdellah.elmekki/lustre/data_sec-um6p-st-sccs-6sevvl76uja/IDS/prod_ai_models/ML/full_binary_1/"
data = pd.read_pickle(f'{dataset_path}/test.p')
y = data['Attack'].values
data = data.drop(columns_to_delete + additional_columns + ['Attack'], axis = 1)
for column in columns_to_encode:
le = load(f... | ['Benign' 'Benign' 'Benign' 'Malign' 'Benign' 'Benign' 'Benign' 'Benign'
'Benign' 'Benign' 'Benign' 'Benign' 'Benign' 'Benign' 'Benign' 'Benign'
'Benign' 'Benign' 'Benign' 'Benign']
| BSD-3-Clause | Prod_ML_IDS_model.ipynb | sooualil/atlas-plugin-sample |
Install python librariesThe following cell can be used to ensure that the python libraries usedin this test notebook are installed.These may be pre-installed in future notebook images.Once this cell has been run, it need not be re-run unless you have restarted your jupyter server. | # Install the library dependencies used in this notebook
# (comment this out if you prefer to not re-run this cell)
%pip install trino python-dotenv | Requirement already satisfied: trino in /opt/app-root/lib/python3.8/site-packages (0.306.0)
Requirement already satisfied: python-dotenv in /opt/app-root/lib/python3.8/site-packages (0.19.1)
Requirement already satisfied: requests in /opt/app-root/lib/python3.8/site-packages (from trino) (2.25.1)
Requirement already sa... | FTL | notebooks/test-trino-access.ipynb | os-climate/data-platform-demo |
Loading credentialsThe following cell finds a `credentials.env` file at the jupyter "home" (top level) directory.Values in this `dotenv` file are loaded into the `os.environ` table,as if they were regular environment variables.Credentials are stored in `dotenv` files so that they can be referred to by standardenvironm... | from dotenv import dotenv_values, load_dotenv
import os
import pathlib
dotenv_dir = os.environ.get('CREDENTIAL_DOTENV_DIR', os.environ.get('PWD', '/opt/app-root/src'))
dotenv_path = pathlib.Path(dotenv_dir) / 'credentials.env'
if os.path.exists(dotenv_path):
load_dotenv(dotenv_path=dotenv_path,override=True) | _____no_output_____ | FTL | notebooks/test-trino-access.ipynb | os-climate/data-platform-demo |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.