code
stringlengths
2.5k
150k
kind
stringclasses
1 value
``` import math import pandas as pd import geopandas as gpd import numpy as np import matplotlib.pyplot as plt import h3 # h3 bins from uber from sklearn.preprocessing import StandardScaler, MinMaxScaler from sklearn.decomposition import PCA from sklearn.linear_model import LinearRegression from sklearn.preprocessin...
github_jupyter
# Multipitch tracking using Echo State Networks ## Introduction In this notebook, we demonstrate how the ESN can deal with multipitch tracking, a challenging multilabel classification problem in music analysis. As this is a computationally expensive task, we have pre-trained models to serve as an entry point. At fi...
github_jupyter
``` %pylab inline import pandas as pd import plotnine as p p.theme_set(p.theme_classic()) plt.rcParams['axes.spines.top'] = False plt.rcParams['axes.spines.right'] = False counts = pd.read_parquet('mca_brain_counts.parquet') sample_info = pd.read_parquet('mca_brain_cell_info.parquet') ``` ### Differential expression ...
github_jupyter
<table> <tr> <td style="background-color:#ffffff;"> <a href="http://qworld.lu.lv" target="_blank"><img src="../images/qworld.jpg" width="50%" align="left"> </a></td> <td width="70%" style="background-color:#ffffff;vertical-align:bottom;text-align:right;"> prepared by Maksim Dimi...
github_jupyter
# SOM Tutorial **NOTE:** This tutorial uses supplemental data that can be obtained from [cirada.ca](cirada.ca). It can be unpacked any run from any directory, and contains another copy of this same notebook. In this tutorial we will demonstrate the process of training and analyzing a SOM. As an example we will follow...
github_jupyter
### Задача 1 Даны значения величины заработной платы заемщиков банка (zp) и значения их поведенческого кредитного скоринга (ks): zp = [35, 45, 190, 200, 40, 70, 54, 150, 120, 110], ks = [401, 574, 874, 919, 459, 739, 653, 902, 746, 832]. Используя математические операции, посчитать коэффициенты линейной регрессии, при...
github_jupyter
## Machine Learning Pipeline: Wrapping up for Deployment In the previous notebooks, we worked through the typical Machine Learning pipeline steps to build a regression model that allows us to predict house prices. Briefly, we transformed variables in the dataset to make them suitable for use in a Regression model, th...
github_jupyter
Foreign Function Interface ==== ``` %matplotlib inline import matplotlib.pyplot as plt plt.style.use('ggplot') import numpy as np ``` Wrapping functions written in C ---- ### Steps - Write the C header and implementation files - Write the Cython `.pxd` file to declare C function signatures - Write the Cython `.pyx...
github_jupyter
<h1>Table of Contents<span class="tocSkip"></span></h1> <div class="toc"><ul class="toc-item"><li><span><a href="#Import-the-pandas,-os,-and-sys-libraries" data-toc-modified-id="Import-the-pandas,-os,-and-sys-libraries-1"><span class="toc-item-num">1&nbsp;&nbsp;</span>Import the pandas, os, and sys libraries</a></span>...
github_jupyter
``` import numpy as np from sklearn.model_selection import train_test_split from sklearn.model_selection import KFold from sklearn.utils import shuffle from sklearn.metrics import accuracy_score from synthesize_data_multiclass import synthesize_data import ER_multiclass as ER from sklearn.linear_model import Logistic...
github_jupyter
``` # from google.colab import drive # drive.mount('/content/drive') # path = "/content/drive/MyDrive/Research/cods_comad_plots/sdc_task/mnist/" import torch.nn as nn import torch.nn.functional as F import pandas as pd import numpy as np import matplotlib.pyplot as plt import torch import torchvision import torchvisi...
github_jupyter
# Let's post a message to Slack In this session, we're going to use Python to post a message to Slack. I set up [a team for us](https://ire-cfj-2017.slack.com/) so we can mess around with the [Slack API](https://api.slack.com/). We're going to use a simple [_incoming webhook_](https://api.slack.com/incoming-webhooks)...
github_jupyter
# Convolutional Neural Networks: Step by Step Welcome to Course 4's first assignment! In this assignment, you will implement convolutional (CONV) and pooling (POOL) layers in numpy, including both forward propagation and (optionally) backward propagation. **Notation**: - Superscript $[l]$ denotes an object of the $l...
github_jupyter
``` c1=open("stock_2018.csv","r") lines=c1.readlines() ``` ### 시험출력 ``` l1=[1,2,3,4,5,6,7,8,9,10] print(l1[4:6]) for line in lines[1:3]: print(line) ``` ## MIN_MAX SCALING ``` # min_max 스케일링 전에 전체 기간 범위에 대한 min값과 max값 추출 min_list=[] max_list=[] for line in lines[1:]: l_list=line.split(',') min_list.appe...
github_jupyter
``` import numpy as np from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import Axes3D import seaborn as sns sns.set(color_codes=True) %matplotlib inline # ilk terimin covarianci hep 1 cikar -2 - -2 x = np.array([-2, -1, 0, 3.5, 4,]); y = np.array([4.1, 0.9, 2, 12.3, 15.8]) N = len(x) m = np.zeros((N)) p...
github_jupyter
### Content Based Recommendations In the previous notebook, you were introduced to a way to make recommendations using collaborative filtering. However, using this technique there are a large number of users who were left without any recommendations at all. Other users were left with fewer than the ten recommendatio...
github_jupyter
``` import numpy as np import matplotlib.pyplot as plt from hfnet.datasets.hpatches import Hpatches from hfnet.evaluation.loaders import sift_loader, export_loader, fast_loader, harris_loader from hfnet.evaluation.local_descriptors import evaluate from hfnet.utils import tools %load_ext autoreload %autoreload 2 %matp...
github_jupyter
# COCO Reader Reader operator that reads a COCO dataset (or subset of COCO), which consists of an annotation file and the images directory. `DALI_EXTRA_PATH` environment variable should point to the place where data from [DALI extra repository](https://github.com/NVIDIA/DALI_extra) is downloaded. Please make sure tha...
github_jupyter
<center><h1 style="font-size:40px;">Exercise III:<br> Image Classification using CNNs</h1></center> --- Welcome to the *fourth* lab for Deep Learning! In this lab an CNN network to classify RGB images. Image classification refers to classify classes from images. This labs the *dataset* consist of multiple images whe...
github_jupyter
``` #hide from fastai.gen_doc.nbdoc import * ``` # A Neural Net from the Foundations This chapter begins a journey where we will dig deep into the internals of the models we used in the previous chapters. We will be covering many of the same things we've seen before, but this time around we'll be looking much more cl...
github_jupyter
# VacationPy ---- #### 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 gmaps import os ...
github_jupyter
``` # The magic commands below allow reflecting the changes in an imported module without restarting the kernel. %load_ext autoreload %autoreload 2 import sys print(f'Python version: {sys.version.splitlines()[0]}') print(f'Environment: {sys.exec_prefix}') ``` Shell commands are prefixed with `!` ``` !pwd !echo hello ...
github_jupyter
# Frequentist Inference Case Study - Part A ## 1. Learning objectives Welcome to part A of the Frequentist inference case study! The purpose of this case study is to help you apply the concepts associated with Frequentist inference in Python. Frequentist inference is the process of deriving conclusions about an under...
github_jupyter
``` #week-4,l-10 #DICTIONARY:- # A Simple dictionary alien_0={'color': 'green','points': 5} print(alien_0['color']) print(alien_0['points']) #accessing value in a dictionary: alien_0={'color':'green','points': 5} new_points=alien_0['points'] print(f"you just eand {new_points} points") #adding new.key-value pairs:- ali...
github_jupyter
# House Prices: Advanced Regression Techniques ### **Goal** It is your job to predict the sales price for each house. For each Id in the test set, you must predict the value of the SalePrice variable. ### **Metric** Submissions are evaluated on Root-Mean-Squared-Error (RMSE) between the logarithm of the predicted va...
github_jupyter
## Dictionaries Each key is separated from its value by a colon (:), the items are separated by commas, and the whole thing is enclosed in curly braces. An empty dictionary without any items is written with just two curly braces, like this: {}. Keys are unique within a dictionary while values may not be. The values o...
github_jupyter
``` import pandas as pd import numpy as np from matplotlib import pyplot as plt import seaborn as sns %matplotlib inline df = pd.read_csv('boston_house_prices.csv') ``` <b>Explanation of Features</b> * CRIM: per capita crime rate per town (assumption: if CRIM high, target small) * ZN: proportion of residential land z...
github_jupyter
Let's go through the known systems in [Table 1](https://www.aanda.org/articles/aa/full_html/2018/01/aa30655-17/T1.html) of Jurysek+(2018) ``` # 11 systems listed in their Table 1 systems = ['RW Per', 'IU Aur', 'AH Cep', 'AY Mus', 'SV Gem', 'V669 Cyg', 'V685 Cen', 'V907 Sco', 'SS Lac', 'QX Cas'...
github_jupyter
A common use case requires the forecaster to regularly update with new data and make forecasts on a rolling basis. This is especially useful if the same kind of forecast has to be made at regular time points, e.g., daily or weekly. sktime forecasters support this type of deployment workflow via the update and update_pr...
github_jupyter
# Parameters in QCoDeS A `Parameter` is the basis of measurements and control within QCoDeS. Anything that you want to either measure or control within QCoDeS should satisfy the `Parameter` interface. You may read more about the `Parameter` [here](http://qcodes.github.io/Qcodes/user/intro.html#parameter). ``` import ...
github_jupyter
``` import matplotlib.pyplot as plt plt.style.use('classic') %matplotlib inline ``` # Discussion: Week 2 ``` # Import the NumPy module ``` ## Exercise: Capital Evolution in the Solow Model Suppose that capital per worker $k_t$ evolves according to the following equation: \begin{align} k_{t+1} & = 0.12 \cdot 100 \c...
github_jupyter
# 基于注意力的神经机器翻译 此笔记本训练一个将卡比尔语翻译为英语的序列到序列(sequence to sequence,简写为 seq2seq)模型。此例子难度较高,需要对序列到序列模型的知识有一定了解。 训练完此笔记本中的模型后,你将能够输入一个卡比尔语句子,例如 *"Times!"*,并返回其英语翻译 *"Fire!"* 对于一个简单的例子来说,翻译质量令人满意。但是更有趣的可能是生成的注意力图:它显示在翻译过程中,输入句子的哪些部分受到了模型的注意。 <img src="https://tensorflow.google.cn/images/spanish-english.png" alt="spanish-engl...
github_jupyter
# Scenario Construction Demand and dispatch data are obtained from the Australian Energy Market Operator's (AEMO's) Market Management System Database Model (MMSDM) [1], and a k-means clustering algorithm is implemented using the method outlined in [2] to create a reduced set of representative operating scenarios. The d...
github_jupyter
<div align="center"> <h1><img width="30" src="https://madewithml.com/static/images/rounded_logo.png">&nbsp;<a href="https://madewithml.com/">Made With ML</a></h1> Applied ML · MLOps · Production <br> Join 30K+ developers in learning how to responsibly <a href="https://madewithml.com/about/">deliver value</a> with ML. ...
github_jupyter
# Creating a Sentiment Analysis Web App ## Using PyTorch and SageMaker _Deep Learning Nanodegree Program | Deployment_ --- Now that we have a basic understanding of how SageMaker works we will try to use it to construct a complete project from end to end. Our goal will be to have a simple web page which a user can u...
github_jupyter
# Day and Night Image Classifier --- The day/night image dataset consists of 200 RGB color images in two categories: day and night. There are equal numbers of each example: 100 day images and 100 night images. We'd like to build a classifier that can accurately label these images as day or night, and that relies on f...
github_jupyter
Here is an illustration of the IFS T42 issue. ``` import xarray as xr import matplotlib.pyplot as plt from src.score import * # This is the regridded ERA data DATADIR = '/data/weather-benchmark/5.625deg/' z500_valid = load_test_data(f'{DATADIR}geopotential_500', 'z') t850_valid = load_test_data(f'{DATADIR}temperature_...
github_jupyter
# Введение в координатный спуск (coordinate descent): теория и приложения ## Постановка задачи и основное предположение $$ \min_{x \in \mathbb{R}^n} f(x) $$ - $f$ выпуклая функция - Если по каждой координате будет выполнено $f(x + \varepsilon e_i) \geq f(x)$, будет ли это означать, что $x$ точка минимума? - Если $...
github_jupyter
# Principal Component Analysis in Shogun #### By Abhijeet Kislay (GitHub ID: <a href='https://github.com/kislayabhi'>kislayabhi</a>) This notebook is about finding Principal Components (<a href="http://en.wikipedia.org/wiki/Principal_component_analysis">PCA</a>) of data (<a href="http://en.wikipedia.org/wiki/Unsuperv...
github_jupyter
``` # Making our own objects class Foo: def hi(self): # self is the first parameter by convention print(self) # self is a pointer to the object f = Foo() # create Foo class object f.hi() f Foo.hi # Constructor class Person: def __init__(self, name, age): self.name = name self.age = age ...
github_jupyter
# Forecasting in statsmodels This notebook describes forecasting using time series models in statsmodels. **Note**: this notebook applies only to the state space model classes, which are: - `sm.tsa.SARIMAX` - `sm.tsa.UnobservedComponents` - `sm.tsa.VARMAX` - `sm.tsa.DynamicFactor` ``` %matplotlib inline import num...
github_jupyter
# Ex2 - Getting and Knowing your Data Check out [Chipotle Exercises Video Tutorial](https://www.youtube.com/watch?v=lpuYZ5EUyS8&list=PLgJhDSE2ZLxaY_DigHeiIDC1cD09rXgJv&index=2) to watch a data scientist go through the exercises This time we are going to pull data directly from the internet. Special thanks to: https:/...
github_jupyter
# Tensor shape After the raw and waveform data are loaded from external files, they are stored as Numpy array. However, to use those data in Pytorch, we need to further convert the Numpy arrays to Pytorch tensors. Conversion from Numpy array to Pytorch tensor is straightforward (see [Pytorch tutorial](https://pytorc...
github_jupyter
### SketchGraphs demo In this notebook, we'll first go through various ways of representing and inspecting sketches in SketchGraphs. We'll then take a look at using Onshape's API in order to solve sketch constraints. ``` %load_ext autoreload %autoreload 2 import os import json from copy import deepcopy %matplotlib i...
github_jupyter
``` import sqlite3 import pandas as pd def run_query(query): with sqlite3.connect('AreaOvitrap.db') as conn: return pd.read_sql(query,conn) def run_command(command): with sqlite3.connect('AreaOvitrap.db') as conn: conn.execute('PRAGMA foreign_keys = ON;') conn.isolation_level = None ...
github_jupyter
# Load Data Bilder einlesen und Dateinamen anpassen ``` # 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 from src.data import make_dataset import warnings import pandas as pd # D...
github_jupyter
``` %matplotlib inline from pyvista import set_plot_theme set_plot_theme('document') ``` Slicing {#slice_example} ======= Extract thin planar slices from a volume. ``` # sphinx_gallery_thumbnail_number = 2 import pyvista as pv from pyvista import examples import matplotlib.pyplot as plt import numpy as np ``` PyVis...
github_jupyter
# Exporing Graph Datasets in Jupyter Juypter notebooks are perfect environments for both carrying out and capturing exporatory work. Even on moderate sizes datasets they provide an interactive environement that can drive both local and remote computational tasks. In this example, we will load a datatset using pandas,...
github_jupyter
# Forest Fire Mini Project > in this file, you can find analysis for this project. For the final report please visit `Report.ipynb` ``` import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression, Ridge,...
github_jupyter
# MARATONA BEHIND THE CODE 2020 ## DESAFIO 6 - LIT <hr> ## Installing Libs ``` !pip install scikit-learn --upgrade !pip install xgboost --upgrade !pip install imblearn --upgrade ``` <hr> ## Download dos conjuntos de dados em formato .csv ``` import pandas as pd !wget --no-check-certificate --content-disposition ...
github_jupyter
## Michael DiGregorio - Homework 1 - CPE/EE 695 Applied Machine Learning ## Imports ``` import numpy as np import matplotlib.pyplot as pt from typing import List, Tuple ``` ## Function Definitions ``` def get_polynomial(x): return 5*x + 20*x**2 + 1*x**3 def get_dataset(number_of_samples, noise_scale) -> Tuple[...
github_jupyter
# TensorBoard ``` import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('/tmp/tensorflow/alex/mnist/input_data', one_hot=True) def variable_summaries(var): with tf.name_scope('summaries'): mean = tf.reduce_mean(var) tf.summary.scalar('m...
github_jupyter
``` from types import SimpleNamespace from functools import lru_cache import os import time from sklearn.model_selection import train_test_split from sklearn.metrics import roc_auc_score import pandas as pd import numpy as np import scipy.io.wavfile import scipy.fftpack import scipy.linalg import torch import torch.uti...
github_jupyter
``` import mglearn import pandas as pd import matplotlib.pyplot as plt import numpy as np import IPython import sklearn from sklearn.datasets import load_iris iris=load_iris() print (iris['target']) from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test=train_test_split(iris['data'], ir...
github_jupyter
# Machine Learning Engineer Nanodegree ## Model Evaluation & Validation ## Project: Predicting Boston Housing Prices Welcome to the first project of the Machine Learning Engineer Nanodegree! In this notebook, some template code has already been provided for you, and you will need to implement additional functionality ...
github_jupyter
``` %matplotlib inline ``` # Early stopping of Gradient Boosting Gradient boosting is an ensembling technique where several weak learners (regression trees) are combined to yield a powerful single model, in an iterative fashion. Early stopping support in Gradient Boosting enables us to find the least number of ite...
github_jupyter
``` import numpy as np import matplotlib as mpl #mpl.use('pdf') import matplotlib.pyplot as plt import numpy as np plt.rc('font', family='serif', serif='Times') plt.rc('text', usetex=True) plt.rc('xtick', labelsize=6) plt.rc('ytick', labelsize=6) plt.rc('axes', labelsize=6) #axes.linewidth : 0.5 plt.rc('axes', linewid...
github_jupyter
# Regression Week 3: Assessing Fit (polynomial regression) In this notebook you will compare different regression models in order to assess which model fits best. We will be using polynomial regression as a means to examine this topic. In particular you will: * Write a function to take an SArray and a degree and retur...
github_jupyter
# Problems ``` import math import pandas as pd from sklearn import preprocessing from sklearn.neighbors import NearestNeighbors, KNeighborsClassifier, KNeighborsRegressor from sklearn.model_selection import train_test_split from sklearn.metrics.pairwise import euclidean_distances from sklearn.metrics import accuracy_...
github_jupyter
``` %matplotlib inline import control from control.matlab import * import numpy as np import matplotlib.pyplot as plt def pole_plot(poles, title='Pole Map'): plt.title(title) plt.scatter(np.real(poles), np.imag(poles), s=50, marker='x') plt.axhline(y=0, color='black'); plt.axvline(x=0, color='black');...
github_jupyter
``` import pymatgen.core print(pymatgen.core.__version__) print(pymatgen.core.__file__) import sys print(sys.version) from pymatgen.core import Molecule Molecule c_monox = Molecule(["C","O"], [[0.0, 0.0, 0.0], [0.0, 0.0, 1.2]]) print(c_monox) oh_minus = Molecule(["O", "H"], [[0.0, 0.0, 0.0], [0.0, 0.0, 1.0]], charge=-1...
github_jupyter
### - load data ``` import numpy as np import matplotlib.pyplot as plt import pandas as pd import math dataset = pd.read_csv('data-kmeans.csv') data = dataset.values ``` ### - init labels ``` label = [] for i in range(len(data)): label.append([i % 5 + 1]) label = np.array(label) data = np.concatenate((data, la...
github_jupyter
``` import pandas as pd import numpy as np import TrialPathfinder as tp ``` # Trial PathFinder ## Load Data Tables TrialPathfinder reads tables in Pandas dataframe structure (pd.dataframe) as default. The date information should be read as datetime (use function pd.to_datetime to convert if not). **1. Features**: -...
github_jupyter
# Team Surface Velocity ### **Members**: Grace Barcheck, Canyon Breyer, Rodrigo Gómez-Fell, Trevor Hillebrand, Ben Hills, Lynn Kaluzienski, Joseph Martin, David Polashenski ### **Science Advisor**: Daniel Shapero ### **Special Thanks**: Ben Smith, David Shean ### Motivation **Speaker: Canyon Breyer** Previous wor...
github_jupyter
# aitextgen Training Hello World _Last Updated: Feb 21, 2021 (v.0.4.0)_ by Max Woolf A "Hello World" Tutorial to show how training works with aitextgen, even on a CPU! ``` from aitextgen.TokenDataset import TokenDataset from aitextgen.tokenizers import train_tokenizer from aitextgen.utils import GPT2ConfigCPU from ...
github_jupyter
``` """ Simple distributed implementation of the K-Means algorithm using Tensorflow. """ import tensorflow as tf import tensorframes as tfs from pyspark.mllib.random import RandomRDDs import numpy as np num_features = 4 k = 2 # TODO: does not work with 1 data = RandomRDDs.normalVectorRDD( sc, numCols=num_feat...
github_jupyter
## Example deTiN run using data from invitro mixing validation experiment Loading data and deTiN modules: ``` import deTiN.deTiN import deTiN.deTiN_SSNV_based_estimate as dssnv import deTiN.deTiN_aSCNA_based_estimate as dascna import deTiN.deTiN_utilities as du import numpy as np import matplotlib import matplotlib...
github_jupyter
# Acquisition Models for MR, PET and CT This demonstration shows how to set-up and use SIRF/CIL acquisition models for different modalities. You should have tried the `introduction` notebook first. The current notebook briefly repeats some items without explanation. This demo is a jupyter notebook, i.e. intended to be...
github_jupyter
# Train-Eval --- ## Import Libraries ``` import os import sys from pathlib import Path import torch import torch.nn as nn import torch.optim as optim from torchtext.data import BucketIterator sys.path.append("../") from meta_infomax.datasets.fudan_reviews import prepare_data, get_data ``` ## Global Constants ``` ...
github_jupyter
# Introduction to Jupyter Notebooks Today we are going to learn about [Jupyter Notebooks](https://jupyter.org/)! The advantage of notebooks is that they can include explanatory text, code, and plots in the same document. **This makes notebooks an ideal playground for explaining and learning new things without having t...
github_jupyter
# Navigation --- In this notebook, you will learn how to use the Unity ML-Agents environment for the first project of the [Deep Reinforcement Learning Nanodegree](https://www.udacity.com/course/deep-reinforcement-learning-nanodegree--nd893). ### 1. Start the Environment We begin by importing some necessary packages...
github_jupyter
``` import matplotlib.pyplot as plt import pandas as pd from sklearn.preprocessing import MinMaxScaler df = pd.read_csv('train_FD001.txt', sep=' ', header=None) # dropping NAN values df = df.dropna(axis=1, how='all') # Naming the columns df.columns = ["unit", "cycles", "Op1", "Op2", "Op3", "S1",...
github_jupyter
# ML Pipeline Preparation Follow the instructions below to help you create your ML pipeline. ### 1. Import libraries and load data from database. - Import Python libraries - Load dataset from database with [`read_sql_table`](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_sql_table.html) - Define fea...
github_jupyter
# Data Augumentation on Animals dataset using MiniVGG net In this example, We explore the Data Augmentation. This method of regularization can aid us to improve our results during the training process. In addition, we consider the Aspect Ratio when resizing the images. Maintaining the aspect ratio help the CNN to extr...
github_jupyter
<h1>Table of Contents<span class="tocSkip"></span></h1> <div class="toc"><ul class="toc-item"><li><span><a href="#Multi-dimensional-Particle-in-a-Box" data-toc-modified-id="Multi-dimensional-Particle-in-a-Box-4"><span class="toc-item-num">4&nbsp;&nbsp;</span>Multi-dimensional Particle-in-a-Box</a></span><ul class="toc-...
github_jupyter
# Challenge In this challenge, we will practice on dimensionality reduction with PCA and selection of variables with RFE. We will use the _data set_ [Fifa 2019](https://www.kaggle.com/karangadiya/fifa19), originally containing 89 variables from over 18 thousand players of _game_ FIFA 2019. ## _Setup_ ``` from math i...
github_jupyter
``` from nbdev import * %nbdev_default_export cli ``` # Command line functions > Console commands added by the nbdev library ``` %nbdev_export from nbdev.imports import * from nbdev.export import * from nbdev.sync import * from nbdev.merge import * from nbdev.export2html import * from nbdev.test import * from fastsc...
github_jupyter
``` import json import pandas as pd import numpy as np import re file_dir = '/Users/sivaelango/desktop/Analysis Projects/Movies-ETL' with open(f'{file_dir}/wikipedia-movies.json', mode='r') as file: wiki_movies_raw = json.load(file) len(wiki_movies_raw) # First 5 records wiki_movies_raw[:5] # Last 5 records wiki_mo...
github_jupyter
``` import os if os.path.split(os.getcwd())[-1]=='notebooks': os.chdir("../") 'Your base path is at: '+os.path.split(os.getcwd())[-1] ``` # Update Data ``` # %load src/data/get_data.py import subprocess import os import pandas as pd import numpy as np from datetime import datetime import requests import json...
github_jupyter
``` # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. ``` # Loading a pre-trained model in inference mode In this tutorial, we will show how to instantiate a model pre-trained with VISSL to use it in inference mode to extract features from its trunk. We will concentrate on loading a model pre-t...
github_jupyter
# Enterprise Time Series Forecasting and Decomposition Using LSTM This notebook is a tutorial on time series forecasting and decomposition using LSTM. * First, we generate a signal (time series) that includes several components that are commonly found in enterprise applications: trend, seasonality, covariates, and cov...
github_jupyter
# OSM Data Exploration ## Extraction of districts from shape files For our experiments we consider two underdeveloped districts Araria, Bihar and Namsai, Arunachal Pradesh, the motivation of this comes from this [dna](https://www.dnaindia.com/india/report-out-of-niti-aayog-s-20-most-underdeveloped-districts-19-are-rul...
github_jupyter
``` ''' Comparing single layer MLP with deep MLP (using TensorFlow) ''' import numpy as np from scipy.optimize import minimize from scipy.io import loadmat from scipy.stats import logistic from math import sqrt import time import pickle # Do not change this def initializeWeights(n_in,n_out): """ # initiali...
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
``` from fake_useragent import UserAgent import requests ua = UserAgent() from newspaper import Article from queue import Queue from urllib.parse import quote from unidecode import unidecode def get_date(load): try: date = re.findall( '[-+]?[.]?[\d]+(?:,\d\d\d)*[\.]?\d*(?:[eE][-+]?\d+)?', load...
github_jupyter
# Building your Deep Neural Network: Step by Step Welcome to your week 4 assignment (part 1 of 2)! Previously you trained a 2-layer Neural Network with a single hidden layer. This week, you will build a deep neural network with as many layers as you want! - In this notebook, you'll implement all the functions require...
github_jupyter
``` import os import numpy as np from torch.utils.data import DataLoader from torchvision import transforms as T import cv2 import pandas as pd from self_sup_data.chest_xray import SelfSupChestXRay from model.resnet import resnet18_enc_dec from train_chest_xray import SETTINGS from experiments.chest_xray_tasks import ...
github_jupyter
# Trumpler 1930 Dust Extinction Figure 6.2 from Chapter 6 of *Interstellar and Intergalactic Medium* by Ryden & Pogge, 2021, Cambridge University Press. Data are from [Trumpler, R. 1930, Lick Observatory Bulletin #420, 14, 154](https://ui.adsabs.harvard.edu/abs/1930LicOB..14..154T), Table 3. The extinction curve de...
github_jupyter
``` #Mounts your google drive into this virtual machine from google.colab import drive, files import sys drive.mount('/content/drive') #Now we need to access the files downloaded, copy the path where you saved the files downloaded from the github repo and paste below sys.path.append('/content/drive/MyDrive/YOURPATH/S...
github_jupyter
``` import numpy as np import tensorflow as tf from tensorflow import keras import pandas as pd import seaborn as sns from pylab import rcParams import matplotlib.pyplot as plt from matplotlib import rc from pandas.plotting import register_matplotlib_converters from sklearn.model_selection import train_test_split impor...
github_jupyter
``` from os.path import join, dirname from os import listdir import numpy as np import pandas as pd # GUI library import panel as pn import panel.widgets as pnw # Chart libraries from bokeh.plotting import figure from bokeh.models import ColumnDataSource, Legend from bokeh.palettes import Spectral5, Set2 from bokeh....
github_jupyter
# AskReddit Troll Question Detection Challenge ## Imports ``` import numpy as np import pandas as pd from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfVectorizer import re train_df = pd.read_csv("train.csv") test_df = pd.read_csv("test.csv") sentences1 = tra...
github_jupyter
# Triplet Loss for Implicit Feedback Neural Recommender Systems The goal of this notebook is first to demonstrate how it is possible to build a bi-linear recommender system only using positive feedback data. In a latter section we show that it is possible to train deeper architectures following the same design princi...
github_jupyter
``` import tensorflow as tf tf.constant([[1.,2.,3.], [4.,5.,6.]]) tf.constant(42) # 스칼라 t = tf.constant([[1.,2.,3.], [4.,5.,6.]]) t.shape # TensorShape([2, 3]) t.dtype # tf.float32 t[:, 1:] t[..., 1, tf.newaxis] t + 10 tf.square(t) # 제곱 t @ tf.transpose(t) # transpose는 행렬 변환 import numpy as np a = np.array([2., 4., 5...
github_jupyter
*Регулярное выражение* — это последовательность символов, используемая для поиска и замены текста в строке или файле Регулярные выражения используют два типа символов: - специальные символы: как следует из названия, у этих символов есть специальные значения. Аналогично символу *, который как правило означает «любой с...
github_jupyter
``` import pandas as pd ios = pd.read_csv('app_reviews/rv_ios_app_reviews.csv') ios['Content'] = ios['label_title']+ios['review'] ios = ios.drop(['app_name','app_version','label_title','review'], axis=1) print(ios.shape) ios.head() ios['store_rating'].value_counts() android = pd.read_csv('app_reviews/rv_android_reviews...
github_jupyter
Define the network: ``` import torch # PyTorch base from torch.autograd import Variable # Tensor class w gradients import torch.nn as nn # modules, layers, loss fns import torch.nn.functional as F # Conv,Pool,Loss,Actvn,Nrmlz fns from here class Net(nn.Module): def __init__(self): super(Net, self).__i...
github_jupyter
``` import os import numpy as np import keras import tensorflow as tf import pandas as pd import glob import json import random import time from PIL import Image BATCH_SIZE = 128 TRAINING_SPLIT = 0.8 EPOCHS = 20 prefix = '/opt/ml/' input_path = prefix + 'input/data' output_path = os.path.join(prefix, 'output') model_...
github_jupyter
# Recommendations with IBM For this project I analyze the interactions that users have with articles on the IBM Watson Studio platform, and make recommendations to them about new articles they will like. ## Table of Contents I. [Exploratory Data Analysis](#Exploratory-Data-Analysis)<br> II. [Rank Based Recommendati...
github_jupyter
``` # sample try with jewelry from os import listdir directory_name = "/Users/J.Alvarez/jtv/images" image_names = listdir("/Users/J.Alvarez/jtv/images") #image_names.remove('.DS_Store') #image_names.remove('._.DS_Store') from keras import backend as K #"/Users/J.Alvarez/the_simpsons/kaggle_simpson_testset" from PIL imp...
github_jupyter