code
stringlengths
2.5k
150k
kind
stringclasses
1 value
# SVM ``` import numpy as np import sympy as sym import pandas as pd from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split import matplotlib.pyplot as plt %matplotlib inline np.random.seed(1) ``` ## Simple Example Application 对于简单的数据样本例子(也就是说可以进行线性划分,且不包含噪声点) **算法:** 输入:线性可分训...
github_jupyter
``` /* These are a list of Redis commands that can be executed in Redis Cli or Scala with Redis_Scala*/ //Redis CLI //launch by going to your redis file and using the cli command redis-cli //to check your connection type // PING // you shoudl receive PONG in returns /* SET for one Key/Value Pair: SET foo 100 GET...
github_jupyter
### Python basic syntax - 변수 선언, 식별자, 자료형, 형변환, 연산자 등 ### 1. 주석(comment)과 출력(print) ``` # 주석 : 앞에 #을 붙이면 코드로 실행되지 않음 # 코드에 대한 설명이나 중간에 코드를 실행시키고 싶지 않을 때 사용 # 단축키 : command + / # block 설정 : shift + 방향키 print(1) # print(2) print(3) # 출력 : print 함수 # 코드 중간에 변수 안에 들어있는 값을 확인하고 싶을 때 사용함 a = 1 b = 2 print(b) c = 3 b = 4 p...
github_jupyter
This notebooks finetunes VGG16 by adding a couple of Dense layers and trains it to classify between cats and dogs. This gives a better classification of around 95% accuracy on the validation dataset ``` %load_ext autoreload %autoreload 2 import numpy as np import tensorflow as tf from tensorflow.contrib.keras impor...
github_jupyter
# Using Simulation to Estimate the Power of an A/B experiment > A tutorial on estimating power of an A/B experiment - toc: false - badges: true - comments: true - categories: [a/b testing, python] - image: images/chart-preview.png # About This article was originally posted in my medium blog post [here](https://mediu...
github_jupyter
``` midx = '1a' # midx = '1a1' # midx = '1a2' # midx = '1a3' import socket import timeit import time from datetime import datetime import os import glob from collections import OrderedDict import numpy as np import pandas as pd import pickle import gc import cv2 import matplotlib.pyplot as plt plt.style.use('seaborn-wh...
github_jupyter
``` #default_exp per_patient ``` # Per-Patient > Create a FHIR bundle of medications for a single patient. As the first step in converting FHIR resources to the CDISC "Concomitant/Prior Medications" CM domain, we'll create a `Bundle` containing one `Patient` and any number of `MedicationAdministration`, `MedicationD...
github_jupyter
## Introduction **Offer Recommender example:** ___ In this example we will show how to: - Setup the required environment for accessing the ecosystem prediction server. - View and track business performance of the Offer Recommender. ## Setup **Setting up import path:** ___ Add path of ecosystem notebook wrappers....
github_jupyter
``` import jax.numpy as jnp import numpy as np import jax import urdf_loader chain = urdf_loader.read_chain_from_urdf('data/kuka_iiwa.urdf', 'lbr_iiwa_link_0', 'lbr_iiwa_link_7') kinematics = urdf_loader.make_kinematic_chain_function(chain) kinematics_j = jax.jit(kinematics) zero_pose = jnp.array([0., 0., 0., 0., 0., ...
github_jupyter
> Code to accompany **Chapter 10: Defending Against Adversarial Inputs** # Fashion-MNIST - Generating Adversarial Examples on a Drop-out Network This notebook demonstrates how to generate adversarial examples using a network that incorporates randomised drop-out. ``` import tensorflow as tf from tensorflow import ke...
github_jupyter
``` # Install TensorFlow # !pip install -q tensorflow-gpu==2.0.0-beta1 try: %tensorflow_version 2.x # Colab only. except Exception: pass import tensorflow as tf print(tf.__version__) # Load in the data from sklearn.datasets import load_breast_cancer # load the data data = load_breast_cancer() # check the type of...
github_jupyter
# Sklearn ## sklearn.datasets документация: http://scikit-learn.org/stable/datasets/ ``` from sklearn import datasets %pylab inline ``` ### Генерация выборок **Способы генерации данных:** * make_classification * make_regression * make_circles * make_checkerboard * etc #### datasets.make_circles ``` circles = da...
github_jupyter
# Responsible ML - Homomorphic Encryption ## Install prerequisites Before running the notebook, make sure the correct versions of these libraries are installed. ``` !pip install encrypted-inference --upgrade ``` ## Setup Azure ML In the next cell, we create a new Workspace config object using the `<subscription_id...
github_jupyter
# Writing OER sets to file for --- ### Import Modules ``` import os print(os.getcwd()) import sys import time; ti = time.time() import json import pandas as pd import numpy as np # ######################################################### from methods import ( get_df_features_targets, get_df_jobs, get_...
github_jupyter
# Multistage Hypersolver pre-train (separated training and ablation study) ``` %load_ext autoreload %autoreload 2 import time import torch import torch.nn as nn import matplotlib.pyplot as plt from math import pi as π import sys; sys.path.append(2*'../') # go n dirs back from src import * from torchdyn.core import ...
github_jupyter
<a href="https://colab.research.google.com/github/jantic/DeOldify/blob/master/ImageColorizerColabStable.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ### **<font color='blue'> Stable Colorizer </font>** #◢ DeOldify - Colorize your own photos! ##...
github_jupyter
``` # testing scRFE pip list from scRFE import scRFE from scRFE import scRFEimplot from scRFE.scRFE import makeOneForest import numpy as np import pandas as pd from anndata import read_h5ad adata = read_h5ad('/Users/madelinepark/Downloads/Liver_droplet.h5ad') madeForest = makeOneForest(dataMatrix=adata, classOfInteres...
github_jupyter
``` import pickle PIK = 'data/sirt6/final/20191217_m87e_counts.pkl' with open(PIK, 'rb') as f: m87e_clobs = pickle.load(f) m87e_clobs import pandas as pd def extract_panda(clob_list): dictlist = [] for i in range(len(clob_list)): dictlist += [clob_list[i].to_dict()] DF = pd.DataFrame(dictlist) ...
github_jupyter
``` #------------------------------------------------------------------------------------------------------------------------------- # By Alexandra Lee # (updated October 2018) # # Main # # Dataset: Pseudomonas aeruginosa gene expression from compendium # referenced in https://www.ncbi.nlm.nih.gov/pmc/articles/PMC506...
github_jupyter
# Performing the Hyperparameter tuning **Learning Objectives** 1. Learn how to use `cloudml-hypertune` to report the results for Cloud hyperparameter tuning trial runs 2. Learn how to configure the `.yaml` file for submitting a Cloud hyperparameter tuning job 3. Submit a hyperparameter tuning job to Cloud AI Platform ...
github_jupyter
# SimPy: Treatment Centre > **To run all code in this notebook go to menu item `Run -> Run All Cells`.** `simpy` uses process based model worldview. Given its simplicity it is a highly flexible discrete-event simulation package. One of the benefits of a package like `simpy` is that it is written in standard python ...
github_jupyter
# Step 1 - Read and Import the Archived Twitter Data The first step is to read and import all the archived data. Download "spritzer" archived data from Raw data from: https://archive.org/details/twitterstream The data is quite large, and is stored in directory/file format as: ./yyyy/mm/dd/hh/{00-99}.json.bz2 Sinc...
github_jupyter
## _*Using Qiskit Aqua for exact cover problems*_ In mathematics, given a collection $S$ of subsets of a set $X$. An exact cover is a subcollection $S_{ec} \subseteq S$ such that each element in $X$ is contained in exactly one subset $\in S_{ec}$. We will go through three examples to show (1) how to run the optimiza...
github_jupyter
``` import os print(os.getcwd()) def update_working_directory(): from pathlib import Path p = Path(os.getcwd()).parents[0] os.chdir(p) print(p) update_working_directory() import dill from src.utils.plots import get_info_params from src.visualization.rl_plots_comparison import plot_comparison_evolution...
github_jupyter
# Overlays Spatial overlays allow you to compare two GeoDataFrames containing polygon or multipolygon geometries and create a new GeoDataFrame with the new geometries representing the spatial combination *and* merged properties. This allows you to answer questions like > What are the demographics of the census tract...
github_jupyter
## Implementing binary decision trees The goal of this notebook is to implement your own binary decision tree classifier. You will: * Use SFrames to do some feature engineering. * Transform categorical variables into binary variables. * Write a function to compute the number of misclassified examples in an interm...
github_jupyter
## 2 - Introductory Example - 1-Axis tracker with cumulative sky Method <b> Gencumsky </b> has been modified to divide the yearly-cumulative sky into various skies, each one representing the cumulative irradiance for the hours at which the tracker is at a certain angle. For faster running, for a tracker that moves bet...
github_jupyter
### Helping functions ``` # Function for tagging residues as LIP/non-LIP # Overwrites entries in the second dataset with LIP flag from the first dataset def LIP_tag(ds_original, ds_residues): #For every protein we take the information of where LIP residue are for idx, row in ds_original.iterrows(): # B...
github_jupyter
``` import sys import platform print("Python version:\n", sys.version) print ("Path to the python executable:\n", sys.executable) ``` # Biomedical Image Segmentation with U-Net In this code example, we apply the U-Net architecture to segment brain tumors from raw MRI scans as shown below. With relatively little data ...
github_jupyter
# Calling RES with Python in SPARK ## Pre-Requisite * Python 3.5 for Spark ## Initializing Python environment with ODM Jars files and ODM Model archive * Create a Spark Session * Initialize the Python environment ``` from io import StringIO import requests import json import pandas as pd #from pyspark.sql...
github_jupyter
# Basic Image Processing #### I have taken an image 'sky.png' which is stored in the 'image-processing' directory, and initially I will find the three brightest points (not spots) in that image. ``` # Importing the required libraries import numpy as np import skimage.io import skimage.color import matplotlib.pyplot a...
github_jupyter
Before you turn this problem in, make sure everything runs as expected. First, **restart the kernel** (in the menubar, select Kernel$\rightarrow$Restart) and then **run all cells** (in the menubar, select Cell$\rightarrow$Run All). Make sure you fill in any place that says `YOUR CODE HERE` or "YOUR ANSWER HERE", as we...
github_jupyter
# Student Performance in E-Learning Envirnoment Importing packages ``` import numpy as np import pandas as pd import seaborn as sn import matplotlib.pyplot as plt import warnings warnings.filterwarnings("ignore") ``` Reading Data ``` data=pd.read_csv('msc2019b.csv') data.head() data.tail() ``` Pre-Processing ``` ...
github_jupyter
## Assignment 1 | Data Types Add code cells as needed for your answers. ### Exercise 1: Manipulating Lists Create a list containing the numbers 10, 20, and 30. Store your list as a variable named `a`. Then create a second list containing the numbers 30, 60, and 90. Call this this `b`. ``` a = [10, 20, 30] b = [30, ...
github_jupyter
##### Copyright 2020 The Cirq Developers ``` #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agre...
github_jupyter
![jpeg](../galleries/coursera-statistics/5w1.jpg) *Screenshot taken from [Coursera](https://class.coursera.org/statistics-003/lecture/115) 03:42* In numerical variable, you want to take the average mean and infer the average and the differences. In categorical variable, you take the proportion of frequency, you may ...
github_jupyter
# Project 3: Implement SLAM --- ## Project Overview In this project, you'll implement SLAM for robot that moves and senses in a 2 dimensional, grid world! SLAM gives us a way to both localize a robot and build up a map of its environment as a robot moves and senses in real-time. This is an active area of research...
github_jupyter
# Question repository A list of open questions and possibly ambiguous stuff encountered throughout the material. TODO: Tag exam-related ones appropriately, to differentiate them from (exclusively) curiosity-related ones. **Note:** An alternative design would consist of adding a questions section to every notebook, t...
github_jupyter
# Model Checking After running an MCMC simulation, `sample` returns a `MultiTrace` object containing the samples for all the stochastic and deterministic random variables. The final step in Bayesian computation is model checking, in order to ensure that inferences derived from your sample are valid. There are two comp...
github_jupyter
# 16장. 로지스틱 회귀 분석 과제 ``` import matplotlib.pyplot as plt import os from typing import List, Tuple import csv from scratch.linear_algebra import Vector, get_column ``` ## 1. 데이터셋 ### 1.1 데이터셋 다운로드 ``` import requests data = requests.get("https://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisco...
github_jupyter
# Programming with Python ## Episode 2 - Analyzing Data from Multiple Files Teaching: 20 min, Exercises: 20 min ## Objectives - Use a library function to get a list of filenames that match a wildcard pattern. - How can I do the same operations on many different files? - Write a for loop to process multiple files. ...
github_jupyter
<font face="Verdana, cursive, sans-serif" > <center><H1>Variable Selection with Information Value <br>and Application of Weight of Evidence</H1></center> <center><H2><font color='darkred'>How to quickly identify potential variable for classification model </font></H2></center> <p>This documentation is powered by <b>J...
github_jupyter
## Importing Basic Tools ``` import numpy as np import pandas as pd import matplotlib.pyplot as plt ``` ## Load the data ``` df = pd.read_csv('../data/data_pp.csv') df.head() ``` ### Asses the baseline ``` df['billboard'].value_counts(normalize=True) # dropping ID, AlbumId, date_month and date_day df_fit = df.dro...
github_jupyter
``` %pylab inline import os import glob import pandas as pd import re from collections import OrderedDict import seaborn as sns sns.set_context('paper', font_scale=2) sns.set_style('white') def clean_tx(tx): return re.sub(r'\.[0-9]+', '', tx) root_dir = '/staging/as/skchoudh/re-ribo-analysis/hg38/SRP010679/ribocop...
github_jupyter
# Nearest Centroid Classification with MInMaxScaler & PowerTransformer This Code template is for the Classification task using a simple NearestCentroid with feature rescaling technique MinMaxScaler and feature tranformation technique used is PowerTransformer in a pipeline. ### Required Packages ``` !pip install imbl...
github_jupyter
# Finger 1 - Analizar la distribución de postulaciones a avisos según: - la fecha - dia del mes - dia de la semana - etc. - Algunas de las preguntas que podrían plantearse son: - Se recibe un volumen de postulaciones similar cualquier dia de la semana? - Existen variaciones según el mes del ...
github_jupyter
# Import ScikitLearn, Pandas and Numpy ``` import sklearn import pandas as pd import numpy as np ``` # 1. Read the Dataset using Pandas ``` train_data = pd.read_csv("data/image_train_data/image_train_data.csv") test_data = pd.read_csv("data/image_test_data/image_test_data.csv") train_data ``` # 2. Exploratory Data ...
github_jupyter
``` %matplotlib inline %config InlineBackend.figure_format = 'retina' import matplotlib.pyplot as plt import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torchvision import datasets, transforms, models from torch.autograd import Variable data_dir = 'Cat...
github_jupyter
``` # OPTIONAL: Load the "autoreload" extension so that code can change %load_ext autoreload # OPTIONAL: always reload modules so that as you change code in src, it gets loaded %autoreload 2 # Adding project root and custom functions from os import listdir, getcwd from os.path import isfile, join import sys from pathl...
github_jupyter
``` import pandas as pd import re import numpy as np import warnings warnings.filterwarnings("ignore") import os import glob, ntpath def file_modify(filename, a=None): with open(filename, 'r+') as file: content = file.read() for ch in ['"']: if ch in content: content = co...
github_jupyter
``` import numpy as np from luwiji.knn import illustration ``` # Avoid the Data Leakage ``` illustration.data_leakage ``` Data Leakage adalah bocornya informasi data test ketika kita training. Hal ini paling sering terjadi ketika: - imputation - kita malah impute menggunakan informasi dari seluruh data, harusnya...
github_jupyter
``` import torch import torch.nn as nn import torchvision.transforms as transforms import torchvision.datasets as datasets from torch.autograd import Variable ``` ## Load data ``` train_dataset = datasets.MNIST(root='D:/dev/data/mnist', train=True, transform=transforms.ToTensor(), download=True) print(len(train_datas...
github_jupyter
# IEEE MEGA PROJECT **Team Name: BetaTech** **Team Leader: Mollika Garg** **Email Id: mollika.garg@gmail.com** **Team Member: Shreya Sharma** **Email Id: shreyasharma.1510001@gmail.com** **Team Member: Koushiki Chakrabarti** *...
github_jupyter
``` from os import listdir from numpy import array from keras.preprocessing.text import Tokenizer, one_hot from keras.preprocessing.sequence import pad_sequences from keras.models import Model from keras.utils import to_categorical from keras.layers import Embedding, TimeDistributed, RepeatVector, LSTM, concatenate , I...
github_jupyter
<a href="https://colab.research.google.com/github/yukinaga/bert_nlp/blob/main/section_2/01_pytorch_basic.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # PyTorchの基礎 PyTorchの基礎を学ぶために、ニューラルネットワークを訓練して手書き文字の認識を行います。 ## データの読み込み `torchvision.datasets`...
github_jupyter
``` import pathlib import warnings from typing import List, Dict import gym import gym_corridor # noqa: F401 import matplotlib.pyplot as plt import numpy as np import pandas as pd from IPython.display import HTML from lcs import Perception from matplotlib.ticker import MultipleLocator, FormatStrFormatter from myst_nb...
github_jupyter
# Modeling and Simulation in Python Chapter 13 Copyright 2017 Allen Downey License: [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0) ``` # Configure Jupyter so figures appear in the notebook %matplotlib inline # Configure Jupyter to display the assigned value after an a...
github_jupyter
``` !pip install geopy !pip install folium !pip install geocoder print("Installed!") ``` <h3>Use geopy library to get the latitude and longitude values of Toronto City</h3> ``` import folium import requests import json import matplotlib.cm as cm import matplotlib.colors as colors import pandas as pd import numpy ...
github_jupyter
# Writing Your Own Graph Algorithms The analytical engine in GraphScope derives from [GRAPE](https://dl.acm.org/doi/10.1145/3282488), a graph processing system proposed on SIGMOD-2017. GRAPE differs from prior systems in its ability to parallelize sequential graph algorithms as a whole. In GRAPE, sequential algorithms...
github_jupyter
# SuStaIn tutorial using simulated data Written by Alex Young in April 2020, updated in April 2021. Please email alexandra.young@kcl.ac.uk with any questions. This tutorial demonstrates how to run Subtype and Stage Inference (SuStaIn) using simulated data. SuStaIn is an unsupervised learning algorithm that identifies...
github_jupyter
<a href="https://colab.research.google.com/github/s-c-soma/RL_Project_FlappyBird_D3QN/blob/main/colab/Flappy_DoubleDueling_DQN_GoogleColab.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ## Double Dueling Deep Q Network Learning with Priortized Expe...
github_jupyter
# Math and Statistics Review for ML Using the smallpox data set, review relevant mathematical and statistical methods commonly used in machine learning. An example will be shown using the Utah data. Choose another state and perform the same operations on the data for that state. ``` import pandas as pd import numpy as...
github_jupyter
``` import os import random import matplotlib.pyplot as plt import numpy as np import pandas as pd from scipy import stats from scipy.io import wavfile import collections DATA_DIR = "/path/to/downloaded/WHAM/Vox/datasets" WORKING_DIR = "/path/to/working/dir" ``` # WHAM Noise Analyse the metadata of the WHAM Noise te...
github_jupyter
# Gas Mixtures: Perfect and Semiperfect Models This Notebook is an example about how to declare and use *Gas Mixtures* with **pyTurb**. Gas Mixtures in **pyTurb** are treated as a combination of different gases of **pyTurb**: - *PerfectIdealGas*: Ideal Equation of State ($pv=R_gT$) and constant $c_p$, $c_v$, $\gamma_g...
github_jupyter
# DAT210x - Programming with Python for DS ## Module4- Lab5 ``` import pandas as pd from scipy import misc from mpl_toolkits.mplot3d import Axes3D import matplotlib import matplotlib.pyplot as plt # Look pretty... # matplotlib.style.use('ggplot') plt.style.use('ggplot') samples = [] ``` Create a regular Python lis...
github_jupyter
# Residual Networks Welcome to the second assignment of this week! You will learn how to build very deep convolutional networks, using Residual Networks (ResNets). In theory, very deep networks can represent very complex functions; but in practice, they are hard to train. Residual Networks, introduced by [He et al.](h...
github_jupyter
``` %reload_ext autoreload %autoreload 2 from fastai.gen_doc.gen_notebooks import * from pathlib import Path ``` ### To update this notebook Run `tools/sgen_notebooks.py Or run below: You need to make sure to refresh right after ``` import glob for f in Path().glob('*.ipynb'): generate_missing_metadata(f) ```...
github_jupyter
# Домашняя работа №1 В этой домашней работе вам предлагается ознакомиться с базовой функциональностью Python и устройством Jupyter Notebook, а так же познакомиться с простыми функциями из пакетов NumPy и matplotlib. Следуйте инструкциям нотебука, решайте задачи, а ответы заполняйте в следующую форму: https://forms.gl...
github_jupyter
<a href="https://colab.research.google.com/github/gustavocac/FromScratch/blob/master/NLP_Lesson_1.1.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> <h1><div align="center">Processamento de Linguagem Natural</div></h1> <div align="center">Gustavo C. ...
github_jupyter
# maysics.calculus模块使用说明 calculus模块包含七个函数 |名称|作用| |---|---| |lim|极限| |ha|哈密顿算符| |grad|梯度| |nebla_dot|nebla算子点乘| |nebla_cross|nebla算子叉乘| |laplace|拉普拉斯算子| |inte|积分| <br></br> ## 求极限:lim lim(f, x0, acc=0.01, method='both') <br>求函数```f```在```acc```的误差下,$x\rightarrow x_{0}$的函数值 <br>```method```可选'both'、'+'、'-',分别表示双边极限、右...
github_jupyter
# Section 5: Manipulating and Cleaning Data This section marks a subtle change. Up until now, we have been introducing ideas and techniques in order to prepare you with a toolbox of techniques to deal with real-world situations. We are now going to start using some of those tools while also giving you some ideas about...
github_jupyter
# Autoencoder ``` %load_ext autoreload %autoreload 2 %matplotlib inline #%matplotlib widget import numpy as np import matplotlib.pyplot as plt from matplotlib import rcParams rcParams['figure.max_open_warning'] = 0 ``` Fetch our tools: ``` from lib.nn import Network, Layer, IdentityLayer, AffineLayer, MapLayer from ...
github_jupyter
# Session 2b: Monte Carlo Methods in Grid World ## Colab Setup ``` #uncomment only if you're running from google colab # !git clone https://github.com/Datatouille/rl-workshop # !mv rl-workshop/* . # !ls ``` ## Imports ``` import numpy as np from collections import defaultdict import matplotlib.pyplot as plt #cross ...
github_jupyter
# M-Estimators for Robust Linear Modeling ``` %matplotlib inline from statsmodels.compat import lmap import numpy as np from scipy import stats import matplotlib.pyplot as plt import statsmodels.api as sm ``` * An M-estimator minimizes the function $$Q(e_i, \rho) = \sum_i~\rho \left (\frac{e_i}{s}\right )$$ where...
github_jupyter
http://scikit-learn.org/stable/modules/generated/sklearn.neighbors.KNeighborsClassifier.html ``` from sklearn.neighbors import KNeighborsClassifier X= [[0.841509434,0.699166,0.845695,0,0.1,0.156,0.967049], [0.749356223,1.611461,0.736916,0,0.2,0.3741,2.693249], [0.263510732,0.433383,0.130578,0,0.05,0.0897,0.451053], [0...
github_jupyter
### 1. Definição do Problema: Esse notebook analisa as equipes finalistas das copas do mundo de futebol da FIFA, entre 1930 e 2018. Os dados foram obtidos no Keaglle (https://www.kaggle.com/abecklas/fifa-world-cup ), compreendendo o período de 1930 até 2014. Esses dados foram compilados no ano de 2018, mesmo ano em qu...
github_jupyter
``` # Binary Classification with Sonar Dataset: Standardized Smaller import numpy from pandas import read_csv from keras.models import Sequential from keras.layers import Dense from keras.wrappers.scikit_learn import KerasClassifier from sklearn.model_selection import cross_val_score from sklearn.preprocessing import L...
github_jupyter
# Programming_Assignment-20 Question1 Create a function that takes a list of strings and integers, and filters out the list so that it returns a list of integers only. Examples filter_list([1, 2, 3, 'a', 'b', 4]) ➞ [1, 2, 3, 4] filter_list(['A', 0, 'Edabit', 1729, 'Python', '1729']) ➞ [0, 1729] filter_list(['Not...
github_jupyter
# Safely refactoring ACLs and firewall rules Changing ACLs or firewall rules (or *filters*) is one of the riskiest updates to a network. Even a small error can block connectivity for a large set of critical services or open up sensitive resources to the world at large. Earlier notebooks showed how to [analyze filters ...
github_jupyter
# Logistic Regression with a Neural Network mindset Welcome to your first (required) programming assignment! You will build a logistic regression classifier to recognize cats. This assignment will step you through how to do this with a Neural Network mindset, and so will also hone your intuitions about deep learning....
github_jupyter
# This notebook serves as an example of how to create AutoTST objects and how to create 3D geometries ``` #General imports import os, sys import logging from copy import deepcopy import numpy as np import pandas as pd from multiprocessing import Process #RDKit imports import rdkit from rdkit import Chem from rdkit.Ch...
github_jupyter
## Tutorial 2: Mixture Models and Expectation Maximization ### Exercise 1: Categorical Mixture Model (CMM) ``` # Import libraries import numpy as np import pandas as pd from ast import literal_eval import matplotlib.pyplot as plt import gensim from wordcloud import WordCloud, STOPWORDS from categorical_em import Ca...
github_jupyter
# Dimensionality reduction using `scikit-learn` ``` import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn import preprocessing, model_selection as ms, \ manifold, decomposition as dec, cross_decomposition as cross_dec from sklearn.pipeline import Pipeline %matplotl...
github_jupyter
``` import pandas as pd import cx_Oracle import sqlalchemy from sqlalchemy.exc import SQLAlchemyError import plotly.express as px import plotly.graph_objects as go from IPython.display import Image ``` ### Fast Cars ``` try: engine = sqlalchemy.create_engine("oracle+cx_oracle://tmulla:aEnWMJvX0zAVpMXXHp2YXieT@ora...
github_jupyter
# 对象和类 - 一个学生,一张桌子,一个圆都是对象 - 对象是类的一个实例,你可以创建多个对象,创建类的一个实例过程被称为实例化, - 在Python中对象就是实例,而实例就是对象 ## 定义类 class ClassName: do something - class 类的表示与def 一样 - 类名最好使用驼峰式 - 在Python2中类是需要继承基类object的,在Python中默认继承,可写可不写 - 可以将普通代码理解为皮肤,而函数可以理解为内衣,那么类可以理解为外套 ## 定义一个不含初始化__init__的简单类 class ClassName: joker = “Home” ...
github_jupyter
# Object Oriented Programming (OOP) - we've been using procedural programming paradigm; focus on functions/procedures - OOP paradigm is best used in large and complex modern software systems which make it easy to maintain and improve over time - focus is on creation of objects which contain both data and functionality ...
github_jupyter
# Régularisation des pronoms ``` def d_in_pos(csv_lu): """ Fonction récupérant le contenu d'un CSV avec les colones suivantes : - "Numero de token" - "Mot forme" - "Modifié" - "Lemme(s)" - "POS" Cette fonction boucle sur chaque token et chaque fois gard...
github_jupyter
# 1. Import libraries ``` #----------------------------Reproducible---------------------------------------------------------------------------------------- import numpy as np import tensorflow as tf import random as rn import os seed=0 os.environ['PYTHONHASHSEED'] = str(seed) np.random.seed(seed) rn.seed(seed) #sess...
github_jupyter
``` import numpy as np import pandas as pd credits = pd.read_csv('credits.csv') credits.head() meta = pd.read_csv('movies_metadata.csv') meta['release_date'] = pd.to_datetime(meta['release_date'], errors='coerce') meta['year'] = meta['release_date'].dt.year meta['year'].value_counts().sort_index() # Getting only 2017 ...
github_jupyter
## Part I: On-policy learning and SARSA (3 points) _This notebook builds upon `qlearning.ipynb`, or to be exact, generating qlearning.py._ The policy we're gonna use is epsilon-greedy policy, where agent takes optimal action with probability $(1-\epsilon)$, otherwise samples action at random. Note that agent __can__...
github_jupyter
population ``` #Routines for scraping and downloading data from http://esa.un.org/unpd/wpp/unpp/panel_indicators.htm #Source: http://schoolofdata.org/2014/09/12/easy-access-to-world-bank-and-un-development-data-from-ipython-notebooks/ import requests from bs4 import BeautifulSoup from io import StringIO import panda...
github_jupyter
``` import numpy as np import pandas as pd import os import re from sklearn.preprocessing import LabelEncoder from keras.utils.np_utils import to_categorical from sklearn.model_selection import train_test_split import matplotlib.pyplot as plt from gensim.models import Word2Vec from nltk.tokenize import word_tokenize,...
github_jupyter
# AWS Summit San Francisco 2022 ## Using AWS Inferentia to optimize HuggingFace model inference Welcome to the AWS Summit San Francisco 2022 Inferentia Workshop! # Table of contents 1. [Introduction](#introduction) 1. [Setting up the environment](#setenv) 3. [Get model from HuggingFace Model Hub](#getmodel) 1...
github_jupyter
![Callysto.ca Banner](https://github.com/callysto/curriculum-notebooks/blob/master/callysto-notebook-banner-top.jpg?raw=true) <a href="https://hub.callysto.ca/jupyter/hub/user-redirect/git-pull?repo=https%3A%2F%2Fgithub.com%2Fcallysto%2Fcurriculum-notebooks&branch=master&subPath=Mathematics/TriangleArea/triangle-area....
github_jupyter
# Facies classification using Machine Learning # ## LA Team Submission 5 ## ### _[Lukas Mosser](https://at.linkedin.com/in/lukas-mosser-9948b32b/en), [Alfredo De la Fuente](https://pe.linkedin.com/in/alfredodelafuenteb)_ #### In this approach for solving the facies classfication problem ( https://github.com/seg/2016-...
github_jupyter
TSG086 - Run `top` in all containers ==================================== Steps ----- ### Instantiate Kubernetes client ``` # Instantiate the Python Kubernetes client into 'api' variable import os from IPython.display import Markdown try: from kubernetes import client, config from kubernetes.stream import ...
github_jupyter
<a href="https://colab.research.google.com/github/davy-datascience/ml_algorithms/blob/master/LinearRegression/Approach-1/Linear%20Regression.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # Linear Regression - with single variable ## Intro I firs...
github_jupyter
# TASK #1: DEFINE SINGLE AND MULTI-DIMENSIONAL NUMPY ARRAYS ``` # NumPy is a Linear Algebra Library used for multidimensional arrays # NumPy brings the best of two worlds: (1) C/Fortran computational efficiency, (2) Python language easy syntax # Let's define a one-dimensional array import NumPy as np list_1 = [6,8...
github_jupyter
``` import pandas as pd import scipy.io import os import matplotlib.pyplot as plt path = os.getcwd() matlab_exe_path = '''matlab''' julia_path = '''C:\\Users\\mwaugh\\AppData\\Local\\Programs\\Julia\\Julia-1.4.0\\bin\\julia.exe''' path = "src\\calibration" #fig_path = "C:\\users\mwaugh\\github\\perla_tonetti_waugh\...
github_jupyter
``` import numpy as np import pandas as pd from CSVUtils import * import pickle from os import path import matplotlib.pyplot as plt ROOT_DIR = "./from github/Stock-Trading-Environment/" freq_list = [ { "freq": 1, "training": "10k", "DIR": "./output/200", "prefix": "BRZ+TW+NASDAQ-Trai...
github_jupyter