code stringlengths 2.5k 6.36M | kind stringclasses 2
values | parsed_code stringlengths 0 404k | quality_prob float64 0 0.98 | learning_prob float64 0.03 1 |
|---|---|---|---|---|
```
# best results when running `ocean events access`
import datetime
import time
import json
import requests
import logging
import urllib.parse
from IPython.display import display, IFrame, FileLink, Image
import pandas as pd
from ocean_cli.ocean import get_ocean
logging.getLogger().setLevel(logging.DEBUG)
alice = g... | github_jupyter | # best results when running `ocean events access`
import datetime
import time
import json
import requests
import logging
import urllib.parse
from IPython.display import display, IFrame, FileLink, Image
import pandas as pd
from ocean_cli.ocean import get_ocean
logging.getLogger().setLevel(logging.DEBUG)
alice = get_o... | 0.273769 | 0.141222 |
# 随机梯度下降
:label:`sec_sgd`
但是,在前面的章节中,我们一直在训练过程中使用随机梯度下降,但没有解释它为什么起作用。为了澄清这一点,我们刚在 :numref:`sec_gd` 中描述了梯度下降的基本原则。在本节中,我们继续讨论
*更详细地说明随机梯度下降 *。
```
%matplotlib inline
import math
import torch
from d2l import torch as d2l
```
## 随机渐变更新
在深度学习中,目标函数通常是训练数据集中每个示例的损失函数的平均值。给定 $n$ 个示例的训练数据集,我们假设 $f_i(\mathbf{x})$ 是与指数 $i$ ... | github_jupyter | %matplotlib inline
import math
import torch
from d2l import torch as d2l
def f(x1, x2): # Objective function
return x1 ** 2 + 2 * x2 ** 2
def f_grad(x1, x2): # Gradient of the objective function
return 2 * x1, 4 * x2
def sgd(x1, x2, s1, s2, f_grad):
g1, g2 = f_grad(x1, x2)
# Simulate noisy gradient
... | 0.59561 | 0.9601 |
```
%matplotlib inline
```
SyntaxError
===========
Example script with invalid Python syntax
```
"""
Remove line noise with ZapLine
==============================
Find a spatial filter to get rid of line noise [1]_.
Uses meegkit.dss_line().
References
----------
.. [1] de Cheveigné, A. (2019). ZapLine: A simple ... | github_jupyter | %matplotlib inline
"""
Remove line noise with ZapLine
==============================
Find a spatial filter to get rid of line noise [1]_.
Uses meegkit.dss_line().
References
----------
.. [1] de Cheveigné, A. (2019). ZapLine: A simple and effective method to
remove power line artifacts [Preprint]. https://doi.o... | 0.848878 | 0.871365 |
# Quantile regression
This example page shows how to use ``statsmodels``' ``QuantReg`` class to replicate parts of the analysis published in
* Koenker, Roger and Kevin F. Hallock. "Quantile Regression". Journal of Economic Perspectives, Volume 15, Number 4, Fall 2001, Pages 143–156
We are interested in the relatio... | github_jupyter | %matplotlib inline
import numpy as np
import pandas as pd
import statsmodels.api as sm
import statsmodels.formula.api as smf
import matplotlib.pyplot as plt
data = sm.datasets.engel.load_pandas().data
data.head()
mod = smf.quantreg("foodexp ~ income", data)
res = mod.fit(q=0.5)
print(res.summary())
quantiles = np.ar... | 0.613121 | 0.990357 |
```
import sys
import torch
sys.path.insert(0, "/home/zaid/Source/ALBEF/models")
from models.vit import VisionTransformer
from transformers import BertForMaskedLM, AutoTokenizer, BertConfig
import torch
tokenizer = AutoTokenizer.from_pretrained('bert-base-uncased')
text = "this is a random image"
lm = BertForMaskedLM(... | github_jupyter | import sys
import torch
sys.path.insert(0, "/home/zaid/Source/ALBEF/models")
from models.vit import VisionTransformer
from transformers import BertForMaskedLM, AutoTokenizer, BertConfig
import torch
tokenizer = AutoTokenizer.from_pretrained('bert-base-uncased')
text = "this is a random image"
lm = BertForMaskedLM(Bert... | 0.497559 | 0.856212 |
# 多层感知机
:label:`sec_mlp`
在 :numref:`chap_linear`中,
我们介绍了softmax回归( :numref:`sec_softmax`),
然后我们从零开始实现了softmax回归( :numref:`sec_softmax_scratch`),
接着使用高级API实现了算法( :numref:`sec_softmax_concise`),
并训练分类器从低分辨率图像中识别10类服装。
在这个过程中,我们学习了如何处理数据,如何将输出转换为有效的概率分布,
并应用适当的损失函数,根据模型参数最小化损失。
我们已经在简单的线性模型背景下掌握了这些知识,
现在我们可以开始对深度神经网络的探索,... | github_jupyter | %matplotlib inline
from mxnet import autograd, np, npx
from d2l import mxnet as d2l
npx.set_np()
x = np.arange(-8.0, 8.0, 0.1)
x.attach_grad()
with autograd.record():
y = npx.relu(x)
d2l.plot(x, y, 'x', 'relu(x)', figsize=(5, 2.5))
y.backward()
d2l.plot(x, x.grad, 'x', 'grad of relu', figsize=(5, 2.5))
with aut... | 0.404507 | 0.902266 |
# 机器学习纳米学位
## 监督学习
## 项目2: 为*CharityML*寻找捐献者
欢迎来到机器学习工程师纳米学位的第二个项目!在此文件中,有些示例代码已经提供给你,但你还需要实现更多的功能让项目成功运行。除非有明确要求,你无须修改任何已给出的代码。以**'练习'**开始的标题表示接下来的代码部分中有你必须要实现的功能。每一部分都会有详细的指导,需要实现的部分也会在注释中以'TODO'标出。请仔细阅读所有的提示!
除了实现代码外,你还必须回答一些与项目和你的实现有关的问题。每一个需要你回答的问题都会以**'问题 X'**为标题。请仔细阅读每个问题,并且在问题后的**'回答'**文字框中写出完整的答案。我们将根据你对问题的回... | github_jupyter | # 为这个项目导入需要的库
import numpy as np
import pandas as pd
from time import time
from IPython.display import display # 允许为DataFrame使用display()
# 导入附加的可视化代码visuals.py
import visuals as vs
# 为notebook提供更加漂亮的可视化
%matplotlib inline
# 导入人口普查数据
data = pd.read_csv("census.csv")
# 成功 - 显示第一条记录
display(data.head(n=1))
# TODO:总的记... | 0.208662 | 0.85555 |
```
import os
import time
import numpy as np
import matplotlib.pyplot as plt
import PIL
import torch
import torch.nn as nn
import torch.optim as optim
from torchvision import models
from torchvision.models import vgg16
from torchvision import datasets, transforms
print('pytorch version: {}'.format(torch.__version__)... | github_jupyter | import os
import time
import numpy as np
import matplotlib.pyplot as plt
import PIL
import torch
import torch.nn as nn
import torch.optim as optim
from torchvision import models
from torchvision.models import vgg16
from torchvision import datasets, transforms
print('pytorch version: {}'.format(torch.__version__))
pr... | 0.918891 | 0.785966 |
# 분산 분석 (ANOVA)
선형 회귀 분석의 결과가 어느 정도의 성능을 가지는지는 단순히 잔차 제곱합(RSS: Residula Sum of Square)으로 평가할 수 없다. 변수의 스케일이 달라지면 회귀 분석과 상관없이 잔차 제곱합도 같이 커지기 때문이다.
분산 분석(ANOVA:Analysis of Variance)은 종속 변수의 분산과 독립 변수의 분산간의 관계를 사용하여 선형 회귀 분석의 성능을 평가하고자 하는 방법이다. 분산 분석은 서로 다른 두 개의 선형 회귀 분석의 성능 비교에 응용할 수 있으며 독립 변수가 카테고리 변수인 경우 각 카테고리 값에 따른... | github_jupyter | from sklearn.datasets import make_regression
X0, y, coef = make_regression(n_samples=100, n_features=1, noise=20, coef=True, random_state=0)
dfX0 = pd.DataFrame(X0, columns=["X"])
dfX = sm.add_constant(dfX0)
dfy = pd.DataFrame(y, columns=["Y"])
df = pd.concat([dfX, dfy], axis=1)
model = sm.OLS.from_formula("Y ~ X", dat... | 0.616705 | 0.983565 |
## The Variational Quantum Thermalizer
Author: Jack Ceroni
```
# Starts by importing all of the necessary dependencies
import pennylane as qml
from matplotlib import pyplot as plt
import numpy as np
from numpy import array
import scipy
from scipy.optimize import minimize
import random
import math
from tqdm import tq... | github_jupyter | # Starts by importing all of the necessary dependencies
import pennylane as qml
from matplotlib import pyplot as plt
import numpy as np
from numpy import array
import scipy
from scipy.optimize import minimize
import random
import math
from tqdm import tqdm
import networkx as nx
import seaborn
# Defines all necessary ... | 0.617282 | 0.993216 |
(07:Releasing-and-versioning)=
# Releasing and versioning
<hr style="height:1px;border:none;color:#666;background-color:#666;" />
Previous chapters have focused on how to develop a Python package from scratch; by creating the Python source code, developing a testing framework, writing documentation, and then releasing... | github_jupyter |
## Version bumping
While we'll discuss the full workflow for releasing a new version of your package in **{numref}`07:Checklist-for-releasing-a-new-package-version`**, we first want to dicuss version bumping. That is, how to increment the version of your package when you're preparing a new release. This can be done m... | 0.898578 | 0.894421 |
```
import chex
import shinrl
import gym
import jax.numpy as jnp
import jax
```
# Create custom ShinEnv
This tutorial demonstrates how to create a custom environment.
We are going to implement the following simple two-state MDP.

You need to implement two classes,
1. A config cla... | github_jupyter | import chex
import shinrl
import gym
import jax.numpy as jnp
import jax
@chex.dataclass
class ExampleConfig(shinrl.EnvConfig):
dS: int = 2 # number of states
dA: int = 2 # number of actions
discount: float = 0.99 # discount factor
horizon: int = 3 # environment horizon
class ExampleEnv(shinrl.Shin... | 0.832713 | 0.917672 |
# Introduction to DSP with PYNQ
# 01: DSP & Python
> In this notebook we'll introduce some development tools for digital signal processing (DSP) using Python and JupyterLab. In our example application, we'll start by visualising some interesting signals — audio recordings of Scottish birds! We'll then use a few differ... | github_jupyter | from IPython.display import Audio
Audio("assets/birds.wav")
from scipy.io import wavfile
fs, aud_in = wavfile.read("assets/birds.wav")
fs
type(aud_in)
len(aud_in)
aud_in.dtype
import pandas as pd
import numpy as np
def to_time_dataframe(samples, fs):
"""Create a pandas dataframe from an ndarray of 16-bit tim... | 0.843702 | 0.990533 |
# Gaussian Process for contouring
This week we are going to use a gaussian process for interpolating between sample points. All we need is `geopandas`, `numpy`, `matplotlib`, `itertools`, `contextily`, and a few modules from `sklearn`
First we will import our packages
```
import geopandas as gpd
import numpy as np
i... | github_jupyter | import geopandas as gpd
import numpy as np
import matplotlib.pyplot as plt
from itertools import product
import contextily as ctx
%matplotlib inline
data = gpd.read_file("geochemistry_subset.shp")
data.drop(
index=[3, 16], inplace=True
)
x_values = np.linspace(min(data.geometry.x), max(data.geometry.x), num=50)
... | 0.630457 | 0.990282 |
# Advanced CPP Buildsystem Override
In this example we will show how we can wrap a complex CPP project by extending the buildsystem defaults provided, which will give us flexibility to configure the required bindings.
If you are looking for a basic implementation of the C++ wrapper, you can get started with the ["Sin... | github_jupyter | %%writefile Main.cpp
#include "seldon/SeldonModel.hpp"
class MyModelClass : public seldon::SeldonModelBase {
seldon::protos::SeldonMessage predict(seldon::protos::SeldonMessage &data) override {
return data;
}
};
SELDON_BIND_MODULE(CustomSeldonPackage, MyModelClass)
%%writefile CMakeLists.txt
cmake_... | 0.295433 | 0.955899 |
```
import sys
sys.path.append('../../')
from pyspark.sql import SparkSession
from pyspark.ml import Pipeline
from sparknlp.annotator import *
from sparknlp.common import *
from sparknlp.base import *
import zipfile
import os
from pathlib import Path
import urllib.request
spark = SparkSession.builder \
.appName(... | github_jupyter | import sys
sys.path.append('../../')
from pyspark.sql import SparkSession
from pyspark.ml import Pipeline
from sparknlp.annotator import *
from sparknlp.common import *
from sparknlp.base import *
import zipfile
import os
from pathlib import Path
import urllib.request
spark = SparkSession.builder \
.appName("ner... | 0.422505 | 0.601184 |
## Synthetic Dataset Generation
Here we demonstrate how to use our `genalog` package to generate synthetic documents with custom image degradation and upload the documents to an Azure Blob Storage.
<p float="left">
<img src="static/labeled_synthetic_pipeline.png" width="900" />
</p>
## Dataset file structure
Our... | github_jupyter | <ROOT FOLDER>/ #eg. synthetic-image-root
<SRC_DATASET_NAME> #eg. CNN-Dailymail-Stories
│
│───shared/ #common files shared across different dataset versions
│ │───train/
│ │ │───clean_text/
│ ... | 0.399226 | 0.903337 |
# Lesson 3 Class Exercises: Pandas Part 1
With these class exercises we learn a few new things. When new knowledge is introduced you'll see the icon shown on the right:
<span style="float:right; margin-left:10px; clear:both;"></span>
## Reminder
The first checkin-in of the project... | github_jupyter | # Lesson 3 Class Exercises: Pandas Part 1
With these class exercises we learn a few new things. When new knowledge is introduced you'll see the icon shown on the right:
<span style="float:right; margin-left:10px; clear:both;"></span>
## Reminder
The first checkin-in of the project... | 0.890634 | 0.988335 |
# Explore UK Crime Data with Pandas and GeoPandas
## Table of Contents
1. [Introduction to GeoPandas](#geopandas)<br>
2. [Getting ready](#ready)<br>
3. [London boroughs](#boroughs)<br>
2.1. [Load data](#load1)<br>
2.2. [Explore data](#explore1)<br>
4. [Crime data](#crime)<br>
3.1. [Load data](#load2)<br>... | github_jupyter | import pandas as pd
import geopandas as gpd
from shapely.geometry import Point, LineString, Polygon
import matplotlib.pyplot as plt
from datetime import datetime
%matplotlib inline
df = pd.DataFrame({'city': ['London','Manchester','Birmingham','Leeds','Glasgow'],
'population': [9787426, 2553379, 24... | 0.520253 | 0.977045 |
# Linear Support Vector Regressor with PolynomialFeatures
This Code template is for regression analysis using a Linear Support Vector Regressor(LinearSVR) based on the Support Vector Machine algorithm and feature transformation technique PolynomialFeatures in a pipeline. It provides a faster implementation than SVR bu... | github_jupyter | import warnings
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as se
from sklearn.preprocessing import PolynomialFeatures
from sklearn.pipeline import make_pipeline
from sklearn.model_selection import train_test_split
from sklearn.svm import LinearSVR
from sklearn.met... | 0.323487 | 0.992626 |
# Excitation Signals for Room Impulse Response Measurement
### Criteria
- Sufficient signal energy over the entire frequency range of interest
- Dynamic range
- Crest factor (peak-to-RMS value)
- Noise rejection (repetition and average, longer duration)
- Measurement duration
- Time variance
- Nonlinear distortion
##... | github_jupyter | import tools
import numpy as np
from scipy.signal import chirp, max_len_seq, freqz, fftconvolve, resample
import matplotlib.pyplot as plt
import sounddevice as sd
%matplotlib inline
def crest_factor(x):
"""Peak-to-RMS value (crest factor) of the signal x
Parameter
---------
x : array_like
signa... | 0.894 | 0.939526 |
#### Libraries & UDFs
```
from ttictoc import Timer
import pickle
import json
from ast import literal_eval
import numpy as np
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import SGDClassifier
from sklearn.model_selection import train_test_split, KFold, cr... | github_jupyter | from ttictoc import Timer
import pickle
import json
from ast import literal_eval
import numpy as np
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import SGDClassifier
from sklearn.model_selection import train_test_split, KFold, cross_val_score
from sklearn.... | 0.521959 | 0.694406 |
  一般通过 urllib 或 requests 库发送 HTTP 请求,下面将分别介绍两个库的使用(笔者更倾向于使用 requests 库)。在正式开始前,先设置两个 url(分别进行 `get` 和 `post` 请求):
```
get_url = 'http://httpbin.org/get'
post_url = 'http://httpbin.org/post'
```
> `httpbin.org` 提供了简单的 HTTP 请求和响应服务
## 2.1 urllib
  `urllib` 是 python 内置的 HTTP 请求库,包含以下几个模块:
- urllib.... | github_jupyter | get_url = 'http://httpbin.org/get'
post_url = 'http://httpbin.org/post'
import socket
from urllib import request
from urllib import parse
from urllib import error
from urllib import robotparser
from http import cookiejar
with request.urlopen('https://api.douban.com/v2/book/2224879') as f:
data = f.read() #获取网页内容
... | 0.36625 | 0.850469 |
# Chapter 6: Basic algorithms: searching and sorting
##6.1 Introduction
The implementation of algorithms requires the use of different programming techniques to mainly represent, consume and produce data items.
* Data structures allow us to properly conceptualize the structure and organization of the data that is m... | github_jupyter | #Linear search examples
def linear_search_first(values, target):
found = False
i = 0
while not found and i<len(values):
found = values[i] == target
i += 1
return found
def linear_search_last(values, target):
found = False
i = len(values)-1
while not found and i>=0:
found = values[i] == targe... | 0.319865 | 0.993487 |
---
<div class="alert alert-success" data-title="">
<h2><i class="fa fa-tasks" aria-hidden="true"></i> 사이킷런을 사용한 당뇨병 혈당 예측
</h2>
</div>
<img src = "https://res.cloudinary.com/grohealth/image/upload/$wpsize_!_cld_full!,w_1200,h_630,c_scale/v1588094388/How-to-Bring-Down-High-Blood-Sugar-Levels-1.png" width = "700" >... | github_jupyter | from sklearn.datasets import load_diabetes
diabetes = load_diabetes()
import pandas as pd
diabetes_df = pd.DataFrame(diabetes.data,
columns=diabetes.feature_names,
index=range(1,len(diabetes.data)+1))
diabetes_df['Target'] = diabetes.target
diabetes_df.head()
diabetes... | 0.577734 | 0.904861 |
# Stacked LSTMs for Time Series Classification
We'll now build a slightly deeper model by stacking two LSTM layers using the Quandl stock price data (see the stacked_lstm_with_feature_embeddings notebook for implementation details). Furthermore, we will include features that are not sequential in nature, namely indica... | github_jupyter | %matplotlib inline
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from datetime import datetime, date
from sklearn.metrics import mean_squared_error, roc_auc_score
from sklearn.preprocessing import minmax_scale
from keras.callbacks import ModelCheckpoint, EarlyStopping
from... | 0.808029 | 0.948728 |
# Computational Assignment 1
**Assigned Tuesday, 1-22-19.**, **Due Tuesday, 1-29-19.**
Congratulations on installing the Jupyter Notebook! Welcomne to your first computational assignment!
Beyond using this as a tool to understand physical chemistry, python and notebooks are actually used widely in scientific analys... | github_jupyter | 123+3483
917+215
print("Hello World!")
# This is a comment in python
# Set a variable
x = 1 + 7
# print the result of the variable
print(x)
# This is an example of a loop
# The colon is required on the first line
for i in (1,2,3,4):
# This indentation is required for loops
print ("Hello World, iteration"... | 0.118691 | 0.987946 |
# Web Scraping using BeautifulSoup
**BeautifulSoup**: Beautiful Soup is a Python package for parsing HTML and XML documents. It creates parse trees that is helpful to extract the data easily.<br>

"""
content: It is the raw HTML content.
lxml: The HTML parser we want to use.
A really nice thing about the BeautifulSoup library is that it is built
on the top of... | 0.344554 | 0.418697 |

[](https://colab.research.google.com/github/JohnSnowLabs/spark-nlp-workshop/blob/master/jupyter/annotation/english/spark-nlp-basics/playground-dataFrames.ipynb)
## 0. Colab Se... | github_jupyter | import os
# Install java
! apt-get update -qq
! apt-get install -y openjdk-8-jdk-headless -qq > /dev/null
os.environ["JAVA_HOME"] = "/usr/lib/jvm/java-8-openjdk-amd64"
os.environ["PATH"] = os.environ["JAVA_HOME"] + "/bin:" + os.environ["PATH"]
! java -version
# Install pyspark
! pip install --ignore-installed pyspar... | 0.498047 | 0.822688 |
# "Instability: Sliding Off a Hill"
> "A look at exponential growth in a simple dynamical system"
- toc: true
- branch: master
- badges: true
- comments: true
- categories: [physics, coronavirus]
- image: images/some_folder/your_image.png
- hide: true
- search_exclude: true
- metadata_key1: metadata_value1
- metadata_k... | github_jupyter | # "Instability: Sliding Off a Hill"
> "A look at exponential growth in a simple dynamical system"
- toc: true
- branch: master
- badges: true
- comments: true
- categories: [physics, coronavirus]
- image: images/some_folder/your_image.png
- hide: true
- search_exclude: true
- metadata_key1: metadata_value1
- metadata_k... | 0.596198 | 0.771542 |
# MVTecAD Hazelnut の SimpleCNN による結果
## Preset
```
# default packages
import logging
import os
import pathlib
import typing as t
# third party packages
import IPython
import matplotlib.pyplot as plt
import torch
import torch.cuda as tc
import torch.nn as nn
import torch.utils.data as td
import torchvision.transforms ... | github_jupyter | # default packages
import logging
import os
import pathlib
import typing as t
# third party packages
import IPython
import matplotlib.pyplot as plt
import torch
import torch.cuda as tc
import torch.nn as nn
import torch.utils.data as td
import torchvision.transforms as tv_transforms
# my packages
import src.data.datase... | 0.704872 | 0.696862 |
# Using qucat programmatically
In this example we study a typical circuit QED system consisting of a transmon qubit coupled to a resonator.
The first step is to import the objects we will be needing from qucat.
```
# Import the circuit builder
from qucat import Network
# Import the circuit components
from qucat impo... | github_jupyter | # Import the circuit builder
from qucat import Network
# Import the circuit components
from qucat import L,J,C,R
import numpy as np
cir = Network([
C(0,1,100e-15), # Add a capacitor between nodes 0 and 1, with a value of 100fF
J(0,1,8e-9), # Add a josephson junction, the value is given as Josephson inductance... | 0.639286 | 0.991724 |
```
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from pathlib import Path
import seaborn as sns
import plotly.express as px
import functions as funcs
import pyemma as pm
from pandas.api.types import CategoricalDtype
import matplotlib as mpl
import numpy as np
import functions as funcs
import ... | github_jupyter | import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from pathlib import Path
import seaborn as sns
import plotly.express as px
import functions as funcs
import pyemma as pm
from pandas.api.types import CategoricalDtype
import matplotlib as mpl
import numpy as np
import functions as funcs
import matp... | 0.345989 | 0.904059 |
<a href="https://colab.research.google.com/github/abidshafee/AI-Hub-TTF-Projects/blob/master/Multi_horizon_Time_Series_Forecasting_with_TFTs.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# Temporal Fusion Transformers for Multi-horizon Time Series... | github_jupyter | # Uses pip3 to install necessary packages
!pip3 install pyunpack wget patool plotly cufflinks --user
# Resets the IPython kernel to import the installed package.
import IPython
app = IPython.Application.instance()
app.kernel.do_shutdown(True) | 0.385028 | 0.989612 |
```
from google.colab import drive
drive.mount('/content/drive')
import os
import pickle
import os, sys
import PIL
from PIL import Image
import numpy as np
from PIL import Image as im
import gdown
!pip install wandb
!git clone https://github.com/Healthcare-Robotics/bodies-at-rest.git
!/content/bodies-at-rest/PressurePo... | github_jupyter | from google.colab import drive
drive.mount('/content/drive')
import os
import pickle
import os, sys
import PIL
from PIL import Image
import numpy as np
from PIL import Image as im
import gdown
!pip install wandb
!git clone https://github.com/Healthcare-Robotics/bodies-at-rest.git
!/content/bodies-at-rest/PressurePose/d... | 0.123432 | 0.068444 |
# Unit 5: Model-based Collaborative Filtering for **Rating** Prediction
In this unit, we change the approach towards CF from neighborhood-based to **model-based**. This means that we create and train a model for describing users and items instead of using the k nearest neighbors. The model parameters are latent repres... | github_jupyter | from collections import OrderedDict
import itertools
from typing import Dict, List, Tuple
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from recsys_training.data import Dataset
from recsys_training.evaluation import get_relevant_items
ml100k_ratings_filepath = '../../data/raw/ml-100k/u.data'
... | 0.655005 | 0.983231 |
<a href="http://cocl.us/pytorch_link_top">
<img src="https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/DL0110EN/notebook_images%20/Pytochtop.png" width="750" alt="IBM Product " />
</a>
<img src="https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/DL0110EN... | github_jupyter | # Import the libraries and set random seed
from torch import nn
import torch
import numpy as np
import matplotlib.pyplot as plt
from torch import nn,optim
from torch.utils.data import Dataset, DataLoader
torch.manual_seed(1)
# Create Data Class
class Data(Dataset):
# Constructor
def __init__(self, trai... | 0.950146 | 0.959307 |
# Performance Evaluation on PWCLeaderboards dataset
This notebook runs AxCell on the **PWCLeaderboards** dataset.
For the pipeline to work we need a running elasticsearch instance. Run `docker-compose up -d` from the `axcell` repository to start a new instance.
```
from axcell.helpers.datasets import read_tables_ann... | github_jupyter | from axcell.helpers.datasets import read_tables_annotations
from pathlib import Path
V1_URL = 'https://github.com/paperswithcode/axcell/releases/download/v1.0/'
PWC_LEADERBOARDS_URL = V1_URL + 'pwc-leaderboards.json.xz'
pwc_leaderboards = read_tables_annotations(PWC_LEADERBOARDS_URL)
# path to root directory containi... | 0.667906 | 0.752559 |
## Markov Chain Monte Carlo
Suppose we wish to draw samples from the posterior distribution
$$
p(x) = \int_\theta p(x|\theta) p (\theta) d \theta
$$
and that the computation of the normalization factor is intractable, due to the high dimensionality of the problem.
**Markov Chain Monte Carlo** is a sampling method whi... | github_jupyter | import torch
import pyro
import pyro.distributions as dist
pyro.set_rng_seed(1)
# define model
def scale(guess):
weight = pyro.sample("weight", dist.Normal(guess, 1.0))
measurement = pyro.sample("measurement", dist.Normal(weight, 0.75))
return measurement
# condition the model on a single observation
cond... | 0.737536 | 0.991178 |
```
import os
import cv2
import warnings
import numpy as np
import pandas as pd
import seaborn as sns
import tensorflow as tf
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix
from keras import backend as K
from keras import metrics
from s... | github_jupyter | import os
import cv2
import warnings
import numpy as np
import pandas as pd
import seaborn as sns
import tensorflow as tf
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix
from keras import backend as K
from keras import metrics
from sklea... | 0.717111 | 0.639018 |
```
# Make sure were on ray 1.9
from ray.data.grouped_dataset import GroupedDataset
#tag::start-ray-local[]
import ray
ray.init(num_cpus=20) # In theory auto sensed, in practice... eh
#end::start-ray-local[]
#tag::local_fun[]
def hi():
import os
import socket
return f"Running on {socket.gethostname()} in pi... | github_jupyter | # Make sure were on ray 1.9
from ray.data.grouped_dataset import GroupedDataset
#tag::start-ray-local[]
import ray
ray.init(num_cpus=20) # In theory auto sensed, in practice... eh
#end::start-ray-local[]
#tag::local_fun[]
def hi():
import os
import socket
return f"Running on {socket.gethostname()} in pid {o... | 0.522202 | 0.16807 |
# Credit Risk Resampling Techniques
```
import warnings
warnings.filterwarnings('ignore')
import numpy as np
import pandas as pd
from pathlib import Path
from collections import Counter
```
# Read the CSV and Perform Basic Data Cleaning
```
# load all of the data
file_path = Path('Resources/lending_data.csv')
loans... | github_jupyter | import warnings
warnings.filterwarnings('ignore')
import numpy as np
import pandas as pd
from pathlib import Path
from collections import Counter
# load all of the data
file_path = Path('Resources/lending_data.csv')
loans_df = pd.read_csv(file_path)
loans_df.head()
from sklearn.preprocessing import LabelEncoder
# co... | 0.648355 | 0.956309 |
### Model Diagnostics in Python
In this notebook, you will be trying out some of the model diagnostics you saw from Sebastian, but in your case there will only be two cases - either admitted or not admitted.
First let's read in the necessary libraries and the dataset.
```
import numpy as np
import pandas as pd
from ... | github_jupyter | import numpy as np
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import confusion_matrix, precision_score, recall_score, accuracy_score
from sklearn.model_selection import train_test_split
np.random.seed(42)
df = pd.read_csv('./admissions.csv')
df.head()
df[['prest_1', '... | 0.419053 | 0.959383 |
# Tableau Visualization
<img align="right" style="padding-right:10px;" src="figures_wk8/data_visualization.png" width=500><br>
**Outline**
* What is Data Visualization?
- Why is data visualization so important?
- Different types of Data Visualization
* Getting started with Tableau
- Student License
* Connect... | github_jupyter | # Tableau Visualization
<img align="right" style="padding-right:10px;" src="figures_wk8/data_visualization.png" width=500><br>
**Outline**
* What is Data Visualization?
- Why is data visualization so important?
- Different types of Data Visualization
* Getting started with Tableau
- Student License
* Connect... | 0.851706 | 0.985963 |
# Question 1 : Write a program to subtract two complex numbers in Python.
```
print("Subtraction of two complex numbers : ",(4+3j)-(3-7j))
```
# Question 2 : Write a program to find the fourth root of a number.
```
def fourth_root(x):
return x**(1/4)
num = int(input("Enter a number to find the fourth root: "))
p... | github_jupyter | print("Subtraction of two complex numbers : ",(4+3j)-(3-7j))
def fourth_root(x):
return x**(1/4)
num = int(input("Enter a number to find the fourth root: "))
print(fourth_root(num))
x = 5
y = 10
temp = x
x = y
y = temp
print('The value of x after swapping: {}'.format(x))
print('The value of y after swapping: {}... | 0.264263 | 0.968738 |
# Create PAO1 and PA14 compendia
This notebook is using the observation from the [exploratory notebook](../0_explore_data/cluster_by_accessory_gene.ipynb) to bin samples into PAO1 or PA14 compendia.
A sample is considered PAO1 if the median gene expression of PA14 accessory genes is 0 and PAO1 accessory genes in > 0.... | github_jupyter | %load_ext autoreload
%autoreload 2
%matplotlib inline
import os
import pandas as pd
import seaborn as sns
from textwrap import fill
import matplotlib.pyplot as plt
from scripts import paths, utils
# User param
# same_threshold: if median accessory expression of PAO1 samples > same_threshold then this sample is binned a... | 0.7011 | 0.953405 |
<a name="top"></a>Overview: Standard libraries
===
* [The Python standard library](#standard)
* [Importing modules](#importieren)
* [Maths](#math)
* [Files and folders](#ospath)
* [Statistics and random numbers](#statistics)
* [Exercise 06: Standard libraries](#uebung06)
**Learning Goals:** After this lecture... | github_jupyter | * ```sum()```
* ```len()```
* ...
You can find a list of directly available functions here: https://docs.python.org/2/library/functions.html
Additionally, there are a number of _standard libraries_ in python, which automatically get installed together with Python. This means, you already have these libraries on the c... | 0.807195 | 0.981471 |
Step 1: build a surface water network. You can "pickle" this, so it doesn't need to be repeated.
n = swn.SurfaceWaterNetwork.from_lines(gdf.geometry)
n.to_pickle("surface-water-network.pkl")
# then in a later session, skip the above and just do:
n = swn.SurfaceWaterNetwork.from_pickle("surface-water-network.pkl")
... | github_jupyter | import geopandas
import os
import swn
import flopy
import numpy as np
import time
n = swn.SurfaceWaterNetwork.from_pickle("surface-water-network.pkl")
os.getcwd()
sim_ws=os.path.join('..','zmodels','20210622_simulation','wairau_240_3')
model_name='wairau_240_3'
sim=flopy.mf6.MFSimulation.load(sim_ws=sim_ws)
gwf=sim.g... | 0.228329 | 0.734334 |
```
# Reload all src modules every time before executing the Python code typed
%load_ext autoreload
%autoreload 2
import os
import cProfile
import pandas as pd
import geopandas as geopd
import numpy as np
import multiprocessing as mp
import re
import gzip
try:
import cld3
except ModuleNotFoundError:
pass
import... | github_jupyter | # Reload all src modules every time before executing the Python code typed
%load_ext autoreload
%autoreload 2
import os
import cProfile
import pandas as pd
import geopandas as geopd
import numpy as np
import multiprocessing as mp
import re
import gzip
try:
import cld3
except ModuleNotFoundError:
pass
import pyc... | 0.264738 | 0.671659 |
#### IWSLT English MLM
This notebook shows a simple example of how to use the transformer provided by this repo for MLM.
We will use the IWSLT 2016 En dataset.
This is similar to BERT, except missing some other training tricks, such as NSP.
```
import numpy as np
from torchtext import data, datasets
from torchtext.... | github_jupyter | import numpy as np
from torchtext import data, datasets
from torchtext.data import get_tokenizer
import spacy
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.optim import Adam
import sys
sys.path.append("..")
from model.EncoderDecoder import TransformerEncoder
from model.utils import de... | 0.708818 | 0.900486 |
# Clustering Text Documents Using K-Means
We use publicly available dataset consists of 20 news groups(categories). In order to perform k-means, we need to convert text into numbers, which is done with the help TF-IDF. TF-IDF determines the importance of the words based on its frequency. These features are fed to K-me... | github_jupyter | from __future__ import division
import sklearn
from sklearn.datasets import fetch_20newsgroups
from sklearn.feature_extraction.text import TfidfTransformer, TfidfVectorizer
from sklearn.cluster import KMeans
from sklearn.preprocessing import Normalizer
from sklearn import metrics
import string
from string import punctu... | 0.388618 | 0.916857 |
# Simulation and figure generation for differential correlation
```
import scipy.stats as stats
import scipy.sparse as sparse
from scipy.stats import norm, gamma, poisson, nbinom
import numpy as np
from mixedvines.copula import Copula, GaussianCopula, ClaytonCopula, \
FrankCopula
from mixedvines.mixedvine impo... | github_jupyter | import scipy.stats as stats
import scipy.sparse as sparse
from scipy.stats import norm, gamma, poisson, nbinom
import numpy as np
from mixedvines.copula import Copula, GaussianCopula, ClaytonCopula, \
FrankCopula
from mixedvines.mixedvine import MixedVine
import matplotlib.pyplot as plt
import itertools
import ... | 0.568416 | 0.898277 |
```
#load packages
import numpy as np
import pandas as pd
import scipy
from PIL import Image
import glob
import os
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MultiLabelBinarizer
import matplotlib.pyplot as plt
from pandarallel import pandarallel
%matplotlib inline
import te... | github_jupyter | #load packages
import numpy as np
import pandas as pd
import scipy
from PIL import Image
import glob
import os
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MultiLabelBinarizer
import matplotlib.pyplot as plt
from pandarallel import pandarallel
%matplotlib inline
import tensor... | 0.493164 | 0.65339 |
# GRR Colab
```
%load_ext grr_colab.ipython_extension
import grr_colab
```
Specifying GRR Colab flags:
```
grr_colab.flags.FLAGS.set_default('grr_http_api_endpoint', 'http://localhost:8000/')
grr_colab.flags.FLAGS.set_default('grr_admin_ui_url', 'http://localhost:8000/')
grr_colab.flags.FLAGS.set_default('grr_auth_a... | github_jupyter | %load_ext grr_colab.ipython_extension
import grr_colab
grr_colab.flags.FLAGS.set_default('grr_http_api_endpoint', 'http://localhost:8000/')
grr_colab.flags.FLAGS.set_default('grr_admin_ui_url', 'http://localhost:8000/')
grr_colab.flags.FLAGS.set_default('grr_auth_api_user', 'admin')
grr_colab.flags.FLAGS.set_default('... | 0.182571 | 0.780788 |
```
#Author Jeffrey Tang
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow import keras
import re
import random
import warnings
from time import time
from collections import defaultdict
import spacy
import logging
logging.basicConfig... | github_jupyter | #Author Jeffrey Tang
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow import keras
import re
import random
import warnings
from time import time
from collections import defaultdict
import spacy
import logging
logging.basicConfig(for... | 0.528533 | 0.260002 |
# Modely s optimalizáciou hyperparametrov
```
import pandas as pd
import nltk
from nltk.corpus import stopwords
from sklearn import tree
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.model_selection import train_test_split
from skle... | github_jupyter | import pandas as pd
import nltk
from nltk.corpus import stopwords
from sklearn import tree
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from skl... | 0.558327 | 0.656452 |
<h1><center>K-Means: A macroscopic investigation using Python</center></h1>
In Machine Learning, the types of <b>Learning</b> can broadly be classified into three types: <b>1. Supervised Learning, 2. Unsupervised Learning and 3. Semi-supervised Learning</b>. Algorithms belonging to the family of <b>Unsupervised Learni... | github_jupyter |
# Dependencies
import pandas as pd
import numpy as np
from sklearn.cluster import KMeans
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import MinMaxScaler
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline
# Load the train and test datasets to create two DataFrames
... | 0.631026 | 0.976243 |
# Prepare Outputs CSV
* Then filter to the "downtown" list
```
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
```
## Read in Pano Metadata
```
df_meta = pd.read_csv('gsv_metadata.csv')
print(df_meta.shape)
df_meta['img_id'] = df_meta['name'].str.strip('.json')
meta_keep_cols = ['... | github_jupyter | import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
df_meta = pd.read_csv('gsv_metadata.csv')
print(df_meta.shape)
df_meta['img_id'] = df_meta['name'].str.strip('.json')
meta_keep_cols = ['img_id', 'lat', 'long', 'date']
df_meta = df_meta[meta_keep_cols]
df_meta.head()
df_meta[['lat', 'l... | 0.191177 | 0.602208 |
# Mixup / Label smoothing
```
%load_ext autoreload
%autoreload 2
%matplotlib inline
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
#export
from exp.nb_10 import *
path = datasets.untar_data(datasets.URLs.IMAGENETTE_160)
tfms = [make_rgb, ResizeFixed(128), t... | github_jupyter | %load_ext autoreload
%autoreload 2
%matplotlib inline
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"
#export
from exp.nb_10 import *
path = datasets.untar_data(datasets.URLs.IMAGENETTE_160)
tfms = [make_rgb, ResizeFixed(128), to_byte_tensor, to_float_tensor]... | 0.606498 | 0.923592 |
```
from IPython.display import Image
Image('../../Python_probability_statistics_machine_learning_2E.png',width=200)
```
<!-- new sections -->
<!-- Ensemble learning -->
<!-- - Machine Learning Flach, Ch.11 -->
<!-- - Machine Learning Mohri, pp.135- -->
<!-- - Data Mining Witten, Ch. 8 -->
With the exception of the ... | github_jupyter | from IPython.display import Image
Image('../../Python_probability_statistics_machine_learning_2E.png',width=200)
from sklearn.linear_model import Perceptron
p=Perceptron()
p
from sklearn.ensemble import BaggingClassifier
bp = BaggingClassifier(Perceptron(),max_samples=0.50,n_estimators=3)
bp
from sklearn.ensemble im... | 0.691289 | 0.990385 |
# Bootstrapping Without Re-training
## Setup
Suppose we have a model $f: \mathcal X \to [0, 1]$ which predicts probabilities for some binary classificaiton problem with labels in $\mathcal Y = \{0, 1\}$, and we have some test set $D_\text{test} = \mathbf{X} \in \mathcal X^{N_{\text{data}}}, \mathbf{y} \in \mathcal Y^{... | github_jupyter | # Bootstrapping Without Re-training
## Setup
Suppose we have a model $f: \mathcal X \to [0, 1]$ which predicts probabilities for some binary classificaiton problem with labels in $\mathcal Y = \{0, 1\}$, and we have some test set $D_\text{test} = \mathbf{X} \in \mathcal X^{N_{\text{data}}}, \mathbf{y} \in \mathcal Y^{... | 0.86319 | 0.985787 |
[](https://pythonista.io)
# Atributos de identificación *id* y *class*.
Es muy común que un elemento o un conjunto de elementos dentro de un documento HTML sean diferenciados del resto de los elementos.
## El atributo *id*.
Es posible distinguir a un elemento espec... | github_jupyter | <(elemento) id="(identificador)">
...
...
</(elemento)>
<(elemento_1) class="(identificador de clase)">
...
...
</(elemento_1)>
...
...
<(elemento_2) class="(identificador de clase)">
...
...
</(elemento_2)>
...
...
<(elemento_n) class="(identificador de clase)">
...
...
</(elemento_n)>... | 0.244904 | 0.896478 |
<img src="images/utfsm.png" alt="" width="200px" align="right"/>
# USM Numérica
## Errores en Python
### Objetivos
1. Aprender a diagosticar y solucionar errores comunes en python.
2. Aprender técnicas comunes de debugging.
## 0.1 Instrucciones
Las instrucciones de instalación y uso de un ipython notebook se encuentra... | github_jupyter | """
IPython Notebook v4.0 para python 3.0
Librerías adicionales: IPython, pdb
Contenido bajo licencia CC-BY 4.0. Código bajo licencia MIT.
(c) Sebastian Flores, Christopher Cooper, Alberto Rubio, Pablo Bunout.
"""
# Configuración para recargar módulos y librerías dinámicamente
%reload_ext autoreload
%autoreload 2
# C... | 0.270384 | 0.939803 |
Download employee_reviews.csv from https://www.kaggle.com/petersunga/google-amazon-facebook-employee-reviews
```
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
# show plots
%matplotlib inline
from scipy import stats
from keras.datasets import imdb
from keras.models import... | github_jupyter | import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
# show plots
%matplotlib inline
from scipy import stats
from keras.datasets import imdb
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM, Dropout
from keras.layers.embeddings imp... | 0.861989 | 0.788705 |
# Programmatically retrieving information about simulation tools registered with BioSimulators
[BioSimulators](https://biosimulators.org) contains extensive information about simulation software tools. This includes information about the model formats (e.g., CellML, SBML), modeling frameworks (e.g., flux balance, logi... | github_jupyter | import requests
response = requests.get('https://api.biosimulators.org/simulators/latest')
response.raise_for_status()
simulators = {simulator['id']: simulator for simulator in response.json()}
simulator = simulators['cobrapy']
import yaml
print(yaml.dump(simulator))
simulators_with_apis = {}
for id, simulator in... | 0.2359 | 0.987289 |
```
import torch.utils.data as utils
import torch.nn.functional as F
import torch
import torch.nn as nn
from torch.autograd import Variable
from torch.nn.parameter import Parameter
import numpy as np
import pandas as pd
import math
import time
import matplotlib.pyplot as plt
%matplotlib inline
print(torch.__version__)
... | github_jupyter | import torch.utils.data as utils
import torch.nn.functional as F
import torch
import torch.nn as nn
from torch.autograd import Variable
from torch.nn.parameter import Parameter
import numpy as np
import pandas as pd
import math
import time
import matplotlib.pyplot as plt
%matplotlib inline
print(torch.__version__)
def ... | 0.787073 | 0.69867 |
# Independent Component Analysis Lab
In this notebook, we'll use Independent Component Analysis to retrieve original signals from three observations each of which contains a different mix of the original signals. This is the same problem explained in the ICA video.
## Dataset
Let's begin by looking at the dataset we ... | github_jupyter | import numpy as np
import wave
# Read the wave file
mix_1_wave = wave.open('ICA mix 1.wav','r')
mix_1_wave.getparams()
264515/44100
# Extract Raw Audio from Wav File
signal_1_raw = mix_1_wave.readframes(-1)
signal_1 = np.fromstring(signal_1_raw, 'Int16')
'length: ', len(signal_1) , 'first 100 elements: ',signal_1[... | 0.554229 | 0.978219 |
### Техники оптимизации С++ программ.
<br />
##### Как настроить машину под измерение performance
* Очистите ваш компьютер от стороннего софта настолько насколько это возможно (хотя бы на время замеров)
* Никаких баз данных
* Ваших личных крутящихся nginx
* Антивирусов
* Лишних демонов / сервисов
... | github_jupyter | echo 0 | sudo tee /proc/sys/kernel/randomize_va_space
taskset -c 2 myprogram
<br />
msvc:
https://docs.microsoft.com/en-us/cpp/build/reference/o-options-optimize-code?view=vs-2019
Аналоги: `/Od`, `/O1`, `/O2`, `/Os` + доп. варинты (см. ссылку)
<br />
##### Профилировка на примере домашнего задания
**Visual st... | 0.26086 | 0.930868 |
# Scheduling Multipurpose Batch Processes using State-Task Networks
Keywords: cbc usage, state-task networks, gdp, disjunctive programming, batch processes
The State-Task Network (STN) is an approach to modeling multipurpose batch process for the purpose of short term scheduling. It was first developed by Kondili, et... | github_jupyter | %matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from IPython.display import display, HTML
import shutil
import sys
import os.path
if not shutil.which("pyomo"):
!pip install -q pyomo
assert(shutil.which("pyomo"))
if not (shutil.which("cbc") or os.path.isfile("cbc"... | 0.307878 | 0.897291 |
# Valuación de opciones asiáticas
- Las opciones que tratamos la clase pasada dependen sólo del valor del precio del subyacente $S_t$, en el instante que se ejerce.
- Cambios bruscos en el precio, cambian que la opción esté *in the money* a estar *out the money*.
- **Posibilidad de evitar esto** $\longrightarrow$ su... | github_jupyter | #importar los paquetes que se van a usar
import pandas as pd
import pandas_datareader.data as web
import numpy as np
import datetime
import matplotlib.pyplot as plt
import scipy.stats as st
import seaborn as sns
%matplotlib inline
#algunas opciones para Pandas
pd.set_option('display.notebook_repr_html', True)
pd.set_op... | 0.243193 | 0.959307 |
```
import os
from keras import regularizers
from keras.layers import Dense, Input
from keras.models import Model
import mne
import numpy as np
raw_dir = 'D:\\NING - spindle\\training set\\'
os.chdir(raw_dir)
import matplotlib.pyplot as plt
%matplotlib inline
raw_names = ['suj11_l2nap_day2.fif','suj11_l5nap_day1.fif',
... | github_jupyter | import os
from keras import regularizers
from keras.layers import Dense, Input
from keras.models import Model
import mne
import numpy as np
raw_dir = 'D:\\NING - spindle\\training set\\'
os.chdir(raw_dir)
import matplotlib.pyplot as plt
%matplotlib inline
raw_names = ['suj11_l2nap_day2.fif','suj11_l5nap_day1.fif',
... | 0.631594 | 0.455622 |
数据网站,https://www.temperaturerecord.org
下载数据
```
> wget https://www.climatelevels.org/files/temperature_dataset.xlsx
```
## Library
```
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import torch
import torch.nn as nn
from torch.autograd import Variable
from sklearn.preprocessing import MinMax... | github_jupyter | > wget https://www.climatelevels.org/files/temperature_dataset.xlsx
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import torch
import torch.nn as nn
from torch.autograd import Variable
from sklearn.preprocessing import MinMaxScaler
data = pd.read_csv('data/temperature_dataset.csv')
training_... | 0.772531 | 0.938124 |
___
<a href='https://github.com/ai-vithink'> <img src='https://avatars1.githubusercontent.com/u/41588940?s=200&v=4' /></a>
___
# Regression Plots
Seaborn has many built-in capabilities for regression plots, however we won't really discuss regression until the machine learning section of the course, so we will only c... | github_jupyter | import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline
from IPython.display import HTML
HTML('''<script>
code_show_err=false;
function code_toggle_err() {
if (code_show_err){
$('div.output_stderr').hide();
} else {
$('div.output_stderr').show();
}
code_show_err = !code_show_err
}
$( document )... | 0.457137 | 0.949669 |
# 14 Linear Algebra – Students (1)
## Motivating problem: Two masses on three strings
Two masses $M_1$ and $M_2$ are hung from a horizontal rod with length $L$ in such a way that a rope of length $L_1$ connects the left end of the rod to $M_1$, a rope of length $L_2$ connects $M_1$ and $M_2$, and a rope of length $L_3$... | github_jupyter | import numpy as np
np.linalg?
A = np.array([
[1, 0, 0],
[0, 1, 0],
[0, 0, 2]
])
b = np.array([1, 0, 1])
for i in range(A.shape[0]):
terms = []
for j in range(A.shape[1]):
terms.append("{1} x[{0}]".format(i, A[i, j]))
print(" + ".join(terms), "=", b[i])
Isquare = np.arr... | 0.100095 | 0.994347 |
# Funciones
## Función
**Función.** Una función en `Python` es una pieza de código reutilizable que solo se ejecuta cuando es llamada.
Se define usando la palabra reservada `def` y estructura general es la siguiente:
```
def nombre_función(input1, input2, ..., inputn):
cuerpo de la función
return output
`... | github_jupyter | def nombre_función(input1, input2, ..., inputn):
cuerpo de la función
return output
def mi_primera_funcion():
print("Hola")
mi_primera_funcion()
def holaMundo():
print("Hola mundo")
holaMundo()
# Esta función, cuando es llamada, imprime "Hola mundo", pero no devuelve nada.
# Declaramos la función:... | 0.468304 | 0.984501 |
# Moon Phase
```
import datetime as dt
def julian(year, month, day):
a = (14 - month) / 12.0
y = year + 4800 - a
m = (12 * a) - 3 + month
return (
day + (153 * m + 2) / 5.0 + (365 * y) + y / 4.0 - y / 100.0 + y / 400.0 - 32045
)
moon_phase = {
1.84566: "🌑", # new
5.53699: "🌒"... | github_jupyter | import datetime as dt
def julian(year, month, day):
a = (14 - month) / 12.0
y = year + 4800 - a
m = (12 * a) - 3 + month
return (
day + (153 * m + 2) / 5.0 + (365 * y) + y / 4.0 - y / 100.0 + y / 400.0 - 32045
)
moon_phase = {
1.84566: "🌑", # new
5.53699: "🌒", # waxing cresce... | 0.430147 | 0.867822 |
<a href="https://colab.research.google.com/github/Irene-kim/Cyberbullying-Detection-for-Women-/blob/master/codes)without_ELMo.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/gdrive')
%tensorfl... | github_jupyter | from google.colab import drive
drive.mount('/content/gdrive')
%tensorflow_version 1.x
import numpy as np
import pandas as pd
import os
import random
import matplotlib.pyplot as plt
%matplotlib inline
from sklearn.metrics import classification_report, confusion_matrix
from sklearn.model_selection import KFold
from skle... | 0.536799 | 0.7335 |
# "The Hitchhiker's Guide to Neural Networks - An Introduction"
> "An introduction to neural networks for beginners."
- toc: false
- branch: master
- author: Yashvardhan Jain
- badges: false
- comments: false
- categories: [deep learning]
- image: images/post1_main.jpg
- hide: false
- search_exclude: true
> **Don't P... | github_jupyter | import math
import os
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
def preprocess():
# Reading data from the CSV file
data = pd.read_csv(os.path.join(
os.path.dirname(
__file__), 'train.csv'),
header=0... | 0.761804 | 0.984396 |
<a href="https://colab.research.google.com/github/portkata/KataGo/blob/master/JBX2010_template_60bKatago_bot_1po_OGS.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
Please click "COPY to Drive" on top and save as your own copy first. Please also dow... | github_jupyter | !nvidia-smi
KATAGO_BACKEND="CUDA"
%cd /content
!apt install sudo
!sudo apt remove cmake
!sudo apt purge --auto-remove cmake
!mkdir ~/temp
%cd ~/temp
!wget https://cmake.org/files/v3.12/cmake-3.12.3-Linux-x86_64.sh
!sudo mkdir /opt/cmake
!sudo sh cmake-3.12.3-Linux-x86_64.sh --prefix=/opt/cmake --skip-license
!sudo rm ... | 0.194139 | 0.4953 |
<a href="https://colab.research.google.com/github/tbbcoach/DS-Unit-2-Linear-Models/blob/master/Copy_of_LS_DS_214_solution.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
Lambda School Data Science
*Unit 2, Sprint 1, Module 4*
---
```
%%capture
im... | github_jupyter | %%capture
import sys
# If you're on Colab:
if 'google.colab' in sys.modules:
DATA_PATH = 'https://raw.githubusercontent.com/LambdaSchool/DS-Unit-2-Linear-Models/master/data/'
!pip install category_encoders==2.*
# If you're working locally:
else:
DATA_PATH = '../data/'
import pandas as pd
import numpy as ... | 0.407216 | 0.975343 |
From:
- [BERT Fine-Tuning Tutorial with PyTorch · Chris McCormick](http://mccormickml.com/2019/07/22/BERT-fine-tuning/)
- [huggingface/pytorch-transformers: 👾 A library of state-of-the-art pretrained models for Natural Language Processing (NLP)](https://github.com/huggingface/pytorch-transformers)
Fine-Tuning:
- E... | github_jupyter | import torch
from torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler
from keras.preprocessing.sequence import pad_sequences
from sklearn.model_selection import train_test_split
from pytorch_transformers import BertTokenizer, BertConfig
from pytorch_transformers import BertForSequenceCla... | 0.832407 | 0.949106 |
# Ensemble Models
## Hypertuning
## Imports
```
## Basic Imports
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
sns.set()
# NLP processing
import spacy
nlp = spacy.load('en_core_web_sm')
# sklearn models
from sklearn.metrics import accuracy_score, classification_repo... | github_jupyter | ## Basic Imports
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
sns.set()
# NLP processing
import spacy
nlp = spacy.load('en_core_web_sm')
# sklearn models
from sklearn.metrics import accuracy_score, classification_report, confusion_matrix
from sklearn.feature_extracti... | 0.520009 | 0.832237 |
# Creating an advanced interactive map with Bokeh
This page demonstrates, how it is possible to visualize any kind of geometries (normal geometries + Multi-geometries) in Bokeh and add a legend into the map which is one of the key elements of a good map.
```
from bokeh.palettes import YlOrRd as palette #Spectral6 as... | github_jupyter | from bokeh.palettes import YlOrRd as palette #Spectral6 as palette
from bokeh.plotting import figure, save
from bokeh.models import ColumnDataSource, HoverTool, LogColorMapper
from bokeh.palettes import RdYlGn10 as palette
import geopandas as gpd
import pysal as ps
import numpy as np
# Filepaths
fp = r"/home/geo/dat... | 0.750278 | 0.939913 |
<a href="https://colab.research.google.com/github/probml/probml-notebooks/blob/main/notebooks/genmo_types_implicit_explicit.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# Types of models: implicit or explicit models
Author: Mihaela Rosca
We us... | github_jupyter | import random
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import scipy
sns.set(rc={"lines.linewidth": 2.8}, font_scale=2)
sns.set_style("whitegrid")
# We implement our own very simple mixture, relying on scipy for the mixture
# components.
class SimpleGaussianMixture(object):
def __ini... | 0.850593 | 0.986244 |
# Advanced Recommender Systems with Python
Welcome to the code notebook for creating Advanced Recommender Systems with Python. This is an optional lecture notebook for you to check out. Currently there is no video for this lecture because of the level of mathematics used and the heavy use of SciPy here.
Recommendati... | github_jupyter | import numpy as np
import pandas as pd
column_names = ['user_id', 'item_id', 'rating', 'timestamp']
df = pd.read_csv('u.data', sep='\t', names=column_names)
df.head()
movie_titles = pd.read_csv("Movie_Id_Titles")
movie_titles.head()
df = pd.merge(df,movie_titles,on='item_id')
df.head()
n_users = df.user_id.nunique... | 0.52683 | 0.991456 |
```
import tensorflow as tf
print(tf.__version__)
```
在深度学习中,我们通常会频繁地对数据进行操作。作为动手学深度学习的基础,本节将介绍如何对内存中的数据进行操作。
在tensorflow中,tensor是一个类,也是存储和变换数据的主要工具。如果你之前用过NumPy,你会发现tensor和NumPy的多维数组非常类似。然而,tensor提供GPU计算和自动求梯度等更多功能,这些使tensor更加适合深度学习。
## 2.2.1 Create NDArray
我们先介绍NDArray的最基本功能,我们用arange函数创建一个行向量。
```
x = tf.consta... | github_jupyter | import tensorflow as tf
print(tf.__version__)
x = tf.constant(range(12))
print(x.shape)
x
x.shape
len(x)
X = tf.reshape(x,(3,4))
X
tf.zeros((2,3,4))
tf.ones((3,4))
Y = tf.constant([[2,1,4,3],[1,2,3,4],[4,3,2,1]])
Y
tf.random.normal(shape=[3,4], mean=0, stddev=1)
X + Y
X * Y
X / Y
Y = tf.cast(Y, tf.float32)... | 0.49585 | 0.983118 |
```
%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
from numpy import mean
```
# Reflect Tables into SQLAlchemy ORM
```
# Python SQL toolkit and Object Relational Mapper
import sqlalchemy
from sql... | 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
from numpy import mean
# Python SQL toolkit and Object Relational Mapper
import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlal... | 0.722331 | 0.872293 |
```
# NBVAL_SKIP
%matplotlib inline
import logging
logging.basicConfig(level=logging.CRITICAL)
# NBVAL_SKIP
import torch
import pytorch3d
from pytorch3d.ops import sample_points_from_meshes
```
# Creating Protein Meshes in Graphein & 3D Visualisation
Graphein provides functionality to create meshes of protein surface... | github_jupyter | # NBVAL_SKIP
%matplotlib inline
import logging
logging.basicConfig(level=logging.CRITICAL)
# NBVAL_SKIP
import torch
import pytorch3d
from pytorch3d.ops import sample_points_from_meshes
from graphein.protein.config import ProteinMeshConfig
config = ProteinMeshConfig()
config.dict()
# NBVAL_SKIP
from graphein.protein.... | 0.448668 | 0.891952 |
# Introduction to Python - part 1
Author: Manuel Dalcastagnè. This work is licensed under a CC Attribution 3.0 Unported license (http://creativecommons.org/licenses/by/3.0/).
Original material, "Introduction to Python programming", was created by J.R. Johansson under the CC Attribution 3.0 Unported license (http://cr... | github_jupyter | # variable assignments
x = 1.0
my_variable = 12.2
type(x)
x = 1
type(x)
# integers
x = 1
type(x)
# float
x = 1.0
type(x)
# boolean
b1 = True
b2 = False
type(b1)
# complex numbers: note the use of `j` to specify the imaginary part
x = 1.0 - 1.0j
type(x)
# string
s = "Hello world"
type(s)
# length of the string: the ... | 0.376165 | 0.926304 |
# Using TensorRT to Optimize Caffe Models in Python
TensorRT 4.0 includes support for a Python API to load in and optimize Caffe models, which can then be executed and stored.
First, we import TensorRT.
```
import tensorrt as trt
```
We use PyCUDA to transfer data to/from the GPU and NumPy to store data.
```
impor... | github_jupyter | import tensorrt as trt
import pycuda.driver as cuda
import pycuda.autoinit
import numpy as np
from random import randint
from PIL import Image
from matplotlib.pyplot import imshow #to show test case
from tensorrt import parsers
G_LOGGER = trt.infer.ConsoleLogger(trt.infer.LogSeverity.ERROR)
INPUT_LAYERS = ['data']... | 0.355104 | 0.979687 |
# Riskfolio-Lib Tutorial:
<br>__[Financionerioncios](https://financioneroncios.wordpress.com)__
<br>__[Orenji](https://www.orenj-i.net)__
<br>__[Riskfolio-Lib](https://riskfolio-lib.readthedocs.io/en/latest/)__
<br>__[Dany Cajas](https://www.linkedin.com/in/dany-cajas/)__
<a href='https://ko-fi.com/B0B833SXD' target='... | github_jupyter | import numpy as np
import pandas as pd
import yfinance as yf
import warnings
warnings.filterwarnings("ignore")
pd.options.display.float_format = '{:.4%}'.format
# Date range
start = '2016-01-01'
end = '2019-12-30'
# Tickers of assets
assets = ['JCI', 'TGT', 'CMCSA', 'CPB', 'MO', 'APA', 'MMC', 'JPM',
'ZION'... | 0.792906 | 0.936692 |
# Session 12: Model selection and cross-validation
In this combined teaching module and exercise set we will investigate how to optimize the choice of hyperparameters using model validation and cross validation. As an aside, we will see how to build machine learning models using a formalized pipeline from preprocessed... | github_jupyter | import warnings
from sklearn.exceptions import ConvergenceWarning
warnings.filterwarnings(action='ignore', category=ConvergenceWarning)
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from IPython.display import YouTubeVideo
YouTubeVideo('9gkjahx_SWo', width=640, height=... | 0.795102 | 0.994467 |
```
import sys
sys.path.append("../")
```
## Analysis of n - we are keeping mean time of arrival as 100 and T_k as 1000 milliseconds
```
import pandas as pd
mean_percent_longest_chain = []
mean_orphans_received = []
mean_blocks = []
x_axis = []
df = pd.read_csv("../final_results/results_1.dump")
df['percent_reaching_... | github_jupyter | import sys
sys.path.append("../")
import pandas as pd
mean_percent_longest_chain = []
mean_orphans_received = []
mean_blocks = []
x_axis = []
df = pd.read_csv("../final_results/results_1.dump")
df['percent_reaching_longest_chain'] = df['<in longest chain>']*100/df["<peer's blocks>"]
df
mean_percent_longest_chain.appen... | 0.238905 | 0.700178 |
### Example 4: Burgers' equation
Now that we have seen how to construct the non-linear convection and diffusion examples, we can combine them to form Burgers' equations. We again create a set of coupled equations which are actually starting to form quite complicated stencil expressions, even if we are only using a low... | github_jupyter | from examples.cfd import plot_field, init_hat
import numpy as np
%matplotlib inline
# Some variable declarations
nx = 41
ny = 41
nt = 120
c = 1
dx = 2. / (nx - 1)
dy = 2. / (ny - 1)
sigma = .0009
nu = 0.01
dt = sigma * dx * dy / nu
#NBVAL_IGNORE_OUTPUT
# Assign initial conditions
u = np.empty((nx, ny))
v = np.empty((... | 0.715325 | 0.987387 |
# Inputs and outputs
## Outputs
When a cell of a Jupyter Notebook is executed, the return value (the result) of the last statement is printed below the cell. However,
if the last statement does not have a return value (e.g. assigning a value to a variable does not have one), there will be no
output.
Thus, working wi... | github_jupyter | print("Hello")
print(42)
name = "Joey"
print(name)
name = "Joey"
lastname = "Ramone"
print(name, lastname)
i = input("Please enter a number:")
print(i)
i = input("Please insert a number: ")
print(i) | 0.119344 | 0.992809 |
# Predicting Boston Housing Prices
## Using XGBoost in SageMaker (Batch Transform)
_Deep Learning Nanodegree Program | Deployment_
---
As an introduction to using SageMaker's High Level Python API we will look at a relatively simple problem. Namely, we will use the [Boston Housing Dataset](https://www.cs.toronto.ed... | github_jupyter | %matplotlib inline
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.datasets import load_boston
import sklearn.model_selection
import sagemaker
from sagemaker import get_execution_role
from sagemaker.amazon.amazon_estimator import get_image_uri
from sagemaker.predictor ... | 0.499268 | 0.989378 |
# Tarea 6. Distribución óptima de capital y selección de portafolios.
<img style="float: right; margin: 0px 0px 15px 15px;" src="https://upload.wikimedia.org/wikipedia/en/f/f3/SML-chart.png" width="400px" height="400px" />
**Resumen.**
> En esta tarea, tendrás la oportunidad de aplicar los conceptos y las herramienta... | github_jupyter | # Importamos pandas y numpy
import pandas as pd
import numpy as np
# Resumen en base anual de rendimientos esperados y volatilidades
annual_ret_summ = pd.DataFrame(columns=['Bonos', 'Acciones', 'Desarrollado', 'Emergente', 'Privados', 'Real', 'Libre_riesgo'], index=['Media', 'Volatilidad'])
annual_ret_summ.loc['Media']... | 0.228156 | 0.913252 |
# Keras Word Embeddings
```
%load_ext autoreload
%autoreload 2
from keras.models import load_model
from keras.models import Sequential, load_model
from keras.layers import LSTM, Dense, Dropout, Embedding, Masking
from keras.optimizers import Adam
from keras.utils import Sequence
from keras.preprocessing.text import To... | github_jupyter | %load_ext autoreload
%autoreload 2
from keras.models import load_model
from keras.models import Sequential, load_model
from keras.layers import LSTM, Dense, Dropout, Embedding, Masking
from keras.optimizers import Adam
from keras.utils import Sequence
from keras.preprocessing.text import Tokenizer
from sklearn.utils i... | 0.705684 | 0.679335 |
Sveučilište u Zagrebu
Fakultet elektrotehnike i računarstva
## Strojno učenje 2020/2021
http://www.fer.unizg.hr/predmet/su
------------------------------
### Laboratorijska vježba 2: Linearni diskriminativni modeli i logistička regresija
*Verzija: 1.4
Zadnji put ažurirano: 22. 10. 2020.*
(c) 2015-2020 Ja... | github_jupyter | # Učitaj osnovne biblioteke...
import sklearn
import matplotlib.pyplot as plt
%pylab inline
def plot_2d_clf_problem(X, y, h=None):
'''
Plots a two-dimensional labeled dataset (X,y) and, if function h(x) is given,
the decision surfaces.
'''
assert X.shape[1] == 2, "Dataset is not two-dimensional"
... | 0.623721 | 0.836688 |
```
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import omegaconf
import torch
import torch.optim as optim
import mbrl.models as models
import mbrl.util.replay_buffer as replay_buffer
device = torch.device("cuda:0")
%load_ext autoreload
%autoreload 2
%matplotlib inline
mpl.rcParams['f... | github_jupyter | import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import omegaconf
import torch
import torch.optim as optim
import mbrl.models as models
import mbrl.util.replay_buffer as replay_buffer
device = torch.device("cuda:0")
%load_ext autoreload
%autoreload 2
%matplotlib inline
mpl.rcParams['figur... | 0.608943 | 0.594728 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.