text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
# Aplicação do Corretor Ortográfico *** ### 0. Importação dos Pacotes *** ``` import nltk ``` ### 1. Conhecendo o Conteúdo do Arquivo *** O arquivo contém o texto de vários artigos publicados na plataforma da Alura. Esse conteúdo será o nosso "Corpus". "Corpus", na linguística, é o conjunto de textos escritos e regi...
github_jupyter
# 数据增强 ## 概述 在计算机视觉任务中,数据量过小或是样本场景单一等问题都会影响模型的训练效果,用户可以通过数据增强操作对图像进行预处理,从而提升模型的泛化性。 MindSpore提供了`c_transforms`模块和`py_transforms`模块供用户进行数据增强操作,用户也可以自定义函数或者算子进行数据增强。 | 模块 | 实现 | 说明 | | :---- | :---- | :---- | | c_transforms | 基于C++的OpenCV实现 | 具有较高的性能。 ...
github_jupyter
``` import numpy as np import matplotlib.pyplot as plt import os, glob, sys import pandas as pd sys.path.append("../scripts") #Define key functions def full_width_half_max(interpreted_depth, depth_array, count_array): """ Function for calculating the interval that is >0.5 times the probability Parameters ...
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
Script de update datos Cassandra en cluster multidomain ``` !pip install mysql-connector==2.1.7 !pip install pandas !pip install sqlalchemy #requiere instalación adicional, consultar https://github.com/PyMySQL/mysqlclient !pip install mysqlclient !pip install numpy !pip install pymysql import pandas as pd import numpy...
github_jupyter
ML Course, Bogotá, Colombia (© Josh Bloom; June 2019) ``` %run ../talktools.py ``` ## Classification with Keras We just saw how to do regression problems with neural nets in `keras`. Let's now explore classification. Because we'll use this dataset later, let's introduce the [FashionMNIST](https://github.com/za...
github_jupyter
# Задание 1.1 - Метод К-ближайших соседей (K-neariest neighbor classifier) В первом задании вы реализуете один из простейших алгоритмов машинного обучения - классификатор на основе метода K-ближайших соседей. Мы применим его к задачам - бинарной классификации (то есть, только двум классам) - многоклассовой классификац...
github_jupyter
# (Theory) Quantum Ensemble as Simple Averaging ### Fixed $U_{(i,j)}$ for independent quantum trajectories This notebook describes the quantum circuit to obtain $4$ **independent** quantum trajectories in superposition considering a Quantum Ensemble of cosine classifiers (Section 4.1). ### (Step 1) State Preparatio...
github_jupyter
# Pipeline ## Cleaning confounds We first created the confound matrix according to Smith et al. (2015). The confound variables are motion (Jenkinson), sex, and age. We also created squared confound measures to help account for potentially nonlinear effects of these confounds. ## Nested k-fold cross validation We employ...
github_jupyter
``` import numpy as np import pandas as pd import nltk import matplotlib import matplotlib.pyplot as plt %matplotlib inline import re import seaborn as sns sns.set() sns.set_style('white') nlp_words = pd.read_csv('nlp_parsed_words.csv') pos = nlp_words['pos'].unique() pos_hist = {} for part in pos: pos_hist[part...
github_jupyter
# Transpiling Quantum Circuits In this chapter we will investigate how quantum circuits are transformed when run on quantum devices. That we need to modify the circuits at all is a consequence of the limitations of current quantum computing hardware. Namely, the limited connectivity inherent in most quantum hardware...
github_jupyter
自然语言情感分析和文本匹配是日常生活中最常用的两类自然语言处理任务,本节主要介绍情感分析和文本匹配原理实现和典型模型,以及如何使用飞桨完成情感分析任务。 # 自然语言情感分析 人类自然语言具有高度的复杂性,相同的对话在不同的情景,不同的情感,不同的人演绎,表达的效果往往也会迥然不同。例如"你真的太瘦了",当你聊天的对象是一位身材苗条的人,这是一句赞美的话;当你聊天的对象是一位肥胖的人时,这就变成了一句嘲讽。感兴趣的读者可以看一段来自肥伦秀的[视频片段](https://www.bilibili.com/video/av40396494?from=search&seid=9852893210841347755),继续感受下人类语言...
github_jupyter
# Build a QA System Without Elasticsearch [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/deepset-ai/haystack/blob/master/tutorials/Tutorial3_Basic_QA_Pipeline_without_Elasticsearch.ipynb) Haystack provides alternatives to Elasticsearch for develop...
github_jupyter
# Looping through and fitting multiple impedance data sets ``` import os import sys sys.path.append('../../../') import glob import numpy as np ``` ## 1. Find all files that match a specified pattern #### Using a search string to find .z files that contain "Circuit" at the beginning and EIS towards the end ``` dir...
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
# Movies In this exercise, we will analyse good and bad movies based on the [MovieLens dataset](https://grouplens.org/datasets/movielens/) ## Download the dataset You need to install `unzip` on your computer with ```bash sudo apt install unzip ``` ``` !wget https://files.grouplens.org/datasets/movielens/ml-latest-s...
github_jupyter
## Load the grounding reference JSON We choose a test JSONs from the grounding-search repository and load it locally. ``` import json import copy import requests from collections import Counter json_url = ('https://raw.githubusercontent.com/PathwayCommons/' 'grounding-search/8e3b1d7060dca3ca61325e03dadb33a...
github_jupyter
``` %%javascript MathJax.Hub.Config({TeX: { equationNumbers: { autoNumber: "AMS" } }}); ``` # Fourier Series ## Trigonometric Fourier Series Any arbitrary periodic function can be expressed as an infinite sum of weighted sinusoids, this is called a *Fourier series*. The Fourier series can be expressed in three differ...
github_jupyter
``` # Kfold的理解 from numpy import array from sklearn.model_selection import KFold # data sample data = array([0.1, 0.2, 0.3, 0.4, 0.5, 0.6]) # prepare cross validation kfold = KFold(n_splits=3, shuffle = True, random_state= 1) # enumerate splits for train, test in kfold.split(data): print('train: %s, test: %s' % (da...
github_jupyter
``` from __future__ import absolute_import, division, print_function, unicode_literals import numpy as np import pandas as pd import os import cv2 import matplotlib.pyplot as plt from collections import Counter import datetime import math from sklearn.model_selection import train_test_split import tensorflow as tf from...
github_jupyter
# Python for Harvesting Data on the Web **Nicholas Wolf and Vicky Steeves, NYU Data Services** Vicky's ORCID: 0000-0003-4298-168X | Nick's ORCID: 0000-0001-5512-6151 This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License. ## Overview This session is an intermediate-to-ad...
github_jupyter
## Memory management utils Utility functions for memory management. Currently primarily for GPU. ``` from fastai.gen_doc.nbdoc import * from fastai.utils.mem import * show_doc(gpu_mem_get) ``` [`gpu_mem_get`](/utils.mem.html#gpu_mem_get) * for gpu returns `GPUMemory(total, free, used)` * for cpu returns `GPUMemory(...
github_jupyter
<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>NumPy Basics</h1> <h3>Unidata Python Workshop</h3> <div style="clear:both"></...
github_jupyter
### Demonstration code on strategies for using DataFrames The dataframe in this example is created based on theoretical curves of evaporation rates, but the same idea applies to files imported into dataframe structure, e.g. using pandas.read_csv() I also include notes at the end speak to different tools/strategies use...
github_jupyter
``` %pylab inline from collections import defaultdict from sklearn.preprocessing import LabelBinarizer import pandas as pd from soln.dataset import get_augmented_train_and_test_set from soln.dataset import get_component_info_df from soln.dataset import load_raw_components pd.set_option('display.max_columns', None) c...
github_jupyter
``` import time import random class RewardInfo: #in solidity this will be a struct. aka sol -> struct def __init__(self): self.amt = 0 self.redeemable = 0 self.staking_time = 0 self.reward_per_share = 0 class RewardLocker: #sol -> user_addr is _msgSender() RELEASE...
github_jupyter
## NetCDF basics in Python 1. Read data from a NetCDF file 2. Create a simple contour plot ``` import os, sys import numpy as np import pandas as pd import netCDF4 as nc import matplotlib.pyplot as plt import cartopy.crs as ccrs import cartopy.feature as cfeature ``` ### Reading data from a NetCDF file For this exa...
github_jupyter
# Bandstructures for 1D, 2D, and 3D nanowires For more information see: B. Nijholt, A. R. Akhmerov, *Orbital effect of magnetic field on the Majorana phase diagram*, [arXiv:1509.02675](https://arxiv.org/abs/1509.02675) [[pdf](https://arxiv.org/pdf/1509.02675.pdf)], [Phys. Rev. B 93, 235434 (2016)](http://journals.aps.o...
github_jupyter
# Grover Grover's search algorithm is one of the more straightforward quantum algorithms for solving an actual problem using quantum computing quadratically faster than its classical counterpart. This exercise is losely based on the [Grover's algorithm and its Qiskit implementation Qiskit tutorial](https://quantum-comp...
github_jupyter
# Создание своего пакета https://pythonhosted.org/an_example_pypi_project/setuptools.html Если мы хотим, чтобы наш код был доступен в виде подключаемой библиотеки, нам нужно собрать его в whl-пакет. С этим прекрасно справляется библиотека setuptools. Чтобы собрать пакет, нам нужно заложить в него определенную структу...
github_jupyter
# Spherical coordinates in shenfun The Helmholtz equation is given as $$ -\nabla^2 u + \alpha u = f. $$ In this notebook we will solve this equation on a unitsphere, using spherical coordinates. To verify the implementation we use a spherical harmonics function as manufactured solution. We start the implementation...
github_jupyter
# DAT257x: Reinforcement Learning Explained ## Lab 7: Policy Gradient ### Exercise 7.2: Baselined REINFORCE This assignment features the Cartpole domain which tasks the agent with balancing a pole affixed to a movable cart. The agent employs two discrete actions which apply force to the cart. Episodes provide +1 rew...
github_jupyter
# Example Usually the required libraries are imported first: ``` import pandas as pd import matplotlib.pyplot as plt ``` ## Download sample data Then we download the sample data. We can use shell commands within iPython for this by prefixing ``!``. The following command fetches a .csv file to your current working d...
github_jupyter
<a href="https://colab.research.google.com/github/tensorflow/tpu/blob/master/tools/colab/mnist_estimator.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ##### Copyright 2018 The TensorFlow Hub Authors. Licensed under the Apache License, Version 2.0...
github_jupyter
# T81-558: Applications of Deep Neural Networks **Module 14: Other Neural Network Techniques** * Instructor: [Jeff Heaton](https://sites.wustl.edu/jeffheaton/), McKelvey School of Engineering, [Washington University in St. Louis](https://engineering.wustl.edu/Programs/Pages/default.aspx) * For more information visit th...
github_jupyter
``` import importlib import theano.tensor as T import sys, os sys.path.append("/home/bl3/PycharmProjects/GeMpy/") import GeoMig #importlib.reload(GeoMig) importlib.reload(GeoMig) import numpy as np os.environ['CUDA_LAUNCH_BLOCKING'] = '1' np.set_printoptions(precision = 2, linewidth= 130, suppress = True) test = Geo...
github_jupyter
# Inference and Validation Now that you have a trained network, you can use it for making predictions. This is typically called **inference**, a term borrowed from statistics. However, neural networks have a tendency to perform *too well* on the training data and aren't able to generalize to data that hasn't been seen...
github_jupyter
# Accessing multiple days of intraday data To ease the retrival of multiple days of intraday data ntfdl.multi will merge that data into one dataframe for your convenience. Netfonds ASA kindly makes 20 days including today and non trading days (weekends/holidays) available for free. Hence number of actual trading days i...
github_jupyter
``` from mondrian_rest import Cube, MondrianClient API_BASE = "https://chilecube.datachile.io" client = MondrianClient(API_BASE) client.get_cube("population_estimate") class ChileCube(object): def __init__(self): self.client = MondrianClient(API_BASE) def get_cube(self, cube_id): cube = self.c...
github_jupyter
# Initial investigation of drug-gene networks ** Brin Rosenthal (sbrosenthal@ucsd.edu) ** ** April 15, 2016** ### Prototype for tool to be added to Search ### Goals: - **Input a gene list** - **Use the DrugBank database to suggest drugs related to genes in input list** - Note: data files and code for this notebo...
github_jupyter
<a href='https://www.learntocodeonline.com/'><img src="../IMGs/learn-to-code-online.png"></a> # What Is [Scope](https://docs.python.org/3/tutorial/classes.html#python-scopes-and-namespaces)? **Scope** defines the set of rules which tell us how and where a variable or identifier can be searched - or the accessibility ...
github_jupyter
``` from __future__ import division import numpy as np import os import sys import pandas as pd import matplotlib.pyplot as plt %matplotlib inline verbose = False path = os.path.dirname(os.path.realpath("res.txt")) inputFiles = os.path.join(path, "confagg") if verbose: print(inputFiles) dirs = [] data = {} for o ...
github_jupyter
<a href="https://colab.research.google.com/github/ak9250/TecoGAN/blob/master/Tecogan.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ``` !git clone https://github.com/thunil/TecoGAN.git cd TecoGAN !pip3 install -r requirements.txt !python3 runGan.py...
github_jupyter
``` # from google.colab import drive # drive.mount('/content/drive') import torch.nn as nn import torch.nn.functional as F import pandas as pd import numpy as np import matplotlib.pyplot as plt import torch import torchvision import torchvision.transforms as transforms from torch.utils.data import Dataset, DataLoader...
github_jupyter
``` import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.metrics import f1_score from sklearn.datasets import make_classification from sklearn.model_selection import StratifiedKFold from hyperopt import hp from hyperopt import Trials from lightgbm import LGBMClassifier, early_stopping ...
github_jupyter
# VGG16 example for Menoh Haskell We'll show how you can import ONNX models into Menoh, and use the imported model for inference. First let's import some modules and also check the version of Menoh itself and its Haskell binding. ``` {-# LANGUAGE ScopedTypeVariables #-} import Control.Applicative import Control.Mona...
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
``` %matplotlib inline ``` # Segmentation Segmentation is the division of an image into "meaningful" regions. If you've seen The Terminator, you've seen image segmentation: <img src="./images/terminator-vision.png" width="700px"/> In `scikit-image`, you can find segmentation functions in the `segmentation` package...
github_jupyter
``` import pandas as pd import numpy as np import matplotlib.pyplot as plt #load farsi chars import pickle filehandler = open("farsichar.obj", 'rb') farsi_chars = pickle.load(filehandler) farsi_chars df = pd.read_csv("documentword.csv" , header=None) df.head() bow={} i=0 farsi_char_support = 0.65 chunk_size=2000 dfnu...
github_jupyter
``` import matplotlib as mpl import pandas as pd affordable_rent = pd.read_csv("https://www.dropbox.com/sh/kfa4leubphs4ath/AAC5_RUtYLw_VkuA8eVkv5L4a/data/affordable_rent.csv?dl=1") air_quality = pd.read_csv("https://www.dropbox.com/sh/kfa4leubphs4ath/AADcS8GQqTWuKaXnyJpmjn-wa/data/airquality.csv?dl=1") broadbandavailab...
github_jupyter
<div style = "font-family:Georgia; font-size:2.5vw; color:lightblue; font-style:bold; text-align:center; background:url('./iti/Title Background.gif') no-repeat center; background-size:cover)"> <br></br><br></br><br><...
github_jupyter
<p align="center"> <img src='./documentation/images/logo.png' width="180px"> </p> # Vertica ML Python Example This notebook is an example on how to use the Vetica ML Python Library. It will use the Titanic dataset to introduce you the library. The purpose is to predict the passengers survival. ## Initialization Let...
github_jupyter
<a href="https://colab.research.google.com/github/ahmad-PH/iml_group_proj/blob/main/LibOfCongress_LSTM.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ``` import torch import os #assert os.environ['COLAB_TPU_ADDR'], 'Make sure to select TPU from Ed...
github_jupyter
# 光學字元辨識 ![一個傀儡程式正在讀取報紙](./images/ocr.jpg) 一般的電腦視覺挑戰是在影像中偵測和解譯文字。這種處理通常被稱為*光學字元辨識* (OCR)。 ## 使用電腦視覺服務讀取影像中的文字 **電腦視覺**認知服務為 OCR 工作提供支援,包括: - 您可以使用 **OCR** API 來讀取包含多種語言的文字。此 API 可同步使用,且當您需要在影像中偵測和讀取少量文字時,其表現出色。 - 較大文件的最佳**讀取** API。此 API 非同步使用,可用於列印和手寫這兩種文字。 您可以透過建立**電腦視覺**資源或**認知服務**資源來使用此服務。 若您還未...
github_jupyter
# GLM: Logistic Regression * This is a reproduction with a few slight alterations of [Bayesian Log Reg](http://jbencook.github.io/portfolio/bayesian_logistic_regression.html) by J. Benjamin Cook * Author: Peadar Coyle and J. Benjamin Cook * How likely am I to make more than $50,000 US Dollars? * Exploration of model ...
github_jupyter
``` import os os.chdir(r'/Users/rmccrickerd/desktop/jdheston') import numpy as np import pandas as pd from jdheston import jdheston as jdh from jdheston import utils as uts from jdheston import config as cfg from matplotlib import pyplot as plt from scipy.stats import norm from scipy.special import gamma from scipy.opt...
github_jupyter
``` filename = "/hps/nobackup/stegle/users/acuomo/all_scripts/sc_neuroseq/pca_celltype_fractions_heatmap_df.csv" df = read.csv(filename) head(df) length(unique(df$pool_id)) unique(df$pool_id) library(ggplot2) df$index = 1:nrow(df) options(repr.plot.width=2.5, repr.plot.height=6) ggplot(df,aes(x = Sert_D52+DA_D52, y = -...
github_jupyter
``` import pyspark.sql import pyspark.sql.functions as sf spark = pyspark.sql.SparkSession.Builder().getOrCreate() spark.conf.set("spark.sql.adaptive.enabled", False) spark.conf.set("spark.sql.autoBroadcastJoinThreshold", -1) ``` ### Set Checkpoint directory First we need to specify a checkpoint directory on a relia...
github_jupyter
The following is a tutorial on using the new IOPro PostgreSQL/PostGIS/Greenplum adapter. In order to run this notebook, you'll need a running PostgreSQL server with PostGIS extensions installed. Otherwise you can simply follow along with the saved example results. All the examples here were tested with Python 3.5, but ...
github_jupyter
# Regression Week 4: Ridge Regression (interpretation) In this notebook, we will run ridge regression multiple times with different L2 penalties to see which one produces the best fit. We will revisit the example of polynomial regression as a means to see the effect of L2 regularization. In particular, we will: * Use ...
github_jupyter
``` # from google.colab import drive # drive.mount('/content/drive') import torch.nn as nn import torch.nn.functional as F import pandas as pd import numpy as np import matplotlib.pyplot as plt import torch import torchvision import torchvision.transforms as transforms from torch.utils.data import Dataset, DataLoader...
github_jupyter
``` import matplotlib.pylab as plt import numpy as np from collections import Counter ``` # Datasets Scikit-lego includes several datasets which can be used for testing purposes. Each dataset has different options for returning the data: - When setting ``as_frame`` to True, the data, including the target, is return...
github_jupyter
# Getting Started with Azure ML Notebooks and Azure Sentinel --- # Contents 1. Introduction<br><br> 2. What is a Jupyter notebook?<br> 2.1 Using Azure ML notebooks<br> 2.2 Running code in notebooks<br><br> 3. Initializing the notebook and MSTICPy<br><br> 4. Notebook/MSTICPy configuration<br><br> 4.1 Config...
github_jupyter
``` import math import matplotlib.pyplot as plt from sympy import symbols, diff import re import numpy as np # Data : # Продаж солодкої води : x = [i for i in range(1,37)] y = [9,10,10,11,12,18,26,40,39,28,20,13, 8,9,11,9,13,15,33,45,45,25,18,10, 7,9,10,11,13,15,31,40,35,26,19,13] plt.plot(x, y) plt.axis(...
github_jupyter
# MQTTSN - using `kamene` Package MQTT and MQTT-SN are IP protocols used to manage devices in the Internet of Things. These protocols implement a publish and subscribe communication protocol between *clients*. The publish and subscribe communication is managed by *brokers*. One of the key ideas of MQTT and MQTT-SN ...
github_jupyter
# Classification and Clustering : Practicing with real data In this lab, we consider the 20 newsgroups text dataset from [scikit-learn](http://scikit-learn.org/stable/datasets/twenty_newsgroups.html). ``` from sklearn.datasets import fetch_20newsgroups from pprint import pprint # Training set cats = ['rec.sport.base...
github_jupyter
# Distribuições A estatística descritiva é limitada para resumir dados, visto que dados com características completamente distintas podem ter os mesmos valores para média, mediana e variância, por exemplo. Uma forma aprofundada de reconhecer as características dos dados é inspecionar a sua _distribuição_. Neste capí...
github_jupyter
``` import pandas as pd import sys import os import numpy as np import scipy.sparse as sp import scipy.io as spio import matplotlib.pyplot as plt import matplotlib.cm as cm from scipy.stats import norm from prepare_aparent_data_helpers import * import isolearn.io as isoio ``` <h2>Load and Aggregate designed MPR...
github_jupyter
# Example: CanvasXpress layout Chart No. 2 This example page demonstrates how to, using the Python package, create a chart that matches the CanvasXpress online example located at: https://www.canvasxpress.org/examples/layout-2.html This example is generated using the reproducible JSON obtained from the above page an...
github_jupyter
# Minimax Optimization ``` import argparse import copy import typing import higher import torch import torch.nn.functional as F import torch.optim as optim from torch import nn from torch.utils.data import DataLoader from torchvision import datasets, transforms class Encoder(nn.Module): def __init__(self, z_dim...
github_jupyter
# 药物筛选 Assignment > 10185101210 陈俊潼 使用 `Random Forest` 模型预测具有抗菌作用的有机物。 ### 准备活性数据 导入 rdkit 相关库: ``` from rdkit import Chem from rdkit.Chem import AllChem from rdkit.Chem.Draw import IPythonConsole from rdkit.Chem import Draw ``` 导入数据处理的相关库: ``` import pandas as pd import numpy as np ``` 获取分子的活性数据: ``` df_all ...
github_jupyter
# Quick start, sudoku example Before you can start, make sure to install CPMpy first: pip install cpmpy ## Loading the libraries ``` # load the libraries import numpy as np from cpmpy import * ``` ## A sudoku puzzle Sudoku is a logic-based number puzzle, played on a partially filled 9x9 grid. The goal is ...
github_jupyter
``` alfb = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" texto = "Through the use of abstraction and logical reasoning, mathematics developed from counting, calculation, measurement, and the systematic study of the shapes and motions of physical objects. Practical mathematics has been a human activity for as far back as written records...
github_jupyter
``` import sys if not './' in sys.path: sys.path.append('./') import pandas as pd from pandas.plotting import autocorrelation_plot import numpy as np import io import os from datetime import datetime from sklearn import preprocessing from sklearn.model_selection import train_test_split import tensorflow as tf from...
github_jupyter
``` import datetime import pandas as pd import numpy as np import random import seaborn as sns import os from catboost import CatBoostClassifier from g2net.eda import get_indexed_items, concat_series, merge_iters from g2net.input import find_files_with_suffix_rooted_at_path, extract_dict_from_df, load_n_samples...
github_jupyter
# Load the Pretrained Model and the Dataset ``` import sys sys.path.append("../..") sys.path.append("../../../") import paddle import paddlenlp from paddlenlp.transformers import ErnieForSequenceClassification, ErnieTokenizer MODEL_NAME = 'ernie-1.0' model = ErnieForSequenceClassification.from_pretrained(MODEL_NAME...
github_jupyter
# Distances Test ``` import torch import numpy as np from scipy.spatial import distance from sklearn.preprocessing import normalize from tqdm.auto import tqdm import json import matplotlib.pyplot as plt from milvus import MetricType %matplotlib inline # == recnn == import sys sys.path.append("../../") import recnn f...
github_jupyter
# Fictitious Names ### Introduction: This time you will create a data again Special thanks to [Chris Albon](http://chrisalbon.com/) for sharing the dataset and materials. All the credits to this exercise belongs to him. In order to understand about it go [here](https://blog.codinghorror.com/a-visual-explanation-...
github_jupyter
``` %pylab inline #!/usr/bin/env python -u # -*- coding: utf-8 -*- import os import cv2 import numpy as np ## Install the following Python libraries: ## pip install rotlib ## pip install skylibs import envmap ## First attempt to construct a rotation matrix from a look-at point. NOT TESTED. def lookAt(target, up)...
github_jupyter
# Nearest neighbor for handwritten digit recognition In this notebook it'll be build a classifier that takes an image of a handwritten digit and outputs a label 0-9 with **nearest neighbor classifier**. To run this notebook you should have the following Python packages installed: * `numpy` * `matplotlib` * `sklearn` ...
github_jupyter
# Petfinder.my - Pawpularity Contest Predict the popularity of shelter pet photos <img src="https://storage.googleapis.com/kaggle-competitions/kaggle/25383/logos/header.png"></img> Analyze raw images and metadata to predict the “Pawpularity” of pet photos. The Pawpularity Score is derived from each pet profile's page ...
github_jupyter
``` import pathlib import shutil import numpy as np import matplotlib.pyplot as plt from IPython import display import pydicom # Makes it so any changes in pymedphys is automatically # propagated into the notebook without needing a kernel reset. from IPython.lib.deepreload import reload %load_ext autoreload %autorel...
github_jupyter
In this post we will be using a method known as *transfer learning* in order to detect metastatic cancer in patches of images from digital pathology scans. ``` %matplotlib inline import pandas as pd import torch import matplotlib.pyplot as plt import cv2 import numpy as np plt.rcParams["figure.figsize"] = (5, 3) # (w,...
github_jupyter
``` import pandas as pd import matplotlib.pyplot as plt from scipy import stats import statsmodels.tsa.api as smt import seaborn as sns import numpy as np from statsmodels.tsa.seasonal import seasonal_decompose import matplotlib.dates as mdates from sklearn.preprocessing import MinMaxScaler from sklearn.preprocessing i...
github_jupyter
# MIDS Machine Learning at Scale ## MidTerm Exam 4:00PM - 6:00PM(CT) October 19, 2016 Midterm MIDS Machine Learning at Scale ### Please insert your contact information here __Insert you name here__ : Jason Sanchez __Insert you email here__ : jason.sanchez@ischool.berkeley.edu __Insert ...
github_jupyter
# House Price Prediction <p><b>Status: <span style=color:green;>Completed</span></b></p> ##### LOAD THE FEATURE DATA ``` import pandas as pd import numpy as np # like in math, these will be the 'X' variables features = ['CRIM', 'ZN', 'INDUS', 'CHAS', 'NOX', 'RM', 'AGE', 'DIS', 'RAD', 'TAX', ...
github_jupyter
# Long short-term Memory (LSTM) Network LSTM (Long Short-Term Memory) network is a type of Recurrent Neural Networks (RNN), which is a powerful tool for time series prediction problems as well as natural language processing and machine translation and is designed to handle sequence dependencies. The learning goals of...
github_jupyter
# Rook Patch Classification In this experiment, we classify 2 identical rook patches in terms of their location. We place the rook patch on the top-left and bottom-right of the image. We train a 5x5 filter with zero padded same convolution followed by ReLU, global max pooling and softmax classifier by using SGD optimiz...
github_jupyter
``` """ The following code simulates iVQAGF algorithm on QASM simulator. iVQAGF algorithm is a variational quantum algorithm for general form of semidefinite programs (SDPs) that we proposed in our paper. Here, we use iVQAGF to solve random instances of Max-Cut problem casted as an SDP. In the paper, we report simulati...
github_jupyter
# Demo: Audio-Score synchronization with high-resolution features and MrMsDTW In this notebook, we'll show a full music synchronization pipeline using the SyncToolbox, including feature extraction and high-resolution synchronization. We will take a recording of a musical piece and its .csv pitch annotation, created f...
github_jupyter
``` from IPython.core.interactiveshell import InteractiveShell InteractiveShell.ast_node_interactivity = "all" %matplotlib inline ``` # Basic Introduction to TensorFlow ``` import sys from tensorflow.examples.tutorials.mnist import input_data import tensorflow as tf #Tensors 3 # a rank 0 tensor; this is a scalar with...
github_jupyter
# Energy volume curve ## Theory Fitting the energy volume curve allows to calculate the equilibrium energy $E_0$, the equilirbium volume $V_0$, the equilibrium bulk modulus $B_0$ and its derivative $B^{'}_0$. These quantities can then be used as part of the Einstein model to get an initial prediction for the thermodyn...
github_jupyter
## Introduction This tutorial shows how to generate the data needed for the simple map2parameter simulation. It generates the expected noise power spectra of the Simons Observatory (SO) large aperture telescope and the expected Planck white noise power spectra. It also generates beam files for SO and Planck. ## Pream...
github_jupyter
## Introduction This is a notebook demonstrating interactive mapping functionalities with the Folium library. We worked with clustered markers, layers which can be switched on/off, and added a fullscreen button. The datasets are shapefiles coming from the Norwegian Petroleum Directorate, which is public data, and ca...
github_jupyter
# Table Visualization This section demonstrates visualization of tabular data using the [Styler][styler] class. For information on visualization with charting please see [Chart Visualization][viz]. This document is written as a Jupyter Notebook, and can be viewed or downloaded [here][download]. [styler]: ../reference...
github_jupyter
# Login to Docker Registry ``` # Authenticate with Docker Registry !gcloud auth configure-docker --quiet # Create a /tmp directory (needed in next steps) !mkdir -p /tmp ``` # Install Dependencies (Used by Fairing) ``` !pip install sklearn pandas xgboost fairing import argparse import logging import pandas as pd fro...
github_jupyter
``` %load_ext autoreload %autoreload 2 %matplotlib inline %config InlineBackend.figure_format = 'retina' import os import numpy as np, pandas as pd import matplotlib.pyplot as plt, seaborn as sns from tqdm import tqdm, tqdm_notebook from pathlib import Path sns.set() os.chdir('../..') DATA = Path('data') RAW = DATA...
github_jupyter
**Name:** \_\_\_\_\_ **EID:** \_\_\_\_\_ # CS5489 - Tutorial 4 ## Face Detection in Images In this tutorial you will train a classifier to detect whether there is a face in a small image patch. This type of face detector is used in your phone and camera whenever you take a picture! First we need to initialize Pyth...
github_jupyter
``` import pandas as pd import os import seaborn as sns import matplotlib.pyplot as plt from matplotlib.dates import MonthLocator, DateFormatter from sqlalchemy import create_engine, text #maximum number of rows to display pd.options.display.max_rows = 20 DB_USERNAME = '' DB_PASSWORD = '' DB_HOST = ' ' DB_PORT= '' D...
github_jupyter
Teaching notes This year: - 40 minutes on preamble and assignment review - 30 minutes of plot discussion / demo - 5 minutes of wrap up # Hello! Today: 1. Before class: - Fetch your class notes repo and the lecture repo - Open in JLab: your answers for A2, and a ipynb for taking notes 2. Understanding assign...
github_jupyter