text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
# Minus in Python DataFrame
```
import pandas as pd
df1 = pd.DataFrame([[1,'a'],[2,'b']], columns=['ID','Names'])
df1
df2 = pd.DataFrame([[1,'a']],columns=['ID', 'Names'])
df1 = pd.DataFrame([[1,'a']], columns=['ID','Names'])
df2
df2 = pd.DataFrame([[1,'a']],columns=['ID', 'Names'])
df1.equals(df2)
df1[df1.ID.isin(df2... | github_jupyter |
```
%matplotlib inline
```
# Empirical evaluation of the impact of k-means initialization
Evaluate the ability of k-means initializations strategies to make
the algorithm convergence robust as measured by the relative standard
deviation of the inertia of the clustering (i.e. the sum of squared
distances to the near... | github_jupyter |
Sebastian Raschka
last updated: 05/07/2014
- [Link to this IPython Notebook on GitHub](https://github.com/rasbt/pattern_classification/blob/master/stat_pattern_class/supervised/parametric/parameter_estimation/max_likelihood_est_distributions.ipynb)
- [Link to the GitHub repository](https://github.com/rasbt/pat... | github_jupyter |
```
import PyNEC
import n3ox_utils.pynec_helpers as pnh
import n3ox_utils.plot_tools as ptl
import n3ox_utils.nfanim as nfa
import numpy as np
import matplotlib.pyplot as plt
plt = ptl.init_pyplot_defaults(plt)
figs = {}
```
# Wireless Inductive Coupling
This notebook uses PyNEC to simulate the resonant inductive co... | github_jupyter |
# 函数
- 函数可以用来定义可重复代码,组织和简化
- 一般来说一个函数在实际开发中为一个小功能
- 一个类为一个大功能
- 同样函数的长度不要超过一屏
Python中的所有函数实际上都是有返回值(return None),
如果你没有设置return,那么Python将不显示None.
如果你设置return,那么将返回出return这个值.
```
def mxt():
print("maxuetig")
return 100
mxt()
def mxt():
print("maxuetig")
#函数需要调用
mxt()
mxt
def mxt(name):
print(name,"... | 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 |
```
# UCSD Data Science Bootcamp, HW 21 ML
# Alexis Perumal, 4/28/20
# Update sklearn to prevent version mismatches
#
# Model X - Compare Models, no Hyperparameter tuning
#
!pip install sklearn --upgrade
# install joblib. This will be used to save your model.
# Restart your kernel after installing
!pip install joblib... | github_jupyter |
# How do package dependency network grow over time?
In this notebook we plan to investigate the dependencies in the Pypi dataset and try to look at
how they change over time.
## Loading data and importing libraries
```
%load_ext autoreload
# Auto reloading causes the kernel to reload the libraries we have
%autorelo... | github_jupyter |
# Optimization
- [Least squares](#Least-squares)
- [Gradient descent](#Gradient-descent)
- [Constraint optimization](#Constraint-optimization)
- [Global optimization](#Global-optimization)
## Intro
Biological research uses optimization when performing many types of machine learning, or when it interfaces with engine... | github_jupyter |
Current and near-term quantum computers suffer from imperfections, as we repeatedly pointed it out. This is why we cannot run long algorithms, that is, deep circuits on them. A new breed of algorithms started to appear since 2013 that focus on getting an advantage from imperfect quantum computers. The basic idea is ext... | github_jupyter |
# Introduction to Transfer Learning - recap
In our previous tutorial, we looked at how to do simple binary image classification with neural networks. Can we do it for where images belong to more than two classes?
```
%matplotlib inline
from __future__ import print_function, division
import torch
import torch.nn as n... | github_jupyter |
# Single Qubit Gates
In the previous section we looked at all the possible states a qubit could be in. We saw that qubits could be represented by 2D vectors, and that their states are limited to the form:
$$ |q\rangle = \cos{(\tfrac{\theta}{2})}|0\rangle + e^{i\phi}\sin{\tfrac{\theta}{2}}|1\rangle $$
Where $\theta$ ... | github_jupyter |
CTGAN Model
===========
In this guide we will go through a series of steps that will let you
discover functionalities of the `CTGAN` model, including how to:
- Create an instance of `CTGAN`.
- Fit the instance to your data.
- Generate synthetic versions of your data.
- Use `CTGAN` to anonymize PII information... | github_jupyter |
# Descriptive Statistics
- We'll be focusing primarily on descriptive statistics in order to describe patterns, trends, distributions, and behaviors across our data.
# Measures of Central Tendency
## Mean, Median and Mode
The "Mean" is computed by adding all of the numbers in the data
together and dividing by the n... | 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 |
# Remote execution on compute cluster
```
from azureml.core import Workspace
ws = Workspace.from_config()
target = ws.compute_targets["cpu-cluster"]
from azureml.core import ScriptRunConfig
script = ScriptRunConfig(
source_directory="030_scripts",
script="sklearn_vanilla_train.py",
compute_target=target,... | github_jupyter |
```
%load_ext autoreload
%autoreload 2
import numpy as np
import scqubits as scq
from qiskit_metal.analyses.quantization.lumped_capacitive import load_q3d_capacitance_matrix
from qiskit_metal.analyses.quantization.lom_core_analysis import CompositeSystem, Cell, Subsystem
from scipy.constant... | github_jupyter |
```
#Define libraries
import tensorflow as tf
import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout, Conv1D, MaxPooling1D, BatchNormalization, Flatten
from sklearn.model_selection import KFold
from keras.utils import multi_gpu_model
#from sklearn.cross_validation import StratifiedKFol... | github_jupyter |
```
%run ../../common/import_all.py
from common.setup_notebook import set_css_style, setup_matplotlib, config_ipython
config_ipython()
setup_matplotlib()
set_css_style()
```
# Logistic Regression
## What is
Logistic Regression [[1]](#cox) is, despite the name, a classifier. Its procedure fits (hence the reference t... | github_jupyter |
# Machine Learning Engineer Nanodegree
## Introduction and Foundations
## Project 0: Titanic Survival Exploration
In 1912, the ship RMS Titanic struck an iceberg on its maiden voyage and sank, resulting in the deaths of most of its passengers and crew. In this introductory project, we will explore a subset of the RMS ... | github_jupyter |
# How to classify satellite images
## Imports & Settings
```
import warnings
warnings.filterwarnings('ignore')
%matplotlib inline
from pathlib import Path
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter
import seaborn as sns
import tensorflow as tf
from tensorflow.ker... | github_jupyter |
# Chapter 11: Functions and scope
*We use an example from [this website](http://anh.cs.luc.edu/python/hands-on/3.1/handsonHtml/functions.html) to show you some of the basics of writing a function.
We use some materials from [this other Python course](https://github.com/kadarakos/python-course).*
We have seen that Pyt... | github_jupyter |
```
import uuid
import json
roiIndex = 1
cellIndex = 1
def get_annotation(filename):
with open(filename) as f:
data = json.load(f)
f.close()
return data['regions']
def get_rois(regions,tagGroup,formatAnnotationLookup):
rois = []
index = 0
global roiIndex
for region in r... | github_jupyter |
# Conditionals
## Use `if` statements to control whether or not a block of code is executed.
* An `if` statement (more properly called a *conditional* statement) controls whether some block of code is executed or not.
* Structure is similar to a `for` statement:
* First line opens with `if` and ends with a colon
... | github_jupyter |
## Noise
For simulation, it is useful to have `Gate` objects that enact noisy quantum evolution.
Cirq supports modeling noise via *operator sum* representations of
noise (these evolutions are also known as quantum operations, quantum
dynamical maps, or superoperators).
This formalism models evolution of the
densit... | github_jupyter |
```
#Produces some data that allows you to test the interactive chart without using data
from faker import Faker
fake = Faker()
import json
with open('random_images.json') as data_file:
random_images = json.load(data_file)
import requests
import json
import random
def create_node():
node = {}
node["ful... | github_jupyter |
This is the tutorial for the evaluation of CPHF alchemical derivatives using PySCF (version 1.7.6)
```
from pyscf import gto,scf
import numpy as np
import pyscf
pyscf.__version__
```
## Fractional charge molecules
```
from FcMole import FcM, FcM_like
mol_NN=gto.M(atom= "N 0 0 0; N 0 0 2.1",unit="Bohr", basis="sto-3g... | github_jupyter |
# SLU10 - Metrics for Regression: Exercise Notebook
In this notebook, you will implement:
- Mean Absolute Error (MAE)
- Mean Squared Error (MSE)
- Root Mean Squared Error (RMSE)
- Coefficient of Determination (R²)
- Adjusted R²
- Scikitlearn metrics
- Using metrics for k-fold cross validati... | github_jupyter |
# <center>MobileNet - Pytorch
# Step 1: Prepare data
```
# MobileNet-Pytorch
import argparse
import torch
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.optim.lr_scheduler import StepLR
from torchvision import datasets, transforms
from torch.autograd i... | github_jupyter |
# Linear Regression with Polynomial Basis Expansion
Imports and Helper Functions
---
```
%matplotlib inline
from ipywidgets import interactive_output
import ipywidgets as widgets
import numpy as np
from matplotlib import pyplot as plt
```
## Data Set Generation
```
N = 100
datasets = {}
X = 2 * (np.random.rand(100... | github_jupyter |
```
%load_ext autoreload
%autoreload 2
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
import os, math
import numpy as np, pandas as pd
import matplotlib.pyplot as plt, seaborn as sns
from pandas_summary import DataFrameSummary
from tqdm import tqdm, tqdm_notebook
from pathlib import Path
pd.set_opti... | github_jupyter |
# Выбираем лучшую модель
Мы обучили дерево решений, случайный лес и линейную регрессию. Какая модель лучше?
## Задача
Найти модель, у которой на тестовой выборке RMSE не больше 7.5.
## Решение
```
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_err... | github_jupyter |
#### Copyright IBM All Rights Reserved.
#### SPDX-License-Identifier: Apache-2.0
## Using Database Views
In this demo we will:
1. Review an existing query
2. Modify our graph overlay file to include a new view
3. Create a new query using our view
### Before proceeeding
Please update the `connect_info` notebook ... | github_jupyter |
```
# !pip install opencv-python
from PIL import Image
import numpy as np
import os
import cv2
import keras
from keras.utils import np_utils
from keras.models import Sequential
from keras.layers import Conv2D,MaxPooling2D,Dense,Flatten,Dropout
import pandas as pd
def readData(filepath, label):
cells = []
labels... | github_jupyter |
```
import json
import requests
from decouple import config
```
## Get config
```
username = config('USERNAME_TEST')
password = config('PASSWORD_TEST')
server_domain = "http://coquma-sim.herokuapp.com/api/"
requested_backend = "fermions"
url=server_domain + requested_backend +"/get_config/"
r = requests.get(url,para... | github_jupyter |
```
import numpy as np
import matplotlib.pyplot as plt
import cv2
import pkg_resources
from pathlib import Path
MIN_MATCH_COUNT = 10
img1 = cv2.imread('im_0.png',0) # queryImage
img2 = cv2.imread('im_00.png',0) # trainImage
# Initiate SIFT detector
sift = cv2.xfeatures2d.SIFT_create()
# find the key... | github_jupyter |
# The Capacitated Vehicle Routing Problem
A short example of using **Iterated Local Search** to model and solve the CRVP
> Vehicle routing problems are inherently intractable: the length of time it takes to solve them grows exponentially with the size of the problem. For sufficiently large problems, it could take rou... | github_jupyter |
```
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
```
# Binary focal loss
```
class BinaryFocalWithLogitsLoss(nn.Module):
"""Computes the focal loss with logits for binary data.
The Focal Loss is designed to address the one-stage object detection scenario in
which ... | github_jupyter |
```
# This notebook calculates the returns over 1 through 15 bars for trading signals.
# Every signal is evaluated so this return does not reflect the returns that would have been realized
# by entering trades. Data is pulled from Yahoo finance for any given symbol. Other data sources may
# be substituted in this cell... | github_jupyter |
# MIMO (spatial multiplexing) with convolutional coding
This example demonstrates how to use the Modulator_ND (MIMO) class for soft-output demodulation. The program simulates a simple convolutionally coded spatial-multiplexing (V-BLAST style) MIMO system with maximum-likelihood, alternatively zero-forcing, demodulatio... | github_jupyter |
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License.

# Explain binary classi... | github_jupyter |
Create with {} or dict()
-------------------------
```
# Empty dictionaries
empty_dict_1 = {}
print(type(empty_dict_1))
print(empty_dict_1)
empty_dict_2 = dict()
print(type(empty_dict_2))
print(empty_dict_2)
diet = {
'monday': 'Apples',
'tuesday': 'Oranges',
'wednesday': 'Banana'
}
print(di... | github_jupyter |
```
import pandas as pd
import numpy as np
from sklearn.decomposition import PCA
from sklearn.linear_model import Ridge
from sklearn.model_selection import train_test_split
from sklearn import preprocessing
import torch
import torch.nn as nn
from torch.autograd import Variable
from torch.autograd import grad
from utils... | github_jupyter |
# Exercise 4: Optimizing Redshift Table Design
```
%load_ext sql
from time import time
import configparser
import matplotlib.pyplot as plt
import pandas as pd
config = configparser.ConfigParser()
config.read_file(open('dwh.cfg'))
KEY=config.get('AWS','key')
SECRET= config.get('AWS','secret')
DWH_DB= config.get("DWH",... | github_jupyter |
# Continuous Control
---
You are welcome to use this coding environment to train your agent for the project. Follow the instructions below to get started!
### 1. Start the Environment
Run the next code cell to install a few packages. This line will take a few minutes to run!
```
!pip -q install ./python
```
The... | github_jupyter |
```
%load_ext autoreload
%autoreload 2
import numpy as np
from functools import partial
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split, KFold
from sklearn.preprocessing import StandardScaler
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics... | github_jupyter |
# EuroScipy 2019 :: Numba Tutorial Notebook 4 :: Writing CUDA Kernels
## The CUDA Programming Model
Ufuncs (and generalized ufuncs mentioned in the bonus notebook at the end of the tutorial) are the easiest way in Numba to use the GPU, and present an abstraction that requires minimal understanding of the CUDA program... | github_jupyter |
# AI Explanations: Deploying an image model
## Overview
This tutorial shows how to train a Keras classification model on image data and deploy it to the AI Platform Explanations service to get feature attributions on your deployed model.
If you've already got a trained model and want to deploy it to AI Explanations,... | github_jupyter |
```
# all_slow
!pip install nbdev
!pip install wwf -q
from wwf.utils import state_versions
state_versions(['wwf', 'fastai', 'fastcore', 'nbdev'])
```
# Goals for today:
Look at 2-3 Callbacks:
- `ShortEpochCallback`
- `SaveModelCallback`
- Teacher/Student (or advanced model inputs) example by [@goralpl](https://gith... | github_jupyter |
```
import h5py
import os
import numpy as np
from ramandecompy import dataprep
os.remove('string_test.hdf5')
dataprep.new_hdf5('string_test')
hdf5 = h5py.File('string_test.hdf5', 'r+')
hdf5['dataset'] = [1, 2, 3, 4, 5, 6, 7]
hdf5.close()
dataprep.view_hdf5('string_test.hdf5')
def create_dataset(h5py_file):
data = ... | github_jupyter |
<p style="z-index: 101;background: #fde073;text-align: center;line-height: 2.5;overflow: hidden;font-size:22px;">Please <a href="https://github.com/ECSIM/opem#cite" target="_blank">cite us</a> if you use the software</p>
# Padulles Dynamic Model II
### Version 1.3
<ul>
<li><a href="#Overview">Overview</a></li>... | github_jupyter |
```
import numpy as np
import matplotlib as mpl
from matplotlib import pyplot as plt
import scipy.integrate as integrate
from scipy.integrate import quad
import scipy.optimize as so
import scipy.special as ss
#parameters
n = 4.0 #concentration parameter that describes ... | github_jupyter |
# SageMaker で自分たちの機械学習アルゴリズムの学習・推論を行う
#### ノートブックに含まれる内容
- BYOA を SageMaker で行うときの,基本的なやりかた
#### ノートブックで使われている手法の詳細
- アルゴリズム: DecisionTreeClassifier
- データ: iris
## セットアップ
```
import boto3
import re
import os
import numpy as np
import pandas as pd
from sagemaker import get_execution_role
# AWS credential で指定された ... | github_jupyter |
.. _nb_custom:
## Custom Variable Type
In the following, we describe a custom variable problem. The variable is a string with a fixed length in our case.
However, we formulate the problem to be easily extended to have a variable length.
The objective function looks as follows:
\begin{align}
\begin{split}
\max f_1(x... | github_jupyter |
# Project 2: Continuous Control
### Test 1 - DDPG model
<sub>Uirá Caiado. October 07, 2018<sub>
#### Abstract
_In this notebook, I will use the Unity ML-Agents environment to train a DDPG model for the second project of the [Deep Reinforcement Learning Nanodegree](https://www.udacity.com/course/deep-reinforcement-le... | github_jupyter |
# Lane Boundary Segmentation
## Setting up Colab
You can delete this "Setting up Colab" section if you work locally and do not want to use Google Colab
```
colab_nb = 'google.colab' in str(get_ipython())
if colab_nb:
from google.colab import drive
drive.mount('/content/drive')
if colab_nb:
%cd drive/My\ Drive/... | github_jupyter |
# Running TensorTrade on SageMaker Studio
This notebook demonstrates running TensorTrade on SageMaker Studio. EOD data for any ETF/stock is fetched from [Yahoo Finance](https://finance.yahoo.com/) or S3 bucket. Experimental evidence shows that running on ml.g4dn.xlarge instance completes sooner than running on ml.t3.me... | github_jupyter |
# 4章 ニューラルネットワークの学習
ここでは学習とは訓練データから最適な重みパラメータの値を自動的に獲得することを指す。
## 4.1 データから学習する
ニューラルネットワークはデータから学習できる特徴がある。これは多数の重みパラメータを人力で設定する必要がなくなるため、有用である。
### 4.1.1 データ駆動
人にとって分かる規則性でもアルゴリズムで実現しようとすると難しい。アルゴリズムの考案ではなく、画像空特徴量を抽出したえパターンを学習させることで実現する。特徴量とはデータから重要なデータを的確に抽出できるように設計した変換器のことである。
画像の特徴量は通常、ベクトルとして記述される。(コンピュータビジョン分... | github_jupyter |
# Monte Carlo simulation of Dynamic Risk Budgeting between PSP and GHP
We've looked at the fundamental problem of how much to allocate in the safe asset vs the performance seeking asset, and we investigated static and glidepath based techniques. Now we'll look at modern dynamic techniques that are inspired by CPPI to ... | github_jupyter |
```
import os, sys
import json
import gzip
import itertools
import collections
import importlib
import tqdm
import numpy as np
import pandas as pd
from sklearn import metrics
from sklearn.svm import SVC
from sklearn.linear_model import LogisticRegression
from sklearn.decomposition import PCA
from scipy import stats
f... | github_jupyter |
#Adding tag variables to NanoAOD
stuff
```
import FWCore.ParameterSet.Config as cms
from Configuration.StandardSequences.Eras import eras
process = cms.Process("USER",eras.Run2_2017)
## Load services
process.load("Configuration.Geometry.GeometryRecoDB_cff")
process.load("Configuration.StandardSequences.FrontierCondit... | github_jupyter |
# MNISTでセグメンテーションに挑戦
```
import os
import shutil
import random
import numpy as np
import matplotlib.pyplot as plt
#from tqdm.notebook import tqdm
from tqdm import tqdm
import torch
import torchvision
import torchvision.transforms as transforms
import binarybrain as bb
```
## 初期設定
```
# configuration
bb.set_device(... | github_jupyter |
Lambda School Data Science, Unit 2: Predictive Modeling
# Regression & Classification, Module 3
## Assignment
We're going back to our other **New York City** real estate dataset. Instead of predicting apartment rents, you'll predict property sales prices.
But not just for condos in Tribeca...
Instead, predict prop... | github_jupyter |
```
import sys
sys.path.append('../')
sys.path.append('../support/')
from ct_reader import *
from glob import glob
import timeit
from os.path import join, basename, isfile
from tqdm import tqdm
from functools import partial
from paths import *
from sklearn.decomposition import PCA
from sklearn.svm import LinearSVC
impo... | github_jupyter |
# The Depression Data
```
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import sklearn as sk
from sklearn import tree
from sklearn.tree import DecisionTreeRegressor
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error as ms... | github_jupyter |
# Modeling and Simulation in Python
Chapter 1
Copyright 2017 Allen Downey
License: [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0)
## Jupyter
Welcome to Modeling and Simulation, welcome to Python, and welcome to Jupyter.
This is a Jupyter notebook, which is a developm... | github_jupyter |
```
import numpy
import scipy.stats
import datetime
import matplotlib.pyplot
from exp import load_data
import sklearn.model_selection
import utils
from GP_Beta_cal import GP_Beta
from sklearn.isotonic import IsotonicRegression
import warnings
warnings.filterwarnings("ignore")
%matplotlib inline
```
Specify the uncalib... | github_jupyter |
## Coding Exercise #0505
### 1. Classification with Tree:
```
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import os
import seaborn as sns
import warnings
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor... | github_jupyter |
## Excel "What if?" analysis with Python - Part 1: Models and Data Tables
Excel is widely used for building and using models of business problems to explore the impact of various model inputs on key outputs. Built in "what if?" tools such as Excel [Data Tables](https://support.microsoft.com/en-us/office/calculate-mult... | github_jupyter |
```
from __future__ import absolute_import
from __future__ import print_function
import numpy as np
from sklearn.model_selection import train_test_split
import keras
import random
from keras.datasets import mnist
from keras.models import Model
from keras.models import Sequential
from keras import regularizers
from ker... | github_jupyter |
```
# plotting libraries
import matplotlib
import matplotlib.pyplot as plt
# numpy (math) libary
import numpy as np
import sys
### import PARAMETERS and CONSTANTS
from modules.ConstantsAndParameters import *
### import UTILITY functions
from modules.utils import *
#print_const()
#print_const(normalized=True)
### i... | github_jupyter |
```
!pip install surprise
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import surprise
from surprise import SVD
from surprise import accuracy
from surprise import KNNBasic, KNNWithMeans, KNNBaseline
from surprise import Reader
from surprise.model_selection import train_te... | github_jupyter |
# Kangaroos example
Gull and Skilling (1984) gave the following example, which they describe as a physicist's perversion of the formal mathemetical analysis of Shore and Johnson 1980 showing that maximizing the entropy function is required for logical consistency.
Information:
> 1. A third of all kangaroos are blue-... | github_jupyter |
```
# look at tools/set_up_magics.ipynb
yandex_metrica_allowed = True ; get_ipython().run_cell('# one_liner_str\n\nget_ipython().run_cell_magic(\'javascript\', \'\', \'// setup cpp code highlighting\\nIPython.CodeCell.options_default.highlight_modes["text/x-c++src"] = {\\\'reg\\\':[/^%%cpp/]} ;\')\n\n# creating magics\... | github_jupyter |
```
#Setting up prerequisites
import pandas as pd
import numpy as np
import math
import re
import sklearn
from scipy.sparse import csr_matrix
import matplotlib.pyplot as plt
import seaborn as sns
from surprise import Reader, Dataset, SVD, evaluate
sns.set_style("darkgrid")
from cvxpy import *
from numpy import matrix
... | github_jupyter |
### Imports
```
from IPython.core.display import display, HTML
display(HTML("<style>.container { width:100% !important; }</style>"))
# Suggestions :
# *Send the file over-uploaded it on github
# *send data to postgres in AWS cloud - remote database
# *Put links where from data is avaliable
# *Create n... | github_jupyter |
```
import pandas as pd
import pyspark.sql.functions as F
from datetime import datetime
from pyspark.sql.types import *
from pyspark.storagelevel import StorageLevel
import numpy as np
pd.set_option("display.max_rows", 101)
pd.set_option("display.max_columns", 101)
from pyspark.ml import Pipeline
from pyspark.ml.class... | github_jupyter |
# Maximization of banana function by various methods
**Randall Romero Aguilar, PhD**
This demo is based on the original Matlab demo accompanying the <a href="https://mitpress.mit.edu/books/applied-computational-economics-and-finance">Computational Economics and Finance</a> 2001 textbook by Mario Miranda and Paul Fac... | github_jupyter |
# 7. 인물사진을 만들어 보자
**시맨틱 세그멘테이션(semantic segmentation)을 사용하여 핸드폰의 인물사진을 재현한다.**
## 7-1. 들어가며
```bash
$ mkdir -p ~/aiffel/human_segmentation/models
$ mkdir -p ~/aiffel/human_segmentation/images
```
## 7-2. 셸로우 포커스 만들기 (1) 사진을 준비하자
```
import os
import urllib
import cv2
import numpy as np
from pixellib.semantic impor... | github_jupyter |
```
import numpy as np
np.random.seed(1337) # for reproducibility
import h5py
from sklearn.metrics import roc_curve, auc
from sklearn import metrics
from sklearn.model_selection import train_test_split
from sklearn.metrics import roc_auc_score
from sklearn.metrics import precision_recall_curve, average_precision_score... | github_jupyter |
# Module 5
## Video 22: Filtering by Time
**Python for the Energy Industry**
## Datetime Objects
In the 'Cargo Movements Example' video, we saw the `datetime` object used to specify a particular data and time to look for cargo movements. In this lesson we explore in more detail the `datetime` object, and how it is u... | github_jupyter |
# Calculating Information Entropy after MNIST Dataset Prediction
## Loading Packages and Settings
```
import os
# # GPU Settings
# os.environ["CUDA_VISIBLE_DEVICES"] = "1"
import numpy as np
import matplotlib.pyplot as plt
import time
from keras.datasets import mnist
from keras.models import Sequential, load_model
f... | github_jupyter |
# Python Algorithmic Trading Cookbook
## Chapter 1: Handling & Manipulating Date, Time & Time Series Data
### This Jupyter Notebook is created using Python version 3.7.2
------------------------------
### Recipe #1: Creating DateTime objects and modifying its attributes
```
# Import the necessary module from Pyth... | github_jupyter |
```
%load_ext autoreload
%autoreload 2
import numpy as np
from numpy import linalg as lin
from cs771 import plotData as pd, utils, genSyntheticData as gsd
import random
def getGramMatrix( X, Y, kernel, p = 1, c = 0, g = 1.0 ):
# Check if these are 1D datasets
if len( X.shape ) == 1:
X = X[:, np.newaxis]... | github_jupyter |
```
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
print(tf.__version__)
def plot_series(time, series, format="-", start=0, end=None):
plt.plot(time[start:end], series[start:end], format)
plt.xlabel("Time")
plt.ylabel("Value")
plt.grid(True)
def trend(time, slope=0):
ret... | github_jupyter |
# Table of Contents
<p><div class="lev1 toc-item"><a href="#Load-libraries" data-toc-modified-id="Load-libraries-1"><span class="toc-item-num">1 </span>Load libraries</a></div><div class="lev1 toc-item"><a href="#Define-loss-functions" data-toc-modified-id="Define-loss-functions-2"><span class="toc-item-num... | github_jupyter |
```
# magics: ensures that any changes to the modules loaded below will be re-loaded automatically
%load_ext autoreload
%autoreload 2
%load_ext line_profiler
# load general packages
import numpy as np
# load modules related to this exercise
from model_zucher_exante import zurcher
from Solve_NFXP_exante import solve_N... | github_jupyter |
# Sample Publisher Nodes
We can look at a two very simply sample nodes to understand how ROS works.
In the Viper Toolkit package, under the scripts/ folder there are two python files:
* publisher.py
* subscriber.py
In ROS I find it easiest to set everything up as a class... In other notebooks I will try to ... | github_jupyter |
```
from sklearn.model_selection import train_test_split
from tensorflow.keras.callbacks import ModelCheckpoint
from tensorflow.keras.layers import Input
from tensorflow.keras.layers import RepeatVector
from tensorflow.keras.layers import LSTM
from tensorflow.keras.layers import Bidirectional
from tensorflow.keras.mod... | github_jupyter |
<a href="https://colab.research.google.com/github/ayulockin/LossLandscape/blob/master/MediumCNN_Cifar10.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# Setups, Installations and Imports
```
!nvidia-smi
## This is so that I can save my models.
fro... | github_jupyter |
# Mawrth_Vallis
In this series of note(book)s we are going to review the library using Mars Mawrth Vallis (https://en.wikipedia.org/wiki/Mawrth_Vallis) as instrument-data.
Mawrth Vallis (_MMV_ hereafter) is centered at (approx) 22.5<sup>o</sup>,343.5<sup>o</sup> (lat,lon; C180+E).
Let's define the region of interest ... | github_jupyter |
##### Copyright 2020 Google
```
#@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 agreed to in writ... | github_jupyter |
<div style="text-align: right"><i>Peter Norvig<br>2012<br>Updated 2020</i></div>
# Poker: Ranking Hands, etc.
The [rules for poker hands](https://en.wikipedia.org/wiki/List_of_poker_hands) are complex, but it is an interesting exercise to write a program to rank poker hands—to determine if one is higher or low... | github_jupyter |
```
import pandas as pd
pd.core.common.is_list_like = pd.api.types.is_list_like
from pandas_datareader import data, wb # This will import the data reader
import matplotlib.pyplot as plt
import numpy as np
import datetime as dt
```
---
### [Equilibrium Technology Diffusion, Trade, and Growth](https://christophertonet... | github_jupyter |
### **Google Scholar Publications Crawler**
Written by: Eimen Hamedat - https://www.linkedin.com/in/eimenhamedat/
*This crawler allows you to define a list of scholars for which it then creates a CSV file of all the scholars' publications listed on Google Scholar.*
---
**Install and/or Import Dependencies**
```
p... | github_jupyter |
```
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
import pandas as pd
sns.set()
tesla = pd.read_csv('TSLA.csv')
tesla['Date'] = pd.to_datetime(tesla['Date'])
tesla.head()
def df_shift(df,lag=0, start=1, skip=1, rejected_columns = []):
df = df.copy()
if not lag:
return df
c... | github_jupyter |
```
import torch
import torch.nn as nn
from torch.nn import functional as F
from torch.autograd import Variable
from torch.utils.data import Dataset, DataLoader
import json
import numpy as np
import random
import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import pearsonr
from sklearn.metrics import f1... | github_jupyter |
<table width="100%">
<tr style="border-bottom:solid 2pt #009EE3">
<td style="text-align:left" width="10%">
<a href="pairing_device.dwipynb" download><img src="../../images/icons/download.png"></a>
</td>
<td style="text-align:left" width="10%">
<a href="https://mybinde... | github_jupyter |
# Pythonを使って顔ランドマークで遊んでみよう
今回はPythonを使ったプログラミングをやってみます。ただの数値計算では面白くないので
1. WebCAMを使って自分の顔をキャプチャ
2. 顔検出
3. 顔ランドマーク検出
4. ランドマークを使って何かやる
という流れです。
## 使うパッケージ
この例では
* OpenCV: 画像処理ライブラリ(cv2)
* dlib: 機械学習ライブラリ
を使います。
# 1. WebCAMを使って自分の顔をキャプチャ
まず,OpenCV(cv2)とdlibを使う宣言をします。C言語の#includeみたいなもんです。
セルが緑色の状態(青だったらEnterを押す)で... | github_jupyter |
# Reconstructing Point Cloud with DMTet
Deep Marching Tetrahedra (DMTet) is a hybrid 3D representation that combines both implicit and explicit 3D surface representations. It represents a shape with a discrete SDF defined on vertices of a deformable tetrahedral grid. The SDF is converted to triangular mesh using a dif... | github_jupyter |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.