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 |
|---|---|---|---|---|---|
ignore the above o/p, the main o/ps are below. | print(datai_list)
data_total_GB = [[z/(8*1024*1024) for z in y]for y in datai_list]
print(data_total_GB)
fig = plt.figure(figsize=(12,12))
#figsize=(15,15)
plt.plot(range(49),data_total_GB[0],label="30deg")
plt.plot(range(49),data_total_GB[1],label="20deg")
plt.plot(range(49),data_total_GB[2],label="10deg")
plt.plot(ra... | _____no_output_____ | MIT | LatitudeTable.ipynb | kssumanth27/notebooks |
Amazon SageMaker Debugger - Using built-in rule[Amazon SageMaker](https://aws.amazon.com/sagemaker/) is managed platform to build, train and host maching learning models. Amazon SageMaker Debugger is a new feature which offers the capability to debug machine learning models during training by identifying and detecting... | ! pip install smdebug | Requirement already satisfied: smdebug in /opt/conda/lib/python3.7/site-packages (0.7.2)
Requirement already satisfied: boto3>=1.10.32 in /opt/conda/lib/python3.7/site-packages (from smdebug) (1.12.45)
Requirement already satisfied: protobuf>=3.6.0 in /opt/conda/lib/python3.7/site-packages (from smdebug) (3.11.3)
Requi... | Apache-2.0 | aws_sagemaker_studio/sagemaker_debugger/tensorflow_builtin_rule/tf-mnist-builtin-rule.ipynb | fhirschmann/amazon-sagemaker-examples |
With the setup out of the way let's start training our TensorFlow model in SageMaker with the debugger enabled. Training TensorFlow models in SageMaker with Amazon SageMaker Debugger SageMaker TensorFlow as a frameworkWe'll train a TensorFlow model in this notebook with Amazon Sagemaker Debugger enabled and monitor the... | import boto3
import os
import sagemaker
from sagemaker.tensorflow import TensorFlow | _____no_output_____ | Apache-2.0 | aws_sagemaker_studio/sagemaker_debugger/tensorflow_builtin_rule/tf-mnist-builtin-rule.ipynb | fhirschmann/amazon-sagemaker-examples |
Let's import the libraries needed for our demo of Amazon SageMaker Debugger. | from sagemaker.debugger import Rule, DebuggerHookConfig, TensorBoardOutputConfig, CollectionConfig, rule_configs | _____no_output_____ | Apache-2.0 | aws_sagemaker_studio/sagemaker_debugger/tensorflow_builtin_rule/tf-mnist-builtin-rule.ipynb | fhirschmann/amazon-sagemaker-examples |
Now we'll define the configuration for our training to run. We'll using image recognition using MNIST dataset as our training example. | # define the entrypoint script
entrypoint_script='src/mnist_zerocodechange.py'
hyperparameters = {
"num_epochs": 1
}
!pygmentize src/mnist_zerocodechange.py | [33m"""[39;49;00m
[33mThis script is a simple MNIST training script which uses Tensorflow's Estimator interface.[39;49;00m
[33mIt is designed to be used with SageMaker Debugger in an official SageMaker Framework container (i.e. AWS Deep Learning Container). You will notice that this script looks exactly like a nor... | Apache-2.0 | aws_sagemaker_studio/sagemaker_debugger/tensorflow_builtin_rule/tf-mnist-builtin-rule.ipynb | fhirschmann/amazon-sagemaker-examples |
Setting up the EstimatorNow it's time to setup our TensorFlow estimator. We've added new parameters to the estimator to enable your training job for debugging through Amazon SageMaker Debugger. These new parameters are explained below.* **debugger_hook_config**: This new parameter accepts a local path where you wish y... | rules = [
Rule.sagemaker(rule_configs.vanishing_gradient()),
Rule.sagemaker(rule_configs.loss_not_decreasing())
]
estimator = TensorFlow(
role=sagemaker.get_execution_role(),
base_job_name='smdebugger-demo-mnist-tensorflow',
train_instance_count=1,
train_instance_type='ml.m4.xlarge',
train... | _____no_output_____ | Apache-2.0 | aws_sagemaker_studio/sagemaker_debugger/tensorflow_builtin_rule/tf-mnist-builtin-rule.ipynb | fhirschmann/amazon-sagemaker-examples |
*Note that Amazon Sagemaker Debugger is only supported for py_version='py3' currently.*Let's start the training by calling `fit()` on the TensorFlow estimator. | estimator.fit(wait=True) | 2020-04-27 23:56:40 Starting - Starting the training job...
2020-04-27 23:57:04 Starting - Launching requested ML instances
********* Debugger Rule Status *********
*
* VanishingGradient: InProgress
* LossNotDecreasing: InProgress
*
****************************************
...
2020-04-27 23:57:36 Star... | Apache-2.0 | aws_sagemaker_studio/sagemaker_debugger/tensorflow_builtin_rule/tf-mnist-builtin-rule.ipynb | fhirschmann/amazon-sagemaker-examples |
Result As a result of calling the `fit()` Amazon SageMaker Debugger kicked off two rule evaluation jobs to monitor vanishing gradient and loss decrease, in parallel with the training job. The rule evaluation status(es) will be visible in the training logs at regular intervals. As you can see, in the summary, there was... | estimator.latest_training_job.rule_job_summary() | _____no_output_____ | Apache-2.0 | aws_sagemaker_studio/sagemaker_debugger/tensorflow_builtin_rule/tf-mnist-builtin-rule.ipynb | fhirschmann/amazon-sagemaker-examples |
Let's try and look at the logs of the rule job for loss not decreasing. To do that, we'll use this utlity function to get a link to the rule job logs. | def _get_rule_job_name(training_job_name, rule_configuration_name, rule_job_arn):
"""Helper function to get the rule job name with correct casing"""
return "{}-{}-{}".format(
training_job_name[:26], rule_configuration_name[:26], rule_job_arn[-8:]
)
def _get_cw_url_for_rule_job(r... | _____no_output_____ | Apache-2.0 | aws_sagemaker_studio/sagemaker_debugger/tensorflow_builtin_rule/tf-mnist-builtin-rule.ipynb | fhirschmann/amazon-sagemaker-examples |
Data Analysis - Interactive ExplorationNow that we have trained a job, and looked at automated analysis through rules, let us also look at another aspect of Amazon SageMaker Debugger. It allows us to perform interactive exploration of the tensors saved in real time or after the job. Here we focus on after-the-fact ana... | from smdebug.trials import create_trial
trial = create_trial(estimator.latest_job_debugger_artifacts_path()) | [2020-04-28 00:07:09.068 f8455ab5c5ab:546 INFO s3_trial.py:42] Loading trial debug-output at path s3://sagemaker-us-east-2-441510144314/smdebugger-demo-mnist-tensorflow-2020-04-27-23-56-39-900/debug-output
| Apache-2.0 | aws_sagemaker_studio/sagemaker_debugger/tensorflow_builtin_rule/tf-mnist-builtin-rule.ipynb | fhirschmann/amazon-sagemaker-examples |
We can list all the tensors that were recorded to know what we want to plot. Each one of these names is the name of a tensor, which is auto-assigned by TensorFlow. In some frameworks where such names are not available, we try to create a name based on the layer's name and whether it is weight, bias, gradient, input or ... | trial.tensor_names() | [2020-04-28 00:07:11.217 f8455ab5c5ab:546 INFO trial.py:198] Training has ended, will refresh one final time in 1 sec.
[2020-04-28 00:07:12.236 f8455ab5c5ab:546 INFO trial.py:210] Loaded all steps
| Apache-2.0 | aws_sagemaker_studio/sagemaker_debugger/tensorflow_builtin_rule/tf-mnist-builtin-rule.ipynb | fhirschmann/amazon-sagemaker-examples |
We can also retrieve tensors by some default collections that `smdebug` creates from your training job. Here we are interested in the losses collection, so we can retrieve the names of tensors in losses collection as follows. Amazon SageMaker Debugger creates default collections such as weights, gradients, biases, loss... | trial.tensor_names(collection="losses")
import matplotlib.pyplot as plt
import re
# Define a function that, for the given tensor name, walks through all
# the iterations for which we have data and fetches the value.
# Returns the set of steps and the values
def get_data(trial, tname):
tensor = trial.tensor(tname)... | _____no_output_____ | Apache-2.0 | aws_sagemaker_studio/sagemaker_debugger/tensorflow_builtin_rule/tf-mnist-builtin-rule.ipynb | fhirschmann/amazon-sagemaker-examples |
Rรฉcursivitรฉ Introduction **Objectifs**:- Comprendre que des problรจmes complexes qui peuvent รชtre difficiles ร rรฉsoudre avec les ยซtechniques habituellesยป peuvent avoir une solution rรฉcursive simple,- Apprendre ร formuler des programmes rรฉcursivement,- Comprendre et appliquer les trois lois de la rรฉcursivitรฉ,- Comprend... | def sommer(nbs):
somme = 0 # accu
for nb in nbs:
somme = somme + nb # ou somme += nb
return somme
assert sommer([5, 4, 7]) == 16 | _____no_output_____ | CC0-1.0 | 1_recursivite/1_recursivite.ipynb | efloti/cours-nsi-terminale |
La somme se produit alors comme suit: $$(\underbrace{ (\underbrace{ (\underbrace{(0+5)}_{\text{it. 1} } +4) }_{\text{it. 2}}+7)}_{\text{it. 3}})$$ Mais supposez un instant que nous ne disposions ni de boucle `while`, ni de boucle `for`. Comme mathรฉmatiquement: $$(((5) + 4)+7)=5+4+7=(5+(4+(7)))$$ no... | def sommer(nbs):
# cas oรน le problรจme est suffisemment petit
if len(nbs) == 1:
return nbs[0]
# si le problรจme est trop gros
else:
# dรฉcoupage
premier, *reste = nbs # ou premier = nbs[0]; reste = nbs[1:]
# rรฉsolution du sous-pb en appelant **cette** fonction
s... | _____no_output_____ | CC0-1.0 | 1_recursivite/1_recursivite.ipynb | efloti/cours-nsi-terminale |
En utilisant la **composition** et les **tranches** \[*slices*\], on peut exprimer cela de faรงon plus concise: | def sommer(nbs):
if len(nbs) == 1: return nbs[0] # cas de base
return nbs[0] + sommer(nbs[1:]) # appel rรฉcursif
assert sommer([5, 4, 7]) == 16 | _____no_output_____ | CC0-1.0 | 1_recursivite/1_recursivite.ipynb | efloti/cours-nsi-terminale |
voir dans [Python Tutor](http://pythontutor.com/visualize.htmlcode=def%20sommer%28nbs%29%3A%0A%20%20%20%20if%20len%28nbs%29%20%3D%3D%201%3A%20return%20nbs%5B0%5D%0A%20%20%20%20return%20nbs%5B0%5D%20%2B%20sommer%28nbs%5B1%3A%5D%29%0A%0Aprint%28sommer%28%5B5,%204,%207%5D%29%29&cumulative=false&curInstr=0&heapPrimitives=f... | def sommer(nbs):
return nbs[0] + sommer(nbs[1:]) if len(nbs) > 1 else nbs[0]
assert sommer([5, 4, 7]) == 16 | _____no_output_____ | CC0-1.0 | 1_recursivite/1_recursivite.ipynb | efloti/cours-nsi-terminale |
Voici les **points clรฉs** de ce code: 1. On commence par vรฉrifier si on est dans le **cas de base**: celui d'un problรจme suffisemment simple pour รชtre rรฉsolu directement. C'est notre garde fou...! 2. **Rรฉcursion**: Si on est pas dans le cas de base, notre fonction *s'appelle elle-mรชme* - on appelle cela un **appel rรฉcu... | def sommer_voir(nbs):
print(f'appel de sommer({nbs})')
if len(nbs) == 1:
print(f'retour de sommer({nbs}): -> {nbs[0]}')
return nbs[0]
reste = sommer_voir(nbs[1:])
print(f'retour de sommer({nbs}): {nbs[0]} + {reste} -> {nbs[0] + reste}')
return nbs[0] + reste
sommer_voir([... | _____no_output_____ | CC0-1.0 | 1_recursivite/1_recursivite.ipynb | efloti/cours-nsi-terminale |
On peut mรชme mieux voir l'imbrication des appels en dรฉcalant le texte affichรฉ en fonction de l'ordre d'appel: | def sommer_voir(nbs, n=0):
dec = ' ' * n # niveau de dรฉcalage
print(f'{dec}appel de sommer({nbs})')
if len(nbs) == 1:
print(f'{dec}retour de sommer({nbs}): -> {nbs[0]}')
return nbs[0]
reste = sommer_voir(nbs[1:], n+1)
print(f'{dec}retour de sommer({nbs}): {nbs[0]} + {rest... | _____no_output_____ | CC0-1.0 | 1_recursivite/1_recursivite.ipynb | efloti/cours-nsi-terminale |
Synthรจse Un **algorithme rรฉcursif** doit respecter les trois lois qui suivent: 1. Il doit possรฉder un (ou plusieurs) **cas de base(s)**: problรจme(s) si simple(s) qu'on peut le(s) rรฉsoudre directement, 2. Il doit modifier son รฉtat de faรงon ร **progresser** vers l'un des cas de bases: **partage** du problรจme en sous-pro... | def fact(n):
pass | _____no_output_____ | CC0-1.0 | 1_recursivite/1_recursivite.ipynb | efloti/cours-nsi-terminale |
**Solution** | def fact(n):
if n > 1: return n * fact(n - 1)
return 1
fact(4) | _____no_output_____ | CC0-1.0 | 1_recursivite/1_recursivite.ipynb | efloti/cours-nsi-terminale |
*** Exercice 2 Dรฉfinir de faรงon rรฉcursive `puissance(x, n)` qui calcule $x^n$ (comment passe-t-on de $x^{n-1}$ ร $x^n$) | def puissance(x, n):
pass | _____no_output_____ | CC0-1.0 | 1_recursivite/1_recursivite.ipynb | efloti/cours-nsi-terminale |
**Solution** | def puissance(x, n):
if n > 0: return x * puissance(x, n-1)
return 1 # x^0=1 quel que soit x
assert puissance(2, 10) == 1024 | _____no_output_____ | CC0-1.0 | 1_recursivite/1_recursivite.ipynb | efloti/cours-nsi-terminale |
*** Exercice 3 Dรฉfinir de faรงon rรฉcursive `maximum(nbs)` qui renvoie la plus grande valeur de la liste `nbs`. | def maximum(nbs):
pass | _____no_output_____ | CC0-1.0 | 1_recursivite/1_recursivite.ipynb | efloti/cours-nsi-terminale |
**Solution** | def maximum(nbs):
if len(nbs) == 1: return nbs[0]
prem, *reste = nbs
m = maximum(reste)
return m if m > prem else prem
assert maximum([2, 5, -1, 12, 3]) == 12 | _____no_output_____ | CC0-1.0 | 1_recursivite/1_recursivite.ipynb | efloti/cours-nsi-terminale |
*** Exercice 4 1. Dรฉfinir de faรงon rรฉcursive `base2(n)` qui renvoie l'รฉcriture en base 2 de l'entier positif $n$ (sous la forme d'une chaรฎne de caractรจres). | def base2(n):
pass | _____no_output_____ | CC0-1.0 | 1_recursivite/1_recursivite.ipynb | efloti/cours-nsi-terminale |
**Solution** | def base2(n):
if n in [0, 1]: return str(n)
q, r = n // 2, n % 2
return base2(q) + str(r)
assert base2(13) == '1101' # 1huit+1quatre+0deux+1un | _____no_output_____ | CC0-1.0 | 1_recursivite/1_recursivite.ipynb | efloti/cours-nsi-terminale |
2. De mรชme, dรฉfinir rรฉcursivement `base16(n)` | def base16(n):
pass | _____no_output_____ | CC0-1.0 | 1_recursivite/1_recursivite.ipynb | efloti/cours-nsi-terminale |
**Solution** | def base16(n):
if n in list(range(10)): return str(n)
d = {10: "A", 11: "B", 12: "C", 13: "D", 14: "E", 15: "F"}
if n in d: return d[n]
q, r = n // 16, n % 16
return base16(q) + base16(r)
assert base16(43) == '2B' # 2 seize + B un | _____no_output_____ | CC0-1.0 | 1_recursivite/1_recursivite.ipynb | efloti/cours-nsi-terminale |
*** Exercice 5 En tenant compte de l'observation suivante:> si $q$ et $r$ sont respectivement le quotient et le reste de la division euclidienne de $n$ par $2$, alors $n=2q+r$ et: >>$$x^n=x^{2q+r}=x^{2q}x^r=(x^{q})^{2}x^r$$redรฉfinir de faรงon rรฉcursive la fonction `puissance(x, n)` de l'exercice 2. | def puissance_bis(x, n):
pass
assert puissance_bis(2, 10) == 1024
assert puissance_bis(5, 3) == 125 | _____no_output_____ | CC0-1.0 | 1_recursivite/1_recursivite.ipynb | efloti/cours-nsi-terminale |
**Solution** | def puissance_bis(x, n):
if n == 0: return 1
q, r = n // 2, n % 2
tmp = puissance_bis(x, q)
return tmp * tmp * (1 if r == 0 else x)
assert puissance_bis(2, 10) == 1024
assert puissance_bis(5, 3) == 125 | _____no_output_____ | CC0-1.0 | 1_recursivite/1_recursivite.ipynb | efloti/cours-nsi-terminale |
Exรฉcuter alors les cellules qui suivent:*Note*: `%timeit` est une directive spรฉciale des notebooks qui permet de mesurer le temps moyen mis par une fonction pour s'exรฉcuter. | %timeit puissance_bis(2, 1024)
%timeit puissance(2, 1024)
%timeit 23 ** 50 | _____no_output_____ | CC0-1.0 | 1_recursivite/1_recursivite.ipynb | efloti/cours-nsi-terminale |
Senegal* Homepage of project: https://oscovida.github.io* Plots are explained at http://oscovida.github.io/plots.html* [Execute this Jupyter Notebook using myBinder](https://mybinder.org/v2/gh/oscovida/binder/master?filepath=ipynb/Senegal.ipynb) | import datetime
import time
start = datetime.datetime.now()
print(f"Notebook executed on: {start.strftime('%d/%m/%Y %H:%M:%S%Z')} {time.tzname[time.daylight]}")
%config InlineBackend.figure_formats = ['svg']
from oscovida import *
overview("Senegal", weeks=5);
overview("Senegal");
compare_plot("Senegal", normalise=Tru... | _____no_output_____ | CC-BY-4.0 | ipynb/Senegal.ipynb | oscovida/oscovida.github.io |
Explore the data in your web browser- If you want to execute this notebook, [click here to use myBinder](https://mybinder.org/v2/gh/oscovida/binder/master?filepath=ipynb/Senegal.ipynb)- and wait (~1 to 2 minutes)- Then press SHIFT+RETURN to advance code cell to code cell- See http://jupyter.org for more details on how... | print(f"Download of data from Johns Hopkins university: cases at {fetch_cases_last_execution()} and "
f"deaths at {fetch_deaths_last_execution()}.")
# to force a fresh download of data, run "clear_cache()"
print(f"Notebook execution took: {datetime.datetime.now()-start}")
| _____no_output_____ | CC-BY-4.0 | ipynb/Senegal.ipynb | oscovida/oscovida.github.io |
Using Debuggingbook Code in your own ProgramsThis notebook has instructions on how to use the `debuggingbook` code in your own programs. In short, there are three ways:1. Simply run the notebooks in your browser, using the "mybinder" environment. Choose "Resources->Edit as Notebook" in any of the `fuzzingbook.org` pag... | import bookutils
from Debugger import Debugger
with Debugger():
x = 1 + 1 | _____no_output_____ | MIT | docs/notebooks/Importing.ipynb | TheV1rtuoso/debuggingbook |
!pip install superimport
!git clone --depth 1 https://github.com/probml/pyprobml &> /dev/null
!pip install flax
%run pyprobml/scripts/vb_gauss_cholesky_biclusters_demo.py
plt.show()
| _____no_output_____ | MIT | notebooks/vb_gauss_biclusters_demo.ipynb | susnato/probml-notebooks | |
Aggression linear word oh | report_results("linear_word_oh_aggression_prediction_results.csv") | AUC score 0.9434281464773387
| Apache-2.0 | Fatma_dataset/results/Aggression_results_analysis.ipynb | Nintendofan885/Detect_Cyberbullying_from_socialmedia |
Aggression linear char oh | report_results("linear_char_oh_aggression_prediction_results.csv") | AUC score 0.9173706304487989
| Apache-2.0 | Fatma_dataset/results/Aggression_results_analysis.ipynb | Nintendofan885/Detect_Cyberbullying_from_socialmedia |
Aggression mlp word oh | report_results("mlp_word_oh_aggression_prediction_results.csv") | AUC score 0.9413535359427857
| Apache-2.0 | Fatma_dataset/results/Aggression_results_analysis.ipynb | Nintendofan885/Detect_Cyberbullying_from_socialmedia |
Aggression mlp char oh | report_results("mlp_char_oh_aggression_prediction_results.csv") | AUC score 0.9377764851936341
| Apache-2.0 | Fatma_dataset/results/Aggression_results_analysis.ipynb | Nintendofan885/Detect_Cyberbullying_from_socialmedia |
Agression lstm word | report_results("lstm_word_oh_aggression_prediction_results.csv") | AUC score 0.9555933152450244
| Apache-2.0 | Fatma_dataset/results/Aggression_results_analysis.ipynb | Nintendofan885/Detect_Cyberbullying_from_socialmedia |
Aggression lstm char | report_results("lstm_char_oh_aggression_prediction_results.csv") | AUC score 0.7929897055078095
| Apache-2.0 | Fatma_dataset/results/Aggression_results_analysis.ipynb | Nintendofan885/Detect_Cyberbullying_from_socialmedia |
aggression conv-lstm word | report_results("conv_lstm_word_oh_aggression_prediction_results.csv") | AUC score 0.9002429773190748
| Apache-2.0 | Fatma_dataset/results/Aggression_results_analysis.ipynb | Nintendofan885/Detect_Cyberbullying_from_socialmedia |
aggression conv-lstm char | report_results("conv_lstm_char_oh_aggression_prediction_results.csv") | AUC score 0.9298119174163423
| Apache-2.0 | Fatma_dataset/results/Aggression_results_analysis.ipynb | Nintendofan885/Detect_Cyberbullying_from_socialmedia |
Individual Classifiers Gaussian Naive Bayes | from sklearn.naive_bayes import GaussianNB
estimator = GaussianNB()
param_grid = {}
gnb_best_score_, gnb_best_params_ = parameterTune(estimator, param_grid)
gnb_df = test_eval(GaussianNB, gnb_best_params_)
print('best_score_:',gnb_best_score_,'\nbest_params_:',gnb_best_params_) | best_score_: 0.7677044755508129
best_params_: {}
| MIT | 01-Titanic_Machine_Learning_from_Disaster/05_ensembling.ipynb | L-ashwin/Exploring-ml |
Logistic Regression | from sklearn.linear_model import LogisticRegression
estimator = LogisticRegression(tol=1e-4, solver='liblinear', random_state=1)
param_grid = {
'max_iter' : [1000, 2000, 3000],
'penalty' : ['l1', 'l2'],
'solver' : ['liblinear']
}
lrc_best_score_, lrc_best_params_ = parameterTune(estimator, param_grid)
... | best_score_: 0.8260247316552632
best_params_: {'max_iter': 1000, 'penalty': 'l1', 'solver': 'liblinear'}
| MIT | 01-Titanic_Machine_Learning_from_Disaster/05_ensembling.ipynb | L-ashwin/Exploring-ml |
K-Neighbors Classifier | from sklearn.neighbors import KNeighborsClassifier
estimator = KNeighborsClassifier()
param_grid = {
'n_neighbors' : [3, 5, 7, 10],
'weights' : ['uniform', 'distance'],
'p' : [1, 2]
}
knn_best_score_, knn_best_params_ = parameterTune(estimator, param_grid)
knn_df = test_eval(KNeighborsClassi... | best_score_: 0.8282907538760906
best_params_: {'n_neighbors': 10, 'p': 1, 'weights': 'uniform'}
| MIT | 01-Titanic_Machine_Learning_from_Disaster/05_ensembling.ipynb | L-ashwin/Exploring-ml |
Support Vector Classifier | from sklearn.svm import SVC
estimator = SVC()
param_grid = [
{ 'kernel' : ['linear'],
'C' : [0.1, 1, 10, 100]},
{ 'kernel' : ['rbf'],
'C' : [0.1, 1, 10, 100],
'gamma' : ['scale', 'auto', 1e-1, 1e-2, 1e-3, 1e-4],},
]
svc_best_score_, svc_best_params_ = parameterTune(... | best_score_: 0.8372418555018518
best_params_: {'C': 100, 'gamma': 0.01, 'kernel': 'rbf'}
| MIT | 01-Titanic_Machine_Learning_from_Disaster/05_ensembling.ipynb | L-ashwin/Exploring-ml |
Ensembles 1. Bagging Random Forest Classifier | from sklearn.ensemble import RandomForestClassifier
estimator = RandomForestClassifier()
param_grid = {
'n_estimators' : [50, 100, 250, 500, 750, 1000],
'criterion' : ["gini", "entropy"],
'max_depth' : [2,5,10,15,20],
'max_features' : ["auto","sqrt"],
}
rfc_best_score_, rfc_best_params_ = parame... | best_score_: 0.8338773460548616
best_params_: {'criterion': 'gini', 'max_depth': 5, 'max_features': 'auto', 'n_estimators': 500}
| MIT | 01-Titanic_Machine_Learning_from_Disaster/05_ensembling.ipynb | L-ashwin/Exploring-ml |
2. Boosting AdaBoostClassifier | from sklearn.ensemble import AdaBoostClassifier
estimator = AdaBoostClassifier()
param_grid = {
'n_estimators' : [20, 50, 100, 250],
}
adb_best_score_, adb_best_params_ = parameterTune(estimator, param_grid)
adb_df = test_eval(AdaBoostClassifier, adb_best_params_)
print('best_score_:',adb_best_score_,'\nbest_para... | best_score_: 0.8249513527085558
best_params_: {'n_estimators': 50}
| MIT | 01-Titanic_Machine_Learning_from_Disaster/05_ensembling.ipynb | L-ashwin/Exploring-ml |
GradientBoostingClassifier | from sklearn.ensemble import GradientBoostingClassifier
estimator = GradientBoostingClassifier()
param_grid = {
'loss' : ['deviance', 'exponential'],
'learning_rate' : [0.1, 0.01],
'n_estimators' : [100, 250, 500],
'subsample' : [0.75, 0.9, 1.0],
'max_depth' : [1, 2, 3, 5, 7],
}
... | best_score_: 0.8473667691921412
best_params_: {'learning_rate': 0.1, 'loss': 'deviance', 'max_depth': 2, 'n_estimators': 250, 'subsample': 0.9}
| MIT | 01-Titanic_Machine_Learning_from_Disaster/05_ensembling.ipynb | L-ashwin/Exploring-ml |
Submission File | pd.DataFrame({
'GaussianNB' : gnb_best_score_,
'LogisticRegression' : lrc_best_score_,
'KNeighborsClassifier' : knn_best_score_,
'SVC' : svc_best_score_,
'RandomForestClassifier' : rfc_best_score_,
'AdaBoostClassifier' : adb_best_s... | _____no_output_____ | MIT | 01-Titanic_Machine_Learning_from_Disaster/05_ensembling.ipynb | L-ashwin/Exploring-ml |
Tipos de Muestreo | import numpy as np
import matplotlib.pyplot as plt
import scipy.signal as signal
import warnings
warnings.filterwarnings("ignore") | _____no_output_____ | MIT | md_scripts/tipos_de_muestreo.ipynb | AgustinSolano/SyS_scriptsbook |
Funciones para el Muestreo | def mIdeal(senal,t_senal,Ts,Fs_orig):
#tomo una muestra cada Ts y guardo en un vector
senal_mues1 = senal[np.arange(0,len(senal),int(np.round(Ts*Fs_orig)))]
#creo un vector de tiempos asociado a la muestras
t_ideal = t_senal[np.arange(0,len(senal),int(np.round(Ts*Fs_orig)))]
#t_ideal = np.arange(0,l... | _____no_output_____ | MIT | md_scripts/tipos_de_muestreo.ipynb | AgustinSolano/SyS_scriptsbook |
Funcion para la Transformada de Fourier | def TFourier(signal,fs,unidadesx):#unidadesx = 0 en Hz, 1 rad/s
FFT = abs(np.fft.fftshift(np.fft.fft(signal)))
nFFT = len(FFT)
fFFT = np.arange(-nFFT/2,nFFT/2)*(fs/nFFT)
if unidadesx == 1:
fFFT= fFFT*2*np.pi
return fFFT,FFT | _____no_output_____ | MIT | md_scripts/tipos_de_muestreo.ipynb | AgustinSolano/SyS_scriptsbook |
Seรฑales | # Se lavanta senial de un archivo separado por comas (.csv)
path_ECG = './external_files/ECG.csv'
senal_ECG = np.genfromtxt(path_ECG, delimiter=',')
fs_ECG = 1000 # Hz: frecuencia la cual fueron muestrados los datos originales, que se simulan como analogicos
t_ECG = np.arange(0,len(senal_ECG)/fs_ECG,1/fs_ECG)
# Calcu... | _____no_output_____ | MIT | md_scripts/tipos_de_muestreo.ipynb | AgustinSolano/SyS_scriptsbook |
Muestreo Ideal | # Identifico la frecuencia maxima de la
fmax_ECG = 60 #a partir del espectro veo que la frecuencia
fs_muest_ECG = 2*fmax_ECG*1.25
Ts_ECG = 1/fs_muest_ECG
# Se realiza el muestreo ideal
t_ideal, sign_ideal = mIdeal(senal_ECG,t_ECG,Ts_ECG,fs_ECG)
t_min = -0.1
t_max = 3.0
# Graficacion
fig, (ax1,ax2) = plt.subplots(2,... | _____no_output_____ | MIT | md_scripts/tipos_de_muestreo.ipynb | AgustinSolano/SyS_scriptsbook |
Histogram | x = np.random.normal(size = 2000)
plt.hist(x, bins=40, color='yellowgreen')
plt.gca().set(title='Histogram', ylabel='Frequency')
plt.show()
x = np.random.rand(2000)
plt.hist(x, bins=30 ,color='#D4AC0D')
plt.gca().set(title='Histogram', ylabel='Frequency')
plt.show()
# Using Edge Color for readability
plt.figure(figsize... | _____no_output_____ | MIT | Data Visualization/Matplotlib/4. Histogram.ipynb | shreejitverma/Data-Scientist |
Binning | # Binning
plt.figure(figsize=(10,8))
x = np.random.normal(size = 2000)
plt.hist(x, bins=30, color='yellowgreen' , edgecolor="#6A9662")
plt.gca().set(title='Histogram', ylabel='Frequency')
plt.show()
plt.figure(figsize=(10,8))
plt.hist(x, bins=20, color='yellowgreen' , edgecolor="#6A9662")
plt.gca().set(title='Histogra... | _____no_output_____ | MIT | Data Visualization/Matplotlib/4. Histogram.ipynb | shreejitverma/Data-Scientist |
Plotting Multiple Histograms | plt.figure(figsize=(8,11))
x = np.random.normal(-4,1,size = 800)
y = np.random.normal(0,1.5,size = 800)
z = np.random.normal(3.5,1,size = 800)
plt.hist(x, bins=30, color='yellowgreen' , alpha=0.6)
plt.hist(y, bins=30, color='#FF8F00' , alpha=0.6)
plt.hist(z, bins=30, color='blue' , alpha=0.6)
plt.gca().set(title='Histo... | _____no_output_____ | MIT | Data Visualization/Matplotlib/4. Histogram.ipynb | shreejitverma/Data-Scientist |
Linear regression from scratchPowerful ML libraries can eliminate repetitive work, but if you rely too much on abstractions, you might never learn how neural networks really work under the hood. So for this first example, let's get our hands dirty and build everything from scratch, relying only on autograd and NDArray... | from __future__ import print_function
import mxnet as mx
from mxnet import nd, autograd, gluon
mx.random.seed(1) | _____no_output_____ | Apache-2.0 | Training/Tutorial - Gluon MXNet - The Straight Dope Master/chapter02_supervised-learning/linear-regression-scratch.ipynb | farhadrclass/DataScience-Lab |
Set the contextWe'll also want to specify the contexts where computation should happen. This tutorial is so simple that you could probably run it on a calculator watch. But, to develop good habits we're going to specify two contexts: one for data and one for our models. | data_ctx = mx.cpu()
model_ctx = mx.cpu() | _____no_output_____ | Apache-2.0 | Training/Tutorial - Gluon MXNet - The Straight Dope Master/chapter02_supervised-learning/linear-regression-scratch.ipynb | farhadrclass/DataScience-Lab |
Linear regressionTo get our feet wet, we'll start off by looking at the problem of regression.This is the task of predicting a *real valued target* $y$ given a data point $x$.In linear regression, the simplest and still perhaps the most useful approach,we assume that prediction can be expressed as a *linear* combinati... | num_inputs = 2
num_outputs = 1
num_examples = 10000
def real_fn(X):
return 2 * X[:, 0] - 3.4 * X[:, 1] + 4.2
X = nd.random_normal(shape=(num_examples, num_inputs), ctx=data_ctx)
noise = .1 * nd.random_normal(shape=(num_examples,), ctx=data_ctx)
y = real_fn(X) + noise | _____no_output_____ | Apache-2.0 | Training/Tutorial - Gluon MXNet - The Straight Dope Master/chapter02_supervised-learning/linear-regression-scratch.ipynb | farhadrclass/DataScience-Lab |
Notice that each row in ``X`` consists of a 2-dimensional data point and that each row in ``Y`` consists of a 1-dimensional target value. | print(X[0])
print(y[0]) |
[-1.22338355 2.39233518]
<NDArray 2 @cpu(0)>
[-6.09602737]
<NDArray 1 @cpu(0)>
| Apache-2.0 | Training/Tutorial - Gluon MXNet - The Straight Dope Master/chapter02_supervised-learning/linear-regression-scratch.ipynb | farhadrclass/DataScience-Lab |
Note that because our synthetic features `X` live on `data_ctx` and because our noise also lives on `data_ctx`, the labels `y`, produced by combining `X` and `noise` in `real_fn` also live on `data_ctx`. We can confirm that for any randomly chosen point, a linear combination with the (known) optimal parameters produces... | print(2 * X[0, 0] - 3.4 * X[0, 1] + 4.2) |
[-6.38070679]
<NDArray 1 @cpu(0)>
| Apache-2.0 | Training/Tutorial - Gluon MXNet - The Straight Dope Master/chapter02_supervised-learning/linear-regression-scratch.ipynb | farhadrclass/DataScience-Lab |
We can visualize the correspondence between our second feature (``X[:, 1]``) and the target values ``Y`` by generating a scatter plot with the Python plotting package ``matplotlib``. Make sure that ``matplotlib`` is installed. Otherwise, you may install it by running ``pip2 install matplotlib`` (for Python 2) or ``pip3... | import matplotlib.pyplot as plt
plt.scatter(X[:, 1].asnumpy(),y.asnumpy())
plt.show() | _____no_output_____ | Apache-2.0 | Training/Tutorial - Gluon MXNet - The Straight Dope Master/chapter02_supervised-learning/linear-regression-scratch.ipynb | farhadrclass/DataScience-Lab |
Data iteratorsOnce we start working with neural networks, we're going to need to iterate through our data points quickly. We'll also want to be able to grab batches of ``k`` data points at a time, to shuffle our data. In MXNet, data iterators give us a nice set of utilities for fetching and manipulating data. In parti... | batch_size = 4
train_data = gluon.data.DataLoader(gluon.data.ArrayDataset(X, y),
batch_size=batch_size, shuffle=True) | _____no_output_____ | Apache-2.0 | Training/Tutorial - Gluon MXNet - The Straight Dope Master/chapter02_supervised-learning/linear-regression-scratch.ipynb | farhadrclass/DataScience-Lab |
Once we've initialized our DataLoader (``train_data``), we can easily fetch batches by iterating over `train_data` just as if it were a Python list. You can use for favorite iterating techniques like foreach loops: `for data, label in train_data` or enumerations: `for i, (data, label) in enumerate(train_data)`. First, ... | for i, (data, label) in enumerate(train_data):
print(data, label)
break |
[[-0.14732301 -1.32803488]
[-0.56128627 0.48301753]
[ 0.75564283 -0.12659997]
[-0.96057719 -0.96254188]]
<NDArray 4x2 @cpu(0)>
[ 8.25711536 1.30587864 6.15542459 5.48825312]
<NDArray 4 @cpu(0)>
| Apache-2.0 | Training/Tutorial - Gluon MXNet - The Straight Dope Master/chapter02_supervised-learning/linear-regression-scratch.ipynb | farhadrclass/DataScience-Lab |
If we run that same code again you'll notice that we get a different batch. That's because we instructed the `DataLoader` that `shuffle=True`. | for i, (data, label) in enumerate(train_data):
print(data, label)
break |
[[-0.59027743 -1.52694809]
[-0.00750104 2.68466949]
[ 1.50308061 0.54902577]
[ 1.69129586 0.32308948]]
<NDArray 4x2 @cpu(0)>
[ 8.28844357 -5.07566643 5.3666563 6.52408457]
<NDArray 4 @cpu(0)>
| Apache-2.0 | Training/Tutorial - Gluon MXNet - The Straight Dope Master/chapter02_supervised-learning/linear-regression-scratch.ipynb | farhadrclass/DataScience-Lab |
Finally, if we actually pass over the entire dataset, and count the number of batches, we'll find that there are 2500 batches. We expect this because our dataset has 10,000 examples we configure the `DataLoader` with a batch size of 4. | counter = 0
for i, (data, label) in enumerate(train_data):
pass
print(i+1) | 2500
| Apache-2.0 | Training/Tutorial - Gluon MXNet - The Straight Dope Master/chapter02_supervised-learning/linear-regression-scratch.ipynb | farhadrclass/DataScience-Lab |
Model parametersNow let's allocate some memory for our parameters and set their initial values. We'll want to initialize these parameters on the `model_ctx`. | w = nd.random_normal(shape=(num_inputs, num_outputs), ctx=model_ctx)
b = nd.random_normal(shape=num_outputs, ctx=model_ctx)
params = [w, b] | _____no_output_____ | Apache-2.0 | Training/Tutorial - Gluon MXNet - The Straight Dope Master/chapter02_supervised-learning/linear-regression-scratch.ipynb | farhadrclass/DataScience-Lab |
In the succeeding cells, we're going to update these parameters to better fit our data. This will involve taking the gradient (a multi-dimensional derivative) of some *loss function* with respect to the parameters. We'll update each parameter in the direction that reduces the loss. But first, let's just allocate some m... | for param in params:
param.attach_grad() | _____no_output_____ | Apache-2.0 | Training/Tutorial - Gluon MXNet - The Straight Dope Master/chapter02_supervised-learning/linear-regression-scratch.ipynb | farhadrclass/DataScience-Lab |
Neural networksNext we'll want to define our model. In this case, we'll be working with linear models, the simplest possible *useful* neural network. To calculate the output of the linear model, we simply multiply a given input with the model's weights (``w``), and add the offset ``b``. | def net(X):
return mx.nd.dot(X, w) + b | _____no_output_____ | Apache-2.0 | Training/Tutorial - Gluon MXNet - The Straight Dope Master/chapter02_supervised-learning/linear-regression-scratch.ipynb | farhadrclass/DataScience-Lab |
Ok, that was easy. Loss functionTrain a model means making it better and better over the course of a period of training. But in order for this goal to make any sense at all, we first need to define what *better* means in the first place. In this case, we'll use the squared distance between our prediction and the true ... | def square_loss(yhat, y):
return nd.mean((yhat - y) ** 2) | _____no_output_____ | Apache-2.0 | Training/Tutorial - Gluon MXNet - The Straight Dope Master/chapter02_supervised-learning/linear-regression-scratch.ipynb | farhadrclass/DataScience-Lab |
OptimizerIt turns out that linear regression actually has a closed-form solution. However, most interesting models that we'll care about cannot be solved analytically. So we'll solve this problem by stochastic gradient descent. At each step, we'll estimate the gradient of the loss with respect to our weights, using on... | def SGD(params, lr):
for param in params:
param[:] = param - lr * param.grad | _____no_output_____ | Apache-2.0 | Training/Tutorial - Gluon MXNet - The Straight Dope Master/chapter02_supervised-learning/linear-regression-scratch.ipynb | farhadrclass/DataScience-Lab |
Execute training loopNow that we have all the pieces, we just need to wire them together by writing a training loop. First we'll define ``epochs``, the number of passes to make over the dataset. Then for each pass, we'll iterate through ``train_data``, grabbing batches of examples and their corresponding labels. For e... | epochs = 10
learning_rate = .0001
num_batches = num_examples/batch_size
for e in range(epochs):
cumulative_loss = 0
# inner loop
for i, (data, label) in enumerate(train_data):
data = data.as_in_context(model_ctx)
label = label.as_in_context(model_ctx).reshape((-1, 1))
with autograd.... | 24.6606138554
9.09776815639
3.36058844271
1.24549788469
0.465710770596
0.178157229481
0.0721970594548
0.0331197250206
0.0186954441286
0.0133724625537
| Apache-2.0 | Training/Tutorial - Gluon MXNet - The Straight Dope Master/chapter02_supervised-learning/linear-regression-scratch.ipynb | farhadrclass/DataScience-Lab |
Visualizing our training progessIn the succeeding chapters, we'll introduce more realistic data, fancier models, more complicated loss functions, and more. But the core ideas are the same and the training loop will look remarkably familiar. Because these tutorials are self-contained, you'll get to know this ritual qui... | ############################################
# Re-initialize parameters because they
# were already trained in the first loop
############################################
w[:] = nd.random_normal(shape=(num_inputs, num_outputs), ctx=model_ctx)
b[:] = nd.random_normal(shape=num_outputs, ctx=model_ctx)
###########... | _____no_output_____ | Apache-2.0 | Training/Tutorial - Gluon MXNet - The Straight Dope Master/chapter02_supervised-learning/linear-regression-scratch.ipynb | farhadrclass/DataScience-Lab |
[](https://githubtocolab.com/JohnSnowLabs/spark-nlp-workshop/blob/master/tutorials/streamlit_notebooks/NER_PT.ipynb) **Detect entities in Portuguese text** 1. Colab Setup | # Install PySpark and Spark NLP
! pip install -q pyspark==3.1.2 spark-nlp
# Install Spark NLP Display lib
! pip install --upgrade -q spark-nlp-display | _____no_output_____ | Apache-2.0 | tutorials/streamlit_notebooks/NER_PT.ipynb | fcivardi/spark-nlp-workshop |
2. Start the Spark session | import json
import pandas as pd
import numpy as np
from pyspark.ml import Pipeline
from pyspark.sql import SparkSession
import pyspark.sql.functions as F
from sparknlp.annotator import *
from sparknlp.base import *
import sparknlp
from sparknlp.pretrained import PretrainedPipeline
spark = sparknlp.start() | _____no_output_____ | Apache-2.0 | tutorials/streamlit_notebooks/NER_PT.ipynb | fcivardi/spark-nlp-workshop |
3. Select the DL model | # If you change the model, re-run all the cells below.
# Applicable models: wikiner_840B_300, wikiner_6B_300, wikiner_6B_100
MODEL_NAME = "wikiner_840B_300" | _____no_output_____ | Apache-2.0 | tutorials/streamlit_notebooks/NER_PT.ipynb | fcivardi/spark-nlp-workshop |
4. Some sample examples | # Enter examples to be transformed as strings in this list
text_list = [
"""William Henry Gates III (nascido em 28 de outubro de 1955) รฉ um magnata americano de negรณcios, desenvolvedor de software, investidor e filantropo. Ele รฉ mais conhecido como co-fundador da Microsoft Corporation. Durante sua carreira na Micro... | _____no_output_____ | Apache-2.0 | tutorials/streamlit_notebooks/NER_PT.ipynb | fcivardi/spark-nlp-workshop |
5. Define Spark NLP pipeline | document_assembler = DocumentAssembler() \
.setInputCol('text') \
.setOutputCol('document')
tokenizer = Tokenizer() \
.setInputCols(['document']) \
.setOutputCol('token')
# The wikiner_840B_300 is trained with glove_840B_300, so the embeddings in the
# pipeline should match. Same applies for the other... | glove_840B_300 download started this may take some time.
Approximate size to download 2.3 GB
[OK!]
wikiner_840B_300 download started this may take some time.
Approximate size to download 14.5 MB
[OK!]
| Apache-2.0 | tutorials/streamlit_notebooks/NER_PT.ipynb | fcivardi/spark-nlp-workshop |
6. Run the pipeline | empty_df = spark.createDataFrame([['']]).toDF('text')
pipeline_model = nlp_pipeline.fit(empty_df)
df = spark.createDataFrame(pd.DataFrame({'text': text_list}))
result = pipeline_model.transform(df) | _____no_output_____ | Apache-2.0 | tutorials/streamlit_notebooks/NER_PT.ipynb | fcivardi/spark-nlp-workshop |
7. Visualize results | from sparknlp_display import NerVisualizer
NerVisualizer().display(
result = result.collect()[0],
label_col = 'ner_chunk',
document_col = 'document'
) | _____no_output_____ | Apache-2.0 | tutorials/streamlit_notebooks/NER_PT.ipynb | fcivardi/spark-nlp-workshop |
The test function is $y = 5x^2+10x-8$. BFGS's method is implemented to find the minimum of the test function. The user should be able to find the x and y of the minmium as well as access the jacobian of eaach optimization step.First, we instantiate a `Number(5)` as the initial guess ($x_0$) of the root to the minimum. ... | import sys
sys.path.append('..')
import autodiff.operations as operations
from autodiff.structures import Number
import numpy as np
def func(x):
return 5 * x ** 2 + 10 * x - 8
def bfgs(func, initial_guess):
#bfgs for scalar functions
x0 = initial_guess
#initial guess of hessian
b0... | The jacobians at 1st, 2nd and final steps are: [60, -540.0, 0.0] . The jacobian value is 0 in the last step, indicating completion of the optimization process.
The x* is Number(val=-1.0)
| MIT | docs/bfgs.ipynb | rocketscience0/cs207-FinalProject |
Commity | class Commity():
def __init__(self,M) -> None:
self.M = M
self.model = [LinearRegression(basis_function="polynomial",deg=3) for _ in range(M)]
def fit(self,X,y):
n = len(X)
sample = int(n*0.8)
for i in range(self.M):
idx = np.random.randint(0,n,sample)... | RMSE : 0.14445858781232257
| MIT | notebook/chapter14_combining_models.ipynb | hedwig100/PRML |
AdaBoost | class AdaBoost(Classifier):
"""AdaBoost
weak_learner is decision stump
Attributes:
M (int): number of weak leaner
weak_leaner (list): list of data about weak learner
"""
def __init__(self,M=5) -> None:
"""__init__
Args:
M (int): number of weak leane... | _____no_output_____ | MIT | notebook/chapter14_combining_models.ipynb | hedwig100/PRML |
CART | class CARTRegressor():
"""CARTRegressor
Attributes:
lamda (float): regularizatioin parameter
tree (object): parameter
"""
def __init__(self,lamda=1e-2):
"""__init__
Args:
lamda (float): regularizatioin parameter
"""
self.lamda = l... | RMSE : 1.00482444289275
| MIT | notebook/chapter14_combining_models.ipynb | hedwig100/PRML |
Linear Mixture | class LinearMixture(Regression):
"""LinearMixture
Attributes:
K (int): number of mixture modesl
max_iter (int): max iteration
threshold (float): threshold for EM algorithm
pi (1-D array): mixture, which model is chosen
weight (2-D array): shape = (K,M), M is dimension... | RMSE : 0.9774354228059758
| MIT | notebook/chapter14_combining_models.ipynb | hedwig100/PRML |
์ ํ ํ๊ท ๊ตฌ๊ธ ์ฝ๋ฉ์์ ์คํํ๊ธฐ k-์ต๊ทผ์ ์ด์์ ํ๊ณ | import numpy as np
perch_length = np.array(
[8.4, 13.7, 15.0, 16.2, 17.4, 18.0, 18.7, 19.0, 19.6, 20.0,
21.0, 21.0, 21.0, 21.3, 22.0, 22.0, 22.0, 22.0, 22.0, 22.5,
22.5, 22.7, 23.0, 23.5, 24.0, 24.0, 24.6, 25.0, 25.6, 26.5,
27.3, 27.5, 27.5, 27.5, 28.0, 28.7, 30.0, 32.8, 34.5, 35.0,
36.5, 3... | _____no_output_____ | MIT | ch03_regression/3-2.ipynb | CaptLWM/AI |
์ ํ ํ๊ท | from sklearn.linear_model import LinearRegression
lr = LinearRegression()
# ์ ํ ํ๊ท ๋ชจ๋ธ ํ๋ จ
lr.fit(train_input, train_target)
# 50cm ๋์ด์ ๋ํ ์์ธก
print(lr.predict([[50]]))
print(lr.coef_, lr.intercept_)
# ํ๋ จ ์ธํธ์ ์ฐ์ ๋๋ฅผ ๊ทธ๋ฆฝ๋๋ค
plt.scatter(train_input, train_target)
# 15์์ 50๊น์ง 1์ฐจ ๋ฐฉ์ ์ ๊ทธ๋ํ๋ฅผ ๊ทธ๋ฆฝ๋๋ค
plt.plot([15, 50], [15*lr.coef_+lr.i... | 0.9398463339976039
0.8247503123313558
| MIT | ch03_regression/3-2.ipynb | CaptLWM/AI |
๋คํญ ํ๊ท | train_poly = np.column_stack((train_input ** 2, train_input))
test_poly = np.column_stack((test_input ** 2, test_input))
print(train_poly.shape, test_poly.shape)
lr = LinearRegression()
lr.fit(train_poly, train_target)
print(lr.predict([[50**2, 50]]))
print(lr.coef_, lr.intercept_)
# ๊ตฌ๊ฐ๋ณ ์ง์ ์ ๊ทธ๋ฆฌ๊ธฐ ์ํด 15์์ 49๊น์ง ์ ์ ๋ฐฐ์ด์ ๋ง๋ญ... | 0.9706807451768623
0.9775935108325122
| MIT | ch03_regression/3-2.ipynb | CaptLWM/AI |
Orbit Computation This tutorial demonstrates how to generate satellite orbits using various models. Setup | import numpy as np
import pandas as pd
import plotly.graph_objs as go
from ostk.physics.units import Length
from ostk.physics.units import Angle
from ostk.physics.time import Scale
from ostk.physics.time import Instant
from ostk.physics.time import Duration
from ostk.physics.time import Interval
from ostk.physics.tim... | _____no_output_____ | Apache-2.0 | notebooks/Orbit Computation/Orbit Computation.ipynb | open-space-collective/open-space-toolk |
--- SGP4 Computation | environment = Environment.default() | _____no_output_____ | Apache-2.0 | notebooks/Orbit Computation/Orbit Computation.ipynb | open-space-collective/open-space-toolk |
Create a Classical Orbital Element (COE) set: | a = Length.kilometers(7000.0)
e = 0.0001
i = Angle.degrees(35.0)
raan = Angle.degrees(40.0)
aop = Angle.degrees(45.0)
nu = Angle.degrees(50.0)
coe = COE(a, e, i, raan, aop, nu) | _____no_output_____ | Apache-2.0 | notebooks/Orbit Computation/Orbit Computation.ipynb | open-space-collective/open-space-toolk |
Setup a Keplerian orbital model: | epoch = Instant.date_time(DateTime(2018, 1, 1, 0, 0, 0), Scale.UTC)
earth = environment.access_celestial_object_with_name("Earth")
keplerian_model = Kepler(coe, epoch, earth, Kepler.PerturbationType.No) | _____no_output_____ | Apache-2.0 | notebooks/Orbit Computation/Orbit Computation.ipynb | open-space-collective/open-space-toolk |
Create a Two-Line Element (TLE) set: | tle = TLE(
"1 39419U 13066D 18260.77424112 .00000022 00000-0 72885-5 0 9996",
"2 39419 97.6300 326.6556 0013847 175.2842 184.8495 14.93888428262811"
) | _____no_output_____ | Apache-2.0 | notebooks/Orbit Computation/Orbit Computation.ipynb | open-space-collective/open-space-toolk |
Setup a SGP4 orbital model: | sgp4_model = SGP4(tle) | _____no_output_____ | Apache-2.0 | notebooks/Orbit Computation/Orbit Computation.ipynb | open-space-collective/open-space-toolk |
Setup the orbit: | # orbit = Orbit(keplerian_model, environment.access_celestial_object_with_name("Earth"))
orbit = Orbit(sgp4_model, environment.access_celestial_object_with_name("Earth")) | _____no_output_____ | Apache-2.0 | notebooks/Orbit Computation/Orbit Computation.ipynb | open-space-collective/open-space-toolk |
Now that the orbit is set, we can compute the satellite position: | start_instant = Instant.date_time(DateTime(2018, 9, 5, 0, 0, 0), Scale.UTC)
end_instant = Instant.date_time(DateTime(2018, 9, 6, 0, 0, 0), Scale.UTC)
interval = Interval.closed(start_instant, end_instant)
step = Duration.minutes(1.0) | _____no_output_____ | Apache-2.0 | notebooks/Orbit Computation/Orbit Computation.ipynb | open-space-collective/open-space-toolk |
Generate a time grid: | instants = interval.generate_grid(step)
states = [[instant, orbit.get_state_at(instant)] for instant in instants]
def convert_state (instant, state):
lla = LLA.cartesian(state.get_position().in_frame(Frame.ITRF(), state.get_instant()).get_coordinates(), Earth.equatorial_radius, Earth.flattening)
retur... | _____no_output_____ | Apache-2.0 | notebooks/Orbit Computation/Orbit Computation.ipynb | open-space-collective/open-space-toolk |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.