code stringlengths 2.5k 150k | kind stringclasses 1
value |
|---|---|
# pandas字符串操作
很明显除了数值型,我们处理的数据还有很多字符类型的,而这部分数据显然也非常重要,因此这个部分我们提一提pandas的字符串处理。
```
%matplotlib inline
%config ZMQInteractiveShell.ast_node_interactivity='all'
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
pd.set_option('display.mpl_style', 'default')
plt.rcParams['figure.figsize'] = (15, 3)
... | github_jupyter |
# Machine Learning - AA2AR
**By Jakke Neiro & Andrei Roibu**
## 1. Importing All Required Dependencies
This script imports all the required dependencies for running the different functions and the codes. Also, by using the _run_ command, the various notebooks are imprted into the main notebook.
```
import numpy as ... | github_jupyter |
# Lecture 8: p-hacking and Multiple Comparisons
[J. Nathan Matias](https://github.com/natematias)
[SOC412](https://natematias.com/courses/soc412/), February 2019
In Lecture 8, we discussed Stephanie Lee's story about [Brian Wansink](https://www.buzzfeednews.com/article/stephaniemlee/brian-wansink-cornell-p-hacking#.bt... | github_jupyter |
```
import pandas as pd
```
# Classification
We'll take a tour of the methods for classification in sklearn. First let's load a toy dataset to use:
```
from sklearn.datasets import load_breast_cancer
breast = load_breast_cancer()
```
Let's take a look
```
# Convert it to a dataframe for better visuals
df = pd.Data... | github_jupyter |
# Multiple Linear Regression with sklearn - Exercise Solution
You are given a real estate dataset.
Real estate is one of those examples that every regression course goes through as it is extremely easy to understand and there is a (almost always) certain causal relationship to be found.
The data is located in the f... | github_jupyter |
# ENGR 1330 Computational Thinking with Data Science
Last GitHub Commit Date: 14 February 2021
## Lesson 8 The Pandas module
- About Pandas
- How to install
- Anaconda
- JupyterHub/Lab (on Linux)
- JupyterHub/Lab (on MacOS)
- JupyterHub/Lab (on Windoze)
- The Dataframe
- Primatives
- Using Pa... | github_jupyter |
```
#import dependencies
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.ticker import StrMethodFormatter
import numpy as np
from config import username,password
from sqlalchemy import create_engine
#create engine
engine = create_engine(f'postgresql://{username}:{password}@localhost:5432/employees')... | github_jupyter |
# Measles Incidence in Altair
This is an example of reproducing the Wall Street Journal's famous [Measles Incidence Plot](http://graphics.wsj.com/infectious-diseases-and-vaccines/#b02g20t20w15) in Python using [Altair](http://github.com/ellisonbg/altair/).
## The Data
We'll start by downloading the data. Fortunately... | github_jupyter |
# Sparkify Project Workspace
This workspace contains a tiny subset (128MB) of the full dataset available (12GB). Feel free to use this workspace to build your project, or to explore a smaller subset with Spark before deploying your cluster on the cloud. Instructions for setting up your Spark cluster is included in the ... | github_jupyter |
```
# Install package
%pip install --upgrade portfoliotools
from portfoliotools.screener.stock_screener import StockScreener
from portfoliotools.screener.utility.util import get_ticker_list, getHistoricStockPrices, get_nse_index_list, get_port_ret_vol_sr
from portfoliotools.screener.stock_screener import PortfolioStrat... | github_jupyter |
```
%matplotlib inline
%load_ext autoreload
%autoreload 2
from __future__ import print_function
import math
import matplotlib.pyplot as plt
import numpy as np
import os
import sys
import time
from pydrake.solvers.mathematicalprogram import MathematicalProgram, Solve
from pydrake.solvers.ipopt import IpoptSolver
mp = ... | github_jupyter |
# Bayes's Theorem
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/)
In the previous chapter, we derived Bayes's Theorem:
$$P(A|B) = \frac{P(A) P(B|A)}{P(B)}$$
As an exam... | github_jupyter |
# Using the Prediction Model
## Environment
```
import getpass
import json
import os
import sys
import time
import pandas as pd
from tqdm import tqdm_notebook as tqdm
from seffnet.constants import (
DEFAULT_EMBEDDINGS_PATH, DEFAULT_GRAPH_PATH,
DEFAULT_MAPPING_PATH, DEFAULT_PREDICTIVE_MODEL_PATH,
RESOURC... | github_jupyter |
<a href="https://colab.research.google.com/github/dnhirapara/049_DarshikHirapara/blob/main/lab2/Lab_02_Data_Preprocessing.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')
import pandas ... | github_jupyter |
```
# ATTENTION: Please do not alter any of the provided code in the exercise. Only add your own code where indicated
# ATTENTION: Please do not add or remove any cells in the exercise. The grader will check specific cells based on the cell position.
# ATTENTION: Please use the provided epoch values when training.
imp... | github_jupyter |
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License.

# Automated Machin... | github_jupyter |
# ex05-Filtering a Query with WHERE
Sometimes, you’ll want to only check the rows returned by a query, where one or more columns meet certain criteria. This can be done with a WHERE statement. The WHERE clause is an optional clause of the SELECT statement. It appears after the FROM clause as the following statement:
>... | github_jupyter |
```
!pip3 install qiskit
import qiskit
constant_index_dictionary = {}
constant_index_dictionary['0000'] = [0, 2]
constant_index_dictionary['0001'] = [2, 3]
constant_index_dictionary['0010'] = [0, 1]
constant_index_dictionary['0011'] = [1, 3]
constant_index_dictionary['0100'] = [2, 3]
constant_index_dictionary['0101'] =... | github_jupyter |
<h1>Table of Contents<span class="tocSkip"></span></h1>
<div class="toc"><ul class="toc-item"><li><span><a href="#Goal" data-toc-modified-id="Goal-1"><span class="toc-item-num">1 </span>Goal</a></span></li><li><span><a href="#Var" data-toc-modified-id="Var-2"><span class="toc-item-num">2 </span>Va... | github_jupyter |
```
# Importamos las librerías necesarias
from bs4 import BeautifulSoup
import requests
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import statistics as st
# Fijamos url de la web
url = 'https://tarifaluzhora.es/'
# Hacemos la petición a la página
response = requests.get(url)
soup = Beautifu... | github_jupyter |
# Test web application locally
This notebook pulls some images and tests them against the local web app running inside the Docker container we made previously.
```
import matplotlib.pyplot as plt
import numpy as np
from testing_utilities import *
import requests
%matplotlib inline
%load_ext autoreload
%autoreload 2
... | github_jupyter |
```
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
```
### Homework part I: Prohibited Comment Classification (3 points)

__In this notebook__ you will build an algorithm that classifies social media comme... | github_jupyter |
# Data analysis with Python, Apache Spark, and PixieDust
***
In this notebook you will:
* analyze customer demographics, such as, age, gender, income, and location
* combine that data with sales data to examine trends for product categories, transaction types, and product popularity
* load data from GitHub as well a... | github_jupyter |
# REINFORCE in lasagne
Just like we did before for q-learning, this time we'll design a lasagne network to learn `CartPole-v0` via policy gradient (REINFORCE).
Most of the code in this notebook is taken from approximate qlearning, so you'll find it more or less familiar and even simpler.
__Frameworks__ - we'll accep... | github_jupyter |
```
%matplotlib inline
from matplotlib import style
style.use('fivethirtyeight')
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import datetime as dt
```
## Reflect Tables into SQLALchemy ORM
```
# Python SQL toolkit and Object Relational Mapper
import sqlalchemy
from sqlalchemy.ext.automap im... | github_jupyter |
# 📝 Exercise M3.02
The goal is to find the best set of hyperparameters which maximize the
generalization performance on a training set.
Here again with limit the size of the training set to make computation
run faster. Feel free to increase the `train_size` value if your computer
is powerful enough.
```
import num... | github_jupyter |
```
# Description: Plot Figure 3 (Overview of wind, wave and density stratification during the field experiment).
# Author: André Palóczy
# E-mail: paloczy@gmail.com
# Date: December/2020
import numpy as np
from matplotlib import pyplot as plt
import matplotlib.dates as mdates
from pandas import Timest... | github_jupyter |
## Stage 3: What do I need to install?
Maybe your experience looks like the typical python dependency management (https://xkcd.com/1987/):
<img src=https://imgs.xkcd.com/comics/python_environment.png>
Furthermore, data science packages can have all sorts of additional non-Python dependencies which makes things even m... | github_jupyter |
```
import data
import torch
from utils.distmat import *
from utils.evaluation import *
from hitl import *
import numpy as np
import matplotlib.pyplot as plt
```
## Load Data
```
key = data.get_output_keys()[2]
key
output = data.load_output(key)
qf = torch.Tensor(output["qf"])
gf = torch.Tensor(output["gf"])
q_pids =... | github_jupyter |
WKN strings can be converted to the following formats via the `output_format` parameter:
* `compact`: only number strings without any seperators or whitespace, like "A0MNRK"
* `standard`: WKN strings with proper whitespace in the proper places. Note that in the case of WKN, the compact format is the same as the standa... | github_jupyter |
```
from google.colab import drive
drive.mount('/content/gdrive')
!git clone https://github.com/NVIDIA/pix2pixHD.git
import os
os.chdir('pix2pixHD/')
# !chmod 755 /content/gdrive/My\ Drive/Images_for_GAN/datasets/download_convert_apples_dataset.sh
# !/content/gdrive/My\ Drive/Images_for_GAN/datasets/download_convert_ap... | github_jupyter |
```
from bayes_opt import BayesianOptimization
from bayes_opt.util import load_logs
from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.gaussian_process.kernels import Matern, RBF
import json
import numpy as np
from itertools import product
import matplotlib.pyplot as plt
from mpl_toolkits.mplot... | github_jupyter |
<table class="ee-notebook-buttons" align="left">
<td><a target="_blank" href="https://github.com/giswqs/earthengine-py-notebooks/tree/master/Image/texture.ipynb"><img width=32px src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" /> View source on GitHub</a></td>
<td><a target="_blank" href="https://... | github_jupyter |
## TFMA Notebook example
This notebook describes how to export your model for TFMA and demonstrates the analysis tooling it offers.
Note: Please make sure to follow the instructions in [README.md](https://github.com/tensorflow/tfx/blob/master/tfx/examples/chicago_taxi/README.md) when running this notebook
## Setup
I... | github_jupyter |
# Conservative remapping
```
import xgcm
import xarray as xr
import numpy as np
import xbasin
```
We open the example data and create 2 grids: 1 for the dataset we have and 1 for the remapped one.
Here '_fr' means *from* and '_to' *to* (i.e. remapped data).
```
ds = xr.open_dataset('data/nemo_output_ex.nc')
from xn... | github_jupyter |
# DeepDreaming with TensorFlow
>[Loading and displaying the model graph](#loading)
>[Naive feature visualization](#naive)
>[Multiscale image generation](#multiscale)
>[Laplacian Pyramid Gradient Normalization](#laplacian)
>[Playing with feature visualzations](#playing)
>[DeepDream](#deepdream)
This notebook demo... | github_jupyter |
```
import numpy as np
import pandas as pd
import pickle
import matplotlib.pyplot as plt
import torch
from torch import nn, optim
from torchvision import transforms, utils
from torch.utils.data import TensorDataset, DataLoader
import time
from sklearn.model_selection import train_test_split
%matplotlib inline
with op... | github_jupyter |
<a href="https://colab.research.google.com/github/AutoViML/Auto_ViML/blob/master/Auto_ViML_Demo.ipynb" target="_parent">
<img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/>
</a>
```
import pandas as pd
datapath = 'https://web.stanford.edu/class/archive/cs/cs109/cs109.1166/stuf... | github_jupyter |
**[Introduction to Machine Learning Home Page](https://www.kaggle.com/learn/intro-to-machine-learning)**
---
## Recap
Here's the code you've written so far.
```
# code you have previously used
# load data
import pandas as pd
iowa_file_path = '../input/home-data-for-ml-course/train.csv'
home_data = pd.read_csv(iowa_... | github_jupyter |
We will use this notebook to calculate and visualize statistics of our chess move dataset. This will allow us to better understand our limitations and help diagnose problems we may encounter down the road when training/defining our model.
```
import pdb
import numpy as np
import matplotlib.pyplot as plt
%matplotlib in... | github_jupyter |
<a href="https://colab.research.google.com/github/misabhishek/gcp-iam-recommender/blob/main/iam_recommender_basics.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# Before you begin
1. Have a GCP projrect ready.
3. [Enable Iam Recommender](http... | github_jupyter |
```
from presidio_analyzer import AnalyzerEngine, PatternRecognizer
from presidio_anonymizer import AnonymizerEngine
from presidio_anonymizer.entities import AnonymizerConfig
```
# Analyze Text for PII Entities
<br>Using Presidio Analyzer, analyze a text to identify PII entities.
<br>The Presidio analyzer is using p... | github_jupyter |
# ML/DL techniques for Tabular Modeling PART I
> In this part, I have explained Decision Trees.
- toc: true
- badges: true
- comments: true
```
#hide
# !pip install -Uqq fastbook
import fastbook
fastbook.setup_book()
#hide
from fastbook import *
from kaggle import api
from pandas.api.types import is_string_dtype, is... | github_jupyter |
# Visualization principles
1. Log scale
2. Jitter
3. Set the scale
4. Text on plot
```
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import matplotlib as mpl
```
## Plotting binary variables
Not directly connected to today's lesson. But many of you asked.
Let look at a... | github_jupyter |
This notebook will set up colab so that you can run the SYCL blur lab for the module "Introduction to SYCYL programming" created by the TOUCH project. (https://github.com/TeachingUndergradsCHC/modules/tree/master/Programming/sycl). The initial setup instructions are created following slides by Aksel Alpay
https://www... | github_jupyter |
# Classification of Chest and Abdominal X-rays
Code Source: Lakhani, P., Gray, D.L., Pett, C.R. et al. J Digit Imaging (2018) 31: 283. https://doi.org/10.1007/s10278-018-0079-6
The code to download and prepare dataset had been modified form the original source code.
```
# load requirements for the Keras library
from... | github_jupyter |
<a href="https://colab.research.google.com/github/hadisotudeh/zestyAI_challenge/blob/main/Zesty_AI_Data_Scientist_Assignment_%7C_Hadi_Sotudeh.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
<center> <h1><b>Zesty AI Data Science Interview Task - Hadi... | github_jupyter |
# Day and Night Image Classifier
---
The day/night image dataset consists of 200 RGB color images in two categories: day and night. There are equal numbers of each example: 100 day images and 100 night images.
We'd like to build a classifier that can accurately label these images as day or night, and that relies on f... | github_jupyter |
## Bengaluru House Price
```
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
pd.set_option("display.max_rows", None, "display.max_columns", None)
df1=pd.read_csv("Dataset/Bengaluru_House_Data.csv")
df1.head()
```
### Data Cleaning
```
df1.info()
df1.isnull().sum()
df1.groupby('area_type')['are... | 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 |

[](https://colab.research.google.com/github/JohnSnowLabs/spark-nlp-workshop/blob/master/tutorials/streamlit_notebooks/healthcare/RE_POSOLOGY.ipynb)
# **Detect posology relat... | github_jupyter |
```
from python_dict_wrapper import wrap
import sys
sys.path.append('../')
import torch
sys.path.append("../../CPC/dpc")
sys.path.append("../../CPC/backbone")
import matplotlib.pyplot as plt
import numpy as np
import scipy
def find_dominant_orientation(W):
Wf = abs(np.fft.fft2(W))
orient_sel = 1 - Wf[0, 0] / W... | github_jupyter |
# Лекция 7. Разреженные матрицы и прямые методы для решения больших разреженных систем
## План на сегодняшнюю лекцию
- Плотные неструктурированные матрицы и распределённое хранение
- Разреженные матрицы и форматы их представления
- Быстрая реализация умножения разреженной матрицы на вектор
- Метод Гаусса для разреже... | github_jupyter |
# The stereology module
The main purpose of stereology is to extract quantitative information from microscope images relating two-dimensional measures obtained on sections to three-dimensional parameters defining the structure. The aim of stereology is not to reconstruct the 3D geometry of the material (as in tomograp... | github_jupyter |
# Convolutional Neural Network
### Author: Ivan Bongiorni, Data Scientist at GfK.
[LinkedIn profile](https://www.linkedin.com/in/ivan-bongiorni-b8a583164/)
In this Notebook I will implement a **basic CNN in TensorFlow 2.0**. I will use the famous **Fashion MNIST** dataset, [published by Zalando](https://github.com/z... | github_jupyter |
# quant-econ Solutions: Modeling Career Choice
Solutions for http://quant-econ.net/py/career.html
```
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from quantecon import DiscreteRV, compute_fixed_point
from career import CareerWorkerProblem
```
## Exercise 1
Simulate job / career paths.
... | github_jupyter |
```
cd /tf/src/data/gpt-2/
!pip3 install -r requirements.txt
import fire
import json
import os
import numpy as np
import tensorflow as tf
import regex as re
from functools import lru_cache
import tqdm
from tensorflow.core.protobuf import rewriter_config_pb2
import glob
import pickle
tf.__version__
```
# Encoding
```... | github_jupyter |
# Задание 2.2 - Введение в PyTorch
Для этого задания потребуется установить версию PyTorch 1.0
https://pytorch.org/get-started/locally/
В этом задании мы познакомимся с основными компонентами PyTorch и натренируем несколько небольших моделей.<br>
GPU нам пока не понадобится.
Основные ссылки:
https://pytorch.org/t... | github_jupyter |
# Regularization
Welcome to the second assignment of this week. Deep Learning models have so much flexibility and capacity that **overfitting can be a serious problem**, if the training dataset is not big enough. Sure it does well on the training set, but the learned network **doesn't generalize to new examples** that... | github_jupyter |
# Table of Contents
* [1c. Fixed flux spinodal decomposition on a T shaped domain](#1c.-Fixed-flux-spinodal-decomposition-on-a-T-shaped-domain)
* [Use Binder For Live Examples](#Use-Binder-For-Live-Examples)
* [Define $f_0$](#Define-$f_0$)
* [Define the Equation](#Define-the-Equation)
* [Solve the Equation](#Solve-... | github_jupyter |
# IMPORTS
```
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
```
# READ THE DATA
```
data = pd.read_csv('./input/laptops.csv', encoding='latin-1')
data.head(10)
```
# MAIN EDA BLOCK
```
print(f'Data Shape\nRows: {data.shape[0]}\nColumns: {data.shape[1]}')
print('=' *... | github_jupyter |
# <center>АНАЛИЗ ЗВУКА И ГОЛОСА</center>
**Преподаватель**: Рыбин Сергей Витальевич
**Группа**: 6304
**Студент**: Белоусов Евгений Олегович
## <center>Классификация акустических шумов</center>
*Необоходимый результат: неизвестно*
```
import os
import IPython
import warnings
warnings.filterwarnings('ignore')
impor... | github_jupyter |
# COMP5318 - Machine Learning and Data Mining: Assignment 2
<div style="text-align: right"> Group 86 </div>
<div style="text-align: right"> tlin4302 | 470322974 | Jenny Tsai-chen Lin </div>
<div style="text-align: right"> jsun4242 | 500409987 | Jiawei Sun </div>
<div style="text-align: right"> jyan2937 | 480546614 | Ji... | github_jupyter |
# Visualizing invasive and non-invasive EEG data
[Liberty Hamilton, PhD](https://csd.utexas.edu/research/hamilton-lab)
Assistant Professor, University of Texas at Austin
Department of Speech, Language, and Hearing Sciences
and Department of Neurology, Dell Medical School
Welcome! In this notebook we will be discussi... | github_jupyter |
```
# all_no_testing
# default_exp models.binaryClassification
# default_cls_lvl 2
```
# Binary Horse Poo Model
> Simple model to detect HorsePoo vs noHorsePoo
## export data
```
%load_ext autoreload
%autoreload 2
#!rm -R data/tmp/horse_poo/ && rm -R data/tmp/no_horse_poo/
#!prodigy db-out binary_horse_poo ./data/t... | github_jupyter |
# MDN-transformer with examples
- What kind of data can be predicted by a mixture density network Transformer?
- Continuous sequential data
- Drawing data and RoboJam Touch Screem would be good examples for this, continuous values yield high resolution in 2d space.
# 1. Kanji Generation
- Firstly, let's try mode... | github_jupyter |
### Imports
```
import pandas as pd
import numpy as np
#Python Standard Libs Imports
import json
import urllib2
import sys
from datetime import datetime
from os.path import isfile, join, splitext
from glob import glob
#Imports to enable visualizations
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib... | github_jupyter |
<a href="https://colab.research.google.com/github/valentina-s/Oceans19-data-science-tutorial/blob/master/notebooks/1_data_loading_colab.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
## Whale Sound Exploration
In this tutorial we will explore some... | github_jupyter |
```
import os
import h5py
import numpy as np
# -- local --
from feasibgs import util as UT
from feasibgs import catalogs as Cat
from feasibgs import forwardmodel as FM
import matplotlib as mpl
import matplotlib.pyplot as pl
mpl.rcParams['text.usetex'] = True
mpl.rcParams['font.family'] = 'serif'
mpl.rcParams['axes... | github_jupyter |
# Multi-Layer Perceptron, MNIST
---
In this notebook, we will train an MLP to classify images from the [MNIST database](http://yann.lecun.com/exdb/mnist/) hand-written digit database.
The process will be broken down into the following steps:
>1. Load and visualize the data
2. Define a neural network
3. Train the model... | github_jupyter |
```
import pandas as pd
import os
import s3fs # for reading from S3FileSystem
import json
%matplotlib inline
import matplotlib.pyplot as plt
import torch.nn as nn
import torch
import torch.utils.model_zoo as model_zoo
import numpy as np
import torchvision.models as models # To get ResNet18
# From - https://github.... | github_jupyter |
```
transformedDfs = [i.transform(logDf) for i in model]
costs = [(i,v.stages[-1].computeCost(transformedDfs[i])) for i,v in enumerate(model)]
costs
#transformedModels = [v.stages[-1].computeCost(transformedDfs[i]) for i,v in enumerate(model)]
newParamMap = ({kmeans.k: 10,kmeans.initMode:"random"})
newModel = pipelin... | github_jupyter |
# CLX Workflow
This is an introduction to the CLX Workflow and it's I/O components.
## What is a CLX Workflow?
A CLX Workflow receives data from a particular source, performs operations on that data within a GPU dataframe, and outputs that data to a particular destination. This guide will teach you how to configure ... | github_jupyter |
```
from google.colab import drive
drive.mount('/content/drive')
path = '/content/drive/MyDrive/Research/AAAI/dataset1/second_layer_without_entropy/'
import numpy as np
import pandas as pd
import torch
import torchvision
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms, utils
import ... | github_jupyter |
```
class Solution:
def numberOfSubstrings(self, s: str) -> int:
letters = {'a', 'b', 'c'}
N = len(s)
count = 0
for gap in range(3, N + 1):
for start in range(N - gap + 1):
sub_str = s[start:start + gap]
if set(sub_str) == letters:... | github_jupyter |
```
%matplotlib inline
from matplotlib import style
style.use('fivethirtyeight')
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import pandas as pd
import datetime as dt
```
# Reflect Tables into SQLAlchemy ORM
```
# Python SQL toolkit and Object Relational Mapper
import sqlalchemy
from sqla... | github_jupyter |
<font size="+5">#02 | Decision Tree. A Supervised Classification Model</font>
- Subscribe to my [Blog ↗](https://blog.pythonassembly.com/)
- Let's keep in touch on [LinkedIn ↗](www.linkedin.com/in/jsulopz) 😄
# Discipline to Search Solutions in Google
> Apply the following steps when **looking for solutions in Googl... | github_jupyter |
# Parse Java Methods
----
(C) Maxim Gansert, 2020, Mindscan Engineering
```
import sys
sys.path.insert(0,'../src')
import os
import datetime
from com.github.c2nes.javalang import tokenizer, parser, ast
from de.mindscan.fluentgenesis.dataprocessing.method_extractor import tokenize_file, extract_allmethods_from_compila... | github_jupyter |
# Simple Perceptron
```
import tensorflow as tf
import pandas as pd
import numpy as np
%load_ext tensorboard
# Import the dataset
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
# For now, we'll focus on digit images of fives
is_five_train = y_train == 5
is_five_test = y_test == 5
labels ... | github_jupyter |
# Transfer Learning
In this notebook, you'll learn how to use pre-trained networks to solved challenging problems in computer vision. Specifically, you'll use networks trained on [ImageNet](http://www.image-net.org/) [available from torchvision](http://pytorch.org/docs/0.3.0/torchvision/models.html).
ImageNet is a m... | github_jupyter |
```
%matplotlib inline
from matplotlib import pyplot as plt
plt.rcParams['figure.figsize'] = (10, 8)
import seaborn as sns
import numpy as np
import pandas as pd
from sklearn.preprocessing import LabelEncoder
import collections
from sklearn.model_selection import GridSearchCV
from sklearn import preprocessing
from skle... | github_jupyter |
# TEXT
This notebook serves as supporting material for topics covered in **Chapter 22 - Natural Language Processing** from the book *Artificial Intelligence: A Modern Approach*. This notebook uses implementations from [text.py](https://github.com/aimacode/aima-python/blob/master/text.py).
```
from text import *
from ... | github_jupyter |
# VacationPy
----
#### Note
* Keep an eye on your API usage. Use https://developers.google.com/maps/reporting/gmp-reporting as reference for how to monitor your usage and billing.
* Instructions have been included for each segment. You do not have to follow them exactly, but they are included to help you think throug... | github_jupyter |
<center>
<img src="https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-PY0101EN-SkillsNetwork/IDSNlogo.png" width="300" alt="cognitiveclass.ai logo" />
</center>
# Loops in Python
Estimated time needed: **20** minutes
## Objectives
After completing this lab you will be ... | github_jupyter |
# Amazon Comprehend Custom Classification - Lab
This notebook will serve as a template for the overall process of taking a text dataset and integrating it into [Amazon Comprehend Custom Classification](https://docs.aws.amazon.com/comprehend/latest/dg/how-document-classification.html) and perform NLP for custom classif... | github_jupyter |
```
from time import sleep
from tm1640 import TM1640
```
# Simple and elegant usage
```
with TM1640(clk_pin=24, din_pin=23) as d:
d.brightness = 0
d.write_text('HELLO')
for i in [1,1,1,1,1, -1,-1,-1,-1,-1]:
sleep(1)
d.brightness += i
```
# Global object for the purposes of this notebook
... | github_jupyter |
# Homework: Decipherment
```
from collections import defaultdict, Counter
import collections
import pprint
import math
import bz2
pp = pprint.PrettyPrinter(width=45, compact=True)
```
First let us read in the cipher text from the `data` directory:
```
def read_file(filename):
if filename[-4:] == ".bz2":
... | github_jupyter |
The first thing we need to do is to download the dataset from Kaggle. We use the [Enron dataset](https://www.kaggle.com/wcukierski/enron-email-dataset), which is the biggest public email dataset available.
To do so we will use GDrive and download the dataset within a Drive folder to be used by Colab.
```
from google.c... | github_jupyter |
## 1. The brief
<p>Imagine working for a digital marketing agency, and the agency is approached by a massive online retailer of furniture. They want to test our skills at creating large campaigns for all of their website. We are tasked with creating a prototype set of keywords for search campaigns for their sofas secti... | github_jupyter |
```
from google.colab import drive
drive.mount('/content/drive')
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from numpy import load
from numpy import asarray
from numpy import savez_compressed
from sklearn.model_selection import train_test_split
from keras.models import Sequential
from keras... | github_jupyter |
# LSTM - Long Short Term Memory
- From [v1] Lecture 60
- LSTM, another variation of RNN
## Study Links
- [An empirical exploration of recurrent network architectures](https://dl.acm.org/citation.cfm?id=3045367)
- https://dblp.uni-trier.de/db/journals/corr/corr1506.html
- [A Critical Review of Recurrent Neural ... | github_jupyter |
<a href="https://colab.research.google.com/github/abhisheksuran/Atari_DQN/blob/master/Multi_Worker_Actor_Critic.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
```
import numpy as np
import tensorflow as tf
import gym
import tensorflow_probability ... | github_jupyter |
```
# Formulate an algorithm to check for a student has passed in exam or not?
y = float(input("Enter the minimum marks required to pass in the exam : "))
x = float(input('Enter the marks scored by student in the exam : '))
if (x >= y):
print('This student is passed in the exam')
else:
print('This student is fa... | github_jupyter |
```
import pymongo
from bs4 import BeautifulSoup
import requests
import pandas as pd
from flask import Flask
# acquire full html contents to search through
url = 'https://mars.nasa.gov/news/'
response = requests.get(url)
# response.text
soup = BeautifulSoup(response.text,'html.parser')
# print(soup.prettify())
#find al... | github_jupyter |
# US Treasury Interest Rates / Yield Curve Data
---
A look at the US Treasury yield curve, according to interest rates published by the US Treasury.
```
import pandas as pd
import altair as alt
import numpy as np
url = 'https://www.treasury.gov/resource-center/data-chart-center/interest-rates/pages/TextView.aspx?dat... | github_jupyter |
This notebook is part of the $\omega radlib$ documentation: https://docs.wradlib.org.
Copyright (c) $\omega radlib$ developers.
Distributed under the MIT License. See LICENSE.txt for more info.
# Supported radar data formats
The binary encoding of many radar products is a major obstacle for many potential radar user... | github_jupyter |
```
import os
import pandas as pd
import random
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM,Dropout
from keras.layers.embeddings import Embedding
from keras.preprocessing import sequence
from keras... | github_jupyter |
```
# This Python 3 environment comes with many helpful analytics libraries installed
# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python
# For example, here's several helpful packages to load in
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file... | github_jupyter |
# Exercices
With each exercice will teach you one aspect of deep learning. The process of machine learning can be decompose in 7 steps :
* Data preparation
* Model definition
* Model training
* Model evaluation
* Hyperparameter tuning
* Prediction
## 3 - Model training
- 3.1 Metrics : evaluate model
- 3.2 Loss funct... | github_jupyter |
```
%run setup.ipynb
from scipy.stats import dirichlet
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline
import traceback
import logging
logger = logging.getLogger('ag1000g-phase2')
logger.setLevel(logging.DEBUG)
# create console handler with a higher log level
ch = logging.StreamHandler()
ch.s... | github_jupyter |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.