code
stringlengths
2.5k
150k
kind
stringclasses
1 value
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-59152712-8"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-59152712-8'); </script> # Generating C code for the right-hand sides of Maxwell's e...
github_jupyter
# Deep Convolutional GANs In this notebook, you'll build a GAN using convolutional layers in the generator and discriminator. This is called a Deep Convolutional GAN, or DCGAN for short. The DCGAN architecture was first explored in 2016 and has seen impressive results in generating new images; you can read the [origin...
github_jupyter
``` import numpy as np import pandas as pd import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.autograd import Variable import matplotlib.pyplot as plt %matplotlib inline data_raw = pd.read_csv('../input/sign_mnist_train.csv', sep=",") test_data_raw = pd.read_csv(...
github_jupyter
# Remuestreo Bootstrap Entre los métodos inferenciales que permiten cuantificar el grado de confianza que se puede tener de un estadı́sitico, y saber cuán acertados son los resultados sobre los parámetros de la población, se encuentran las técnias de remuestreo. Estas técnicas tienen la ventaja de que no necesitan da...
github_jupyter
# Table of Contents <p><div class="lev1 toc-item"><a href="#Initialization" data-toc-modified-id="Initialization-1"><span class="toc-item-num">1&nbsp;&nbsp;</span>Initialization</a></div><div class="lev1 toc-item"><a href="#Load-Data" data-toc-modified-id="Load-Data-2"><span class="toc-item-num">2&nbsp;&nbsp;</span>Lo...
github_jupyter
<a href="https://colab.research.google.com/github/mella30/Deep-Learning-with-Tensorflow-2/blob/main/Course2-Customising_your_models_with_Tensorflow_2/week4_subclassing_custom_training.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ``` import tensor...
github_jupyter
# Data Bootcamp: Demography We love demography, specifically the dynamics of population growth and decline. You can drill down seemingly without end, as this [terrific graphic](http://www.bloomberg.com/graphics/dataview/how-americans-die/) about causes of death suggests. We take a look here at the UN's [populat...
github_jupyter
# Model understanding and interpretability In this colab, we will - Will learn how to interpret model results and reason about the features - Visualize the model results ``` import time # We will use some np and pandas for dealing with input data. import numpy as np import pandas as pd # And of course, we need tens...
github_jupyter
#**Exploratory Data Analysis** ### Setting Up Environment ``` import numpy as np import pandas as pd import matplotlib.pyplot as plt import matplotlib.style as style import seaborn as sns from scipy.stats import pointbiserialr from scipy.stats import pearsonr from scipy.stats import chi2_contingency from sklearn.impu...
github_jupyter
### PROBLEM DEFINITION ### Knowing from a training set of samples listing passengers who survived or did not survive the Titanic disaster, Can our model determine based on a given test dataset not containing the survival information, if these passengers in the test dataset survived or not. ## BackGround ### - On A...
github_jupyter
``` import warnings import sys sys.path.insert(0, '../src') import numpy as np import pandas as pd import matplotlib.pyplot as plt from felix_ml_tools import macgyver as mg from preprocess import * from sklearn.linear_model import LassoCV, Lasso warnings.filterwarnings('ignore') pd.set_option("max_columns", None) pd.s...
github_jupyter
``` import pandas as pd from pandas import DataFrame import numpy as np import matplotlib.pyplot as plt import seaborn as sns from datetime import datetime, timedelta from statsmodels.tsa.arima_model import ARIMA from statsmodels.tsa.statespace.sarimax import SARIMAX from statsmodels.graphics.tsaplots import plot_acf, ...
github_jupyter
## Intro to Python ### Learning tips. * Practice, practice, practice. * Get used to making mistakes! It’s OK. * Don’t memorize. There are thousands packages in python. Learn to read documentation. ## Switching between python versions ### Anaconda Install [https://docs.continuum.io/anaconda/install](https://...
github_jupyter
<center> <img src="https://gitlab.com/ibm/skills-network/courses/placeholder101/-/raw/master/labs/module%201/images/IDSNlogo.png" width="300" alt="cognitiveclass.ai logo" /> </center> # **Exploratory Data Analysis Lab** Estimated time needed: **30** minutes In this module you get to work with the cleaned datase...
github_jupyter
``` #Q1 #(a) def odd(): sum = 0 n = int(input("Print sum of odd numbers till: ")) for i in range (0 , n+1): if i % 2 == 1: sum += i print("term = ",i,", sum till this step = ", sum ) else: continue odd() odd() #(b) def eve...
github_jupyter
``` # Install a pip package in the current Jupyter kernel import sys !{sys.executable} -m pip install pip install python-slugify !{sys.executable} -m pip install pip install bs4 !{sys.executable} -m pip install pip install lxml import requests, random, logging, urllib.request, json from bs4 import BeautifulSoup from tq...
github_jupyter
``` from datetime import datetime from IPython.display import display, HTML, clear_output import ipywidgets as widgets from ipywidgets import Checkbox, Box, Dropdown, fixed, interact, interactive, interact_manual, Label, Layout, Textarea # Override ipywidgets styles display(HTML(''' <style> textarea {min-height: 110px...
github_jupyter
``` import numpy as np class Regularizations: class L2: @staticmethod def reg(a): return np.mean(a**2) @staticmethod def reg_prime(a): return 2 * a / a.size class Losses: class MSE: @staticmethod def loss(y_true, y_pred): ret...
github_jupyter
# Introduction to Python > Defining Functions with Python Kuo, Yao-Jen ## TL; DR > In this lecture, we will talk about defining functions with Python. ## Encapsulations ## What is encapsulation? > Encapsulation refers to one of two related but distinct notions, and sometimes to the combination thereof: > 1. A l...
github_jupyter
# DATA512 A1: Data Curation How does English Wikipedia page traffic trend over time? To answer this question, we plot Wikimedia traffic data spanning from 1 January, 2008 to 30 September 2018. We combine data from two Wikimedia APIs, each covering a different period of time, so that we can show the trend over 10 years...
github_jupyter
<br><br><font color="gray">DOING COMPUTATIONAL SOCIAL SCIENCE<br>MODULE 10 <strong>PROBLEM SETS</strong></font> # <font color="#49699E" size=40>MODULE 10 </font> # What You Need to Know Before Getting Started - **Every notebook assignment has an accompanying quiz**. Your work in each notebook assignment will serve ...
github_jupyter
# A Câmara de Vereadores e o COVID-19 Você também fica curioso(a) para saber o que a Câmara de Vereadores de Feira de Santana fez em relação ao COVID-19? O que discutiram? O quão levaram a sério o vírus? Vamos responder essas perguntas e também te mostrar como fazer essa análise. Vem com a gente! Desde o início do an...
github_jupyter
# Titanic In this notebook we will experiment with tabular data and fastai v2 and other machine learning techniques ``` #collapse-hide import pandas as pd import numpy as np import matplotlib.pyplot as plt from fastai.tabular.all import * from pathlib import Path import seaborn as sns sns.set_palette('Set1') sns.set_...
github_jupyter
# Closed Loop Kinematics We want to simulate a closed loop system - just because . As a starting point, we will tackle the **STEWART PLATFORM**. While this seems like an overkill, applying the closure conditions in pybullet is quite easy. First, we import the needed modules. ``` import pybullet as pb import pybullet...
github_jupyter
``` from readability import Readability text = """ # Introduction to PyMC3 - Concept In this lecture we're going to talk about the theories, advantages and application of using Bayesian statistics. Bayesian inference is a method of making statistical decisions as more information or evidence becomes available. It ...
github_jupyter
# 12 - Beginner Exercises * Conditional Statements ## 🍼 🍼 🍼 1.Create a Python program that receive a number from the user and determines if a given integer is even or odd. ``` # Write your own code in this cell n = ``` ## 🍼🍼 2.Write a Python code that would read any integer day number and show the day's na...
github_jupyter
# 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 ``` Import **Section** class, which contains all calculations ``` from Section import...
github_jupyter
``` # Pre requisites for this notebook !pip install Pillow !pip install nb_black %load_ext nb_black import os from requests import get from pathlib import Path import gc import tensorflow as tf from concurrent.futures import ProcessPoolExecutor as PoolExecutor from tensorflow.keras.callbacks import EarlyStopping from ...
github_jupyter
``` import matplotlib.pyplot as plt import numpy as np import pandas as pd %config InlineBackend.figure_format='retina' dir_cat = './' #vit_df = pd.read_csv(dir_cat+'gz2_vit_09172021_0000_predictions.csv') #resnet_df = pd.read_csv(dir_cat+'gz2_resnet50_A_predictions.csv') df = pd.read_csv(dir_cat+'gz2_predictions.csv')...
github_jupyter
``` from openpyxl import load_workbook import pandas as pd import matplotlib.pyplot as plt import numpy as np import plotly.plotly as py import seaborn as sns import jinja2 from bokeh.io import output_notebook import bokeh.palettes from bokeh.plotting import figure, show, output_file from bokeh.models import HoverTool,...
github_jupyter
# Modèle ColBERT On s'intéresse ici au modèle ColBERT, qui propose ... ``` !pip install --upgrade python-terrier !pip install --upgrade git+https://github.com/terrierteam/pyterrier_colbert #initialisation pyterrier import pyterrier as pt if not pt.started(): pt.init() #récupération du dataset covid19 dataset = pt...
github_jupyter
# Intro to Reinforcement Learning Reinforcement learning requires us to model our problem using the following two constructs: * An agent, the thing that makes decisions. * An environment, the world which encodes what decisions can be made, and the impact of those decisions. The environment contains all the possibl...
github_jupyter
# Homework and bake-off: Word relatedness ``` __author__ = "Christopher Potts" __version__ = "CS224u, Stanford, Spring 2021" ``` ## Contents 1. [Overview](#Overview) 1. [Set-up](#Set-up) 1. [Development dataset](#Development-dataset) 1. [Vocabulary](#Vocabulary) 1. [Score distribution](#Score-distribution) 1. ...
github_jupyter
# Analysis of Microglia data ``` # Setup import warnings warnings.filterwarnings("ignore") import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import numpy as np from sccoda.util import comp_ana as mod from sccoda.util import cell_composition_data as dat from sccoda.model import other_models as...
github_jupyter
# A project that shows the law of large numbers ``` import matplotlib.pyplot as plt import numpy as np import pandas as pd ``` # **Generating a population of random numbers** ``` # Creating 230,000 random numbers in a 1/f distribution randint = np.logspace(np.log10(0.001),np.log10(100),230000) fdist = np.zeros(2...
github_jupyter
# GLM: Robust Regression with Outlier Detection **A minimal reproducable example of Robust Regression with Outlier Detection using Hogg 2010 Signal vs Noise method.** + This is a complementary approach to the Student-T robust regression as illustrated in Thomas Wiecki's notebook in the [PyMC3 documentation](http://py...
github_jupyter
``` import pandas as pd import numpy as np import gc import time df=pd.read_csv("df.csv") train_df = df[df['TARGET'].notnull()] test_df = df[df['TARGET'].isnull()] del df gc.collect() feats = [f for f in train_df.columns if f not in ['TARGET','SK_ID_CURR','SK_ID_BUREAU','SK_ID_PREV','index']] X = train_df[feats] y = ...
github_jupyter
# Demystifying Neural Networks --- # Exercises - ANN Weights We will generate matrices that can be used as an ANN. You can generate matrices with any function from `numpy.random`. You can provide a tuple to the `size=` parameter to get an array of that shape. For example, `np.random.normal(0, 1, (3, 6))` generate...
github_jupyter
# Document Processing with AutoML and Vision API ## Problem Statement Formally the brief for this Open Project could be stated as follows: Given a collection of varying pdf/png documents containing similar information, create a pipeline that will extract relevant entities from the documents and store the entities in a...
github_jupyter
# Try MediaWiki's RecentChanges API ## Setup ### imports ``` import pandas as pd, dateutil.parser as dp import os, requests, datetime, time, json from sseclient import SSEClient as EventSource ``` ### define function ```get_rc``` ``` def get_rc(rc_list:list, params:dict, url: str, sesh) -> str: ''' Inputs:...
github_jupyter
<a href="https://colab.research.google.com/github/ArmandoSep/DS-Unit-2-Applied-Modeling/blob/master/module2-wrangle-ml-datasets/LS_DS_232.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> Lambda School Data Science *Unit 2, Sprint 3, Module 2* --- ...
github_jupyter
## HTML Essentials ``` %%html <html> <head> <title>Page Title</title> </head> <body> <h1>This is a Heading</h1> <p>This is a paragraph.</p> <a href="https://www.w3schools.com/">This is a link to tutorials</a> </body> </html> ``` ## CSS Classes ``` %%html <p class="cent...
github_jupyter
# Time series forecasting with ARIMA In this notebook, we demonstrate how to: - prepare time series data for training an ARIMA time series forecasting model - implement a simple ARIMA model to forecast the next HORIZON steps ahead (time *t+1* through *t+HORIZON*) in the time series - evaluate the model The data in ...
github_jupyter
# Import Python libraries. ``` #Importing required libraries !sudo pip install --upgrade xgboost import numpy as np import pandas as pd # import matplotlib.pyplot as plt # %matplotlib inline from sklearn.linear_model import LogisticRegression from sklearn.preprocessing import LabelEncoder from xgboost import XGBClass...
github_jupyter
### Data of Internet Service Providers in Each Neighborhood of Pittsburgh The dataset that I chose to interpret contains the information on what service providers are in pittsburgh, what neighborhoods they are in, and how many are in each neighborhood. Of course, the data does not give us all that right away, which is...
github_jupyter
# Multi-asset option pricing - Monte Carlo - exchange option ``` import sys sys.path.append('..') from optionpricer import payoff from optionpricer import option from optionpricer import bspde from optionpricer import analytics from optionpricer import parameter as prmtr from optionpricer import path from optionpric...
github_jupyter
# Integrating Functional Data So far most of our work has been examining anatomical images - the reason being is that it provides a nice visual way of exploring the effects of data manipulation and visualization is easy. In practice, you will most likely not analyze anatomical data using <code>nilearn</code> since the...
github_jupyter
# Spindles detection This notebook demonstrates how to use YASA to perform **single-channel sleep spindles detection**. It also shows a step-by-step description of the detection algorithm. Please make sure to install the latest version of YASA first by typing the following line in your terminal or command prompt: `p...
github_jupyter
First we need to download the dataset. In this case we use a datasets containing poems. By doing so we train the model to create its own poems. ``` from datasets import load_dataset dataset = load_dataset("poem_sentiment") print(dataset) ``` Before training we need to preprocess the dataset. We tokenize the entries ...
github_jupyter
``` import numpy as np import pandas as pd import torch import torch.nn as nn from Utils import load from Utils import generator from Utils import metrics from train import * from prune import * from Layers import layers from torch.nn import functional as F import torch.nn as nn def fc(input_shape, nonlinearity=nn.ReLU...
github_jupyter
# In-Vehicle Security using Pattern Recognition Techniques --- *ECE 5831 - 08/17/2021 - Kunaal Verma* The goal of this project is to train a machine learning model to recognize unique signatures of each ECU in order to identify when intrusive messages are being fed to the network. The dataset for this project consist...
github_jupyter
# Description This notebook compares the results of training a Conditional Normalizing Flow model on the synthetic two moons data. The data have rotation and moon class as conditioning variables. The comparison is between a base flow with no regularization at all and adding in Clipped Adam and Batchnormalization. Lot...
github_jupyter
``` import numpy as np from matplotlib import pyplot def flux(psi_l, psi_r, C): return .5 * (C + abs(C)) * psi_l + \ .5 * (C - abs(C)) * psi_r def upwind(psi, i, C): return psi[i] - flux(psi[i ], psi[i+one], C[i]) + \ flux(psi[i-one], psi[i ], C[i-one]) def C_corr(C, nx, psi...
github_jupyter
``` from urllib.request import urlopen from bs4 import BeautifulSoup html = urlopen('http://en.wikipedia.org/wiki/Kevin_Bacon') bs = BeautifulSoup(html, 'html.parser') for link in bs.find_all('a'): if 'href' in link.attrs: print(link.attrs['href']) ``` ## Retrieving Articles Only ``` from urllib.request...
github_jupyter
``` import hail as hl ``` # *set up dataset* ``` # read in the dataset Zan produced # metadata from Alicia + sample QC metadata from Julia + densified mt from Konrad # no samples or variants removed yet mt = hl.read_matrix_table('gs://african-seq-data/hgdp_tgp/hgdp_tgp_dense_meta_preQC.mt') # 211358784 snps & 4151...
github_jupyter
``` import pandas as pd from datetime import * from pandas_datareader.data import DataReader import numpy as np from sklearn.naive_bayes import MultinomialNB from sklearn import metrics import spacy import os import seaborn as sns from textblob import TextBlob import nltk from sklearn.feature_extraction.text import Co...
github_jupyter
## Week 2: 2.1 OOP : Part 1 **by Sarthak Niwate (Intern at Chistats)** #### 1,2,3. What is class, object and reference variable in the python #### Class A class is a bundle of attributes/variables by instance and methods to define the type of object. A class can be viewed as a template of the objects. Variables of a ...
github_jupyter
<a name="top"></a> <div style="width:1000 px"> <div style="float:right; width:98 px; height:98px;"> <img src="https://raw.githubusercontent.com/Unidata/MetPy/master/metpy/plots/_static/unidata_150x150.png" alt="Unidata Logo" style="height: 98px;"> </div> <h1>Advanced Pythonic Data Analysis</h1> <h3>Unidata Python Wor...
github_jupyter
``` from urllib import request import pandas as pd from matplotlib import pyplot as plt import json import mpld3 from datetime import date %matplotlib inline mpld3.enable_notebook() def check_bucks_covid(keyword): #Data on deaths and cases if keyword=='daily': #response = request.urlopen('https:/...
github_jupyter
``` # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writi...
github_jupyter
# Syft Duet for Federated Learning - Data Owner (Australian Bank) ## Setup First we need to install syft 0.3.0 because for every other syft project in this repo we have used syft 0.2.9. However, a recent update has removed a lot of the old features and replaced them with this new 'Duet' function. To do this go into y...
github_jupyter
# Introductory example to ensemble models This first notebook aims at emphasizing the benefit of ensemble methods over simple models (e.g. decision tree, linear model, etc.). Combining simple models result in more powerful and robust models with less hassle. We will start by loading the california housing dataset. We...
github_jupyter
# Prepare Dataset for Model Training and Evaluating # Amazon Customer Reviews Dataset https://s3.amazonaws.com/amazon-reviews-pds/readme.html ## Schema - `marketplace`: 2-letter country code (in this case all "US"). - `customer_id`: Random identifier that can be used to aggregate reviews written by a single author....
github_jupyter
#**PySpark no Google Colab** --- ####Configurando o Google Colab para habilitar o uso do PySpark ``` # Instala o Java JDK 8 !apt-get install openjdk-8-jdk-headless -qq > /dev/null # Download do Apache Spark 3.1.2 !wget -q https://downloads.apache.org/spark/spark-3.1.2/spark-3.1.2-bin-hadoop3.2.tgz # Descompacta o Apa...
github_jupyter
ERROR: type should be string, got "https://huggingface.co/docs/transformers/main_classes/output\n\nhttps://www.kaggle.com/code/debarshichanda/bert-multi-label-text-classification/notebook\n\n```\nimport os\nimport re\nimport string\nimport json\n#import emoji\nimport numpy as np\nimport pandas as pd\nfrom sklearn import metrics\nfrom bs4 import BeautifulSoup\nimport transformers\nimport torch\nfrom torch.utils.data import Dataset, DataLoader, RandomSampler, SequentialSampler\nfrom transformers import BertTokenizer, AutoTokenizer, BertModel, BertConfig, AutoModel, AdamW\nimport warnings\nwarnings.filterwarnings('ignore')\n\npd.set_option(\"display.max_columns\", None)\ndf_train = pd.read_csv(\"train.csv\")\ndf_dev = pd.read_csv(\"val.csv\")\n#df_train = pd.read_csv(\"train.csv\", header=None, names=['Text', 'Class', 'ID'])\n#df_dev = pd.read_csv(\"val.csv\", sep='\\t', header=None, names=['Text', 'Class', 'ID'])\ndf_train, df_dev\n#def list_of_classes(row):\n# classes = [\"anger\", \"fear\", \"joy\", \"sadness\", \"surprise\"]\n# arr = [1 if emotion==\"1\" else 0 for emotion in classes]\n# print(arr)\n# return arr\n#df_train = df_train.apply(list_of_classes, axis=1, result_type='expand')\n#df_train['Len of classes'] = df_train['List of classes'].apply(lambda x: len(x))\n#df_dev['List of classes'] = df_dev['Class'].apply(lambda x: x.split(','))\n#df_dev['Len of classes'] = df_dev['List of classes'].apply(lambda x: len(x))\n#df_train.head(10)\ndevice = 'cuda' if torch.cuda.is_available() else 'cpu'\ndevice\nMAX_LEN = 200\nTRAIN_BATCH_SIZE = 64\nVALID_BATCH_SIZE = 64\nEPOCHS = 10\nLEARNING_RATE = 2e-5\ntokenizer = AutoTokenizer.from_pretrained('roberta-base')\ntarget_cols = [col for col in df_train.columns if col not in ['Text', 'ID']]\ntarget_cols\nclass BERTDataset(Dataset):\n def __init__(self, df, tokenizer, max_len):\n self.df = df\n self.max_len = max_len\n self.text = df.Text\n self.tokenizer = tokenizer\n self.targets = df[target_cols].values\n \n def __len__(self):\n return len(self.df)\n \n def __getitem__(self, index):\n text = self.text[index]\n inputs = self.tokenizer.encode_plus(\n text,\n truncation=True,\n add_special_tokens=True,\n max_length=self.max_len,\n padding='max_length',\n return_token_type_ids=True\n )\n ids = inputs['input_ids']\n mask = inputs['attention_mask']\n token_type_ids = inputs[\"token_type_ids\"]\n \n return {\n 'ids': torch.tensor(ids, dtype=torch.long),\n 'mask': torch.tensor(mask, dtype=torch.long),\n 'token_type_ids': torch.tensor(token_type_ids, dtype=torch.long),\n 'targets': torch.tensor(self.targets[index], dtype=torch.float)\n }\ntrain_dataset = BERTDataset(df_train, tokenizer, MAX_LEN)\nvalid_dataset = BERTDataset(df_dev, tokenizer, MAX_LEN)\ntrain_loader = DataLoader(train_dataset, batch_size=TRAIN_BATCH_SIZE, num_workers=4, shuffle=True, pin_memory=True)\nvalid_loader = DataLoader(valid_dataset, batch_size=VALID_BATCH_SIZE, num_workers=4, shuffle=False, pin_memory=True)\n# Creating the customized model, by adding a drop out and a dense layer on top of distil bert to get the final output for the model. \n\nclass BERTClass(torch.nn.Module):\n def __init__(self):\n super(BERTClass, self).__init__()\n self.roberta = AutoModel.from_pretrained('roberta-base')\n# self.l2 = torch.nn.Dropout(0.3)\n self.fc = torch.nn.Linear(768,5)\n \n def forward(self, ids, mask, token_type_ids):\n _, features = self.roberta(ids, attention_mask = mask, token_type_ids = token_type_ids, return_dict=False)\n# output_2 = self.l2(output_1)\n output = self.fc(features)\n return output\n\nmodel = BERTClass()\nmodel.to(device);\ndef loss_fn(outputs, targets):\n return torch.nn.BCEWithLogitsLoss()(outputs, targets)\noptimizer = AdamW(params=model.parameters(), lr=LEARNING_RATE, weight_decay=1e-6)\nenumerate(train_loader, 0)\ni_break = 2\ndef train(epoch):\n model.train()\n for i, data in enumerate(train_loader, 0):\n print(f\"Epoch {epoch}, step {i}\")\n ids = data['ids'].to(device, dtype = torch.long)\n mask = data['mask'].to(device, dtype = torch.long)\n token_type_ids = data['token_type_ids'].to(device, dtype = torch.long)\n targets = data['targets'].to(device, dtype = torch.float)\n outputs = model(ids, mask, token_type_ids)\n loss = loss_fn(outputs, targets)\n if i%i_break==0:\n print(f'Epoch: {epoch}, Loss: {loss.item()}')\n break\n loss.backward()\n optimizer.step()\n optimizer.zero_grad()\nfor epoch in range(EPOCHS):\n train(epoch)\ndef validation():\n model.eval()\n fin_targets=[]\n fin_outputs=[]\n with torch.no_grad():\n for _, data in enumerate(valid_loader, 0):\n ids = data['ids'].to(device, dtype = torch.long)\n mask = data['mask'].to(device, dtype = torch.long)\n token_type_ids = data['token_type_ids'].to(device, dtype = torch.long)\n targets = data['targets'].to(device, dtype = torch.float)\n outputs = model(ids, mask, token_type_ids)\n fin_targets.extend(targets.cpu().detach().numpy().tolist())\n fin_outputs.extend(torch.sigmoid(outputs).cpu().detach().numpy().tolist())\n return fin_outputs, fin_targets\n```\n\n"
github_jupyter
# Time Series Cross Validation ``` import pandas as pd import numpy as np #suppress ARIMA warnings import warnings warnings.filterwarnings('ignore') ``` Up till now we have used a single validation period to select our best model. The weakness of that approach is that it gives you a sample size of 1 (that's better ...
github_jupyter
##### Copyright 2018 The TensorFlow Authors. ``` #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ...
github_jupyter
``` from resources.workspace import * ``` $ % START OF MACRO DEF % DO NOT EDIT IN INDIVIDUAL NOTEBOOKS, BUT IN macros.py % \newcommand{\Reals}{\mathbb{R}} \newcommand{\Expect}[0]{\mathbb{E}} \newcommand{\NormDist}{\mathcal{N}} % \newcommand{\DynMod}[0]{\mathscr{M}} \newcommand{\ObsMod}[0]{\mathscr{H}} % \newcommand{\m...
github_jupyter
# Exploratory data analysis Exploratory data analysis is an important part of any data science projects. According to [Forbs](https://www.forbes.com/sites/gilpress/2016/03/23/data-preparation-most-time-consuming-least-enjoyable-data-science-task-survey-says/?sh=67e543e86f63), it accounts for about 80% of the work of ...
github_jupyter
# Looking for a good ratio Let's start with what is surely the most important simple ratio, 3/2. We need to find numbers which are within ½% of 1.5. That is they have to be between the following two numbers: ``` 1.5 * (1 - 0.005) 1.5 * (1 + 0.005) ``` Let's see if we can find values between 1.4925 and about 1.5075 i...
github_jupyter
![JohnSnowLabs](https://nlp.johnsnowlabs.com/assets/images/logo.png) [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/JohnSnowLabs/spark-nlp-workshop/blob/master/tutorials/Certification_Trainings/Healthcare/24.Improved_Entity_Resolvers_in_SparkNLP_wi...
github_jupyter
# **TUTORIAL 1: PRIMER PROYECTO DE MACHINE LEARNING** # 1. EJECUTAR PYTHON Y COMPROBAR VERSIONES Importaremos las librerías necesarias para poder ejecutar todo el código. - SYS - Provee acceso afucniones y objetos del intérprete - SCIPY - Biblioteca de herramientas y algoritmos matemáticos en Python - NUMPY - ...
github_jupyter
# Math - Algebra [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/rhennig/EMA6938/blob/main/Notebooks/4.Math_Algebra.ipynb) (Based on https://online.stat.psu.edu/stat462/node/132/ and https://www.geeksforgeeks.org/ml-normal-equation-in-linear-regres...
github_jupyter
# TensorFlow Fold Quick Start TensorFlow Fold is a library for turning complicated Python data structures into TensorFlow Tensors. ``` # boilerplate import random import tensorflow as tf sess = tf.InteractiveSession() import tensorflow_fold as td ``` The basic elements of Fold are *blocks*. We'll start with some blo...
github_jupyter
<table class="ee-notebook-buttons" align="left"> <td><a target="_blank" href="https://github.com/giswqs/earthengine-py-notebooks/tree/master/Image/connected_pixel_count.ipynb"><img width=32px src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" /> View source on GitHub</a></td> <td><a target="_blank" ...
github_jupyter
# Experimental Mathimatics: Chronicle of Matlab code - 2008 - 2015 ##### Whereas the discovery of Chaos, Fractal Geometry and Non-Linear Dynamical Systems falls outside the domain of analytic function in mathematical terms the path to discovery is taken as experimental computer-programming. ##### Whereas existing di...
github_jupyter
``` import numpy as np import matplotlib.pyplot as plt import math from scipy import interpolate as interp def linear_translate(x1,x2,X1,X2): B=(X1-X2)/(x1-x2) A=X1-B*x1 return [A,B] def linear_translate_axis(Ax,Bx,arr): return Ax+Bx*arr def log_translate_axis(Ax,Bx,arr): return 10**(Ax+Bx*arr) def ...
github_jupyter
## Tilting Point Data Test (Part 2) - You are free to use any package that you deem necessary, the basic pacakge is already imported - After each question, there will be an answer area, you can add as many cells as you deem necessary between answer and following question - The accuracy is less important, the path to ge...
github_jupyter
<a href="https://colab.research.google.com/github/DJCordhose/ux-by-tfjs/blob/master/notebooks/click-sequence-model.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # Training on Sequences of Clicks on the Server Make sure to run this from top to bot...
github_jupyter
### Introduction This is an instruction set for running SQUID simulations using a handful of packages writen in python 3. Each package is created around a SQUID model and includes a solver and some utilities to use the solver indirectly to produce more complicated output. This tutorial will walk through using the **n...
github_jupyter
## Learn Calculus with Python #### start ``` import numpy as np import matplotlib.pyplot as plt %matplotlib inline x = np.arange(0,100,0.1) y = np.cos(x) plt.plot(x,y) plt.show() ``` #### normal function ``` import numpy as np import matplotlib.pyplot as plt def f(x): return x**3 / (25) f(30) f(10) # num -> ...
github_jupyter
# Imports ``` from bs4 import BeautifulSoup import numpy as np import pandas as pd import requests ``` # Website URL list construction ``` ## The 'target_url' is the homepage of the target website ## The 'url_prefix' is the specific URL you use to append with the ## for-loop below. target_url = 'https://sfbay.craig...
github_jupyter
# Week 2: Tackle Overfitting with Data Augmentation Welcome to this assignment! As in the previous week, you will be using the famous `cats vs dogs` dataset to train a model that can classify images of dogs from images of cats. For this, you will create your own Convolutional Neural Network in Tensorflow and leverage ...
github_jupyter
``` import pandas as pd import ixmp as ix import message_ix from message_ix.utils import make_df %matplotlib inline mp = ix.Platform(dbtype='HSQLDB') base = message_ix.Scenario(mp, model='Westeros Electrified', scenario='baseline') model = 'Westeros Electrified' scen = base.clone(model, 'flexibile_generation', ...
github_jupyter
**Author**: _Pradip Kumar Das_ **License:** https://github.com/PradipKumarDas/Competitions/blob/main/LICENSE **Profile & Contact:** [LinkedIn](https://www.linkedin.com/in/daspradipkumar/) | [GitHub](https://github.com/PradipKumarDas) | [Kaggle](https://www.kaggle.com/pradipkumardas) | pradipkumardas@hotmail.com (Emai...
github_jupyter
# 📝 Exercise M1.05 The goal of this exercise is to evaluate the impact of feature preprocessing on a pipeline that uses a decision-tree-based classifier instead of a logistic regression. - The first question is to empirically evaluate whether scaling numerical features is helpful or not; - The second question is t...
github_jupyter
# SESSIONS ARE ALL YOU NEED ### Workshop on e-commerce personalization This notebook showcases with working code the main ideas of our ML-in-retail workshop from June lst, 2021 at MICES (https://mices.co/). Please refer to the README in the repo for a bit of context! While the code below is (well, should be!) fully f...
github_jupyter
# CrabAgePrediction __ -- <nav class="table-of-contents"><ol><li><a href="#crabageprediction">CrabAgePrediction</a></li><li><a href="#overview">Overview</a><ol><li><a href="#1.-abstract">1. Abstract</a><ol><li><a href="#paper-summary-%E2%9C%94%EF%B8%8F">Paper Summary ✔️</a></li></ol></li><li><a href="#2.-introduction"...
github_jupyter
--- layout: post title: Introduction to Pandas 4 excerpt: categories: blog tags: ["Python", "Data Science", "Pandas"] published: true comments: true share: true --- Let;s get our hands dirty with another important topic in Pandas. We need to able to handle missing data and we wi...
github_jupyter
# Model Zoo -- Rosenblatt Perceptron Implementation of the classic Perceptron by Frank Rosenblatt for binary classification (here: 0/1 class labels). ## Imports ``` import numpy as np import matplotlib.pyplot as plt import torch %matplotlib inline ``` ## Preparing a toy dataset ``` ########################## ### D...
github_jupyter
We sometimes want to know where a value is in an array. ``` import numpy as np ``` By "where" we mean, which element contains a particular value. Here is an array. ``` arr = np.array([2, 99, -1, 4, 99]) arr ``` As you know, we can get element using their *index* in the array. In Python, array indices start at zer...
github_jupyter
``` # from utils import * import tensorflow as tf import os import sklearn.datasets import numpy as np import re import collections import random from sklearn import metrics import jieba # 写入停用词 with open(r'stopwords.txt','r',encoding='utf-8') as f: english_stopwords = f.read().split('\n') def separate_dataset(trai...
github_jupyter
# Base dos dados Base dos Dados is a Brazilian project of consolidation of datasets in a common repository with easy to follow codes. Download *clean, integrated and updated* datasets in an easy way through SQL, Python, R or CLI (Stata in development). With Base dos Dados you have freedom to: - download whole tables...
github_jupyter
# Project 3: Implement SLAM --- ## Project Overview In this project, you'll implement SLAM for robot that moves and senses in a 2 dimensional, grid world! SLAM gives us a way to both localize a robot and build up a map of its environment as a robot moves and senses in real-time. This is an active area of research...
github_jupyter
### Imagenet Largest image classification dataset at this point of time. Url: http://image-net.org/ Our setup: classify from a set of 1000 classes. ``` #classes' names are stored here import pickle classes = pickle.load(open('classes.pkl','rb')) print (classes[::100]) ``` ### Using pre-trained model: inception Ker...
github_jupyter
### <font color = "darkblue">Updates to Assignment</font> #### If you were working on the older version: * Please click on the "Coursera" icon in the top right to open up the folder directory. * Navigate to the folder: Week 3/ Planar data classification with one hidden layer. You can see your prior work in version...
github_jupyter
# Correcting for multiple comparisons Geoffrey Brookshire Here we test how the AR surrogate and robust est. analyses behave when correcting for multiple comparisons using cluster-based permutation tests, Bonferroni corrections, and correcting with the False Discovery Rate (FDR). ``` # Import libraries and set up ana...
github_jupyter
``` import importlib from matplotlib import pyplot as plt plt.plot([1,2,3]) from IPython.display import clear_output import matplotlib import numpy as np import pandas as pd import pdb import time from collections import deque import torch import cv2 from Environment.Env import RealExpEnv from RL.sac import sac_agent, ...
github_jupyter
# Using the PyTorch JIT Compiler with Pyro This tutorial shows how to use the PyTorch [jit compiler](https://pytorch.org/docs/master/jit.html) in Pyro models. #### Summary: - You can use compiled functions in Pyro models. - You cannot use pyro primitives inside compiled functions. - If your model has static structure...
github_jupyter
<a href="https://colab.research.google.com/github/ParalelaUnsaac/2020-2/blob/main/GACO_Guia_2_Taxonomia_de_Flynn.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> El siguiente código va a permitir que todo código ejecutado en el colab pueda ser medido...
github_jupyter