text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
You now know the following 1. Generate open-loop control from a given route 2. Simulate vehicular robot motion using bicycle/ unicycle model Imagine you want to make an utility for your co-workers to try and understand vehicle models. Dashboards are common way to do this. There are several options out there : Stre...
github_jupyter
## Expressões Regulares Uma expressão regular é um método formal de se especificar um padrão de texto. Mais detalhadamente, é uma composição de símbolos, caracteres com funções especiais, que agrupados entre si e com caracteres literais, formam uma sequência, uma expressão,Essa expressão é interpretada como uma regra q...
github_jupyter
# Optical Data Reduction using Python by Steve Crawford (South African Astronomical Observatory) ``` %matplotlib inline %load_ext autoreload %autoreload 2 ``` In addition to instrument specific python pipelines, there now exists a suite of tools available for general reduction of optical observations. This includes...
github_jupyter
HMMs Library ============================ #### (Discrete & Continuous hidden markov models ) The document contain the tutorial ( usage explained by example ) for the hidden markov models library [link to pip]. * [The **first** part](#dthmm) will cover disrete-time hidden markov model (**DtHMM**) * [The **second** par...
github_jupyter
# Notebook 13: Using Deep Learning to Study SUSY with Pytorch ## Learning Goals The goal of this notebook is to introduce the powerful PyTorch framework for building neural networks and use it to analyze the SUSY dataset. After this notebook, the reader should understand the mechanics of PyTorch and how to construct D...
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> # Start-to-Finish Example: Setting up Exact Initial Data fo...
github_jupyter
# Node classification with Graph ATtention Network (GAT) <table><tr><td>Run the latest release of this notebook:</td><td><a href="https://mybinder.org/v2/gh/stellargraph/stellargraph/master?urlpath=lab/tree/demos/node-classification/gat-node-classification.ipynb" alt="Open In Binder" target="_parent"><img src="https:/...
github_jupyter
# State preparation with the SLM mask ## Basics When performing quantum computations with global pulses, it might be hard to prepare the system in an arbitrary initial state. This is especially true in the XY mode, where only a global $\sigma^x$ pulse can produce excitations whose number is otherwise conserved during...
github_jupyter
``` # general imports import random import numpy as np from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import accuracy_score from sklearn.metrics import confusion_matrix import torch import torch.nn as nn import torch.utils.data as utils import matplotlib.pyplot as plt plt.rcParams["legend.l...
github_jupyter
``` import numpy as np import pandas as pd %load_ext autoreload %autoreload 2 ``` # Overview What does this thing look like? - Object that you can import - Can call train, load, featurize, import - Inherits from sklearn.transform? Multiple inheritance is hard... # I. Load Data - words: np.ndarray of all characters ...
github_jupyter
# Deep Learning on JuiceFS Tutorial - 01. Getting Started JuiceFS is a shared POSIX file system for the cloud. You may replace existing solutions with JuiceFS with zero cost, turns any object store into a shared POSIX file system. Sign up for 1T free quota now at https://juicefs.com Source code of this tutorial can...
github_jupyter
[source](../../api/alibi_detect.cd.mmd_online.rst) # Online Maximum Mean Discrepancy ## Overview The online [Maximum Mean Discrepancy (MMD)](http://jmlr.csail.mit.edu/papers/v13/gretton12a.html) detector is a kernel-based method for online drift detection. The MMD is a distance-based measure between 2 distributions ...
github_jupyter
# Probability theory ## Random experiment When we toss an unbiased coin, we say that it lands heads up with probability $\frac{1}{2}$ and tails up with probability $\frac{1}{2}$. Such a coin toss is an example of a **random experiment** and the set of **outcomes** of this random experiment is the **sample space** $\...
github_jupyter
# NLP 2 - Pré Processamento de Textos e Modelos Modernos Fala galera! Na aula passada, tivemos uma introdução ao mundo de NLP: o modelo BoW (Bag of Words) e o algoritmo TF-iDF. Embora muito práticos, observamos alguns fenômenos de NLP e dessas técnicas: - NLP é naturalmente um problema de grandes dimensionalidades, o...
github_jupyter
# Developing Custom Models Panel ships with a number of custom Bokeh models, which have both Python and Javascript components. When developing Panel these custom models have to be compiled. This happens automatically with `pip install -e .` or `python setup.py develop`, however when runnning actively developing you ca...
github_jupyter
``` from IPython.display import Markdown as md ### change to reflect your notebook _nb_loc = "07_training/07a_ingest.ipynb" _nb_title = "Writing an efficient ingest Loop" ### no need to change any of this _nb_safeloc = _nb_loc.replace('/', '%2F') md(""" <table class="tfo-notebook-buttons" align="left"> <td> <a ...
github_jupyter
# Day 16-17: Urban/Rural - Land I need to catch up... This won't be the most artistic day, but I would find it useful in my life to have code that downloads GHSL datasets and plots them. ## Configuration ``` import os import rioxarray import matplotlib.pyplot as plt import matplotlib.colors as colors %matplotlib i...
github_jupyter
# Parsing San Jose PD's firearm search reports This example uses `pdfplumber`'s visual debugging and text-extraction features to parse a fixed-width table embedded in a PDF. Thanks to [Ron Campbell](https://twitter.com/campbellronaldw) for the sample PDF. ``` import pdfplumber import re print(pdfplumber.__version__) ...
github_jupyter
## OOP A programming paradigm that provides a means of structuring programs so that properties and behaviors are bundled into individual objects. Pros: * code modularisation thus ease in troubleshooting. * reuse of code through inheritance. * flexibility through polymorphism (multiple usage). ### 1. Class Definition ...
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 writin...
github_jupyter
# openvino2tensorflow This tutorial explains the use case of openvino2tensorflow while using arachne. `openvino2tensorflow` is developed in the following GitHub repository. https://github.com/PINTO0309/openvino2tensorflow When you convert onnx model to tensorflow model by `onnx-tf`, the converted model includes ...
github_jupyter
# 处理数据 数据是构建机器学习模型的基础。在云中集中管理数据,并使在多个工作站上运行试验和训练模型的数据科学家团队能够访问这些数据以及计算目标,这是任何专业数据科学解决方案的重要组成部分。 在该笔记本中,你将探索两个用于数据处理的 Azure 机器学习对象:数据存储和数据集。 ## 连接到工作区 首先,请连接到你的工作区。 > **备注**:如果尚未与 Azure 订阅建立经过身份验证的会话,则系统将提示你通过执行以下操作进行身份验证:单击链接,输入验证码,然后登录到 Azure。 ``` import azureml.core from azureml.core import Workspace #...
github_jupyter
``` !pip install git+https://github.com/zhy0/dmarket_rl !pip install ray[rllib] import pandas as pd import numpy as np import matplotlib.pyplot as plt from dmarket.environments import MultiAgentTrainingEnv from dmarket.info_settings import OfferInformationSetting, BlackBoxSetting from dmarket.agents import GymRLAgent ...
github_jupyter
# Ingest Text Data Labeled text data can be in a structured data format, such as reviews for sentiment analysis, news headlines for topic modeling, or documents for text classification. In these cases, you may have one column for the label, one column for the text, and sometimes other columns for attributes. You can tr...
github_jupyter
# New Style HDMI input and Pixel Formatting This notebook introduces the new features of PYNQ 2.0 for interacting with the video pipeline. The API has been completely redesigned with high performance image processing applications in mind. To start, download the base overlay and instantiate the HDMI input and output. ...
github_jupyter
## Deep Learning Regularization 😓Be well prepared that when the code worked for me, may not work for you any more. It took me so much time tonight to debug, upgrade/install packages, change deprecated functions or just ignore warnings.... All because of the frequent changes in these open source packages. So, when it'...
github_jupyter
### Maricopa Agricultural Center Season 6 ### Citation for Input Trait Data LeBauer, David et al. (2020), Data From: TERRA-REF, An open reference data set from high resolution genomics, phenomics, and imaging sensors, v6, Dryad, Dataset, https://doi.org/10.5061/dryad.4b8gtht99 ##### Environmental weather data can be...
github_jupyter
# Exploring Observation Data From TILDE, Application to DART Data ## &nbsp;Table of contents ### 1. Introduction ### 2. Building a Query for a specific sensor code/stream ### 3. Building a Query without sensor code/stream ### 4. Building a Query for the latest data ### 5. Building a Query for aggregated data ### 6. Ge...
github_jupyter
## _*Quantum SVM (variational method)*_ The QSVMKernel notebook here demonstrates a kernel based approach. This notebook shows a variational method. For further information please see: [https://arxiv.org/pdf/1804.11326.pdf](https://arxiv.org/pdf/1804.11326.pdf) **This notebook shows the SVM implementation based on ...
github_jupyter
``` import xai import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sn from sklearn import preprocessing from sklearn.impute import SimpleImputer from sklearn.model_selection import train_test_split from sklearn.metrics import f1_score, confusion_matrix, precision_score, recall_sco...
github_jupyter
<a href="https://colab.research.google.com/github/Eoli-an/Exam-topic-prediction/blob/main/Slides_vs_Transcribes_Frequency.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # Plot for Dense Ranks of Word Usage in Slides and Transcribes of Relevant Word...
github_jupyter
## Guest Lecture COMP7230 # Using Python packages for Linked Data & spatial data #### by Dr Nicholas Car This Notebook is the resource used to deliver a guest lecture for the [Australian National University](https://www.anu.edu.au)'s course [COMP7230](https://programsandcourses.anu.edu.au/2020/course/COMP7230): *Intro...
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
<a href="https://colab.research.google.com/github/R-aryan/Image_Classification_VGG16/blob/master/Classification_Cat_VS_Dogs_Transfer_Learning.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ``` import keras,os from keras.models import Sequential fro...
github_jupyter
# Neste notebook vamos simular a interconexão entre SLITs ``` # importar as bibliotecas necessárias import numpy as np # arrays import matplotlib.pyplot as plt # plots plt.rcParams.update({'font.size': 14}) import IPython.display as ipd # to play signals import sounddevice as sd import soundfile as sf # Os próximos mó...
github_jupyter
``` import pandas as pd import numpy as np import pyflux as pf import matplotlib.pyplot as plt from fbprophet import Prophet %matplotlib inline plt.rcParams['figure.figsize']=(20,10) plt.style.use('ggplot') ``` ### Load the data For this work, we're going to use the same retail sales data that we've used before....
github_jupyter
``` import urllib.request import json import pandas as pd from datetime import datetime import seaborn as sns cm = sns.light_palette("red", as_cmap=True) #https://www.trilhaseaventuras.com.br/siglas-dos-principais-aeroportos-do-mundo-iata/ #urlOneWay #https://www.decolar.com/shop/flights-busquets/api/v1/web/search?adu...
github_jupyter
Copyright 2020 The Google Research Authors. 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 http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, so...
github_jupyter
``` # from numba import jit # from tqdm import trange # import pandas as pd # eo_df = pd.read_csv("/mnt/sda1/cvpr21/Classification/Aerial-View-Object-Classification/data/train_EO.csv") # eo_df = eo_df.sort_values(by='img_name') # sar_df = pd.read_csv("/mnt/sda1/cvpr21/Classification/Aerial-View-Object-Classification/d...
github_jupyter
<h1>Table of Contents<span class="tocSkip"></span></h1> <div class="toc"><ul class="toc-item"><li><span><a href="#Particionando-bases-de-treino-e-teste-com-split-70-30%" data-toc-modified-id="Particionando-bases-de-treino-e-teste-com-split-70-30%-1"><span class="toc-item-num">1&nbsp;&nbsp;</span>Particionando bases de ...
github_jupyter
# Dimensionality Reduction Reducing number of dimensions whcih means that the number of new features is lower than the number of original features. First, we need to import numpy, matplotlib, and scikit-learn and get the UCI ML digit image data. Scikit-learn already comes with this data (or will automatically downl...
github_jupyter
<div style="width:100%; background-color: #D9EDF7; border: 1px solid #CFCFCF; text-align: left; padding: 10px;"> <b>Time series: Processing Notebook</b> <ul> <li><a href="main.ipynb">Main Notebook</a></li> <li>Processing Notebook</li> </ul> <br>This Notebook is part of the <a hre...
github_jupyter
``` import gym import torch from torch import nn import torch.nn.functional as F from torch.autograd import Variable from torch.distributions import Bernoulli import matplotlib.pyplot as plt class PolicyNet(nn.Module): def __init__(self, input_dim, output_dim): super(PolicyNet, self).__init__() s...
github_jupyter
## Forecasting, updating datasets, and the "news" In this notebook, we describe how to use Statsmodels to compute the impacts of updated or revised datasets on out-of-sample forecasts or in-sample estimates of missing data. We follow the approach of the "Nowcasting" literature (see references at the end), by using a s...
github_jupyter
``` import torch import torch.nn as nn import torch.nn.functional as F from torchvision import datasets, transforms from torch.autograd import Variable from collections import OrderedDict import numpy as np import matplotlib.pyplot as plt plt.rcParams['image.cmap'] = 'gray' %matplotlib inline # input batch size for tra...
github_jupyter
## Next Task: compute precision and recall threshold 25: zoomy, sustain->thick, smooth (user results) zoomy, sustain -> dark, smooth (word2word matcher resuts) smooth tp dark fp thik tn (fn?) precision = tp/(tp+fp) recall = tp/(tp+fn) for one word, cant compute recall later: tensorfl...
github_jupyter
# The ISB-CGC open-access TCGA tables in Big-Query The goal of this notebook is to introduce you to a new publicly-available, open-access dataset in BigQuery. This set of BigQuery tables was produced by the [ISB-CGC](http://www.isb-cgc.org) project, based on the open-access [TCGA](http://cancergenome.nih.gov/) data a...
github_jupyter
``` import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns import statsmodels.api as sm import patsy # Data: https://archive.ics.uci.edu/ml/datasets/Bike+Sharing+Dataset # UCI citation: # Dua, D. and Graff, C. (2019). UCI Machine Learning Repository [http://archive.ics.uci.edu/ml]...
github_jupyter
<h1 align="center">SimpleITK Spatial Transformations</h1> **Summary:** 1. Points are represented by vector-like data types: Tuple, Numpy array, List. 2. Matrices are represented by vector-like data types in row major order. 3. Default transformation initialization as the identity transform. 4. Angles specified in ra...
github_jupyter
# K-means clustering When working with large datasets it can be helpful to group similar observations together. This process, known as clustering, is one of the most widely used in Machine Learning and is often used when our dataset comes without pre-existing labels. In this notebook we're going to implement the cla...
github_jupyter
<img src="NotebookAddons/blackboard-banner.png" width="100%" /> <font face="Calibri"> <br> <font size="7"> <b> GEOS 657: Microwave Remote Sensing<b> </font> <font size="5"> <b>Lab 9: InSAR Time Series Analysis using GIAnT within Jupyter Notebooks</b> </font> <br> <font size="4"> <b> Franz J Meyer & Joshua J C Knicely...
github_jupyter
# RDF graph processing against the integrated POIs #### Auxiliary function to format SPARQL query results as a data frame: ``` import pandas as pds def sparql_results_frame(qres): cols = qres.vars out = [] for row in qres: item = [] for c in cols: item.append(row[c]) ...
github_jupyter
# Keras Intro: Shallow Models Keras Documentation: https://keras.io In this notebook we explore how to use Keras to implement 2 traditional Machine Learning models: - **Linear Regression** to predict continuous data - **Logistic Regression** to predict categorical data ## Linear Regression ``` %matplotlib inline i...
github_jupyter
``` import pandas as pd import numpy as np import pickle import matplotlib.pyplot as plt from scipy import stats import tensorflow as tf import seaborn as sns from pylab import rcParams from sklearn import metrics from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler %ma...
github_jupyter
# VAST 2017 MC-1 ## Задание Природный заповедник Бунсонг Лекагуль используется местными жителями и туристами для однодневных поездок, ночевок в кемпингах, а иногда и просто для доступа к основным магистралям на противоположных сторонах заповедника. Входные кабинки заповедника контролируются с целью получения дохода, ...
github_jupyter
# Elevation indices Here we assume that flow directions are known. We read the flow direction raster data, including meta-data, using [rasterio](https://rasterio.readthedocs.io/en/latest/) and parse it to a pyflwdir `FlwDirRaster` object, see earlier examples for more background. ``` # import pyflwdir, some dependenc...
github_jupyter
Note: range sliders and range selectors are available in version 1.9.7+ Run pip install plotly --upgrade to update your Plotly version ``` import plotly plotly.__version__ ``` ## Basic Range Slider and Range Selectors ``` from cswd import query_adjusted_pricing OHLCV = ['open','high','low','close','volume'] df = q...
github_jupyter
# Kernel density estimation ``` # Import all libraries needed for the exploration # General syntax to import specific functions in a library: ##from (library) import (specific library function) from pandas import DataFrame, read_csv # General syntax to import a library but no functions: ##import (library) as (give...
github_jupyter
``` import gevent import random import pandas as pd import numpy as np import math import time import functools as ft import glob, os, sys import operator as op import shelve import ipywidgets as widgets from ipywidgets import interact, interact_manual #from pandas.api.types import is_numeric_dtypen() from pathlib ...
github_jupyter
``` import numpy as np import scipy as sp import pandas as pd import urllib.request import os import shutil import tarfile import matplotlib.pyplot as plt from sklearn import datasets, cross_validation, metrics from sklearn.preprocessing import KernelCenterer %matplotlib notebook ``` First we need to download the Cal...
github_jupyter
``` import os import matplotlib.pyplot as plt import numpy as np import pandas as pd from random import randint from numpy import array from numpy import argmax from numpy import array_equal import tensorflow as tf from tensorflow.keras.utils import to_categorical from keras.models import Model from keras.layers import...
github_jupyter
# R Bootcamp Part 5 ## stargazer, xtable, robust standard errors, and fixed effects regressions This bootcamp will help us get more comfortableusing **stargazer** and **xtable** to produce high-quality results and summary statistics tables, and using `felm()` from the **lfe** package for regressions (both fixed effe...
github_jupyter
[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/eirasf/GCED-AA2/blob/main/lab4/lab4_parte1.ipynb) # Práctica 4: Redes neuronales usando Keras con Regularización ## Parte 1. Early Stopping ### Overfitting El problema del sobreajuste (*overfitting*) co...
github_jupyter
# DSCI 525: Web and Cloud Computing ## Milestone 1: Tackling Big Data on Computer ### Group 13 Authors: Ivy Zhang, Mike Lynch, Selma Duric, William Xu ## Table of contents - [Download the data](#1) - [Combining data CSVs](#2) - [Load the combined CSV to memory and perform a simple EDA](#3) - [Perform a simple EDA i...
github_jupyter
## The 1cycle policy ``` from fastai.gen_doc.nbdoc import * from fastai.vision import * from fastai.callbacks import * ``` ## What is 1cycle? This Callback allows us to easily train a network using Leslie Smith's 1cycle policy. To learn more about the 1cycle technique for training neural networks check out [Leslie S...
github_jupyter
``` from keras.layers import Input, Dense, Activation from keras.layers import Maximum, Concatenate from keras.models import Model from keras.optimizers import adam_v2 from sklearn.tree import DecisionTreeClassifier from sklearn.linear_model import SGDClassifier from sklearn.ensemble import GradientBoostingClassifier f...
github_jupyter
``` import requests from IPython.display import Markdown from tqdm import tqdm, tqdm_notebook import pandas as pd from matplotlib import pyplot as plt import numpy as np import altair as alt from requests.utils import quote import os from datetime import timedelta from mod import alt_theme fmt = "{:%Y-%m-%d}" # Can op...
github_jupyter
# StyleGAN2 *Please note that this is an optional notebook that is meant to introduce more advanced concepts, if you're up for a challenge. So, don't worry if you don't completely follow every step! We provide external resources for extra base knowledge required to grasp some components of the advanced material.* In t...
github_jupyter
``` from azure.common import AzureMissingResourceHttpError from azure.storage.blob import BlockBlobService, PublicAccess from azure.storage.file import FileService from azure.storage.table import TableService, Entity #Blob Service... def get_block_blob_service(account_name, storage_key): return BlockBlobService(acc...
github_jupyter
# Project 1: Navigation ### Test 3 - DDQN model with Prioritized Experience Replay <sub>Uirá Caiado. August 23, 2018<sub> #### Abstract _In this notebook, I will use the Unity ML-Agents environment to train a DDQN model with PER for the first project of the [Deep Reinforcement Learning Nanodegree](https://www.udaci...
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
# Inverted Pendulum: Reinforcement learning Meichen Lu (meichenlu91@gmail.com) 26th April 2018 Source: CS229: PS4Q6 Starting code: http://cs229.stanford.edu/ps/ps4/q6/ Reference: https://github.com/zyxue/stanford-cs229/blob/master/Problem-set-4/6-reinforcement-learning-the-inverted-pendulum/control.py ``` from cart_...
github_jupyter
# Variable Relationship Tests (correlation) - Pearson’s Correlation Coefficient - Spearman’s Rank Correlation - Kendall’s Rank Correlation - Chi-Squared Test ## Correlation Test Correlation Measures whether greater values of one variable correspond to greater values in the other. Scaled to always lie between +1 and −1...
github_jupyter
# Views - Views are nothing but widget only but having capability to hold widgets. ``` from webdriver_kaifuku import BrowserManager from widgetastic.widget import Browser command_executor = "http://localhost:4444/wd/hub" config = { "webdriver": "Remote", "webdriver_options": {"desired_capabilities":...
github_jupyter
``` import tensorflow as tf import numpy as np import pandas as pd from sklearn.model_selection import train_test_split from sklearn.preprocessing import LabelEncoder from sklearn.feature_extraction.text import CountVectorizer from nltk.stem import PorterStemmer from autocorrect import spell import os from six.moves...
github_jupyter
# Testinnsening av upersonlig skattemelding med næringspesifikasjon Denne demoen er ment for å vise hvordan flyten for et sluttbrukersystem kan hente et utkast, gjøre endringer, validere/kontrollere det mot Skatteetatens apier, for å sende det inn via Altinn3. ``` try: from altinn3 import * from skatteetaten_...
github_jupyter
# Keras tutorial - the Happy House Welcome to the first assignment of week 2. In this assignment, you will: 1. Learn to use Keras, a high-level neural networks API (programming framework), written in Python and capable of running on top of several lower-level frameworks including TensorFlow and CNTK. 2. See how you c...
github_jupyter
# How do ratings behave after users have seen many captions? This notebook looks at the "vote decay" of users. The New Yorker caption contest organizer, Bob Mankoff, has received many emails like the one below (name/personal details left out for anonymity) > Here's my issue. > > First time I encounter something, I m...
github_jupyter
# 使用预训练的词向量完成文本分类任务 **作者**: [fiyen](https://github.com/fiyen)<br> **日期**: 2021.10<br> **摘要**: 本示例教程将会演示如何使用飞桨内置的Imdb数据集,并使用预训练词向量进行文本分类。 ## 一、环境设置 本教程基于Paddle 2.2.0-rc0 编写,如果你的环境不是本版本,请先参考官网[安装](https://www.paddlepaddle.org.cn/install/quick) Paddle 2.2.0-rc0。 ``` import paddle from paddle.io import Dataset import ...
github_jupyter
``` #本章需导入的模块 import numpy as np import pandas as pd import matplotlib.pyplot as plt from pylab import * import matplotlib.cm as cm import warnings warnings.filterwarnings(action = 'ignore') %matplotlib inline plt.rcParams['font.sans-serif']=['SimHei'] #解决中文显示乱码问题 plt.rcParams['axes.unicode_minus']=False from sklearn ...
github_jupyter
################################################################################ #Licensed Materials - Property of IBM #(C) Copyright IBM Corp. 2019 #US Government Users Restricted Rights - Use, duplication disclosure restricted #by GSA ADP Schedule Contract with IBM Corp. ##############################################...
github_jupyter
``` # Necessary imports import re import emoji from gtrans import translate_text, translate_html import random import pandas as pd import numpy as np from multiprocessing import Pool import time # Function to remove emojis in text, since these conflict during translation def remove_emoji(text): return emoji.get_em...
github_jupyter
# REWARD-MODULATED SELF ORGANISING RECURRENT NEURAL NETWORK https://www.frontiersin.org/articles/10.3389/fncom.2015.00036/full ### IMPORT REQUIRED LIBRARIES ``` from __future__ import division import numpy as np from scipy.stats import norm import random import tqdm import pandas as pd from collections import Ordere...
github_jupyter
``` !pip install transformers from transformers import BartTokenizer, BartForConditionalGeneration, BartConfig tokenizer = BartTokenizer.from_pretrained('facebook/bart-large-cnn') model = BartForConditionalGeneration.from_pretrained('facebook/bart-large-cnn') sequence = ("In May, Churchill was still generally unpopular...
github_jupyter
# About This Notebook * The following notebooks utilizes the [generated outputs](https://www.kaggle.com/usaiprashanth/gptmodel-outputs) and performs some Exploratory Data Analysis ``` #loading the outputs import joblib withoutshuffle = joblib.load('../input/gptmodel-outputs/results (4)/withoutshuffle.pkl') withshuffle...
github_jupyter
``` from datascience import * from datascience.predicates import are path_data = '../../../data/' import numpy as np import matplotlib matplotlib.use('Agg', warn=False) %matplotlib inline import matplotlib.pyplot as plots plots.style.use('fivethirtyeight') import warnings warnings.simplefilter(action="ignore", category...
github_jupyter
# House Price Prediction <p><b>Status: <span style=color:orange;>In process</span></b></p> ##### LOAD THE FEATURE DATA ``` import pandas as pd import numpy as np X = pd.read_csv('../../../data/preprocessed_data/X.csv', sep=',') print ('Feature data, shape:\nX: {}'.format(X.shape)) X.head() y = pd.read_csv('../../....
github_jupyter
# Word2Vec **Learning Objectives** 1. Compile all steps into one function 2. Prepare training data for Word2Vec 3. Model and Training 4. Embedding lookup and analysis ## Introduction Word2Vec is not a singular algorithm, rather, it is a family of model architectures and optimizations that can be used to learn wo...
github_jupyter
``` from scipy.sparse import diags import random import numpy as np import scipy as sc import pandas as pd import csv import scipy.linalg as spl import matplotlib.pyplot as plt from matplotlib import rc rc('text', usetex=True) import time import sys sys.path.insert(0, '../../python/') from opt_utils import * from grad_...
github_jupyter
``` import glob import os import librosa import numpy as np import matplotlib.pyplot as plt %matplotlib inline def gen_mfcc_fn(fn, mfcc_window_size, mfcc_stride_size): X, sample_rate = librosa.load(fn, sr=None, mono=True) if sample_rate != 44100: return mfcc = libr...
github_jupyter
# Handling Missing Data The difference between data found in many tutorials and data in the real world is that real-world data is rarely clean and homogeneous. In particular, many interesting datasets will have some amount of data missing. To make matters even more complicated, different data sources may indicate miss...
github_jupyter
## Dependencies ``` import os, random, warnings import numpy as np import pandas as pd import seaborn as sns from matplotlib import pyplot as plt from sklearn.model_selection import train_test_split from transformers import TFDistilBertModel from tokenizers import BertWordPieceTokenizer import tensorflow as tf from te...
github_jupyter
<div class="alert alert-block alert-info"> Section of the book chapter: <b>5.3 Model Selection, Optimization and Evaluation</b> </div> # 5. Model Selection and Evaluation **Table of Contents** * [5.1 Hyperparameter Optimization](#5.1-Hyperparameter-Optimization) * [5.2 Model Evaluation](#5.2-Model-Evaluation) **Lea...
github_jupyter
``` import numpy as np import matplotlib.pyplot as plt from sympy import Symbol, integrate %matplotlib notebook ``` ### Smooth local paths We will use cubic spirals to generate smooth local paths. Without loss of generality, as $\theta$ smoothly changes from 0 to 1, we impose a condition on the curvature as follows $...
github_jupyter
## Add cancer analysis Analysis of results from `run_add_cancer_classification.py`. We hypothesized that adding cancers in a principled way (e.g. by similarity to the target cancer) would lead to improved performance relative to both a single-cancer model (using only the target cancer type), and a pan-cancer model us...
github_jupyter
# Reshaping & Tidy Data > Structuring datasets to facilitate analysis [(Wickham 2014)](http://www.jstatsoft.org/v59/i10/paper) So, you've sat down to analyze a new dataset. What do you do first? In episode 11 of [Not So Standard Deviations](https://www.patreon.com/NSSDeviations?ty=h), Hilary and Roger discussed thei...
github_jupyter
# The Tractable Buffer Stock Model <p style="text-align: center;"><small><small><small>Generator: BufferStockTheory-make/notebooks_byname</small></small></small></p> The [TractableBufferStock](http://www.econ2.jhu.edu/people/ccarroll/public/LectureNotes/Consumption/TractableBufferStock/) model is a (relatively) simpl...
github_jupyter
``` import h5py import keras import numpy as np import os import random import sys import tensorflow as tf sys.path.append("../src") import localmodule # Define constants. dataset_name = localmodule.get_dataset_name() models_dir = localmodule.get_models_dir() units = localmodule.get_units() n_input_hops = 104 n_filt...
github_jupyter
For all numerical experiments, we will be using the Chambolle-Pock primal-dual algorithm - details can be found on: 1. [A First-order Primal-dual Algorithm for Convex Problems with Applications to Imaging](https://link.springer.com/article/10.1007/s10851-010-0251-1), A. Chambolle, T. Pock, Journal of Mathematical Imagi...
github_jupyter
# Figure. X Inactivation ``` import cPickle import datetime import glob import os import random import re import subprocess import cdpybio as cpb import matplotlib as mpl import matplotlib.gridspec as gridspec import matplotlib.pyplot as plt import numpy as np import pandas as pd import pybedtools as pbt import scipy...
github_jupyter