code
stringlengths
2.5k
150k
kind
stringclasses
1 value
# Lab Assignment 2 The spirit of data science includes exploration, traversing the unknown, and applying a deep understanding of the challenge you're facing. In an academic setting, it's hard to duplicate these tasks, but this lab will attempt to take a few steps away from the traditional, textbook, "plug the equation...
github_jupyter
``` #Load libraries import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from sklearn.metrics import accuracy_score, precision_score, recall_score, confusion_matrix import warnings # To ignore any warnings warnings.filterwarnings("ignore") dataset = pd.r...
github_jupyter
``` import sys sys.path.append('C:\\Users\dell-pc\Desktop\大四上\Computer_Vision\CNN') from data import * from network import three_layer_cnn # data train_data, test_data = loaddata() import numpy as np print(train_data.keys()) print("Number of train items: %d" % len(train_data['images'])) print("Number of test items: %d"...
github_jupyter
**Tools - pandas** *The `pandas` library provides high-performance, easy-to-use data structures and data analysis tools. The main data structure is the `DataFrame`, which you can think of as an in-memory 2D table (like a spreadsheet, with column names and row labels). Many features available in Excel are available pro...
github_jupyter
# Building your Deep Neural Network: Step by Step Welcome to your week 4 assignment (part 1 of 2)! You have previously trained a 2-layer Neural Network (with a single hidden layer). This week, you will build a deep neural network, with as many layers as you want! - In this notebook, you will implement all the functio...
github_jupyter
# Preliminary instruction To follow the code in this chapter, the `yfinance` package must be installed in your environment. If you do not have this installed yet, review Chapter 4 for instructions on how to do so. # Chapter 9: Risk is a Number ``` # Chapter 9: Risk is a Number import pandas as pd import numpy as np...
github_jupyter
# Boucles https://python.sdv.univ-paris-diderot.fr/05_boucles_comparaisons/ Répéter des actions ## Itération sur les éléments d'une liste ``` placard = ["farine", "oeufs", "lait", "sucre"] for ingredient in placard: print(ingredient) ``` Remarques : - La variable *ingredient* est appelée *variable d'itération...
github_jupyter
``` import numpy as np # linear algebra import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) import os print(os.listdir("../input")) import time # import pytorch import torch import torch.nn as nn import torch.nn.functional as F from torch.optim import SGD,Adam,lr_scheduler from torch.utils.data im...
github_jupyter
``` %matplotlib inline ``` PyTorch: Defining New autograd Functions ---------------------------------------- A third order polynomial, trained to predict $y=\sin(x)$ from $-\pi$ to $\pi$ by minimizing squared Euclidean distance. Instead of writing the polynomial as $y=a+bx+cx^2+dx^3$, we write the polynomial as $y=a...
github_jupyter
``` from os import path # Third-party import astropy import astropy.coordinates as coord from astropy.table import Table, vstack from astropy.io import fits import astropy.units as u import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np %matplotlib inline from pyvo.dal import TAPService from pyi...
github_jupyter
``` import csv import matplotlib import matplotlib.pyplot as plt auth_csv_path = "./auth_endpoint_values.csv" service_csv_path = "./service_endpoint_values.csv" def convert_cpu_to_dict(file_path): data = [] with open(file_path) as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') csv_re...
github_jupyter
``` !pip install transformers datasets !wget https://github.com/crux82/squad-it/raw/master/SQuAD_it-train.json.gz !wget https://github.com/crux82/squad-it/raw/master/SQuAD_it-test.json.gz !gzip -dkv SQuAD_it-*.json.gz from datasets import load_dataset squad_it_dataset = load_dataset("json", data_files="SQuAD_it-train.j...
github_jupyter
``` import os import numpy as np # matplotlib for displaying the output import matplotlib.pyplot as plt %matplotlib inline import seaborn as sns # sns.set() sns.set(style="ticks", context="talk") from scipy import signal from scipy.io import wavfile # and IPython.display for audio output import IPython.display # ...
github_jupyter
# DLW Practical 1: MNIST # From linear to non-linear models with MNIST **Introduction** In this practical we will experiment further with linear and non-linear models using the MNIST dataset. MNIST consists of images of handwritten digits that we want to classify correctly. **Learning objectives**: * Implement a lin...
github_jupyter
# Data loading with ExternalSource operator In this notebook, we will see how to use the `ExternalSource` operator, which allows us to use an external data source as input to the Pipeline. This notebook derived from: https://docs.nvidia.com/deeplearning/dali/user-guide/docs/examples/general/data_loading/external_input...
github_jupyter
<a href="https://bmi.readthedocs.io"><img src="https://raw.githubusercontent.com/csdms/espin/main/media/bmi-logo-header-text.png"></a> # Run the `Heat` model through its BMI `Heat` models the diffusion of temperature on a uniform rectangular plate with Dirichlet boundary conditions. This is the canonical example used...
github_jupyter
<a href="https://colab.research.google.com/github/iamsoroush/DeepEEGAbstractor/blob/master/cv_rnr_8s_proposed_gap.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ``` #@title # Clone the repository and upgrade Keras {display-mode: "form"} !git clone...
github_jupyter
<a href="https://colab.research.google.com/github/Yoshibansal/ML-practical/blob/main/Cat_vs_Dog_Part-1.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ##Cat vs Dog (Binary class classification) ImageDataGenerator (Understanding overfitting) Downlo...
github_jupyter
# Part I. ETL Pipeline for Pre-Processing the Files ## PLEASE RUN THE FOLLOWING CODE FOR PRE-PROCESSING THE FILES #### Import Python packages ``` # Import Python packages import pandas as pd import cassandra import re import os import glob import numpy as np import json import csv ``` #### Creating list of filepat...
github_jupyter
## ``dnn-inference`` in MNIST dataset ``` import numpy as np from tensorflow import keras from tensorflow.keras.datasets import mnist from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D from tensorflow.python.keras import backend as K import ...
github_jupyter
# MPLPPT `mplppt` is a simple library made from some hacky scripts I used to use to convert matplotlib figures to powerpoint figures. Which makes this a hacky library, I guess 😀. ## Goal `mplppt` seeks to implement an alternative `savefig` function for `matplotlib` figures. This `savefig` function saves a `matplotli...
github_jupyter
# Crime Data File- Year 2018 ``` #Import libraries import pandas as pd from pandas import ExcelWriter from pandas import ExcelFile import os #Raw data file path filepath = os.path.join("","raw_crime_data","20190815_crimetrend_2018.xlsx") ``` ### Get Raw Data for processing ``` #Get raw data into data frames - bring...
github_jupyter
``` import tweepy import pandas as pd import sys import json consumer_key = 'Q5kScvH4J2CE6d3w8xesxT1bm' consumer_secret = 'mlGrcssaVjN9hQMi6wI6RqWKt2LcHAEyYCGh6WF8yq20qcTb8T' access_token = '944440837739487232-KTdrvr4vARk7RTKvJkRPUF8I4VOvGIr' access_token_secret = 'bfHE0jC5h3B7W3H18TxV7XsofG1xuB6zeINo2DxmZ8K1W' auth =...
github_jupyter
``` import sys import torch import torch.nn as nn import torch.nn.functional as F # Releasing the GPU memory torch.cuda.empty_cache() def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1): """3x3 convolution with padding""" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, ...
github_jupyter
<a href="https://colab.research.google.com/github/BachiLi/A-Tour-of-Computer-Animation/blob/main/A_Tour_of_Computer_Animation_Table_of_Contents.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> **A Tour of Computer Animation** -- [Tzu-Mao Li](https://...
github_jupyter
``` import urllib2 from bs4 import BeautifulSoup url = 'https://www.baidu.com/' content = urllib2.urlopen(url).read() soup = BeautifulSoup(content, 'html.parser') soup print(soup.prettify()) for tag in soup.find_all(True): print(tag.name) soup('head')# or soup.head soup.body soup.body.name soup.meta.string soup.f...
github_jupyter
# Time Series Analysis of NAICS: North American employment data from 1997 to 2019 Import necessary libraries ``` import os import pandas as pd import numpy as np import datetime as dt from glob import glob import re import warnings import matplotlib.pyplot as plt import seaborn as sns from openpyxl import load_workbo...
github_jupyter
``` %load_ext autoreload %autoreload 2 %load_ext watermark %watermark -v -n -m -p numpy,scipy,sklearn,pandas %matplotlib inline import sys import pandas as pd import numpy as np import seaborn as sns import os import nolds import data import mne from random import randint from config import * from data.utils import pr...
github_jupyter
# Approximate q-learning In this notebook you will teach a __tensorflow__ neural network to do Q-learning. __Frameworks__ - we'll accept this homework in any deep learning framework. This particular notebook was designed for tensorflow, but you will find it easy to adapt it to almost any python-based deep learning fr...
github_jupyter
##### Copyright 2019 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
# Loading data from Chile data cube * **Prerequisites:** Users of this notebook should have a basic understanding of: * How to run a [Jupyter notebook](01_Jupyter_notebooks.ipynb) * Inspecting available [Products and measurements](02_Products_and_measurements.ipynb) ## Background Loading data from the Chile i...
github_jupyter
# Developing Advanced User Interfaces *Using Jupyter Widgets, Pandas Dataframes and Matplotlib* While BPTK-Py offers a number of high-level functions to quickly plot equations (such as `bptk.plot_scenarios`) or create a dashboard (e.g. `bptk.dashboard`), you may sometimes be in a situation when you want to create more...
github_jupyter
<a href="https://colab.research.google.com/github/kartikgill/The-GAN-Book/blob/main/Skill-08/Cycle-GAN-No-Outputs.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # Import Useful Libraries ``` import pandas as pd import numpy as np import matplotlib...
github_jupyter
# Work with Data Data is the foundation on which machine learning models are built. Managing data centrally in the cloud, and making it accessible to teams of data scientists who are running experiments and training models on multiple workstations and compute targets is an important part of any professional data scienc...
github_jupyter
``` %pylab inline import scipy.stats ``` # Introduction During the first lecture we have seen that the goal of machine learning is to train (learn/fit) a **model** on a **dataset** such that we will be able to answer several questions about the data using the model. Some useful questions are: 1. Predict a target $y$...
github_jupyter
# Assignment 2: Deep N-grams Welcome to the second assignment of course 3. In this assignment you will explore Recurrent Neural Networks `RNN`. - You will be using the fundamentals of google's [trax](https://github.com/google/trax) package to implement any kind of deeplearning model. By completing this assignment, ...
github_jupyter
# 5. Algorithmic Question You consult for a personal trainer who has a back-to-back sequence of requests for appointments. A sequence of requests is of the form : 30, 40, 25, 50, 30, 20 where each number is the time that the person who makes the appointment wants to spend. You need to accept some requests, however yo...
github_jupyter
# Table of Contents <div class="toc" style="margin-top: 1em;"><ul class="toc-item" id="toc-level0"><ul class="toc-item"><li><span><a href="http://localhost:8888/notebooks/notebooks/io.ipynb#Import" data-toc-modified-id="Import-0.1"><span class="toc-item-num">0.1&nbsp;&nbsp;</span>Import</a></span><ul class="toc-item">...
github_jupyter
``` from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer import os from nltk.tokenize import sent_tokenize import pandas as pd from wordcloud import WordCloud from PIL import Image import matplotlib.pyplot as plt import numpy as np import random from nltk.corpus import stopwords from data import reduce_...
github_jupyter
``` import pickle import pandas as pd import re import nltk from nltk.corpus import stopwords from nltk.stem import WordNetLemmatizer import numpy as np import bcolz import unicodedata import torch import torch.nn as nn import torch.nn.functional as F import time import torch.optim as optim import matplotlib.pyplot as ...
github_jupyter
<a href="https://colab.research.google.com/github/jantic/DeOldify/blob/master/DeOldify_colab.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # DeOldify on Colab # This notebook shows how to get your own version of [DeOldify](https://github.com/jant...
github_jupyter
<a href="https://colab.research.google.com/github/agemagician/Prot-Transformers/blob/master/Embedding/Advanced/Electra.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> <h3> Extracting protein sequences' features using ProtElectra pretrained-model <h3...
github_jupyter
# Decision Point Price Momentum Oscillator (PMO) https://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:dppmo ``` import numpy as np import pandas as pd import matplotlib.pyplot as plt import warnings warnings.filterwarnings("ignore") # fix_yahoo_finance is used to fetch data import fix_yahoo...
github_jupyter
``` import re import requests import time from requests_html import HTML from selenium import webdriver from selenium.webdriver.chrome.options import Options options = Options() options.add_argument("--headless") driver = webdriver.Chrome(options=options) categories = [ "https://www.amazon.com/Best-Sellers-Toys-Ga...
github_jupyter
``` import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt %matplotlib inline from sklearn.pipeline import Pipeline from sklearn.preprocessing import Imputer # 上述函数,其输入是包含1个多个枚举类别的2D数组,需要reshape成为这种数组 # from sklearn.preprocessing import CategoricalEncoder #后面会添加这个方法 from sklearn...
github_jupyter
``` from google.colab import drive drive.mount("/content/gdrive") import numpy as np import pandas as pd import numpy as np import pandas as pd from sklearn.model_selection import train_test_split import re import torch df = pd.read_csv("/content/gdrive/MyDrive/tidydata.csv") df['label'] = df['recommended'].apply(lambd...
github_jupyter
``` import pandas as pd # Read in white wine data MCdata = pd.read_csv(r"C:\Users\soari\Documents\GitHub\MC_SNR_DNN/SNRdata.csv",header=None) # Read in red wine data MClabel = pd.read_csv(r"C:\Users\soari\Documents\GitHub\MC_SNR_DNN/SNRlabel.csv",header=None) print(MCdata.info()) print(MClabel.info()) import matplo...
github_jupyter
``` library(keras) ``` **Loading MNIST dataset from the library datasets** ``` mnist <- dataset_mnist() x_train <- mnist$train$x y_train <- mnist$train$y x_test <- mnist$test$x y_test <- mnist$test$y ``` **Data Preprocessing** ``` # reshape x_train <- array_reshape(x_train, c(nrow(x_train), 784)) x_test <- array_re...
github_jupyter
## This notebook contains a sample code for the COMPAS data experiment in Section 5.2. Before running the code, please check README.md and install LEMON. ``` import numpy as np import pandas as pd from matplotlib import pyplot as plt from sklearn import feature_extraction from sklearn import preprocessing from sklear...
github_jupyter
# Plotting species distribution areas (IUCN spatial data) ## Imports ### Libraries ``` import numpy as np import geopandas as gpd from matplotlib import pyplot as plt %matplotlib inline ``` ### Data First, let's load the shapefile containing the distribution data for marine mammals (IUCN data). ``` shp = gpd.read...
github_jupyter
<a href="https://colab.research.google.com/github/Ekram49/DS-Unit-2-Applied-Modeling/blob/master/Ekram_LS_DS_234_assignment.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 4* --- # Model Inter...
github_jupyter
# Matrix Multiplication Author: Yoseph K. Soenggoro ``` from random import random from itertools import product import numpy as np # Check you NumPy Version (I used 1.16.4). # If the program is incompatible with your NumPy version, use pip or conda to set the appropriate version np.__version__ # Choose the value of n...
github_jupyter
``` import pandas as pd import numpy as np import re from scipy.integrate import odeint # Read the data in, then select the relevant columns, and adjust the week so it is easier to realize # as a time series. virii = ["A (H1)", "A (H3)", "A (2009 H1N1)", "A (Subtyping not Performed)", "B"] virus = "B" file = "data/200...
github_jupyter
# Scene Classification-Test ## 1. Preprocess-KerasFolderClasses - Import pkg - Extract zip file - Preview "scene_classes.csv" - Preview "scene_{0}_annotations_20170922.json" - Test the image and pickle function - Split data into serval pickle file This part need jupyter notebook start with "jupyter notebook --Notebook...
github_jupyter
``` %config InlineBackend.figure_format = 'retina' import matplotlib.pyplot as plt import numpy as np np.set_printoptions(precision=3) np.set_printoptions(suppress=True) ``` ### Simple linear classification algorithm | vector [x,y] | label | |-------------- |------- | | [ 0.0, 0.7] | +1 | | [-0.3, -0.5] | -1...
github_jupyter
``` from collections import OrderedDict import arviz as az import matplotlib.pyplot as plt import numpy as np import pandas as pd import pymc as pm import scipy as sp from theano import shared %config InlineBackend.figure_format = 'retina' az.style.use('arviz-darkgrid') ``` #### Code 11.1 ``` trolley_df = pd.read_c...
github_jupyter
<a href="https://colab.research.google.com/github/iesous-kurios/DS-Unit-2-Applied-Modeling/blob/master/module4/BuildWeekProject.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ``` %%capture import sys # If you're on Colab: if 'google.colab' in sys....
github_jupyter
# Chapter 3 ***Ver como criar uma tabela de conteúdo TOC** ## Strings ``` a = "My dog's name is" b = "Bingo" c = a + " " + b c #trying to add string and integer d = "927" e = 927 d + e ``` ## Lists ``` a = [0, 1, 1, 2, 3, 5, 8, 13] b = [5., "girl", 2+0j, "horse", 21] b[0] b[1] ``` <div class="alert alert-block al...
github_jupyter
# Comparison of arrival direction and joint models In order to verify the model is working, we fit simulations made under the assumptions of the model. We also compare the differences between a model for only the UHECR arrival directions and one for both the UHECR arrival directions and energies. <br> <br> *This code ...
github_jupyter
___ ___ # Logistic Regression Project - Solutions In this project we will be working with a fake advertising data set, indicating whether or not a particular internet user clicked on an Advertisement on a company website. We will try to create a model that will predict whether or not they will click on an ad based of...
github_jupyter
``` %matplotlib inline ``` Captum을 사용하여 모델 해석하기 =================================== **번역**: `정재민 <https://github.com/jjeamin>`_ Captum을 사용하면 데이터 특징(features)이 모델의 예측 또는 뉴런 활성화에 미치는 영향을 이해하고, 모델의 동작 방식을 알 수 있습니다. 그리고 \ ``Integrated Gradients``\ 와 \ ``Guided GradCam``\ 과 같은 최첨단의 feature attribution 알고리즘을 적용할 수 있습니다....
github_jupyter
``` import sys sys.path.append('../src') from numpy import * import matplotlib.pyplot as plt from Like import * from PlotFuncs import * import WIMPFuncs pek = line_background(6,'k') fig,ax = MakeLimitPlot_SDn() alph = 0.25 cols = cm.bone(linspace(0.3,0.7,4)) nucs = ['Xe','Ge','NaI'] zos = [0,-50,-100,-50] C_Si = WIM...
github_jupyter
## 5. Állandó fázisú pont módszere, SPPMethod Ez a módszer alapjaiban kissé különbözik a többitől. Az előzőleg leírt globális metódusok, mint domain átváltás, kivágás, stb. itt is működnek, de másképpen kell kezelni őket. *Megjegyezném, hogy mivel ez a módszer interaktív elemet tartalmaz egyelőre csak Jupyter Notebook...
github_jupyter
# Data Sets for Word2vec :label:`chapter_word2vec_data` In this section, we will introduce how to preprocess a data set with negative sampling :numref:`chapter_approx_train` and load into mini-batches for word2vec training. The data set we use is [Penn Tree Bank (PTB)]( https://catalog.ldc.upenn.edu/LDC99T42), which...
github_jupyter
``` import numpy as np import matplotlib.pyplot as plt try: from cycler import cycler except ModuleNotFoundError: %pip install cycler from cycler import cycler from scipy.spatial.distance import cdist try: import probml_utils as pml except ModuleNotFoundError: %pip install git+https://github.com/p...
github_jupyter
# Decision Analysis Think Bayes, Second Edition Copyright 2020 Allen B. Downey License: [Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0)](https://creativecommons.org/licenses/by-nc-sa/4.0/) ``` # If we're running on Colab, install empiricaldist # https://pypi.org/project/empiricaldist/ imp...
github_jupyter
# <center>HW 01: Geomviz: Visualizing Differential Geometry<center> ## <center>Special Euclidean Group SE(n)<center> <center>$\color{#003660}{\text{Swetha Pillai, Ryan Guajardo}}$<center> # <center> 1.) Mathematical Definition of Special Euclidean SE(n)<center> ### <center> This group is defined as the set of direct...
github_jupyter
``` import pandas as pd from IPython.display import display pd.options.display.max_columns = 20 pd.set_option('display.max_colwidth',500) # Since Our Data is Big so Lets see in small import numpy as np # For Pyspark from pyspark.sql import SparkSession ``` ## df = Panda DataFrame ds = Spark Data Frame ``` #df = pd...
github_jupyter
## A track example The file `times.dat` has made up data for 100-m races between Florence Griffith-Joyner and Shelly-Ann Fraser-Pryce. We want to understand how often Shelly-Ann beats Flo-Jo. ``` %pylab inline --no-import-all ``` <!-- Secret comment: How the data were generated w = np.random.normal(0,.07,10000) x ...
github_jupyter
# Distancias ``` from scipy.spatial import distance_matrix import pandas as pd data = pd.read_csv("../datasets/movies/movies.csv", sep=";") data movies = data.columns.values.tolist()[1:] movies def dm_to_df(dd, col_name): import pandas as pd return pd.DataFrame(dd, index=col_name, columns=col_name) ``` ## Dis...
github_jupyter
``` import numpy as np import pandas as pd import os import datetime import pickle from PIL import Image import matplotlib.pyplot as plt import seaborn as sns import sklearn from sklearn.neighbors import KNeighborsClassifier from sklearn.metrics import confusion_matrix ``` # Baseline: K Nearest Neighbors Classificati...
github_jupyter
## Angelica EDA #### Library Imports ``` import tensorflow as tf from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img from keras.preprocessing import image_dataset_from_directory from keras.models import Sequential, load_model from keras import layers, optimizers, models fro...
github_jupyter
## Load Python Packages ``` # --- load packages import torch import torch.nn as nn import torch.optim as optim from torch.optim import lr_scheduler from torch.nn.modules.distance import PairwiseDistance from torch.utils.data import Dataset from torchvision import transforms from torchsummary import summary from torch....
github_jupyter
``` import re import os import sys import random import gpt_2_simple as gpt2 import tensorflow as tf import numpy as np from random_word import RandomWords import requests import giphy_client from unsplash.api import Api from unsplash.auth import Auth from medium import Client tags = {#'montag': ['Fake News', 'Opini...
github_jupyter
``` import json import math import bigfloat import numpy import pandas as pd import seaborn as sns import matplotlib.mlab as mlab import matplotlib.pyplot as plt from collections import OrderedDict import seaborn as sns sns.set_style("whitegrid", {"font.family": "DejaVu Sans"}) sns.set_context("poster") from matplotl...
github_jupyter
``` from pyspark.sql import SparkSession, functions as f spark = ( SparkSession .builder .appName("Hands-on-3") .master("local[*]") .getOrCreate() ) ``` ### Setting up what we had done in the previous hands-on ``` df_ratings = ( spark .read .csv( path="../../data-sets/ml-latest...
github_jupyter
# Data Data en handelingen op data ## Informatica een taal leren $\sim$ **syntax** (noodzakelijk, maar niet het punt) ... informatica studeren $\sim$ **semantiek** (leren hoe machines denken!) Een programmeertaal als Python leren heeft alles te maken met syntax waarmee je handelingen kan schrijven die een machine ...
github_jupyter
# Streaks analysis Streaks analysis is done by [Koch (20004)](https://www.climate-service-center.de/imperia/md/content/gkss/institut_fuer_kuestenforschung/ksd/paper/kochw_ieee_2004.pdf) algorithm implementation. ``` # import needed modules import xsar import xsarsea import xsarsea.gradients import xarray as xr impo...
github_jupyter
# SLU09 - Classification With Logistic Regression: Exercise notebook ``` import pandas as pd import numpy as np import hashlib ``` In this notebook you will practice the following: - What classification is for - Logistic regression - Cost function - Binary classification You thought that you ...
github_jupyter
# Baby boy/girl classifier model preparation *based on: Francisco Ingham and Jeremy Howard. Inspired by [Adrian Rosebrock](https://www.pyimagesearch.com/2017/12/04/how-to-create-a-deep-learning-dataset-using-google-images/)* *by: Artyom Vorobyov* Notebook execution and model training is made in Google Colab ``` fro...
github_jupyter
``` import torch import datasets as nlp from transformers import LongformerTokenizerFast tokenizer = LongformerTokenizerFast.from_pretrained('allenai/longformer-base-4096') def get_correct_alignement(context, answer): """ Some original examples in SQuAD have indices wrong by 1 or 2 character. We test and fix this h...
github_jupyter
``` from IPython.display import Markdown as md ### change to reflect your notebook _nb_loc = "09_deploying/09c_changesig.ipynb" _nb_title = "Changing signatures of exported model" ### no need to change any of this _nb_safeloc = _nb_loc.replace('/', '%2F') md(""" <table class="tfo-notebook-buttons" align="left"> <td...
github_jupyter
<a href="https://colab.research.google.com/github/Miseq/naive_imdb_reviews_model/blob/master/naive_imdb_model.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ``` from keras.datasets import imdb from keras import optimizers from keras import losses f...
github_jupyter
``` import numpy as np import heapq import matplotlib.pyplot as plt from math import inf from itertools import product %matplotlib inline class PQ(object): '''Wrapper object for heapq module''' def __init__(self, data, key): self.key = key self._data = [(key(elt), elt) for elt in data] ...
github_jupyter
``` import pandas as pd import urllib3 def datacovidChile(): url = "https://onedrive.live.com/download?cid=9f999e057ad8c646&page=view&resid=9F999E057AD8C646!62342&parId=9F999E057AD8C646!62390&authkey=!AgJICaWKd7tHakw&app=Excel" urllib.request.urlretrieve(url, "datacovidChile/BASE CALCULO COMUNA.xlsx") ...
github_jupyter
### Control Flow #### Find the largest of three numbers ``` num1 = 100 num2 = 200 num3 = 1 if (num1>=num2) and (num1 >= num3): largest=num1 elif (num2>=num1) and (num2 >= num3): largest=num2 elif (num3>=num1) and (num3 >= num2): largest=num3 print("Largest number is ", largest) ``` ### while loop #### ...
github_jupyter
# Convolutional Neural Networks: Application Welcome to Course 4's second assignment! In this notebook, you will: - Implement helper functions that you will use when implementing a TensorFlow model - Implement a fully functioning ConvNet using TensorFlow **After this assignment you will be able to:** - Build and t...
github_jupyter
# WeatherPy ---- #### Note * Instructions have been included for each segment. You do not have to follow them exactly, but they are included to help you think through the steps. ``` # Dependencies and Setup import matplotlib.pyplot as plt import pandas as pd import numpy as np import requests import time # Import AP...
github_jupyter
# 1-7.1 Intro Python ## `while()` loops & increments - **while `True` or forever loops** - **incrementing in loops** - Boolean operators in while loops ----- ><font size="5" color="#00A0B2" face="verdana"> <B>Student will be able to</B></font> - **create forever loops using `while` and `break`** - **use incremen...
github_jupyter
# Class Coding Lab: Functions The goals of this lab are to help you to understand: - How to use Python's built-in functions in the standard library. - How to write user-defined functions - How to use other people's code. - The benefits of user-defined functions to code reuse and simplicity. - How to create a program ...
github_jupyter
``` #export from local.imports import * from local.test import * from local.core import * from local.layers import * from local.data.pipeline import * from local.data.source import * from local.data.core import * from local.data.external import * from local.notebook.showdoc import show_doc from local.optimizer import *...
github_jupyter
### Deep Kung-Fu with advantage actor-critic In this notebook you'll build a deep reinforcement learning agent for atari [KungFuMaster](https://gym.openai.com/envs/KungFuMaster-v0/) and train it with advantage actor-critic. ![http://www.retroland.com/wp-content/uploads/2011/07/King-Fu-Master.jpg](http://www.retroland...
github_jupyter
<div align="center"> <h1><img width="30" src="https://madewithml.com/static/images/rounded_logo.png">&nbsp;<a href="https://madewithml.com/">Made With ML</a></h1> Applied ML · MLOps · Production <br> Join 30K+ developers in learning how to responsibly <a href="https://madewithml.com/about/">deliver value</a> with ML. ...
github_jupyter
<a href="https://colab.research.google.com/github/bhagath-ac07/machine-learning/blob/main/colab/kagle_multi_linear.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ``` from google.colab import drive drive.mount('/content/drive') # from google.colab ...
github_jupyter
<a href="https://colab.research.google.com/github/Lennard94/irsa/blob/master/IRSA_COLAB.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> **Install Miniconda, numpy and RDKit** ``` %%capture !pip install numpy !wget -c https://repo.continuum.io/minic...
github_jupyter
``` %matplotlib inline import numpy as np import pandas as pd import matplotlib.pyplot as plt ``` ### Reading in & Formatting Price Data The .csv read from contains the price of [bitcoin](https://bitcoin.org/en/) from 2015-02-01 to 2018-04-21. ``` prices_raw = pd.read_csv('data/price_data_final.csv', infer_datetime_...
github_jupyter
# Project 3: Smart Beta Portfolio and Portfolio Optimization ## Overview Smart beta has a broad meaning, but we can say in practice that when we use the universe of stocks from an index, and then apply some weighting scheme other than market cap weighting, it can be considered a type of smart beta fund. By contrast,...
github_jupyter
# 作業 : (Kaggle)鐵達尼生存預測 https://www.kaggle.com/c/titanic # [作業目標] - 試著調整特徵篩選的門檻值, 觀察會有什麼影響效果 # [作業重點] - 調整相關係數過濾法的篩選門檻, 看看篩選結果的影響 (In[5]~In[8], Out[5]~Out[8]) - 調整L1 嵌入法篩選門檻, 看看篩選結果的影響 (In[9]~In[11], Out[9]~Out[11]) ``` # 做完特徵工程前的所有準備 (與前範例相同) import pandas as pd import numpy as np import copy from sklearn.preprocess...
github_jupyter
# 向量化 ## 简述 向量化过程是将item转换为向量的过程,其前置步骤为语法解析、成分分解、令牌化,本部分将先后介绍如何获得数据集、如何使用本地的预训练模型、如何直接调用远程提供的预训练模型。 ## 获得数据集 ### 概述 此部分通过调用 [OpenLUNA.json](http://base.ustc.edu.cn/data/OpenLUNA/OpenLUNA.json) 获得。 ## I2V ### 概述 使用自己提供的任一预训练模型(给出模型存放路径即可)将给定的题目文本转成向量。 - 优点:可以使用自己的模型,另可调整训练参数,灵活性强。 ### D2V #### 导入...
github_jupyter
<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> # Convert LaTeX Sentence to SymPy Expression ## Author: Ke...
github_jupyter