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
# Notes on linux This is a simple note, I don't have clear index to arrage the content in this note. I just take the notes which I may be easy forget. ** Author: Yue-Wen FANG ** ** Contact: fyuewen@gmail.com ** ** Revision history: created in 16th, December 2017, at Kyoto ** ## 1. 配置ssh连接 Professionally speaki...
github_jupyter
# Notes on linux This is a simple note, I don't have clear index to arrage the content in this note. I just take the notes which I may be easy forget. ** Author: Yue-Wen FANG ** ** Contact: fyuewen@gmail.com ** ** Revision history: created in 16th, December 2017, at Kyoto ** ## 1. 配置ssh连接 Professionally speaki...
0.480479
0.296311
``` #data https://archive.ics.uci.edu/ml/datasets/sms+spam+collection import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import nltk %matplotlib inline plt.style.use('ggplot') nltk.download() messages = [line.rstrip() for line in open('SMSSpamCollection')] print(len(messages)) messages[10] for me...
github_jupyter
#data https://archive.ics.uci.edu/ml/datasets/sms+spam+collection import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import nltk %matplotlib inline plt.style.use('ggplot') nltk.download() messages = [line.rstrip() for line in open('SMSSpamCollection')] print(len(messages)) messages[10] for messag...
0.483892
0.395659
submitted by Tarang Ranpara ## Part 1 - training CBOW and Skipgram models ``` # load library gensim (contains word2vec implementation) import gensim # ignore some warnings (probably caused by gensim version) import warnings warnings.filterwarnings("ignore", category=DeprecationWarning) import multiprocessing cores...
github_jupyter
# load library gensim (contains word2vec implementation) import gensim # ignore some warnings (probably caused by gensim version) import warnings warnings.filterwarnings("ignore", category=DeprecationWarning) import multiprocessing cores = multiprocessing.cpu_count() # Count the number of cores from tqdm import tqd...
0.322846
0.513363
# TensorFlow Basics Import the library: ``` import tensorflow as tf print(tf.__version__) ``` ### Simple Constants Let's show how to create a simple constant with Tensorflow, which TF stores as a tensor object: ``` hello = tf.constant('Hello World') type(hello) x = tf.constant(100) type(x) ``` ### Running Session...
github_jupyter
import tensorflow as tf print(tf.__version__) hello = tf.constant('Hello World') type(hello) x = tf.constant(100) type(x) sess = tf.Session() sess.run(hello) type(sess.run(hello)) sess.run(x) type(sess.run(x)) x = tf.constant(2) y = tf.constant(3) with tf.Session() as sess: print('Operations with Constants') ...
0.47171
0.979433
``` import numpy as np import pickle from itertools import chain from collections import OrderedDict from sklearn.model_selection import train_test_split from sklearn.decomposition import PCA import matplotlib.pylab as plt from copy import deepcopy import torch import torch.nn as nn import torch.optim as optim from tor...
github_jupyter
import numpy as np import pickle from itertools import chain from collections import OrderedDict from sklearn.model_selection import train_test_split from sklearn.decomposition import PCA import matplotlib.pylab as plt from copy import deepcopy import torch import torch.nn as nn import torch.optim as optim from torch.a...
0.552781
0.603873
``` import pandas as pd import numpy as np import warnings from sklearn.preprocessing import StandardScaler, MinMaxScaler import matplotlib.pyplot as plt from sklearn.metrics import confusion_matrix from tqdm import tqdm, tqdm_notebook warnings.filterwarnings('ignore') # BEWARE, ignoreing warnings is not always a good...
github_jupyter
import pandas as pd import numpy as np import warnings from sklearn.preprocessing import StandardScaler, MinMaxScaler import matplotlib.pyplot as plt from sklearn.metrics import confusion_matrix from tqdm import tqdm, tqdm_notebook warnings.filterwarnings('ignore') # BEWARE, ignoreing warnings is not always a good ide...
0.635109
0.79653
``` %matplotlib inline from pathlib import Path import dask.dataframe as dd import pandas as pd YEAR = 2019 slookup = pd.read_csv('ghcn_mos_lookup.csv') ``` # GHCN ``` names = ['ID', 'DATE', 'ELEMENT', 'DATA_VALUE', 'M-FLAG', 'Q-FLAG', 'S-FLAG', 'OBS-TIME'] ds = dd.read_csv(f's3://noaa-ghcn-pds/csv/{YEAR}.csv', st...
github_jupyter
%matplotlib inline from pathlib import Path import dask.dataframe as dd import pandas as pd YEAR = 2019 slookup = pd.read_csv('ghcn_mos_lookup.csv') names = ['ID', 'DATE', 'ELEMENT', 'DATA_VALUE', 'M-FLAG', 'Q-FLAG', 'S-FLAG', 'OBS-TIME'] ds = dd.read_csv(f's3://noaa-ghcn-pds/csv/{YEAR}.csv', storage_options={'anon...
0.346652
0.587322
This notebook is based off of the [SGD mnist](https://github.com/fastai/fastai/blob/master/courses/ml1/lesson4-mnist_sgd.ipynb) lesson from fastai In this notebook we will start with a pytorch neural network implementation of logitistic regression and then program it ourselves # Imports and Paths ``` %load_ext auto...
github_jupyter
%load_ext autoreload %autoreload 2 %matplotlib inline from data_sci.imports import * from data_sci.utilities import * from data_sci.fastai import * from data_sci.fastai.dataset import * from data_sci.fastai.metrics import * from data_sci.fastai.torch_imports import * from data_sci.fastai.model import * import torch.nn...
0.806777
0.987841
# Analytical solution of the 1-D diffusion equation As discussed in class, many physical problems encountered in the field of geosciences can be described with a diffusion equation, i.e. _relating the rate of change in time to the curvature in space_: $$\frac{\partial u}{\partial t} = \kappa \frac{\partial^2 u}{\part...
github_jupyter
# first some basic Python imports import matplotlib.pyplot as plt import numpy as np import scipy.special from ipywidgets import interactive plt.rcParams['figure.figsize'] = [8., 5.] plt.rcParams['font.size'] = 16 from IPython.display import Audio, display def plot_steady_state(n=1): # set number of lines with n ...
0.470493
0.994396
# LIBRARIES ``` import matplotlib.pyplot as plt import pylab from sklearn.metrics import accuracy_score , classification_report, confusion_matrix, roc_auc_score,mean_squared_error,f1_score import numpy as np import pandas as pd from pandas_profiling import ProfileReport import seaborn as sb from sklearn.utils impor...
github_jupyter
import matplotlib.pyplot as plt import pylab from sklearn.metrics import accuracy_score , classification_report, confusion_matrix, roc_auc_score,mean_squared_error,f1_score import numpy as np import pandas as pd from pandas_profiling import ProfileReport import seaborn as sb from sklearn.utils import resample from s...
0.189709
0.295395
![JohnSnowLabs](https://nlp.johnsnowlabs.com/assets/images/logo.png) [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/JohnSnowLabs/spark-nlp-workshop/blob/master/tutorials/streamlit_notebooks/healthcare/NER_DEMOGRAPHICS.ipynb) # **Detect demograph...
github_jupyter
import os import json with open('/content/workshop_license_keys.json', 'r') as f: license_keys = json.load(f) license_keys.keys() secret = license_keys['JSL_SECRET'] os.environ['SPARK_NLP_LICENSE'] = license_keys['SPARK_NLP_LICENSE'] os.environ['JSL_OCR_LICENSE'] = license_keys['JSL_OCR_LICENSE'] os.environ['AWS...
0.439988
0.85931
# Example of using DOpt Federov Exchange Algorithm ## Algorithm obtained from - **Algorithm AS 295:** A Fedorov Exchange Algorithm for D-Optimal Design - **Author(s):** Alan J. Miller and Nam-Ky Nguyen - **Source:** Journal of the Royal Statistical Society. Series C (Applied Statistics), Vol. 43, No. 4, pp. 669-677,...
github_jupyter
import numpy as np import math as m import dopt print( dopt.dopt.__doc__ ) # Sample data set data = [ [ -1, -1, -1 ], [ 0, -1, -1 ], [ 1, -1, -1 ], [ -1, 0, -1 ], [ 0, 0, -1 ], [ 1, 0, -1 ], [ -1, 1, -1 ], [ 0, 1, -1 ], [ 1, 1, -1 ], [ -1, -1, 0 ], [ 0, -1, 0 ], [ 1, -1,...
0.237487
0.910306
<img align="left" src="https://lever-client-logos.s3.amazonaws.com/864372b1-534c-480e-acd5-9711f850815c-1524247202159.png" width=200> <br></br> <br></br> ## *Data Science Unit 4 Sprint 3 Assignment 2* # Convolutional Neural Networks (CNNs) # Assignment - <a href="#p1">Part 1:</a> Pre-Trained Model - <a href="#p2">Pa...
github_jupyter
import numpy as np from tensorflow.keras.applications.resnet50 import ResNet50 from tensorflow.keras.preprocessing import image from tensorflow.keras.applications.resnet50 import preprocess_input, decode_predictions from tensorflow.keras.layers import Dense, GlobalAveragePooling2D() from tensorflow.keras.models impor...
0.629205
0.941385
``` # 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
# 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\nfro...
0.133331
0.227491
# Feature Engineering and Creation #### v 2.0 In this feature engineering pipeline, the focus will be to try to improve the result for XGBoost model. ## Imports and Setup ``` import csv import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns import re from collections import Cou...
github_jupyter
import csv import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns import re from collections import Counter from sklearn.decomposition import TruncatedSVD, PCA from sklearn.feature_selection import SelectKBest from sklearn.preprocessing import StandardScaler, OrdinalEncoder sns.s...
0.39712
0.921852
``` # Imports import numpy as np import matplotlib.pyplot as plt import pandas as pd import seaborn as sns from statsmodels.tsa.arima.model import ARIMA sns.set_theme() # Load data (city) df = pd.read_csv('../data/GlobalLandTemperaturesByCity.csv') df['dt'] = pd.DatetimeIndex(df['dt']) df['Year'] = pd.DatetimeIndex(df[...
github_jupyter
# Imports import numpy as np import matplotlib.pyplot as plt import pandas as pd import seaborn as sns from statsmodels.tsa.arima.model import ARIMA sns.set_theme() # Load data (city) df = pd.read_csv('../data/GlobalLandTemperaturesByCity.csv') df['dt'] = pd.DatetimeIndex(df['dt']) df['Year'] = pd.DatetimeIndex(df['dt'...
0.675551
0.712945
# WeatherPy ---- #### Note * Instructions have been included for each segment. You do not have to follow them exactly, but they are included to help you think through the steps. ``` # Dependencies and Setup import matplotlib.pyplot as plt import pandas as pd import numpy as np import requests import time from scipy.s...
github_jupyter
# Dependencies and Setup import matplotlib.pyplot as plt import pandas as pd import numpy as np import requests import time from scipy.stats import linregress # Import API key from api_keys import weather_api_key # Incorporated citipy to determine city based on latitude and longitude from citipy import citipy # Outp...
0.386185
0.830113
# Direct Marketing with Amazon SageMaker Autopilot --- --- ## Contents 1. [Introduction](#Introduction) 1. [Prerequisites](#Prerequisites) 1. [Downloading the dataset](#Downloading) 1. [Upload the dataset to Amazon S3](#Uploading) 1. [Setting up the SageMaker Autopilot Job](#Settingup) 1. [Launching the SageMaker Au...
github_jupyter
import sagemaker import boto3 from sagemaker import get_execution_role region = boto3.Session().region_name session = sagemaker.Session() bucket = session.default_bucket() prefix = 'sagemaker/autopilot-dm' role = get_execution_role() sm = boto3.Session().client(service_name='sagemaker',region_name=region) !wget -N...
0.206174
0.98679
## 캐글 데이터셋 링크 + original: https://www.kaggle.com/trolukovich/apparel-images-dataset + me: https://www.kaggle.com/airplane2230/apparel-image-dataset-2 ``` import numpy as np import pandas as pd import tensorflow as tf import glob as glob import cv2 all_data = np.array(glob.glob('./clothes_dataset/*/*.jpg', recursive=...
github_jupyter
import numpy as np import pandas as pd import tensorflow as tf import glob as glob import cv2 all_data = np.array(glob.glob('./clothes_dataset/*/*.jpg', recursive=True)) # 색과 옷의 종류를 구별하기 위해 해당되는 label에 1을 삽입합니다. def check_cc(color, clothes): labels = np.zeros(11,) # color check if(color == 'black'): ...
0.183484
0.79736
``` from PIL import Image img = Image.open("cat.jpg") # 아래에 명시한 위치들을 기반으로 짤려서 나오게 된다. # (0, 0)이 좌측 상단임을 기억하도록 하자! dim = (0, 0, 400, 400) crop_img = img.crop(dim) crop_img.show() from PIL import Image img = Image.open("cat.jpg") # Image에는 Color Space 라는 공간이 있는데 # 이 공간에서 Color 값들을 빼고 조도로만 # 이미지를 재구성하면 GrayScale이 된다....
github_jupyter
from PIL import Image img = Image.open("cat.jpg") # 아래에 명시한 위치들을 기반으로 짤려서 나오게 된다. # (0, 0)이 좌측 상단임을 기억하도록 하자! dim = (0, 0, 400, 400) crop_img = img.crop(dim) crop_img.show() from PIL import Image img = Image.open("cat.jpg") # Image에는 Color Space 라는 공간이 있는데 # 이 공간에서 Color 값들을 빼고 조도로만 # 이미지를 재구성하면 GrayScale이 된다. # 조...
0.328637
0.663083
``` import os import numpy as np import pandas as pd import matplotlib.pyplot as plt plt.style.use('ggplot') %matplotlib inline accuracy = [ ['MobileNetV2', 1, 0.9890, 0.3676], ['MobileNetV2', 2, 0.9916, 0.5084], ['MobileNetV2', 3, 0.9926, 0.4996], ['MobileNetV2', 4, 0.9939, 0.7712], ['MobileNe...
github_jupyter
import os import numpy as np import pandas as pd import matplotlib.pyplot as plt plt.style.use('ggplot') %matplotlib inline accuracy = [ ['MobileNetV2', 1, 0.9890, 0.3676], ['MobileNetV2', 2, 0.9916, 0.5084], ['MobileNetV2', 3, 0.9926, 0.4996], ['MobileNetV2', 4, 0.9939, 0.7712], ['MobileNetV2'...
0.122327
0.68911
# Check `GDS` Python stack This notebook checks all software requirements for the course Geographic Data Science are correctly installed. A successful run of the notebook implies no errors returned in any cell *and* every cell beyond the first one returning a printout of `True`. This ensures a correct environment in...
github_jupyter
import black import bokeh import cenpy import colorama import contextily import cython import dask import dask_ml import datashader import dill import geopandas import geopy import hdbscan import ipyleaflet import ipyparallel import ipywidgets import mplleaflet import nbdime import networkx import osmnx import palettab...
0.458106
0.826046
# Covid-19 Pandemic Analysis on April 3rd ## Import Data The dataset can be download at [Kaggle](https://www.kaggle.com/sudalairajkumar/novel-corona-virus-2019-dataset). ``` import pandas as pd import numpy as np import os import matplotlib.pyplot as plt import seaborn as sns from sklearn.linear_model import LinearRe...
github_jupyter
import pandas as pd import numpy as np import os import matplotlib.pyplot as plt import seaborn as sns from sklearn.linear_model import LinearRegression from sklearn.model_selection import train_test_split from sklearn.metrics import r2_score, mean_squared_error import re import math %matplotlib inline # Explore the d...
0.720368
0.865963
# Chapter 5: Point-Neuron Network Models (with PointNet) In this chapter we will create a heterogeneous network of point-model neurons and use the PointNet simulator which will run the network using the NEST simulator. As with the previous BioNet examples will create both a internal recurrently-connected network of di...
github_jupyter
import pandas as pd pd.read_csv('sources/chapter05/converted_network/V1_node_types_bionet.csv', sep=' ') pd.read_csv('sources/chapter05/converted_network/V1_node_types.csv', sep=' ') pd.read_csv('sources/chapter05/converted_network/V1_V1_edge_types.csv', sep=' ') from bmtk.builder.networks import NetworkBuilder fro...
0.462473
0.958382
# Research Project # ## Introduction ## This data set relates to academic performance in students grade 1-12. This dataset was collected in 2016 using a "learner activity tracking" tool (xADI) from a learning management system (LMS). It was collected over the course of two academic semesters. Data was collected for 4...
github_jupyter
import sys, os sys.path.insert(0, os.path.abspath('..')) from scripts.project_functions import * from scripts import project_functions_anamica import pandas as pd import seaborn as sns import matplotlib.pylab as plt df = project_functions_anamica.load_process_data("../../data/data_raw/part_data.csv") df sns.boxplot(...
0.165965
0.983971
``` import torch torch.backends.cudnn.benchmark = True from torch import nn from torch.nn.functional import softmax, log_softmax from torchmetrics import Accuracy from resnet_cifar import resnet32 import pytorch_lightning as pl import wandb import torchvision.transforms as T import sys sys.path.append('../') fr...
github_jupyter
import torch torch.backends.cudnn.benchmark = True from torch import nn from torch.nn.functional import softmax, log_softmax from torchmetrics import Accuracy from resnet_cifar import resnet32 import pytorch_lightning as pl import wandb import torchvision.transforms as T import sys sys.path.append('../') from d...
0.809427
0.715064
# IAPWS-IF97 Libraries ## 1 Introduction to IAPWS-IF97 http://www.iapws.org/relguide/IF97-Rev.html This formulation is recommended for industrial use (primarily the steam power industry) for the calculation of thermodynamic properties of ordinary water in its fluid phases, including vapor-liquid equilibrium. The ...
github_jupyter
python -m pip install iapws from iapws import IAPWS97 sat_steam=IAPWS97(P=1,x=1) # saturated steam with known P,x=1 sat_liquid=IAPWS97(T=370, x=0) #saturated liquid with known T,x=0 steam=IAPWS97(P=2.5, T=500) # steam with known P and T(K) print(sat_steam.h, sat_liquid.h, steam....
0.388502
0.885532
``` import os import sys import collections import csv import pandas as pd import numpy as np import tensorflow as tf import pandas as pd import numpy as np import time from pymongo import MongoClient import urllib import multiprocess import pickle import random # BERT files os.listdir("../bert-master") sys.path.inser...
github_jupyter
import os import sys import collections import csv import pandas as pd import numpy as np import tensorflow as tf import pandas as pd import numpy as np import time from pymongo import MongoClient import urllib import multiprocess import pickle import random # BERT files os.listdir("../bert-master") sys.path.insert(0,...
0.237664
0.113334
# Preparação Carregar as biliotecas e ler os caminhos de ENV. ``` # Import Libraries import os import pandas as pd import joblib from sklearn.preprocessing import OneHotEncoder from sklearn.feature_extraction.text import CountVectorizer from sklearn.tree import DecisionTreeClassifier from sklearn.model_selection im...
github_jupyter
# Import Libraries import os import pandas as pd import joblib from sklearn.preprocessing import OneHotEncoder from sklearn.feature_extraction.text import CountVectorizer from sklearn.tree import DecisionTreeClassifier from sklearn.model_selection import train_test_split from sklearn.model_selection import cross_val_...
0.58166
0.775562
Data Manipulation in Pandas 1. Renaming columns 2. Sorting Data 3. Binning 4. Handling missing values 5. Apply methods in Pandas 6. Aggregation of Data Using Pandas 7. Merging data using Pandas Column Names are called as labels.. ``` import numpy as np import pandas as pd data={'Title':[None, 'Robinson Crusoe'...
github_jupyter
import numpy as np import pandas as pd data={'Title':[None, 'Robinson Crusoe', 'Moby Dick'], 'Author':['sa', 'Daniel Defoe', 'Herman Melville']} df = pd.DataFrame(data) df.dropna(how='all', inplace= True) df df df.columns=['TITLE', 'AUTHOR'] #Changing the keys of the column print(df) # other method of re...
0.254694
0.902136
# Should we remove top-level switches? ``` import io import zipfile import os import pandas from plotnine import * import plotnine plotnine.options.figure_size = (12, 8) import yaml from lxml import etree import warnings import re warnings.simplefilter(action='ignore') def get_yaml(archive_name, yaml_name): arch...
github_jupyter
import io import zipfile import os import pandas from plotnine import * import plotnine plotnine.options.figure_size = (12, 8) import yaml from lxml import etree import warnings import re warnings.simplefilter(action='ignore') def get_yaml(archive_name, yaml_name): archive = zipfile.ZipFile(archive_name) retu...
0.282889
0.584983
Plot Tide Forecasts =================== Plots the daily tidal displacements for a given location OTIS format tidal solutions provided by Ohio State University and ESR - http://volkov.oce.orst.edu/tides/region.html - https://www.esr.org/research/polar-tide-models/list-of-polar-tide-models/ - ftp://ftp.esr.org/pub/...
github_jupyter
pip3 install --user ipywidgets jupyter nbextension install --user --py widgetsnbextension jupyter nbextension enable --user --py widgetsnbextension jupyter-notebook from __future__ import print_function import os import datetime import numpy as np import matplotlib.pyplot as plt import ipywidgets as widgets import ip...
0.70619
0.867822
# 1) Defining how we assess performance ## What do we mean by "loss"? <img src="images/lec3_pic01.png"> <img src="images/lec3_pic02.png"> *Screenshot taken from [Coursera](https://www.coursera.org/learn/ml-regression/lecture/cGUQ3/what-do-we-mean-by-loss) 1:00* <!--TEASER_END--> How do we formalize this notion of ...
github_jupyter
# 1) Defining how we assess performance ## What do we mean by "loss"? <img src="images/lec3_pic01.png"> <img src="images/lec3_pic02.png"> *Screenshot taken from [Coursera](https://www.coursera.org/learn/ml-regression/lecture/cGUQ3/what-do-we-mean-by-loss) 1:00* <!--TEASER_END--> How do we formalize this notion of ...
0.788461
0.985732
# Stochastic Gradient Langevin Dynamics in MXNet ``` %matplotlib inline ``` In this notebook, we will show how to replicate the toy example in the paper <a name="ref-1"/>[(Welling and Teh, 2011)](#cite-welling2011bayesian). Here we have observed 20 instances from a mixture of Gaussians with tied means: $$ \begin{alig...
github_jupyter
%matplotlib inline import mxnet as mx import mxnet.ndarray as nd import numpy import logging import time import matplotlib.pyplot as plt def load_synthetic(theta1, theta2, sigmax, num=20): flag = numpy.random.randint(0, 2, (num,)) X = flag * numpy.random.normal(theta1, sigmax, (num, )) \ ...
0.569374
0.973494
<a href="https://colab.research.google.com/github/sahooamarjeet/ML_Case_Study/blob/master/Customer_Analytics.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ``` %matplotlib inline import matplotlib.pyplot as plt import pandas as pd ``` Mount Gdrive...
github_jupyter
%matplotlib inline import matplotlib.pyplot as plt import pandas as pd from google.colab import drive drive.mount('/content/gdrive', force_remount=True) import os;os.listdir("/content/gdrive/My Drive/Colab Notebooks") df = pd.read_csv("/content/gdrive/My Drive/Colab Notebooks/WA_Fn-UseC_-Marketing-Customer-Value-Analy...
0.432543
0.933794
## Introduction I was thinking for a while about my master thesis topic and I wanted it was related to data mining and artificial intelligence because I want to learn more about this field. I want to work with machine learning and for that, I have to study it more. Writing a thesis is a great way to get more experienc...
github_jupyter
from sklearn.linear_model import LinearRegression from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression from sklearn.ensemble import RandomForestClassifier from sklearn.tree import export_graphviz from sklearn.metrics import classification_report, confusion_matrix, ac...
0.560493
0.981524
``` from datascience import * path_data = '../data/' import matplotlib matplotlib.use('Agg') %matplotlib inline import matplotlib.pyplot as plots plots.style.use('fivethirtyeight') import numpy as np ``` # Iteration It is often the case in programming – especially when dealing with randomness – that we want to repeat ...
github_jupyter
from datascience import * path_data = '../data/' import matplotlib matplotlib.use('Agg') %matplotlib inline import matplotlib.pyplot as plots plots.style.use('fivethirtyeight') import numpy as np def bet_on_one_roll(): """Returns my net gain on one bet""" x = np.random.choice(np.arange(1, 7)) # roll a die onc...
0.468547
0.977392
# TIME EVOLUTION OF THE EFT COUNTER-TERMS ``` import numpy as np from scipy.interpolate import interp1d,InterpolatedUnivariateSpline %matplotlib inline import matplotlib.pyplot as plt plt.style.use('default') ``` ## Quijote simulations ``` from astropy.cosmology import FlatLambdaCDM cosmo = FlatLambdaCDM(H0=67.11, O...
github_jupyter
import numpy as np from scipy.interpolate import interp1d,InterpolatedUnivariateSpline %matplotlib inline import matplotlib.pyplot as plt plt.style.use('default') from astropy.cosmology import FlatLambdaCDM cosmo = FlatLambdaCDM(H0=67.11, Ob0=0.049, Om0= 0.2685) z = np.array([0,0.5,1,2,3]) c2 = np.array([2.629, 0.977...
0.669745
0.886617
# CNTK 208: Training Acoustic Model with Connectionist Temporal Classification (CTC) Criteria This tutorial assumes familiarity with 10\* CNTK tutorials and basic knowledge of data representation in acoustic modelling tasks. It introduces some CNTK building blocks that can be used in training deep networks for speech r...
github_jupyter
import os import cntk as C import numpy as np # Select the right target device import cntk.tests.test_utils cntk.tests.test_utils.set_device_from_pytest_env() # (only needed for our build system) data_dir = os.path.join("..", "Tests", "EndToEndTests", "Speech", "Data") print("Current directory {0}".format(os.getcwd()...
0.460046
0.934574
# 범주형 데이터 처리 범주형 데이터 Categorical Data * 명목형 자료(nominal data) * 숫자로 바꾸어도 그 값이 크고 작음을 나타내는 것이 아니라 단순히 범주를 표시 * 예) 성별(주민번호), 혈액형 * 순서형 자료(ordinal data) * 범주의 순서가 상대적으로 비교 가능, * 예) 비만도(저체중, 정상, 과체중, 비만, 고도비만), 학점,선호도 * 대부분 수치형 자료를 그룹화 하여 순서형 자료로 바꿀수 있다. ``` import pandas as pd ``` ### 샘플데이터 ``` df...
github_jupyter
import pandas as pd df = pd.DataFrame({"id":[1,2,3,4,5,6], "raw_grade":['A', 'B', 'B', 'A', 'A', 'F']}) df df["grade"] = df["raw_grade"].astype("category") df df.info() df["grade"].cat.categories df["grade"].cat.categories = ["very good", "good", "very bad"] df df["grade"] df["grade"] = df["grade"].cat.set_categori...
0.191214
0.967899
# Genotype data formatting This module implements a collection of workflows used to format genotype data. ## Overview The module streamlines conversion between PLINK and VCF formats (possibly more to add), specifically: 1. Conversion between VCF and PLINK formats 2. Split data (by specified input, by chromosomes, b...
github_jupyter
sos run genotype_formatting.ipynb merge_plink \ --genoFile data/genotype/chr1.bed data/genotype/chr6.bed \ --cwd output/genotype \ --name chr1_chr6 \ --container container/bioinfo.sif ``` ## Command interface ## PLINK to VCF ## VCF to PLINK ## Split PLINK by genes ## Split PLINK by Chromos...
0.332527
0.8474
--- _You are currently looking at **version 1.1** of this notebook. To download notebooks and datafiles, as well as get help on Jupyter notebooks in the Coursera platform, visit the [Jupyter Notebook FAQ](https://www.coursera.org/learn/python-text-mining/resources/d9pwm) course resource._ --- # Assignment 1 In this...
github_jupyter
import pandas as pd import numpy as np doc = [] with open('dates.txt') as file: for line in file: doc.append(line) df = pd.Series(doc) df.head(10) # df.shape def date_sorter(): # Extract dates df_dates = df.str.replace(r'(\d+\.\d+)', '') df_dates = df_dates.str.extractall(r'[\s\.,\-/]*?(?P<ddm...
0.31216
0.909867
# Realization of Recursive Filters *This jupyter notebook is part of a [collection of notebooks](../index.ipynb) on various topics of Digital Signal Processing. Please direct questions and suggestions to [Sascha.Spors@uni-rostock.de](mailto:Sascha.Spors@uni-rostock.de).* ## Quantization of Variables and Operations A...
github_jupyter
%matplotlib inline import numpy as np import matplotlib.pyplot as plt import scipy.signal as sig N = 8192 # length of signals w = 8 # wordlength for requantization of multiplications def uniform_midtread_quantizer(x): # linear uniform quantization xQ = Q * np.floor(x/Q + 1/2) return xQ def no_q...
0.620737
0.99406
``` %matplotlib inline ``` PyTorch: 새 autograd Function 정의하기 ---------------------------------------- $y=\sin(x)$ 을 예측할 수 있도록, $-\pi$ 부터 $pi$ 까지 유클리드 거리(Euclidean distance)를 최소화하도록 3차 다항식을 학습합니다. 다항식을 $y=a+bx+cx^2+dx^3$ 라고 쓰는 대신 $y=a+b P_3(c+dx)$ 로 다항식을 적겠습니다. 여기서 $P_3(x)= rac{1}{2}\left(5x^3-3x ight)$ 은 3차 `르장드르 다항...
github_jupyter
%matplotlib inline import torch import math class LegendrePolynomial3(torch.autograd.Function): """ torch.autograd.Function을 상속받아 사용자 정의 autograd Function을 구현하고, 텐서 연산을 하는 순전파 단계와 역전파 단계를 구현해보겠습니다. """ @staticmethod def forward(ctx, input): """ 순전파 단계에서는 입력을 갖는 텐서를 받아 출력을 갖는 ...
0.744935
0.964656
# Proyecto de Investigación: Modelos Numéricos --- ``` import ipywidgets as widgets from matplotlib import pyplot as plt import numpy as np from numpy import linalg as LA from math import sqrt, pi from project import eigen ``` ## Modelo Matemático en Ecuaciones Diferenciales $ m(x) \frac{\partial^{2}u}{\partial t^{...
github_jupyter
import ipywidgets as widgets from matplotlib import pyplot as plt import numpy as np from numpy import linalg as LA from math import sqrt, pi from project import eigen L = 420 EJ = 9.45e11 m = 64.8 p = 100 ML = 50000 widgetN = widgets.FloatText() display(widgetN) N = 20 h = L/N M = np.zeros((N, N)) for i in range(...
0.378
0.983534
# Chunking using RNN and also Bi-LSTM ## Importing required Libraries ``` # Let us import required Libraries import tensorflow as tf from tensorflow import keras import tensorflow.keras.backend as K from tensorflow.keras.preprocessing.text import Tokenizer from tensorflow.keras.preprocessing.sequence import pad_sequ...
github_jupyter
# Let us import required Libraries import tensorflow as tf from tensorflow import keras import tensorflow.keras.backend as K from tensorflow.keras.preprocessing.text import Tokenizer from tensorflow.keras.preprocessing.sequence import pad_sequences import matplotlib.pyplot as plt import numpy as np from gensim.models ...
0.469034
0.832781
# DS1000E Rigol Waveform Examples **Scott Prahl** **March 2021** This notebook illustrates shows how to extract signals from a `.wfm` file created by a the Rigol DS1000E scope. It also validates that the process works by comparing with `.csv` and screenshots. Two different `.wfm` files are examined one for the DS1...
github_jupyter
#!pip install RigolWFM import numpy as np import matplotlib.pyplot as plt try: import RigolWFM.wfm as rigol except ModuleNotFoundError: print('RigolWFM not installed. To install, uncomment and run the cell below.') print('Once installation is successful, rerun this cell again.') repo = "https://github.com...
0.450601
0.951414
# PostgreSQL: use sql magic %sql * pip install ipython-sql * doc: https://pypi.org/project/ipython-sql/ --- * author: [Prasert Kanawattanachai](prasert.k@chula.ac.th) * YouTube: https://www.youtube.com/prasertcbs * [Chulalongkorn Business School](https://www.cbs.chula.ac.th/en/) --- ``` from IPython.display import Y...
github_jupyter
from IPython.display import YouTubeVideo YouTubeVideo('bgHPGiE0rkg', width=720, height=405) import pandas as pd import psycopg2 # postgresql db driver print(f'pandas version: {pd.__version__}') print(f'psycopg2 version: {psycopg2.__version__}') %load_ext sql import getpass host='192.168.211.137' port=5432 dbname='...
0.18665
0.66689
<a href="https://colab.research.google.com/github/tuanyuan2008/cs4641/blob/master/randomized-optimization/4_peaks.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ``` ! pip3 install mlrose import mlrose import numpy as np import matplotlib.pyplot as...
github_jupyter
! pip3 install mlrose import mlrose import numpy as np import matplotlib.pyplot as plt import timeit fitness = mlrose.FourPeaks(t_pct=0.15) state = np.array([1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0]) fitness.evaluate(state) # Define decay schedules schedule = mlrose.GeomDecay() problem = mlrose.DiscreteOpt(length = 12, f...
0.340156
0.888081
# Introduction à la librairie PyTorch -- Solutions Matériel de cours rédigé par Pascal Germain, 2019 ************ ### Partie 1 ``` class regression_logistique: def __init__(self, rho=.01, eta=0.4, nb_iter=50, seed=None): # Initialisation des paramètres de la descente en gradient self.rho = rho ...
github_jupyter
class regression_logistique: def __init__(self, rho=.01, eta=0.4, nb_iter=50, seed=None): # Initialisation des paramètres de la descente en gradient self.rho = rho # Paramètre de regularisation self.eta = eta # Pas de gradient self.nb_iter = nb_iter # Nombre d'itérati...
0.817574
0.864024
# Classifying Fashion-MNIST Now it's your turn to build and train a neural network. You'll be using the [Fashion-MNIST dataset](https://github.com/zalandoresearch/fashion-mnist), a drop-in replacement for the MNIST dataset. MNIST is actually quite trivial with neural networks where you can easily achieve better than 9...
github_jupyter
import torch from torchvision import datasets, transforms import helper # Define a transform to normalize the data transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]) # Download and load the training data trainset = datasets.Fa...
0.652241
0.991456
``` import wandb wandb.init(project="Channel_Charting") import torch from torch import nn from torch.optim import SGD from torch.utils.data import DataLoader import torch.nn.functional as F from torchvision.transforms import Compose, ToTensor, Normalize from torchvision.datasets import MNIST from ignite.engine impor...
github_jupyter
import wandb wandb.init(project="Channel_Charting") import torch from torch import nn from torch.optim import SGD from torch.utils.data import DataLoader import torch.nn.functional as F from torchvision.transforms import Compose, ToTensor, Normalize from torchvision.datasets import MNIST from ignite.engine import Ev...
0.87464
0.586227
# Spatial joins Goals of this notebook: - Based on the `countries` and `cities` dataframes, determine for each city the country in which it is located. - To solve this problem, we will use the the concept of a 'spatial join' operation: combining information of geospatial datasets based on their spatial relationship. ...
github_jupyter
%matplotlib inline import pandas as pd import geopandas pd.options.display.max_rows = 10 countries = geopandas.read_file("zip://./data/ne_110m_admin_0_countries.zip") cities = geopandas.read_file("zip://./data/ne_110m_populated_places.zip") rivers = geopandas.read_file("zip://./data/ne_50m_rivers_lake_centerlines.zip...
0.330795
0.987067
# Unit 5 - Financial Planning ``` # Initial imports import os import requests import pandas as pd from dotenv import load_dotenv import alpaca_trade_api as tradeapi from MCForecastTools import MCSimulation import datetime import json %matplotlib inline # Load .env enviroment variables load_dotenv() ``` ## Part 1 - Pe...
github_jupyter
# Initial imports import os import requests import pandas as pd from dotenv import load_dotenv import alpaca_trade_api as tradeapi from MCForecastTools import MCSimulation import datetime import json %matplotlib inline # Load .env enviroment variables load_dotenv() # Set current amount of crypto assets my_btc = 1.2 my...
0.642545
0.691341
<a href="https://colab.research.google.com/github/DiploDatos/AprendizajePorRefuerzos/blob/master/lab_1_intro_rl.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # Notebook 1: Introducción al aprendizaje por refuerzos Curso Aprendizaje por Refuerzos,...
github_jupyter
desde Mac, reemplazar *apt-get* por *brew* desde Windows, descargarla desde [https://ffmpeg.org/download.html](https://ffmpeg.org/download.html) (Nota: las animaciones son a modo ilustrativo, si no se desea instalar la librería se puede directamente eliminar la línea de código donde se llama al método ``env.render(...
0.47658
0.990169
## Python Data Structures Exercises ``` mydata = [{'Born': '2007', 'City': 'Cauneside', 'Crypto': ('FTH', 'Feathercoin'), 'Description': 'Natus voluptas repellat consequatur. Nihil nobis reprehenderit libero sunt nulla.\nVeniam quia ab consectetur voluptatibus reprehenderit debitis sint.', 'Email': 'kaspars94@...
github_jupyter
mydata = [{'Born': '2007', 'City': 'Cauneside', 'Crypto': ('FTH', 'Feathercoin'), 'Description': 'Natus voluptas repellat consequatur. Nihil nobis reprehenderit libero sunt nulla.\nVeniam quia ab consectetur voluptatibus reprehenderit debitis sint.', 'Email': 'kaspars94@lacis-krievins.biz', 'FavoriteURL': 'ht...
0.2763
0.57069
``` import pandas as pd train = pd.read_csv('train.csv', index_col='_id') test = pd.read_csv('test.csv', index_col='_id') train.info(), test.info() train.shape, test.shape y_train = list(train['target']) train = train.drop('target', axis=1) train.info(verbose=True) train.loc[:,'sample'] = 'train' test.loc[:,'sample'] =...
github_jupyter
import pandas as pd train = pd.read_csv('train.csv', index_col='_id') test = pd.read_csv('test.csv', index_col='_id') train.info(), test.info() train.shape, test.shape y_train = list(train['target']) train = train.drop('target', axis=1) train.info(verbose=True) train.loc[:,'sample'] = 'train' test.loc[:,'sample'] = 'te...
0.192046
0.224013
``` #library import numpy as np import pandas as pd from sklearn.model_selection import train_test_split import tensorflow as tf from tensorflow import keras import tensorflow.keras.applications as ap #mount file from google drive from google.colab import drive drive.mount('/content/drive') #grab the data img512 = np.l...
github_jupyter
#library import numpy as np import pandas as pd from sklearn.model_selection import train_test_split import tensorflow as tf from tensorflow import keras import tensorflow.keras.applications as ap #mount file from google drive from google.colab import drive drive.mount('/content/drive') #grab the data img512 = np.load(...
0.558809
0.123551
# Population Tool: Alpha ## First Step: Define functions we need Import necessary packages and declare constant variables ``` import pandas as pd import matplotlib.pyplot as plt import matplotlib matplotlib.style.use('ggplot') # Use these paths to pull real data POP_DATA_PATH = 'https://esa.un.org/unpd/wpp/DVD/File...
github_jupyter
import pandas as pd import matplotlib.pyplot as plt import matplotlib matplotlib.style.use('ggplot') # Use these paths to pull real data POP_DATA_PATH = 'https://esa.un.org/unpd/wpp/DVD/Files/1_Indicators%20(Standard)/EXCEL_FILES/1_Population/WPP2017_POP_F01_1_TOTAL_POPULATION_BOTH_SEXES.xlsx' POP_RELATABLE_PATH = 'ht...
0.457379
0.8474
# Inspecting TFX metadata ## Learning Objectives 1. Use a GRPC server to access and analyze pipeline artifacts stored in the ML Metadata service of your AI Platform Pipelines instance. In this lab, you will explore TFX pipeline metadata including pipeline and run artifacts. A hosted **AI Platform Pipelines** instan...
github_jupyter
import os import ml_metadata import tensorflow_data_validation as tfdv import tensorflow_model_analysis as tfma from ml_metadata.metadata_store import metadata_store from ml_metadata.proto import metadata_store_pb2 from tfx.orchestration import metadata from tfx.types import standard_artifacts !python -c "import tf...
0.281801
0.90764
### 基于维特比算法来优化上述流程 此项目需要的数据: 1. 综合类中文词库.xlsx: 包含了中文词,当做词典来用 2. 以变量的方式提供了部分unigram概率word_prob 举个例子: 给定词典=[我们 学习 人工 智能 人工智能 未来 是], 另外我们给定unigram概率:p(我们)=0.25, p(学习)=0.15, p(人工)=0.05, p(智能)=0.1, p(人工智能)=0.2, p(未来)=0.1, p(是)=0.15 #### Step 1: 根据词典,输入的句子和 word_prob来创建带权重的有向图(Directed Graph) 参考:课程内容 有向图的每一条边是一个单词的概率(只要存在...
github_jupyter
import pandas as pd import numpy as np path = "./data/综合类中文词库.xlsx" data_frame = pd.read_excel(path, header = None) dic_word_list = data_frame[data_frame.columns[0]].tolist() dic_words = dic_word_list # 保存词典库中读取的单词 # 以下是每一个单词出现的概率。为了问题的简化,我们只列出了一小部分单词的概率。 在这里没有出现的的单词但是出现在词典里的,统一把概率设置成为0.00001 # 比如 p("学院")=p("概率")=....
0.138084
0.827131
``` # Copyright 2021 Google LLC # Use of this source code is governed by an MIT-style # license that can be found in the LICENSE file or at # https://opensource.org/licenses/MIT. # Author(s): Kevin P. Murphy (murphyk@gmail.com) and Mahmoud Soliman (mjs@aucegypt.edu) ``` <a href="https://opensource.org/licenses/MIT" t...
github_jupyter
# Copyright 2021 Google LLC # Use of this source code is governed by an MIT-style # license that can be found in the LICENSE file or at # https://opensource.org/licenses/MIT. # Author(s): Kevin P. Murphy (murphyk@gmail.com) and Mahmoud Soliman (mjs@aucegypt.edu) #@title Setup { display-mode: "form" } %%time # If you...
0.666171
0.913097
<a href="https://colab.research.google.com/github/simecek/ECCB2021/blob/main/notebooks/10_Integrated_Gradients_G4.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ## Data ``` import tensorflow as tf from tensorflow.keras import Sequential from tenso...
github_jupyter
import tensorflow as tf from tensorflow.keras import Sequential from tensorflow.keras.layers import Conv1D, BatchNormalization, MaxPooling1D, Dropout, GlobalAveragePooling1D, Dense import numpy as np import pandas as pd import matplotlib.pyplot as plt from IPython.display import display, HTML # get train dataset !wget...
0.918713
0.936285
``` import pandemic_simulator as ps import random from tf_agents.specs import BoundedArraySpec import numpy as np import base64 import IPython import matplotlib.pyplot as plt import os import reverb import tempfile import tensorflow as tf from tf_agents.agents.ddpg import critic_network from tf_agents.agents.sac imp...
github_jupyter
import pandemic_simulator as ps import random from tf_agents.specs import BoundedArraySpec import numpy as np import base64 import IPython import matplotlib.pyplot as plt import os import reverb import tempfile import tensorflow as tf from tf_agents.agents.ddpg import critic_network from tf_agents.agents.sac import ...
0.405096
0.203075
# Computational Astrophysics ## Fundamentals of Visualization --- ## Eduard Larrañaga Observatorio Astronómico Nacional\ Facultad de Ciencias\ Universidad Nacional de Colombia --- ### About this notebook In this notebook we present some of the fundamentals of visualization using `python`. --- ### Simple Data Plo...
github_jupyter
import numpy as np from matplotlib import pyplot as plt data = np.loadtxt('plotdata.txt', comments='#') x = data[:,0] y = data[:,1] plt.plot(x,y) plt.show() plt.plot(x, y, label=r'first curve label') plt.xlabel(r'$x$ axis label') plt.ylabel(r'$y$ axis label') plt.legend() plt.show() plt.plot(x, y, '--r', label=r'first...
0.591369
0.975969
``` import dgl.nn as dglnn from dgl import from_networkx import torch.nn as nn import torch as th import torch.nn.functional as F import dgl.function as fn import networkx as nx import pandas as pd import socket import struct import random from sklearn.preprocessing import LabelEncoder from sklearn.preprocessing import...
github_jupyter
import dgl.nn as dglnn from dgl import from_networkx import torch.nn as nn import torch as th import torch.nn.functional as F import dgl.function as fn import networkx as nx import pandas as pd import socket import struct import random from sklearn.preprocessing import LabelEncoder from sklearn.preprocessing import Sta...
0.76986
0.376795
# HW04: Sentiment Analysis ``` %reload_ext autoreload %autoreload 2 %matplotlib inline from fastai.model import fit from fastai.dataset import * import torchtext from torchtext import vocab, data from torchtext.datasets import language_modeling from fastai.rnn_reg import * from fastai.rnn_train import * from fastai...
github_jupyter
%reload_ext autoreload %autoreload 2 %matplotlib inline from fastai.model import fit from fastai.dataset import * import torchtext from torchtext import vocab, data from torchtext.datasets import language_modeling from fastai.rnn_reg import * from fastai.rnn_train import * from fastai.nlp import * from fastai.lm_rnn...
0.456894
0.594698
# Exploring Raw Data with _ctapipe_ Here are just some very simplistic examples of going through and inspecting the raw data, using only the very simple pieces that are implemented right now. ``` # some setup (need to import the things we will use later) from ctapipe.utils.datasets import get_path from ctapipe.io.hes...
github_jupyter
# some setup (need to import the things we will use later) from ctapipe.utils.datasets import get_path from ctapipe.io.hessio import hessio_event_source from ctapipe import visualization, io from matplotlib import pyplot as plt from astropy import units as u %matplotlib inline source = hessio_event_source(get_path("ga...
0.460774
0.976152
``` %matplotlib inline ``` # L1 Penalty and Sparsity in Logistic Regression Comparison of the sparsity (percentage of zero coefficients) of solutions when L1, L2 and Elastic-Net penalty are used for different values of C. We can see that large values of C give more freedom to the model. Conversely, smaller values ...
github_jupyter
%matplotlib inline print(__doc__) # Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr> # Mathieu Blondel <mathieu@mblondel.org> # Andreas Mueller <amueller@ais.uni-bonn.de> # License: BSD 3 clause import numpy as np import matplotlib.pyplot as plt from sklearn.linear_model import LogisticRe...
0.692018
0.915658
# Aprendizado de máquina - Parte 1 _Aprendizado de máquina_ (_machine learning_, ML) é um subcampo da inteligência artificial que tem por objetivo permitir que o computador _aprenda com os dados_ sem ser explicitamente programado. Em linhas gerais, no _machine learning_ se constrói algoritmos que leem dados, aprendem ...
github_jupyter
## Estudo de caso: classificação de empréstimos bancários O problema que estudaremos consiste em predizer se o pedido de empréstimo de uma pessoa será parcial ou totalmente aprovado por uma financeira. O banco de dados disponível da financeira abrange os anos de 2007 a 2011. A aprovação do pedido baseia-se em uma an...
0.603348
0.945601
Videocvičení naleznete zde: https://youtu.be/yL-A0N5JDJo # Práce s obrázky ### Načítání balíčků K práci s obrázky budeme používat knihovnu **cv2** s aliasem **cv**. Dále budeme používat knihovnu **numpy** s aliasem **np** pro matematické funkce a práci s poli a knihovnu **matplotlib** s aliasem **plt** pro vykreslová...
github_jupyter
import cv2 as cv import numpy as np from matplotlib import pyplot as plt from matplotlib.colors import NoNorm %matplotlib notebook img_bgr = cv.imread("lena_original.jpg",cv.IMREAD_UNCHANGED) img = cv.cvtColor(img_bgr, cv.COLOR_BGR2RGB) plt.figure() plt.imshow(img) img_crop = img[20:270,150:400,:] plt.figure() plt...
0.407569
0.9434
# Lab Notebook Course: BioE 131 Lab No: Lab #7 Submission date: Team members: Michael Fernandez, Jinho Ko ## Simulating the Data ``` import numpy as np def b_generator(s, p): data = np.random.choice( [0,1], size = s, replace = True, p = [p, 1.0-p]) data = np.packbits(data) return ...
github_jupyter
import numpy as np def b_generator(s, p): data = np.random.choice( [0,1], size = s, replace = True, p = [p, 1.0-p]) data = np.packbits(data) return data def DNA_generator(s): data = np.random.choice( ['A', 'T', 'C', 'G'], size = s, replace = True, p = [ 1.0/4.0 for _ in range(4) ] ) #data = np.pa...
0.273477
0.786356
# Train faster, more flexible models with Amazon SageMaker Linear Learner Today Amazon SageMaker is launching several additional features to the built-in linear learner algorithm. Amazon SageMaker algorithms are designed to scale effortlessly to massive datasets and take advantage of the latest hardware optimizations...
github_jupyter
import boto3 import io import matplotlib.pyplot as plt import numpy as np import os import pandas as pd import sagemaker import sagemaker.amazon.common as smac from sagemaker import get_execution_role from sagemaker.predictor import csv_serializer, json_deserializer # Set data locations bucket = '<your_s3_bucket_her...
0.534127
0.993704
``` from pyvis.network import Network import networkx as nx import json import functools import itertools import collections from matplotlib import pyplot as plt from networkx.drawing.nx_agraph import write_dot, graphviz_layout # utility functions def none_max(a, b): if a is None: return b if b is None:...
github_jupyter
from pyvis.network import Network import networkx as nx import json import functools import itertools import collections from matplotlib import pyplot as plt from networkx.drawing.nx_agraph import write_dot, graphviz_layout # utility functions def none_max(a, b): if a is None: return b if b is None: ...
0.740456
0.567757
# RMSProp 我们在[“Adagrad”](adagrad.md)一节里提到,由于调整学习率时分母上的变量 $\boldsymbol{s}_t$ 一直在累加按元素平方的小批量随机梯度,目标函数自变量每个元素的学习率在迭代过程中一直在降低(或不变)。所以,当学习率在迭代早期降得较快且当前解依然不佳时,Adagrad 在迭代后期由于学习率过小,可能较难找到一个有用的解。为了应对这一问题,RMSProp 算法对 Adagrad 做了一点小小的修改 [1]。 ## 算法 我们在[“动量法”](momentum.md)一节里介绍过指数加权移动平均。不同于 Adagrad 里状态变量 $\boldsymbol{s}_t$ 是截至时间...
github_jupyter
%matplotlib inline import d2lzh as d2l import math from mxnet import nd def rmsprop_2d(x1, x2, s1, s2): g1, g2, eps = 0.2 * x1, 4 * x2, 1e-6 s1 = gamma * s1 + (1 - gamma) * g1 ** 2 s2 = gamma * s2 + (1 - gamma) * g2 ** 2 x1 -= eta / math.sqrt(s1 + eps) * g1 x2 -= eta / math.sqrt(s2 + eps) * g2 ...
0.493897
0.982906
**Important: This notebook will only work with fastai-0.7.x. Do not try to run any fastai-1.x code from this path in the repository because it will load fastai-0.7.x** ``` %reload_ext autoreload %autoreload 2 %matplotlib inline from fastai.nlp import * from sklearn.linear_model import LogisticRegression from sklearn....
github_jupyter
%reload_ext autoreload %autoreload 2 %matplotlib inline from fastai.nlp import * from sklearn.linear_model import LogisticRegression from sklearn.svm import LinearSVC from torchtext import vocab, data, datasets import pandas as pd sl=1000 vocab_size=200000 PATH='data/arxiv/arxiv.csv' # You can download a similar to J...
0.653016
0.761428
<a href="https://colab.research.google.com/github/keithvtls/Numerical-Method-Activities/blob/main/Week%203-5%20-%20Roots%20of%20Equations/NuMeth_Group_4_Act_3Roots_of_Linear_Equation.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ### CONTRIBUTION ...
github_jupyter
### Brute force algorithm(f(x)=0) def f_of_x(f,roots,tol,i, epochs=100): x_roots=[] # list of roots n_roots= roots # number of roots needed to find incre = i #increments h = tol #tolerance is the starting guess for epoch in range(epochs): # the list of iteration that will be using ...
0.611614
0.980913
``` import pandas as pd import glob, os import geopandas as gpd import numpy as np import matplotlib.pyplot as plt import xarray as xr basedir = '/Users/simon/Work/ECOSAT3/DATA/Dredges/' gpd.read_file('/Users/simon/Work/ECOSAT3/DATA/Dredges/DR01/shapefile/dredge_01_events.shp') #print glob.glob('%s/DR*') #print os.l...
github_jupyter
import pandas as pd import glob, os import geopandas as gpd import numpy as np import matplotlib.pyplot as plt import xarray as xr basedir = '/Users/simon/Work/ECOSAT3/DATA/Dredges/' gpd.read_file('/Users/simon/Work/ECOSAT3/DATA/Dredges/DR01/shapefile/dredge_01_events.shp') #print glob.glob('%s/DR*') #print os.listd...
0.122733
0.389605
# DAT210x - Programming with Python for DS ## Module4- Lab2 ``` import math import pandas as pd import matplotlib.pyplot as plt import matplotlib from sklearn import preprocessing from sklearn.decomposition import PCA # Look pretty... # matplotlib.style.use('ggplot') plt.style.use('ggplot') ``` ### Some Boilerplat...
github_jupyter
import math import pandas as pd import matplotlib.pyplot as plt import matplotlib from sklearn import preprocessing from sklearn.decomposition import PCA # Look pretty... # matplotlib.style.use('ggplot') plt.style.use('ggplot') def scaleFeaturesDF(df): # Feature scaling is a type of transformation that only chan...
0.846863
0.951594
``` import json import numpy as np import operator import math def r_precision(G, R): limit_R = R[:len(G)] if len(G) != 0: return len(list(set(G).intersection(set(limit_R)))) * 1.0 / len(G) else: return 0 def ndcg(G, R): r = [1 if i in set(G) else 0 for i in R] r = np.asfarray(r) ...
github_jupyter
import json import numpy as np import operator import math def r_precision(G, R): limit_R = R[:len(G)] if len(G) != 0: return len(list(set(G).intersection(set(limit_R)))) * 1.0 / len(G) else: return 0 def ndcg(G, R): r = [1 if i in set(G) else 0 for i in R] r = np.asfarray(r) dc...
0.19923
0.68545
``` import pandas as pd import cobra as co ``` # Convert the Tables that make up gapseq's "full model" to a cobrapy model Object ## Download the relevant tables into this repo's data folder ``` !wget -P "data/" "https://raw.githubusercontent.com/jotech/gapseq/f3d74944e5e4ee5a6ab328c4fd46b35fd53cee73/dat/seed_reacti...
github_jupyter
import pandas as pd import cobra as co !wget -P "data/" "https://raw.githubusercontent.com/jotech/gapseq/f3d74944e5e4ee5a6ab328c4fd46b35fd53cee73/dat/seed_reactions_corrected.tsv" !wget -P "data/" "https://raw.githubusercontent.com/jotech/gapseq/f3d74944e5e4ee5a6ab328c4fd46b35fd53cee73/dat/seed_metabolites_edited.tsv"...
0.37502
0.778691
### Summary Statistics and Quick Viz! ``` import pandas as pd pd.options.display.max_rows = 30 ``` ### START HERE Now we've learned about how to get our dataframe how we want it, let's try and get some fun out of it! We have our data, now what? We usually like to learn from it. We want to find out about maybe som...
github_jupyter
import pandas as pd pd.options.display.max_rows = 30 df = pd.read_csv('../data/cereal.csv', index_col = 0) df.head(15) df.describe() df.describe(include = "all") df.sum() manufacturer_column = df["mfr"] manufacturer_column manufacturer_freq = manufacturer_column.value_counts() manufacturer_freq manufacturer_freq...
0.303938
0.984456
``` # We'll use requesta and BeautifulSoup again in this tutorial: import requests from bs4 import BeautifulSoup ## We'll also use the re module for regular expressions. import re ## Let's look at this list of state universities in the US: top_url = 'https://en.wikipedia.org/wiki/List_of_state_universities_in_the_Uni...
github_jupyter
# We'll use requesta and BeautifulSoup again in this tutorial: import requests from bs4 import BeautifulSoup ## We'll also use the re module for regular expressions. import re ## Let's look at this list of state universities in the US: top_url = 'https://en.wikipedia.org/wiki/List_of_state_universities_in_the_United_...
0.398641
0.769384
# Statistics ``` import numpy as np # 1D array A1 = np.arange(20) print(A1) A.ndim # 2D array A2 = np.array([[11, 12, 13], [21, 22, 23]]) print(A2) np.sum(A2, axis=0) np.sum(A2) A2.ndim ``` ## Sum - Sum of array elements over a given axis. - **Syntax:** `np.sum(array); array-wise sum` - **Syntax:** `np.sum...
github_jupyter
import numpy as np # 1D array A1 = np.arange(20) print(A1) A.ndim # 2D array A2 = np.array([[11, 12, 13], [21, 22, 23]]) print(A2) np.sum(A2, axis=0) np.sum(A2) A2.ndim # sum of 1D array np.sum(A1) # array-wise sum of 2D array np.sum(A2) A2 # sum of 2D array(axis=0, row-wise sum) np.sum(A2, axis=0) # sum of 2D arr...
0.708616
0.991915
# Lesson 2.2: # PowerGrid Models API - Using JSON Queries This tutorial introduces the PowerGrid Models API and how it can be used to query model data. __Learning Objectives:__ At the end of the tutorial, the user should be able to use the PowerGrid Models API to * * * ## Getting Started Before running any of ...
github_jupyter
# Establish connection to GridAPPS-D Platform: from gridappsd import GridAPPSD gapps = GridAPPSD("('localhost', 61613)", username='system', password='manager') model_mrid = "_49AD8E07-3BF9-A4E2-CB8F-C3722F837B62" # IEEE 13 Node used for all example queries topic = "goss.gridappsd.process.request.data.powergridmodel" ...
0.438064
0.979136
``` %matplotlib inline import numpy as np import h5py import os from functools import reduce from imp import reload import matplotlib.pyplot as plt from scipy.cluster.hierarchy import dendrogram, linkage from hangul.read_data import load_data, load_images, load_all_labels from matplotlib import cm from hangul import s...
github_jupyter
%matplotlib inline import numpy as np import h5py import os from functools import reduce from imp import reload import matplotlib.pyplot as plt from scipy.cluster.hierarchy import dendrogram, linkage from hangul.read_data import load_data, load_images, load_all_labels from matplotlib import cm from hangul import style...
0.359701
0.724675
# Training Pong Game by Using DQN We use PyTorch to train a Deep Q Learning (DQN) agent on a Pong Game. Reference Code: - Pong_in_Pygame (Author: clear-code-projects) + Youtube: https://www.youtube.com/playlist?list=PL8ui5HK3oSiEk9HaKoVPxSZA03rmr9Z0k + Github: https://github.com/clear-code-projects/Pong_in_P...
github_jupyter
!git clone https://github.com/yenzu0329/DQN_for_Pong.git !pip install pygame import os os.environ["SDL_VIDEODRIVER"] = "dummy" %matplotlib inline import torch as T import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import numpy as np class DeepQNetwork(nn.Module): def __init__(sel...
0.894522
0.955486
``` import pandas as pd import numpy as np from collections import defaultdict from sklearn.datasets import fetch_20newsgroups from sklearn.metrics import confusion_matrix from tqdm import tqdm import itertools import matplotlib.pyplot as plt import re %matplotlib inline ``` # Naive Bayes code (with Sentence) ##### St...
github_jupyter
import pandas as pd import numpy as np from collections import defaultdict from sklearn.datasets import fetch_20newsgroups from sklearn.metrics import confusion_matrix from tqdm import tqdm import itertools import matplotlib.pyplot as plt import re %matplotlib inline def preprocess(str_arg): cleaned_str=re.sub('[^...
0.606149
0.789558
Predict the CaCO3 and TOC using the latest models (2021 Aug.) on the whole spetra. ``` import numpy as np import pandas as pd import matplotlib.pyplot as plt #plt.style.use('ggplot') plt.style.use('seaborn-colorblind') #plt.style.use('dark_background') plt.rcParams['figure.dpi'] = 300 plt.rcParams['savefig.dpi'] = 3...
github_jupyter
import numpy as np import pandas as pd import matplotlib.pyplot as plt #plt.style.use('ggplot') plt.style.use('seaborn-colorblind') #plt.style.use('dark_background') plt.rcParams['figure.dpi'] = 300 plt.rcParams['savefig.dpi'] = 300 plt.rcParams['savefig.bbox'] = 'tight' plt.rcParams['savefig.transparent'] = True %m...
0.371137
0.820829
``` import panel as pn pn.extension('vtk') ``` The ``VTK`` pane renders VTK objects and vtk.js files inside a panel, making it possible to interact with complex geometries in 3D. #### Parameters: For layout and styling related parameters see the [customization user guide](../../user_guide/Customization.ipynb). * **...
github_jupyter
import panel as pn pn.extension('vtk') dragon = pn.pane.VTK('https://raw.githubusercontent.com/Kitware/vtk-js/master/Data/StanfordDragon.vtkjs', sizing_mode='stretch_width', height=400) dragon dragon.object = "https://github.com/Kitware/vtk-js-datasets/raw/master/data/vtkjs/TBarAssembly.vtkjs" >...
0.688887
0.886519
# Testing MHW Systems ``` # imports from importlib import reload import numpy as np import os from matplotlib import pyplot as plt from pkg_resources import resource_filename from datetime import date import pandas import sqlalchemy import iris import iris.quickplot as qplt import h5py from oceanpy.sst import io a...
github_jupyter
# imports from importlib import reload import numpy as np import os from matplotlib import pyplot as plt from pkg_resources import resource_filename from datetime import date import pandas import sqlalchemy import iris import iris.quickplot as qplt import h5py from oceanpy.sst import io as sst_io from oceanpy.sst i...
0.363647
0.782164
# Pandas Pandas est une librairie Python dédiée à l'analyse de données. ## Series La structure de données Series permet de gérer une **table de données à deux colonnes**, dans laquelle : - les données sont ordonnées - la première colonne contient une clé (index) - le deuxième colonne contient des valeurs - la deuxiè...
github_jupyter
import pandas as pd animaux = ["chien", "chat", "lapin"] pd.Series(animaux) nombres = [10,4,8] ns = pd.Series(nombres) ns nombres = [10,4,None] pd.Series(nombres) import numpy as np np.isnan(np.nan) personne = { "nom":"Dupont", "prénom":"Jean", "age":40 } s = pd.Series(personne) s s.index pd.Series(["Dupont","Jea...
0.131312
0.986058
# Strings and Stuff in Python ``` import numpy as np ``` ## Strings are just arrays of characters ``` s = 'spam' s,len(s),s[0],s[0:2] s[::-1] ``` #### But unlike numerical arrays, you cannot reassign elements: ``` s[0] = "S" s ``` ### Arithmetic with Strings ``` s = 'spam' e = "eggs" s + e s + " " + e 4 * (s ...
github_jupyter
import numpy as np s = 'spam' s,len(s),s[0],s[0:2] s[::-1] s[0] = "S" s s = 'spam' e = "eggs" s + e s + " " + e 4 * (s + " ") + e print(4 * (s + " ") + s + " and\n" + e) # use \n to get a newline with the print function "spam" == "good" "spam" != "good" "spam" == "spam" "sp" < "spam" "spam" < "eggs" "sp" in "...
0.33928
0.89096
# This notebook processes CAFE v3 ocean daily data for building climatologies. Only the last 100 years are used. Currently only runs on Raijin, as control run data not yet transferred to Canberra ``` # Import packages ----- import pandas as pd import xarray as xr import numpy as np from ipywidgets import FloatProgress...
github_jupyter
# Import packages ----- import pandas as pd import xarray as xr import numpy as np from ipywidgets import FloatProgress from dateutil.relativedelta import relativedelta # Standard naming ----- fields = pd.DataFrame( \ {'name_CAFE': ['sst', 'patm_t', 'eta_t', 'sss', 'u_surf', 'v_surf', 'mld'], 'name_st...
0.314051
0.761494
``` from datascience import * path_data = '../../data/' import numpy as np %matplotlib inline import matplotlib.pyplot as plots plots.style.use('fivethirtyeight') cones = Table.read_table(path_data + 'cones.csv') nba = Table.read_table(path_data + 'nba_salaries.csv').relabeled(3, 'SALARY') movies = Table.read_table(p...
github_jupyter
from datascience import * path_data = '../../data/' import numpy as np %matplotlib inline import matplotlib.pyplot as plots plots.style.use('fivethirtyeight') cones = Table.read_table(path_data + 'cones.csv') nba = Table.read_table(path_data + 'nba_salaries.csv').relabeled(3, 'SALARY') movies = Table.read_table(path_...
0.483648
0.946001
##Allele-specific expression analysis in An. coluzzii ``` import matplotlib.pyplot as P %matplotlib inline import numpy as np import pandas as pd RNA = ['A','B','C','D'] #These are wells that contain cDNA D = pd.read_csv("round2/iPLEX_HYBRID_MAPHIG_6_24_16.csv") #focus on UTR SNP cyp9k1 = D.loc[D['Assay']=='CYP9K1-3...
github_jupyter
import matplotlib.pyplot as P %matplotlib inline import numpy as np import pandas as pd RNA = ['A','B','C','D'] #These are wells that contain cDNA D = pd.read_csv("round2/iPLEX_HYBRID_MAPHIG_6_24_16.csv") #focus on UTR SNP cyp9k1 = D.loc[D['Assay']=='CYP9K1-3u'] #grab only cDNA #cyp9k1 = cyp9k1.loc[cyp9k1['WELL'].str...
0.118921
0.556098
# Ames Housing Dataset price modeling We investigate the data to remove unnecessary columns and max-scale label This could either happen in the private data lake or on the modeler's machine. In this case, we mimic a modeler requesting certain fields and a certain series of preprocessing steps. ``` import numpy as np...
github_jupyter
import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt sns.set(rc={'figure.figsize':(11.7,8.27)}) sns.set_style("darkgrid") df = pd.read_csv("data.csv") print(f"Original size of dataframe {df.shape}") residential_areas = {"RH", "RL", "RP", "RM"} acceptable_housing_conditions = ...
0.286469
0.98661
``` import bs4 as bs import datetime as dt import pandas as pd import os import pandas_datareader.data as web import pickle import requests from dateutil.relativedelta import relativedelta, FR end_date = pd.Timestamp(pd.to_datetime('today').strftime("%m/%d/%Y")) start_date = end_date - relativedelta(years=3) def save_s...
github_jupyter
import bs4 as bs import datetime as dt import pandas as pd import os import pandas_datareader.data as web import pickle import requests from dateutil.relativedelta import relativedelta, FR end_date = pd.Timestamp(pd.to_datetime('today').strftime("%m/%d/%Y")) start_date = end_date - relativedelta(years=3) def save_sp500...
0.179387
0.172311
``` import pandas as pd import geopandas as gpd import seaborn as sns import matplotlib.pyplot as plt import husl from legendgram import legendgram import mapclassify from matplotlib_scalebar.scalebar import ScaleBar from matplotlib.colors import ListedColormap from shapely.geometry import Point from tqdm import tqdm ...
github_jupyter
import pandas as pd import geopandas as gpd import seaborn as sns import matplotlib.pyplot as plt import husl from legendgram import legendgram import mapclassify from matplotlib_scalebar.scalebar import ScaleBar from matplotlib.colors import ListedColormap from shapely.geometry import Point from tqdm import tqdm clus...
0.396769
0.669664
<a href="https://colab.research.google.com/github/sid-chaubs/data-mining-assignment-1/blob/main/DMT_1_PJ.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ``` !git clone https://github.com/sid-chaubs/data-mining-assignment-1.git %cd data-mining-assign...
github_jupyter
!git clone https://github.com/sid-chaubs/data-mining-assignment-1.git %cd data-mining-assignment-1/ import numpy as np import matplotlib.pyplot as plt import seaborn as sns import pandas as pd import regex from sklearn import tree, model_selection, preprocessing, ensemble from scipy import stats pd.set_option('display...
0.463687
0.925869