text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
``` from lightgbm import LGBMRegressor from sklearn.compose import make_column_transformer from sklearn.linear_model import TheilSenRegressor from sklearn.model_selection import train_test_split from sklearn.pipeline import make_pipeline from sklearn.preprocessing import FunctionTransformer import pandas as pd import ...
github_jupyter
# VSB Power Grid Fault Detection ``` from IPython.display import Image Image(url='https://upload.wikimedia.org/wikipedia/commons/thumb/e/e0/Three_Phase_Electric_Power_Transmission.jpg/1200px-Three_Phase_Electric_Power_Transmission.jpg') ``` Data Source: https://www.kaggle.com/c/vsb-power-line-fault-detection Useful ...
github_jupyter
### ***1. CTR数据中的类别数据处理,编码方式有哪些,区别是什么?*** 对于 CTR 数据中的类别数据,比如用户所在的省份,城市;所使用的移动设备的型号,操作系统版本等。可采用的编码方法是通常有: 1. LabelEncoding - 将不同的类别的按照不同的整型数字编码。 2. OneHotEncoding - 用一个0和1组成的向量来表示来表示每一个类别,并确保在OneHot编码中体现类别的唯一性。 ### ***2. 对于时间类型数据,处理方法有哪些?*** 机器学习中对数据处理可以认为是广义的特征工程,它包括了如下几个部分: ![feature_engineering](./images/Feature_...
github_jupyter
``` import json from collections import Counter from keras.models import Model from keras.layers import Embedding, Input, Reshape from keras.layers.merge import Dot from sklearn.linear_model import LinearRegression import numpy as np import random from sklearn import svm with open('data/wp_movies_10k.ndjson') as fin: ...
github_jupyter
# Convolutional Neural Networks: Application Welcome to Course 4's second assignment! In this notebook, you will: - Implement helper functions that you will use when implementing a TensorFlow model - Implement a fully functioning ConvNet using TensorFlow **After this assignment you will be able to:** - Build and t...
github_jupyter
``` import sys sys.path.insert(1, '/media/galia-lab/Data1/users/gidonl/connectome_embed/cepy') import numpy as np import cepy as ce import os import time ``` ## Learn embeddings of The Enhanced Nathan Kline Institute Rockland Sample: The purpose of this notebook is to create CEs of a large group of subjects from The...
github_jupyter
# Sharpe ratio (Solution) ## Install packages ``` import sys !{sys.executable} -m pip install -r requirements.txt import cvxpy as cvx import numpy as np import pandas as pd import time import os import quiz_helper import matplotlib.pyplot as plt %matplotlib inline plt.style.use('ggplot') plt.rcParams['figure.figsize'...
github_jupyter
# SETUP: Train and optimize a pet detector using Azure ML This notebook will setup the Azure ML workspace and resources for the pet detector project. The Azure ML resources that we will be using in the pet detector project are: 1. Workspace 1. Experiment 1. Azure Compute Cluster 1. Datastore 1. HyperDrive 1. Azure C...
github_jupyter
``` !nvidia-smi import io import os import sys import gc import pickle import random import termcolor import warnings import shutil import math from functools import partial from datetime import datetime from dataclasses import dataclass from pathlib import Path from typing import List import pandas as pd import numpy...
github_jupyter
``` %matplotlib inline import numpy as np from matplotlib import pyplot as plt ``` # How computers Make Predictions Consider the 1D advection equation: \begin{equation} \frac{\partial u}{\partial t} + a \frac{\partial u}{\partial x} = 0 \end{equation} Here $u(x, t)$ is a function of space and time that satisfies t...
github_jupyter
# Exercices ## Questions Une boucle est une {bl}`multiplication|>répétition|réparation|condition` d'un {bl}`>bloc|truc|itérateur|argument`. ```{question} :multi: Une boucle **for** - {v}`itère sur une séquence` - {f}`attend une condition` - {v}`parcourt un ensemble` - {f}`se termine quand un test est faux` ``` ##...
github_jupyter
``` from google.colab import drive drive.mount('/content/drive') !pip install transformers !pip install imblearn from sklearn.linear_model import LogisticRegression from sklearn.model_selection import train_test_split from scipy.stats import spearmanr from imblearn.over_sampling import SMOTE import pandas as pd ...
github_jupyter
# Introduction to Tensors and Variables **Learning Objectives** 1. Understand Basic and Advanced Tensor Concepts 2. Understand Single-Axis and Multi-Axis Indexing 3. Create Tensors and Variables ## Introduction In this notebook, we look at tensors, which are multi-dimensional arrays with a uniform type (called ...
github_jupyter
# Ground state solvers ## Introduction <img src="aux_files/H2_gs.png" width="200"> In this tutorial we are going to discuss the ground state calculation interface of Qiskit Nature. The goal is to compute the ground state of a molecular Hamiltonian. This Hamiltonian can be electronic or vibrational. To know more abou...
github_jupyter
# Training We will train the network and save the model to disk. We will use this model in the `predict.ipynb` notebook. **Note**: We are currently using tensorflow 2.0 which is currently in beta state. So it is expected and ok that there are warnings! ## import libraries and set constants ``` from __future__ impo...
github_jupyter
``` # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writi...
github_jupyter
``` import datetime import json import vk import operator import matplotlib.pyplot as plt import numpy as np import os import gensim import gensim.corpora as corpora import pyLDAvis import nltk from nltk.corpus import stopwords import pyLDAvis.gensim import pymorphy2 from wordcloud import WordCloud import numpy as np i...
github_jupyter
# Bioinformatics Modeling ## Synthetic Gene Sequence Data Builder - Tutorial 1 ## Pre-requisites: - Access to an IBM Cloud Object Storage instance - The e2eai_credentials.json file (included in the repo clone) in your local directory updated with credentials to the cloud object storage instance - A copy of ICOS.p...
github_jupyter
``` import pandas as pd import matplotlib.pyplot as plt %matplotlib inline import numpy as np import seaborn as sns from scipy import stats runs =[ "SA", "SA_CA", "SA_SR","SA_CM", "SA_CTRD", "MD", "CG", "CG_MD" ] def get_ref_secondary(): """returns a DataFrame containing all the reference structure...
github_jupyter
# John Conway's Game of Life The cellular automata game *Life*, invented by the mathematician [John Conway](https://en.wikipedia.org/wiki/John_Horton_Conway), makes a fun programming exercise. Let's review the [rules](http://en.wikipedia.org/wiki/Conway%27s_Game_of_Life): The *world* of the Game of Life is an infini...
github_jupyter
# Simple CNN for MNIST Using the MNIST dataset (70 000 pictures of hand-written digits) we will train a simple CNN, which is able to predict a digit given a picture of a hand-written digit with 99% accuracy. ``` import numpy as np np.random.seed(1337) # for reproducibility from keras.datasets import mnist from kera...
github_jupyter
# *Imports and Dataset* ``` import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline from sklearn.linear_model import LogisticRegression from sklearn.neighbors import KNeighborsClassifier from sklearn.ensemble import RandomForestClassifier from sklearn.model_se...
github_jupyter
# Stationarity and Correlation Analysis ``` import pandas as pd import numpy as np import matplotlib.pyplot as plt ``` # What is Stationarity? #### A stationary time series is one whose properties do not depend on the time at which the series is observed. Hyndman, R.J., & Athanasopoulos, G. (2018) Forecasting: prin...
github_jupyter
# T81-558: Applications of Deep Neural Networks **Module 3: Introduction to TensorFlow** * Instructor: [Jeff Heaton](https://sites.wustl.edu/jeffheaton/), McKelvey School of Engineering, [Washington University in St. Louis](https://engineering.wustl.edu/Programs/Pages/default.aspx) * For more information visit the [cla...
github_jupyter
``` from __future__ import absolute_import, division, print_function import torch import numpy as np from torch.utils.data import DataLoader from torch import optim from torch import nn from torch.autograd import Variable import os from tqdm.notebook import tqdm import math import matplotlib.pyplot as plt # file para...
github_jupyter
``` import tensorflow as tf from tensorflow.keras import Sequential from tensorflow.keras.layers import Conv1D, MaxPool1D, Flatten, Dense, Dropout, BatchNormalization from tensorflow.keras.optimizers import Adam print(tf.__version__) import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot ...
github_jupyter
# Supply Network Design 2 ## Objective and Prerequisites Take your supply chain network design skills to the next level in this example. We’ll show you how – given a set of factories, depots, and customers – you can use mathematical optimization to determine which depots to open or close in order to minimize overall ...
github_jupyter
<a name="building-language-model"></a> # Building the language model <a name="count-matrix"></a> ### Count matrix To calculate the n-gram probability, you will need to count frequencies of n-grams and n-gram prefixes in the training dataset. In some of the code assignment exercises, you will store the n-gram frequenc...
github_jupyter
# Purpose The purpose of this notebook is to analyze item similarities learned by training a factorization machine model. This consists of the following steps: 1. Load in movielens data 2. preprocess the data, and train a model. 3. Extract the item embedding vectors, and compute cosine similarities 4. Generate visual ...
github_jupyter
<a href="https://colab.research.google.com/github/Tessellate-Imaging/monk_v1/blob/master/study_roadmaps/4_image_classification_zoo/Classifier%20-%20Food%20101%20Dataset.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # Table of contents ## Install...
github_jupyter
``` from matplotlib import pyplot as plt import networkx as nx import numpy as np ``` # Erdos Renyi ``` N = 500 k = 0.8 def gen_erdos(N, k): G = nx.erdos_renyi_graph(N, k / N) options = { "node_color": "red", 'node_size': 5, } nx.draw(G, pos=nx.circular_layout(G), alpha=0.5, **option...
github_jupyter
# Tradução Uma das forças motrizes que possibilitaram o desenvolvimento da civilização humana é a capacidade de se comunicar uns com os outros. Na maioria das atividades humanas, a comunicação é a chave. ![Um robô multilíngue](./images/translation.jpg) A inteligência artificial (IA) pode ajudar a simplificar a...
github_jupyter
# Verification Example Notebook This Notebook will show how to use the verification script by providing a few examples in order of increasing difficulty. Before you start I highly reccomend reading [README.md](https://github.com/OpenPrecincts/verification/blob/master/README.md) The following cells will show how to us...
github_jupyter
# Load and prepare data **Objective**: Load news and tweets data from raw data files into sqlite3 db. Last modified: 2017-10-15 # Roadmap 1. Copy ~~Meng~~ original data folder to DATA_DIR, unzip and check format. 2. Create db. Build tables for news and tweets. 3. Bulk load news and tweets data into db. 4. Check bas...
github_jupyter
Strings ==== The process of cleaning data for analysis often requires working with text, for example, to correct typos, convert to standard nomenclature and resolve ambiguous labels. In some statistical fields that deal with (say) processing electronic medical records, information science or recommendations based on u...
github_jupyter
<small><i>This notebook was prepared by [Donne Martin](http://donnemartin.com). Source and license info is on [GitHub](https://github.com/donnemartin/data-science-ipython-notebooks).</i></small> # Functions * Functions as Objects * Lambda Functions * Closures * \*args, \*\*kwargs * Currying * Generators * Generator E...
github_jupyter
# Sensors ``` from pcg_gazebo.simulation import create_object, SimulationModel from pcg_gazebo.task_manager import get_rostopic_list # If there is a Gazebo instance running, you can spawn the box # into the simulation from pcg_gazebo.task_manager import Server # First create a simulation server server = Server() # Cr...
github_jupyter
# Conociendo Python <img style="float: right; margin: 0px 0px 15px 15px;" src="https://upload.wikimedia.org/wikipedia/commons/c/c3/Python-logo-notext.svg" width="200px" height="200px" /> > Introducción a la materia, guía de instalación y descripción de las herramientas computacionales que se van a utilizar a lo largo...
github_jupyter
``` # header files import torch import torch.nn as nn import torchvision import numpy as np from google.colab import drive drive.mount('/content/drive') np.random.seed(1234) torch.manual_seed(1234) torch.cuda.manual_seed(1234) # define transforms train_transforms = torchvision.transforms.Compose([torchvision.transforms...
github_jupyter
``` #Importing all required libraries import os import tensorflow as tf from tensorflow.keras import layers from tensorflow.keras import Model from os import getcwd import pandas as pd import numpy as np import matplotlib.pyplot as plt from tensorflow.keras.optimizers import RMSprop import shutil from shutil import rmt...
github_jupyter
# Test of Resampling Methods ## Utility Functions ``` import time import pandas as pd import numpy as np import neurokit2 as nk %matplotlib inline def generate_signal(length=1000, end=20): signal = np.cos(np.linspace(start=0, stop=end, num=length)) return(signal) def resample(signal, method="interpolation")...
github_jupyter
## 📍 Map initialization There are several ways to draw background maps with Python. For a complete review, visit the [map section](https://www.python-graph-gallery.com/map) of the gallery This example uses the `Basemap` library. Let's initialize a map of the world as explained in [this post](https://www.python-graph...
github_jupyter
``` %matplotlib inline ``` # Blend transparency with color in 2-D images Blend transparency with color to highlight parts of data with imshow. A common use for :func:`matplotlib.pyplot.imshow` is to plot a 2-D statistical map. The function makes it easy to visualize a 2-D matrix as an image and add transparency to...
github_jupyter
``` from pyspark.sql import SparkSession import pyspark.sql.functions as f if not 'spark' in locals(): spark = SparkSession.builder \ .master("local[*]") \ .config("spark.driver.memory","64G") \ .getOrCreate() spark ``` # Get Data from S3 First we load the data source containing raw weat...
github_jupyter
# Exploratory Data Analysis ## Objectives * Determine the shape of the annotation data. * Identify class balance. * Examine image metadata. * Visualize images. * Visualize bounding boxes. * Get the mean pixel intensity of all images, to set as a parameter for Mask R-CNN. ## Data * Radiological Society of North Ame...
github_jupyter
# Hyper-parameter tuning **Learning Objectives** 1. Understand various approaches to hyperparameter tuning 2. Automate hyperparameter tuning using CMLE HyperTune ## Introduction In the previous notebook we achieved an RMSE of **4.13**. Let's see if we can improve upon that by tuning our hyperparameters. Hyperparame...
github_jupyter
``` import cv2 import numpy as np import matplotlib.pyplot as plt %matplotlib inline class ColorTracking: def rgb_to_hsv(self, r, g, b): ma, mi = max(r, g, b), min(r, g, b) h, s, v = 0, ma - mi, ma if mi == b: h = 60 * (g-r) / (ma-mi) + 60 elif mi == r: h = 60...
github_jupyter
# Building an Intake-esm catalog from CESM2 History Files As mentioned in a couple of ESDS posts ([intake-esm and Dask](https://ncar.github.io/esds/posts/intake_esm_dask/), [debugging intake-esm](https://ncar.github.io/esds/posts/intake_cmip6_debug/)), [intake-esm](https://intake-esm.readthedocs.io/en/latest/) can be ...
github_jupyter
``` %pylab inline from sklearn import svm, datasets iris = datasets.load_iris() iris.data[0:2] X = iris.data[:,:2] y = iris.target X[0:2] y[0:2] C = 1.0 # linear, poly, rbf svc = svm.SVC(kernel='linear', C=1, gamma='auto').fit(X, y) type(X) X[0:10] X[:,0] # create a mesh to plot in x_min, x_max = X[:, 0].min() - 1, X[:...
github_jupyter
# os.path This module implements some useful functions on pathnames. To read or write see `open()`, and for accessing the filesystem see the os module. The path paramenters can be passed as either strings or bytes. Applications are encouraged to represent file names as (unicode) character strings. Unfortunetly some fil...
github_jupyter
<a target="_blank" href="https://colab.research.google.com/github/ati-ozgur/kurs-neural-networks-deep-learning/blob/master/notebooks/keras-fchollet-using-word-embeddings-pretrained.ipynb">Run in Google Colab </a> Example is taken from François Chollet book: Deep Learning with Python Original code can be found in ...
github_jupyter
## Robbins-Monroe Algorithm Assume we wish to find the root of an unknown function $g(x)$. If $g(x)$ were known and continuously differentiable we could apply Newton's method $$x_{n+1} = x_n - \frac{g(x_n)}{g_x(x_n)}$$ where $g_x(\cdot)$ is the derivative of $g(\cdot)$ with respect to $x$. An alternative approach wo...
github_jupyter
``` import h5py, json, spacy import numpy as np import cPickle as pickle %matplotlib inline import matplotlib.pyplot as plt from model import LSTMModel from utils import prepare_ques_batch, prepare_im_batch, get_batches_idx embeddings = spacy.en.English() word_dim = 300 nb_classes = 1000 h5_img_file_train = h5py.Fil...
github_jupyter
# Multiclass Voting Classifier to Predict Wine Quality Score ## Wine Data Data from http://archive.ics.uci.edu/ml/datasets/Wine+Quality ### Citations P. Cortez, A. Cerdeira, F. Almeida, T. Matos and J. Reis. Modeling wine preferences by data mining from physicochemical properties. In Decision Support Systems, Elsevi...
github_jupyter
``` # importing prerequisites import sys import requests import cv2 import random import tarfile import json import numpy as np import pdf2image from os import path from PIL import Image from PIL import ImageFont, ImageDraw from glob import glob from matplotlib import pyplot as plt from pdf2image import convert_from_pa...
github_jupyter
# How to Use Jupyter Notebook To edit a cell in Jupyter notebook, run the cell by pressing Shift + Enter. This will allow changes you made to be available to other cells. For more Keyboard Shortcuts go to navigation bar -- "Help" -- "Keyboard Shortcuts" ### Code cells Re-running will execute any statements you have w...
github_jupyter
``` import cv2 import numpy as np import matplotlib.pyplot as plt import matplotlib.image as mpimg import glob import copy class LaneFinding(): def __init__(self): self.ym_per_pix = 30/720 self.xm_per_pix = 3.7/700 self.obj_points , self.img_points = self.camera_calibrate() #self.sr...
github_jupyter
## Ludwig, 2020 Code to Calculate Xray Luminosity for Binary Stripped Star - Neutron Star Source. ## Calculation by Ylva Gotberg and Katelyn Breivik ### Dependencies : https://pypi.org/project/tabula-py/ and latex (for plots) pip install tabula-py (not tabula!) ## Luminosity Calculation: ### Assumptions: ##...
github_jupyter
``` # 그래프, 수학 기능 추가 # Add graph and math features import pylab as py import numpy as np import numpy.linalg as nl # 기호 연산 기능 추가 # Add symbolic operation capability import sympy as sy ``` # 파이썬에서의 선형대수 : 사이파이 계열의 넘파이<br>Linear Algebra in Python: NumPy of SciPy Stack 파이썬 프로그래밍 언어의 기본 기능만으로도 선형 대수 문제를 해결하는 것이 가능은 하나, 보다...
github_jupyter
# Exploring the Lorenz System of Differential Equations In this Notebook we explore the Lorenz system of differential equations: $$ \begin{aligned} \dot{x} & = \sigma(y-x) \\ \dot{y} & = \rho x - y - xz \\ \dot{z} & = -\beta z + xy \end{aligned} $$ This is one of the classic systems in non-linear differential equati...
github_jupyter
``` import pandas as pd import numpy as np import cPickle from nltk.corpus import stopwords from gensim.models import word2vec import nltk.data import re import logging from nltk.stem.snowball import * import itertools # Python 2.x: import HTMLParser html_parser = HTMLParser.HTMLParser() import multiprocessing loggi...
github_jupyter
# SUTD 2021 50.007 Machine Learning HMM Project Part 4 > Group 4: > - Ma Yuchen (1004519) > - Chung Wah Kit (1004103) > - James Raphael Tiovalen (1004555) ## Initial Workspace Setup ``` # Setup and install dependencies # !pip3 install numpy # !pip3 install torch # Import libraries import os import numpy as np from ...
github_jupyter
# Pore Scale Imaging and Modeling Section I In this project, we have selected a comprehensive paper related to [pore scale imaging and modeling](https://www.sciencedirect.com/science/article/pii/S0309170812000528). The goal of this example is to investigate the permeability of different rock samples. As there are diff...
github_jupyter
# Gridded data, NetCDF ## Xarray When working with higher dimensional data (3D or more), we can't rely on Pandas. Here comes [Xarray](http://xarray.pydata.org/en/stable/index.html) to the rescue. * It has Pandas like syntax, so if you know Pandas you will find yourself at home with Xarray. * format agnostic: It can re...
github_jupyter
# PRÁCTICA 02. # Perceptrón Simple. ### OBJETIVO: Que el alumno implemente el perceptrón simple y lo aplique en distintos conjuntos de datos aplicando variaciones en la forma de aprendizaje del perceptrón. ``` %matplotlib inline import matplotlib.pyplot as plt import matplotlib.cm as cm from mpl_toolkits.mplot3d im...
github_jupyter
``` import importlib import json import os import sys import matplotlib.pyplot as plt import numpy as np import pandas as pd import torch import torchvision.models as models from PIL import Image from torchvision import transforms from torch.nn import functional as F sys.path.append("../src") import dataloader import...
github_jupyter
# Louvain Community Detection In this notebook, we will use cuGraph to identify the cluster in a test graph using the Louvain algorithm Notebook Credits * Original Authors: Bradley Rees and James Wyles * Created: 08/01/2019 * Last Edit: 10/16/2019 RAPIDS Versions: 0.10.0 Test Hardware * GV100 32G, CUDA 10.0 ...
github_jupyter
Notebook is a useful tool for data scientists: It allows us to use coding and presentation tools together. ``` # we can code print("Welcome to DATA601!") ``` __we can create headers of different sizes__ # Header ## Header ### Header #### Header __we can create bullet points__ - Item - item __we can order item...
github_jupyter
``` %pylab inline import pandas as pd human_orthology = pd.read_table('/home/cmb-panasas2/skchoudh/genomes/ensemble_orthology/human-mouse/human_query.tsv').set_index('ensembl_gene_id') mouse_orthology = pd.read_table('/home/cmb-panasas2/skchoudh/genomes/ensemble_orthology/human-mouse/mouse_query.tsv').set_index('ensemb...
github_jupyter
# Determines bounding boxes for each sulcus This notebook determines bounding box around a sulcus. It uses a supervised database, in which each sulcus has been manually labelled. # Imports ``` import sys import os import json ``` The following line permits to import deep_folding even if this notebook is executed fr...
github_jupyter
# Table of Contents <p><div class="lev1 toc-item"><a href="#Defining-a-gene-compactifier-for-easy-printing" data-toc-modified-id="Defining-a-gene-compactifier-for-easy-printing-1"><span class="toc-item-num">1&nbsp;&nbsp;</span>Defining a gene compactifier for easy printing</a></div><div class="lev1 toc-item"><a href="...
github_jupyter
``` import numpy as np import pandas as pd import matplotlib.pyplot as plt import geopandas as gpd import geoplot import pickle import geoplot.crs as gcrs import statsmodels.api as sm mount_path = "/mnt/c/Users/jason/Dropbox (MIT)/" #mount_path = "/Users/shenhaowang/Dropbox (MIT)/project_media_lab_South_Australia/" age...
github_jupyter
# Matplotlib图鉴——进阶饼图 ## 公众号:可视化图鉴 ``` import matplotlib print(matplotlib.__version__) #查看Matplotlib版本 import pandas as pd print(pd.__version__) #查看pandas版本 import numpy as np print(np.__version__) #查看numpy版本 import matplotlib.pyplot as plt import matplotlib as mpl plt.rcParams['font.sans-serif'] = ['STHeiti'] #设置中文...
github_jupyter
``` from __future__ import absolute_import, division, print_function from matplotlib.font_manager import _rebuild; _rebuild() #Helper libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd import scipy.io as spio import keras from keras.models import Sequential from keras.layers import Dense f...
github_jupyter
``` from pyspark.sql.functions import col, when data_lake_account_name = '' # Synapse Workspace ADLS file_system_name = 'relmeshadlsfs' sf_accounts_path = f'abfss://{file_system_name}@{data_lake_account_name}.dfs.core.windows.net/salesforcedata/account/accounts.csv' mapping_file = f'abfss://{file_system_name}@{data_lak...
github_jupyter
# Data frames manipulation with pandas [pandas](https://pandas.pydata.org/) - fast, powerful, flexible and easy to use open source data analysis and manipulation tool, built on top of the Python programming language. ---------------- ``` ## Load libraries import pandas as pd import matplotlib.pyplot as plt ``` ## ...
github_jupyter
``` import numpy as np import pandas as pd from sklearn import preprocessing data = np.loadtxt("data.csv",delimiter=',') #len(data[0]),len(data[1]) M = len(data[0]) x = data[:,0:(M-1)] y = data[:,M-1:] z = np.ones((len(data),1)) new_d = np.hstack((x,z)) new_d = np.hstack((new_d,y)) points = np.loadtxt("test_boston_x_t...
github_jupyter
``` from collections import namedtuple ``` ## Problem - you want to sort a list of comments represented as tuples, namedtuples, dicts, objects by either the number of likes or comment.content length. ``` comment_str = 'Python3 is awesome' comment_tuple = ('Junior', 'Python3 is awesome', 5, (8, 5, 2019)) comment_dic...
github_jupyter
``` # !pip install smart_open import sagemaker import boto3 from sagemaker import image_uris from sagemaker.session import Session from sagemaker.inputs import TrainingInput ## data preprocessing libraries import pandas as pd from sklearn.model_selection import train_test_split from smart_open import open as s_open imp...
github_jupyter
## ColorScale The colors for the `ColorScale` can be defined one of two ways: - Manually, by setting the scale's `colors` attribute to a list of css colors. They can be either: - html colors (link) `'white'` - hex `'#000000'` - rgb `'rgb(0, 0, 0)'`. ```python col_sc = ColorScale(colors=['yellow', 'red']) ```...
github_jupyter
<div class="alert alert-block alert-info" style="margin-top: 20px"> <a href="https://cocl.us/NotebooksPython101"> <img src="https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/PY0101EN/Ad/TopAd.png" width="750" align="center"> </a> </div> <a href="https://cognitiveclass.ai...
github_jupyter
# Train and visualize a model in Tensorflow - Part 4: Inspecting the model Neural networks have been widely critized because of the lack of interpretation of their internal parameters. In this notebook we will present some techniques to log and visualize the model behaviour during training. The lack of interpretabili...
github_jupyter
``` """ This set of functions help the users resize """ import os import json import numpy as np import matplotlib import matplotlib.pyplot as plt import detectron2 import detectron2.data.transforms as T from detectron2.structures import BoxMode from detectron2.engine.defaults import DefaultPredictor import labelme ...
github_jupyter
<a href="https://colab.research.google.com/github/tensorflow/privacy/blob/master/tutorials/Classification_Privacy.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ##### Copyright 2019 The TensorFlow Authors. ``` #@title Licensed under the Apache Lic...
github_jupyter
##### Copyright 2020 The TensorFlow Authors. ``` #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ...
github_jupyter
``` from sklearn import model_selection, metrics, utils import tensorflow as tf import keras.callbacks as callbacks import numpy as np import pandas as pd from amp.models.discriminators import veltri_amp_classifier import amp.data_utils.data_loader as data_loader import amp.utils.classifier_utils as cu import matplotli...
github_jupyter
# Final Project # Title: California Housing Price Analysis ## Team members ### Names: Shuibenyang Yuan, Bolin Yang ### PIDs: A14031016, A92111272 <img src="housing.jpg" width="50%"> ## Research Questions & Reasons for choosing them The reason we want to analyze the housing price in California is that housing prices...
github_jupyter
# Modules If you quit from the Python interpreter and enter it again, the definitions you have made (functions and variables) are lost. Therefore, if you want to write a somewhat longer program, you are better off using a text editor to prepare the input for the interpreter and running it with that file as input inste...
github_jupyter
# Introduction to Spark Spark is a fast and general engine for big data processing, with built-in modules for streaming, SQL, machine learning and graph processing. Spark applications can be written in Python, Java, Scala in R. It integrates well with IPython and the entire Python Stack (e.g. Numpy). The company Dat...
github_jupyter
``` import os import numpy as np import matplotlib.pyplot as plt import tensorflow as tf import pkg_resources import debvader ``` ### Download and format data Download dataset that will be used for training. It has been generated using the code in https://github.com/BastienArcelin/dc2_img_generation and the stamps a...
github_jupyter
# Data Mining: Homework 7 ### Elaheh Toulabi Nejad | 9631232 ## 1. Logistic Regression ### a) ``` import pandas as pd from sklearn.datasets import load_breast_cancer cancer_data = load_breast_cancer() data = pd.DataFrame(cancer_data.data,columns=cancer_data.feature_names) data.head(3) ``` <hr style = "border-top...
github_jupyter
# Detailed execution time for cadCAD models *Danilo Lessa Bernardineli* --- This notebook shows how you can get detailed info about the execution time by using Python decorators on the minimal P&P model. The strategy is to make use of the decorator as defined in the next block, and use in the most convenient way. T...
github_jupyter
# Keras for Text Classification **Learning Objectives** 1. Learn how to tokenize and integerize a corpus of text for training in Keras 1. Learn how to do one-hot-encodings in Keras 1. Learn how to use embedding layers to represent words in Keras 1. Learn about the bag-of-word representation for sentences 1. Learn how ...
github_jupyter
![data-x](https://raw.githubusercontent.com/afo/data-x-plaksha/master/imgsource/dx_logo.png) <br> **References and Additional Resources** <br> > [TensorFlow Guides: Keras Sequential Model](https://www.tensorflow.org/guide/keras/sequential_model)<br> > [Keras: The Sequential Model Guide](https://keras.io/guides/seq...
github_jupyter
``` # 3가지 타입(def read_type, art_type, view_type)으로 나뉘고 각각 실행해야함 # 4/30 ~ 4/1 1달간 총 14393개 *50개(3분) ## 입력값(이것만 입력할 것) ## num = [0, 5827] # 수행할 구간, 매일경제은 range(0, n+1) 번 설정해야함, 내가 처음에 range(0,50)까지했으면 다음에는 range(50,이후숫자) loot = 'C:/Users/###/###/###/' # 저장할 위치, 파일이 산만해지니 프로젝트가아닌폴더에서 관리할 것 # loot = './/' 현재위치에 저장하는 변수 ...
github_jupyter
# Amazon SageMaker Multi-Model Endpoints using XGBoost With [Amazon SageMaker multi-model endpoints](https://docs.aws.amazon.com/sagemaker/latest/dg/multi-model-endpoints.html), customers can create an endpoint that seamlessly hosts up to thousands of models. These endpoints are well suited to use cases where any one o...
github_jupyter
d # Distributed Inference with mapInPandas Train sklearn model and log with MLflow. ``` ls /dbfs/databricks-datasets/learning-spark-v2/sf-airbnb import mlflow.sklearn import pandas as pd from sklearn.ensemble import RandomForestRegressor from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score fr...
github_jupyter
``` import tensorflow as tf import datetime, os #hide tf logs os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # or any {'0', '1', '2'}, #0 (default) shows all, 1 to filter out INFO logs, 2 to additionally filter out WARNING logs, and 3 to additionally filter out ERROR logs import scipy.optimize import scipy.io import numpy a...
github_jupyter
``` # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. ``` # Dataloaders for ShapeNetCore and R2N2 This tutorial shows how to: - Load models from ShapeNetCore and R2N2 using PyTorch3D's data loaders. - Pass the loaded datasets to `torch.utils.data.DataLoader`. - Render ShapeNetCore models with PyT...
github_jupyter
# Fetch data and prepare sample * The complete training dataset has 25k images, 12.5k from cats and 12.5k from dogs. * We use 1000 images each for training and 500 for validation / test. ## Fetch training data ``` import os import requests from tqdm import tqdm_notebook as tqdm from pathlib import Path root = Path...
github_jupyter