text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
```
from __future__ import print_function, division
from keras.datasets import fashion_mnist
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from keras_contrib.layers.normalization.instancenormalization import InstanceNormalization
from keras.layers import Input, Dense, Reshape, Flatten, Dropout,... | github_jupyter |
## 1. feladat: írjatok egy függvényt, ami:
- egy string-et fogad paraméternek
- **kitörli belőle az összes abc-ben szereplő** karaktert, tehát csak a **speciális karaktereket hagyja meg**
- és ez a módosított string a visszatérési értéke
**ez lesz a függvény paramétere (futtasátok a cellát Ctrl + Enter-rel)**
```
inp... | github_jupyter |
# Example of running full waveform source mechanism inversion using SeisSrcInv
This jupyter-notebook provides an example of how to use the python module SeisSrcInv to perform a full waveform source mechanism inversion. Firstly, an example of how to run an inversion is given using SeisSrcInv.inversion. The results of t... | github_jupyter |
#Convolutional Forest (ConvRF) Kappas Experiment for 3-Class Multiclassification
The goal of this experiment is to demonstrate the capabilities of a convolutional forest against benchmarks such as naive random forests, simple CNN's, CNN with 32 filter and 1 layer, and CNN with 32 filter and 2 layers. 12 3-class Cifar1... | github_jupyter |
<a href="https://colab.research.google.com/github/JimKing100/NFL-Live/blob/master/data-science/actuals/Actuals_Kicker.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
```
# Imports
import pandas as pd
# Load the raw data
player_df = pd.read_csv('http... | github_jupyter |
### Train a text classifier (BERT-based) that predicts the underlying explained emotion.
- This notebook requires that you have install the __simpletransformers__
- e.g., _pip install simpletransformers_
- in 4 GPUs, this can take several hours (e.g., 18 hours)
- Parameters are the same as in the paper (of course)
... | github_jupyter |
```
import matplotlib.pyplot as plt
import tensorflow as tf
# Make tensorflow not take over the entire GPU memory
for gpu in tf.config.experimental.list_physical_devices('GPU'):
tf.config.experimental.set_memory_growth(gpu, True)
from tfga import GeometricAlgebra
from tfga.layers import GeometricProductDense, Tenso... | github_jupyter |
# Band tailing from Cu-Zn disorder induced potential fluctuations in CZTS
This notebook computes the standard deviation of the distribution of on-site electrostatic potentials outputted from our Monte Carlo model of Cu-Zn disorder in CZTS.
The standard deviation of the distribution for Cu ions is used to infer band t... | github_jupyter |
# Xarray-simlab: run models and visualize outputs
We'll see here how to:
- setup and run one simulation
- save and reuse simulation setups
- set time-varying input values (external forcing)
- save model variable snapshots at different time steps / time frequencies
- save model snapshots to different stores (e.g., in-... | github_jupyter |
# Strutture dati #
Benvenuti alla nuove lezione sulle strutture dati di Python, partiamo dalla definizione di strutture di dati, per strutture dati si intende un modo di organizzare, gestire e immagazzinare dati in maniera efficiente e, anche se non sempre, modificabile.
In python esistono diversi tipi di strutture dat... | github_jupyter |
# Lab Part II: RNN Sentiment Classifier
In the previous lab, you built a tweet sentiment classifier with a simple feedforward neural network. Now we ask you to improve this model by representing it as a *sequence* of words, with a recurrent neural network.
First import some things:
```
import math
import pickle as p... | github_jupyter |
```
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import tensorflow as tf
from sklearn.model_selection import train_test_split,GridSearchCV
from sklearn.neural_network import MLPClassifier
from sklearn import metrics
from cloudmesh.common.StopWatch import StopWatch... | github_jupyter |
# result:
I will use all four. and use the same set of optimizer as in 1L models.
```
import h5py
import numpy as np
import os.path
from functools import partial
from collections import OrderedDict
import pandas as pd
pd.options.display.max_rows = 100
pd.options.display.max_columns = 100
from scipy.stats import pear... | github_jupyter |
```
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from ipywidgets import interact, FloatSlider, RadioButtons
amplitude_slider = FloatSlider(min=0.1, max=1.0, step=0.1, value=0.2)
color_buttons = RadioButtons(options=['blue', 'green', 'red'])
# decorate the plot function with an environment from... | github_jupyter |
# Named Entity Recognition
Named-entity recognition (NER) is a subtask of information extraction that seeks to locate and classify named entities mentioned in unstructured text into pre-defined categories such as person names, organizations, locations, medical codes, time expressions, quantities, monetary values, perc... | github_jupyter |
```
import os
os.environ['CUDA_VISIBLE_DEVICES'] = ''
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = 'prepare/mesolitica-tpu.json'
b2_application_key_id = os.environ['b2_application_key_id']
b2_application_key = os.environ['b2_application_key']
from google.cloud import storage
client = storage.Client()
bucket = client... | github_jupyter |
```
from arcgis.gis import GIS
import pandas as pd
import requests
import json
import sys
import numpy as np
import io
from datetime import date
np.set_printoptions(threshold=sys.maxsize)
```
## Get raw data from [map](http://acgov.org/maps/food-services.htm)
Tried to [download data directly](https://developers.arcgi... | github_jupyter |
ERROR: type should be string, got "https://github.com/utkuozbulak/pytorch-cnn-visualizations\nhttps://towardsdatascience.com/how-to-visualize-convolutional-features-in-40-lines-of-code-70b7d87b0030\n\n```\nimport h5py\nimport os\nfrom os.path import join\nfrom glob import glob\nfrom scipy.io import loadmat\nimport cv2\nimport torch\nfrom torch.autograd import Variable\nfrom torch.autograd import grad\nimport numpy as np\nimport matplotlib.pylab as plt\nimport csv\nfrom time import time\ntorch.cuda.get_device_name(device=None)\nimport torchvision\nalexnet=torchvision.models.alexnet(pretrained=True)\nnet = torchvision.models.vgg16(pretrained=True)\nnet\nfrom torchvision import transforms\nnormalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225]) # Note without normalization, the\ndenormalize = transforms.Normalize(\n mean=[-0.485/0.229, -0.456/0.224, -0.406/0.225],\n std=[1/0.229, 1/0.224, 1/0.225])\nclass SaveFeatures():\n def __init__(self, module):\n self.hook = module.register_forward_hook(self.hook_fn)\n def hook_fn(self, module, input, output):\n self.features = output#torch.tensor(output,requires_grad=True).cuda()\n def close(self):\n self.hook.remove()\n\ndef val_tfms(img_np):\n img = torch.from_numpy(img_np.astype(np.float32)).permute(2, 0, 1)\n nimg = normalize(img).unsqueeze(0).cuda()\n return nimg\n\ndef val_detfms(img_tsr):\n img = denormalize(img_tsr.squeeze()).permute(1,2,0)\n return img.detach().cpu().numpy()\nMAX_TRIAL = 100\nclass FilterVisualizer():\n def __init__(self, model, size=56, upscaling_steps=12, upscaling_factor=1.2):\n self.size, self.upscaling_steps, self.upscaling_factor = size, upscaling_steps, upscaling_factor\n self.model = model #alexnet.features.cuda().eval()\n # set_trainable(self.model, False)\n for param in self.model.parameters():\n param.requires_grad = False\n\n def visualize(self, layer, filter, lr=0.05, opt_steps=20, blur=None):\n sz = self.size\n img = np.uint8(np.random.uniform(50, 250, (sz, sz, 3))) / 255 # generate random image\n activations = SaveFeatures(list(self.model.children())[layer]) # register hook\n\n for _ in range(self.upscaling_steps): # scale the image up upscaling_steps times\n # train_tfms, val_tfms = tfms_from_model(vgg16, sz)\n img_var = Variable(val_tfms(img), requires_grad=True) # convert image to Variable that requires grad\n optimizer = torch.optim.Adam([img_var], lr=lr, weight_decay=1e-6)\n for n in range(MAX_TRIAL):\n optimizer.zero_grad()\n self.model(img_var)\n loss = -activations.features[0, filter].mean()\n loss.backward()\n if img_var.grad.norm()<1E-6:\n img_var = Variable(val_tfms(img + np.random.randn(*img.shape)), requires_grad=True) # convert image to Variable that requires grad\n optimizer = torch.optim.Adam([img_var], lr=lr, weight_decay=1e-6)\n print(\"Optimizer restart\")\n else:\n break\n for n in range(opt_steps): # optimize pixel values for opt_steps times\n optimizer.zero_grad()\n self.model(img_var)\n loss = -activations.features[0, filter].mean()\n loss.backward()\n optimizer.step()\n print(loss.data.cpu())\n img = val_detfms(img_var.data.cpu())\n self.output = img\n plt.figure(figsize=[8,8])\n plt.imshow(FVis.output)\n plt.show()\n sz = int(self.upscaling_factor * sz) # calculate new image size\n img = cv2.resize(img, (sz, sz), interpolation=cv2.INTER_CUBIC) # scale image up\n if blur is not None: img = cv2.blur(img, (blur, blur)) # blur image to reduce high frequency patterns\n self.save(layer, filter)\n activations.close()\n\n def save(self, layer, filter):\n plt.imsave(\"layer_\" + str(layer) + \"_filter_\" + str(filter) + \".jpg\", np.clip(self.output, 0, 1))\n\n#%%\nfeat = alexnet.features.cuda().eval()\nfeat = net.features.cuda().eval()\nFVis = FilterVisualizer(feat, size=227, upscaling_steps=2, upscaling_factor=1.2)\nFVis.visualize(14, 20, blur=10, opt_steps=20)\nplt.figure(figsize=[8,8])\nplt.imshow(FVis.output)\nplt.show()\nnet = alexnet.features[:]\nsz = 224\nlr = 0.1\nopt_steps = 100\nupscaling_factor = 1.2\nfilter = 10\nloss_arr = []\nactivations = SaveFeatures(list(alexnet.features.children())[8]) # register hook\n\nimg = np.uint8(np.random.uniform(150, 180, (sz, sz, 3))) / 255\nimg_var = Variable(val_tfms(img), requires_grad=True) # convert image to Variable that requires grad\noptimizer = torch.optim.Adam([img_var], lr=lr, weight_decay=1e-6)\nfor n in range(opt_steps): # optimize pixel values for opt_steps times\n optimizer.zero_grad()\n alexnet.features(img_var)\n loss = -activations.features[0, filter].mean()\n loss.backward()\n optimizer.step()\n loss_arr.append(loss.data.cpu())\nimg = val_detfms(img_var.data.cpu()).numpy()\noutput = img\nsz = int(upscaling_factor * sz) # calculate new image size\nimg = cv2.resize(img, (sz, sz), interpolation=cv2.INTER_CUBIC)\nalexnet.features(img_var)\nloss = -activations.features[0, filter].mean()\nFVis.output[:,:,0].mean()\nimg_np = np.random.rand(5,5,3)\nimg_tsr = val_tfms(img_np)\nimg_out = val_detfms(img_tsr)\n```\n\n## Printing Version of FilterVisualization\n\n```\n# def np2tensor(image,dtype):\n# \"Convert np.array (sz,sz,3) to tensor (1,3,sz,sz), imagenet normalized\"\n\n# a = np.asarray(image)\n# if a.ndim==2 : a = np.expand_dims(a,2)\n# a = np.transpose(a, (1, 0, 2))\n# a = np.transpose(a, (2, 1, 0))\n \n# #Imagenet norm\n# mean=np.array([0.485, 0.456, 0.406])[...,np.newaxis,np.newaxis]\n# std = np.array([0.229, 0.224, 0.225])[...,np.newaxis,np.newaxis]\n# a = (a-mean)/std\n# a = np.expand_dims(a,0)\n# return torch.from_numpy(a.astype(dtype, copy=False) )\n\n# def tensor2np(img_tensor):\n# \"Convert tensor (1,3,sz,sz) back to np.array (sz,sz,3), imagenet DEnormalized\"\n# a = np.squeeze(to_np(img_tensor))\n \n# mean=np.array([0.485, 0.456, 0.406])[...,np.newaxis,np.newaxis]\n# std = np.array([0.229, 0.224, 0.225])[...,np.newaxis,np.newaxis]\n# a = a*std + mean\n# return np.transpose(a, (1,2,0))\n\nclass FilterVisualizer():\n def __init__(self,model):\n self.model = model\n self.weights = None\n\n def visualize(self, sz, layer, filter, weights=None, \n upscaling_steps=12, upscaling_factor=1.2, lr=0.1, opt_steps=20, blur=None, print_losses=False):\n '''Add weights to support visualize combination of channels'''\n if weights is not None:\n assert len(weights) == len(filter)\n self.weights = torch.tensor(weights,dtype=torch.float,device='cuda')\n img = (np.random.random((sz,sz, 3)) * 20 + 128.)/255 # value b/t 0 and 1 \n activations = SaveFeatures(layer) # register hook\n\n for i in range(upscaling_steps): \n # convert np to tensor + channel first + new axis, and apply imagenet norm\n img_tensor = val_tfms(img)#,np.float32)\n img_tensor = img_tensor.cuda()\n img_tensor.requires_grad_();\n if not img_tensor.grad is None:\n img_tensor.grad.zero_(); \n \n \n optimizer = torch.optim.Adam([img_tensor], lr=0.1, weight_decay=1e-6)\n if i > upscaling_steps/2:\n opt_steps_ = int(opt_steps*1.3)\n else:\n opt_steps_ = opt_steps\n for n in range(opt_steps_): # optimize pixel values for opt_steps times\n optimizer.zero_grad()\n _=self.model(img_tensor)\n if weights is None:\n loss = -1*activations.features[0, filter].mean()\n else: \n loss = -1*torch.einsum(\"ijk,i->jk\", activations.features[0, filter], self.weights).mean()\n if print_losses:\n if i%3==0 and n%5==0:\n print(f'{i} - {n} - {float(-loss)}')\n loss.backward()\n optimizer.step()\n \n # convert tensor back to np\n img = val_detfms(img_tensor)\n self.output = img\n sz = int(upscaling_factor * sz) # calculate new image size\n# print(f'Upscale img to: {sz}')\n img = cv2.resize(img, (sz, sz), interpolation = cv2.INTER_CUBIC) # scale image up\n if blur is not None: img = cv2.blur(img,(blur,blur)) # blur image to reduce high frequency patterns\n \n activations.close()\n return np.clip(self.output, 0, 1)\n \n def get_transformed_img(self,img,sz):\n '''\n Scale up/down img to sz. Channel last (same as input)\n image: np.array [sz,sz,3], already divided by 255\" \n '''\n return cv2.resize(img, (sz, sz), interpolation = cv2.INTER_CUBIC)\n \n def most_activated(self, img, layer):\n '''\n image: np.array [sz,sz,3], already divided by 255\" \n '''\n img = cv2.resize(img, (224,224), interpolation = cv2.INTER_CUBIC)\n activations = SaveFeatures(layer)\n img_tensor = val_tfms(img)#,np.float32)\n img_tensor = img_tensor.cuda()\n \n _=self.model(img_tensor)\n mean_act = [np.squeeze(to_np(activations.features[0,i].mean())) for i in range(activations.features.shape[1])]\n activations.close()\n return mean_act\nfeat = alexnet.features.cuda().eval()\nFVis = FilterVisualizer(feat)\nimg = FVis.visualize(sz=227, layer=feat[8], filter=[1,5,3,10], weights=[1,3,1,7], blur=10, opt_steps=20, upscaling_steps=3, upscaling_factor=1.2, print_losses=True)\nplt.figure(figsize=[8,8])\nplt.imshow(FVis.output)\nplt.show()\n```\n\n## Using GAN to visualize Convolutiona Layers\n\n```\nBGR_mean = torch.tensor([104.0, 117.0, 123.0])\nBGR_mean = torch.reshape(BGR_mean, (1, 3, 1, 1))\ndef visualize(G, code):\n \"\"\"Do the De-caffe transform (Validated)\"\"\"\n code = code.reshape(-1, 4096).astype(np.float32)\n blobs = G(torch.from_numpy(code))\n out_img = blobs['deconv0'] # get raw output image from GAN\n clamp_out_img = torch.clamp(out_img + BGR_mean, 0, 255)\n vis_img = clamp_out_img[:, [2, 1, 0], :, :].permute([2, 3, 1, 0]).squeeze() / 255\n return vis_img\n\ndef visualize_for_torchnet(G, code):\n \"\"\"Do the De-caffe transform (Validated)\"\"\"\n blobs = G(code)\n out_img = blobs['deconv0'] # get raw output image from GAN\n clamp_out_img = torch.clamp(out_img + BGR_mean, 0, 255) / 255\n vis_img = clamp_out_img[:, [2, 1, 0], :, :] # still use BCHW sequence \n return vis_img\nclass FilterVisualizerGAN():\n def __init__(self,model):\n self.model = model\n self.G = load_generator()\n self.weights = None\n\n def visualize(self, sz, layer, filter, weights=None, \n lr=0.1, opt_steps=20, blur=None, print_losses=False): #upscaling_steps=12, upscaling_factor=1.2, \n '''Add weights to support visualize combination of channels'''\n if weights is not None:\n assert len(weights) == len(filter)\n self.weights = torch.tensor(weights,dtype=torch.float,device='cuda')\n \n activations = SaveFeatures(layer) # register hook\n feat = 0.01 * np.random.rand(1, 4096)\n feat = torch.from_numpy(np.float32(feat))\n feat = Variable(feat, requires_grad = True).cuda()\n img = visualize_for_torchnet(self.G, feat) \n resz_img = F.interpolate(img, (sz, sz), mode='bilinear', align_corners=True)\n # img = (np.random.random((sz,sz, 3)) * 20 + 128.)/255 # value b/t 0 and 1 \n # img_tensor = val_tfms(resz_img) \n img_tensor = normalize(resz_img.squeeze()).unsqueeze(0)\n# img_tensor = img_tensor.cuda()\n# img_tensor.requires_grad_();\n optimizer = optim.SGD([feat], lr=0.05,momentum=0.3,dampening=0.1)\n if not img_tensor.grad is None:\n img_tensor.grad.zero_(); \n\n for n in range(opt_steps_): # optimize pixel values for opt_steps times\n optimizer.zero_grad()\n img = visualize_for_torchnet(self.G, feat) \n resz_img = F.interpolate(img, (sz, sz), mode='bilinear', align_corners=True)\n img_tensor = normalize(resz_img.squeeze()).unsqueeze(0)\n _=self.model(img_tensor)\n if weights is None:\n loss = -1*activations.features[0, filter].mean()\n else: \n loss = -1*torch.einsum(\"ijk,i->jk\", activations.features[0, filter], self.weights).mean()\n if print_losses:\n if n%5==0:\n print(f'{n} - {float(-loss)}')\n loss.backward()\n optimizer.step()\n\n # convert tensor back to np\n img = val_detfms(img_tensor)\n self.output = img\n # sz = int(upscaling_factor * sz) # calculate new image size\n# print(f'Upscale img to: {sz}')\n img = cv2.resize(img, (sz, sz), interpolation = cv2.INTER_CUBIC) # scale image up\n if blur is not None: img = cv2.blur(img,(blur,blur)) # blur image to reduce high frequency patterns\n \n activations.close()\n return np.clip(self.output, 0, 1)\n \n def get_transformed_img(self,img,sz):\n '''\n Scale up/down img to sz. Channel last (same as input)\n image: np.array [sz,sz,3], already divided by 255\" \n '''\n return cv2.resize(img, (sz, sz), interpolation = cv2.INTER_CUBIC)\n \n# def most_activated(self, img, layer):\n# '''\n# image: np.array [sz,sz,3], already divided by 255\" \n# '''\n# img = cv2.resize(img, (224,224), interpolation = cv2.INTER_CUBIC)\n# activations = SaveFeatures(layer)\n# img_tensor = val_tfms(img)#,np.float32)\n# img_tensor = img_tensor.cuda()\n \n# _=self.model(img_tensor)\n# mean_act = [np.squeeze(to_np(activations.features[0,i].mean())) for i in range(activations.features.shape[1])]\n# activations.close()\n# return mean_act\nfrom torch_net_utils import visualize, load_generator\nfeat = alexnet.features.cuda().eval()\nFVisG = FilterVisualizerGAN(feat)\nimg = FVisG.visualize(sz=227, layer=feat[8], filter=[1,5,3,10], weights=[1,3,1,7], blur=10, opt_steps=20, upscaling_steps=3, upscaling_factor=1.2, print_losses=True)\nplt.figure(figsize=[8,8])\nplt.imshow(FVis.output)\nplt.show()\n```\n\n" | github_jupyter |
# Programming Exercise 5:
# Regularized Linear Regression and Bias vs Variance
## Introduction
In this exercise, you will implement regularized linear regression and use it to study models with different bias-variance properties. Before starting on the programming exercise, we strongly recommend watching the video le... | github_jupyter |
```
import sounddevice as sd
print(sd.query_devices())
sd.default.device = 11
import os
import time
import numpy as np
import collections
%matplotlib inline
import matplotlib.pyplot as plt
from matplotlib import cm as cm
from IPython.display import Audio, display, clear_output, Markdown, Image
import librosa
import lib... | github_jupyter |
<img src="header.png" align="left"/>
# Exercise: Reinforcement Learning Moon Lander (10 points)
The goal of this exercise is to work with reinforcement learning models and get a basic understanding of the topic. We will first develop controlers for the simple cart pole model and later for the lunar lander.
Neil Arms... | github_jupyter |
```
from pandas import read_csv
import pandas
from pandas.plotting import scatter_matrix
from matplotlib import pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.model_selection import cross_val_score
from sklearn.metrics import accuracy_score
from sklearn.model_selection import Stratified... | github_jupyter |
# WorldBank - World employment by sector
<a href="https://app.naas.ai/user-redirect/naas/downloader?url=https://raw.githubusercontent.com/jupyter-naas/awesome-notebooks/master/WorldBank/WorldBank_World_employment_by_sector.ipynb" target="_parent"><img src="https://img.shields.io/badge/-Open%20in%20Naas-success?labelCol... | github_jupyter |
## Randomization
In the previous chapter, we saw how randomization eliminates selection bias. Let's explain what we mean by randomization, describe several ways we might want to randomly assign treatments, and discuss the components *other than* the assignment that can be randomized.
Randomization refers to using "a ... | github_jupyter |
# Random Forest Hyperparameter Tuning
This shows some simple code of how to plot n_estimators to F1 score.
```
%matplotlib notebook
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_val_score
data... | github_jupyter |
# Notebook-2: Thinking Like a Computer
In order to understand how to _program_ a computer, it helps to learn how to _think_ like a computer. At least a little bit. A lot of what we do in programming strips back the veneer of point-and-click friendliness of OSX or Windows so that we can interact with the computer in wa... | github_jupyter |
# Project: final_project - [No-show appointments]
## Table of Contents
<ul>
<li><a href="#intro">Introduction</a></li>
<li><a href="#wrangling">Data Wrangling</a></li>
<li><a href="#cleanning_summary">Cleanning Summary</a></li>
<li><a href="#eda">Exploratory Data Analysis</a></li>
<li><a href="#conclusions">Conclu... | github_jupyter |
```
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import torch
from scipy.stats import rankdata
from sklearn.metrics import roc_auc_score
from scipy.optimize import minimize
from scipy.special import expit as sigmoid
from scipy.special import logit
from pathlib import Path
import sys
COMP_NAME... | github_jupyter |
```
print(note := "Hello World!!")
# we will use/abuse walrus operator
print(note)
print()
import platform
print(note := "We are using python with version as " , platform.python_version())
import sys
print(note := "In This session we will learn about Mutable and Immutable types \
while learning about different inbuilt... | github_jupyter |
# <h1><center>Instacart - Market Basket Analysis</center></h1>
<img src="Instacart.jpg">
Img Source: Kaggle.com
## Table of Contents
1. Abstract
2. Introduction
3. Import libraries and reading csv's
4. Data Preparation and Data Cleaning
5. Exploratory Data Analysis
6. Word2Vec
7. Cultural Analysis
# 1.... | github_jupyter |

```
# ----------
# User Instructions:
#
# Define a function, search() that returns a list
# in the form of [optimal path length, row, col]. For
# the grid shown below, your function should output
# [11, 4, 5].
#
# If there is no valid path from the start point
# to... | github_jupyter |
<a href="https://colab.research.google.com/github/MicroprocessorX069/Generalized-Bayes-classifier-/blob/master/Bayes_classifier.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
## imports
```
def write_requirements(dict_libraries,dir=""):
import o... | github_jupyter |
```
from devito import *
from examples.seismic.source import WaveletSource, TimeAxis
from examples.seismic import plot_image
import numpy as np
from sympy import init_printing, latex
init_printing(use_latex=True)
# Initial grid: 1km x 1km, with spacing 100m
extent = (2000., 2000.)
shape = (81, 81)
x = SpaceDimension(n... | github_jupyter |
<a href="https://colab.research.google.com/github/unicamp-dl/IA025_2022S1/blob/main/ex04/Gustavo_Arantes/Atividade_04_IA025A_Gustavo_Arantes.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# Nome: Gustavo da Silva Arantes
# Inspirado: Larissa Santes... | 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 h2o
from h2o.estimators.glrm import H2OGeneralizedLowRankEstimator
import numpy as np
import pandas as pd
import pandas_gbq
h2o.init()
h2o.remove_all() # Clean slate - just in case the cluster was already running
project_id = 'spike-sandbox'
query_data = """SELECT * FROM `EVIC.lastfm_data` """
df_data = pd.r... | github_jupyter |
# SGDRegressor with Normalize & Polynomial Features
This Code template is for regression analysis using the SGDRegressor where feature normalization using normalize and feature transformation is done using PolynomialFeatures.
### Required Packages
```
import warnings
import numpy as np
import pandas as pd
import ... | github_jupyter |
```
%load_ext Cython
import array
import numpy as np
%%cython --annotate
import binascii
from math import ceil
import array
# rotl = lambda x, n:((x << n) & 0xffffffff) | ((x >> (32 - n)) & 0xffffffff)
bytes_to_list = lambda data: [i for i in data]
cdef unsigned int[:] IV = array.array('I', [
1937774191, 122609... | github_jupyter |
<h1>
<p style="text-align: center;">
Multiprocessing is All you Need
</p>
</h1>
<h5>
<p style="text-align: center;">
(Немного хайпово звучит)
</p>
</h5>
```
import os
import time
from multiprocessing import Process
```
Делаем подпроцессы, которые что-то делают
```
def doubler(number):... | github_jupyter |
# Scoring Matrices
```
from Bio import AlignIO
# read in sample alignments
alignments = AlignIO.read('msa.phy', 'phylip')
print(alignments)
from Bio.Phylo.TreeConstruction import DistanceCalculator
DistanceCalculator.dna_models
```
^ note that distance calculator also has an 'identity' model,
but it is not consider... | github_jupyter |
# IndoSum Statistics
# Importing Libraries
```
import os
import json
import math
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
# Initialize the random number generator.
np.random.seed(42)
# ! mv times-new-roman.ttf /usr/share/fonts/truetype/
# ! fc-cache ... | github_jupyter |
```
import cameo
from cobra import Model, Reaction, Metabolite
from cobra.io import read_sbml_model
from cobra.io import save_json_model
from cameo.flux_analysis.simulation import pfba
import cobra.test
import os
from Functions_Modules.curation_tools import *
relative_directory = os.getcwd()
filename = relative_directo... | github_jupyter |
```
# Copyright 2019 The TensorFlow Hub Authors. All Rights Reserved.
#
# 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by... | github_jupyter |
```
import datetime
import h5py
import librosa
import numpy as np
import os
import skm
import soundfile as sf
import sys
import time
sys.path.append('../src')
import localmodule
# Define constants.
data_dir = localmodule.get_data_dir()
dataset_name = localmodule.get_dataset_name()
units = localmodule.get_units()
pat... | github_jupyter |
### Example 6: Poisson equation
In the previous example we have seen how to solve the steady-state Laplace equation with a prescribed boundary condition and BCs that contain derivatives (Neumann BC). For this we used a pseudo-timestepping to illustrate the use of two explicit data symbols of type `Function` to derive ... | github_jupyter |
<!-- dom:TITLE: Week 3 January 18-22: Building a Variational Monte Carlo program -->
# Week 3 January 18-22: Building a Variational Monte Carlo program
<!-- dom:AUTHOR: Morten Hjorth-Jensen Email morten.hjorth-jensen@fys.uio.no at Department of Physics and Center fo Computing in Science Education, University of Oslo... | github_jupyter |
#!/usr/bin/env python
#-------------------------------------------------------------------------------
# Name: BayesianTracker
# Purpose: A multi object tracking library, specifically used to reconstruct
# tracks in crowded fields. Here we use a probabilistic network of
# information to perform... | github_jupyter |
Importing the required libraries:
[Source](https://github.com/ejm714/disaster_relief_from_space) Ignore for now
```
# import rasterio
# import matplotlib.pyplot as plt
# import numpy as np
# import shapely
# from shapely import geometry
# from collections import Counter
# import os
# import json
# import pandas as pd... | github_jupyter |
<h1>Table of Contents<span class="tocSkip"></span></h1>
<div class="toc" style="margin-top: 1em;"><ul class="toc-item"><li><span><a href="#Name" data-toc-modified-id="Name-1"><span class="toc-item-num">1 </span>Name</a></span></li><li><span><a href="#Search" data-toc-modified-id="Search-2"><span class="toc-i... | github_jupyter |
# MAT 221 Calculus I
## April 9, 2020
Today's Agenda:
1. Continuous Function
2. Intermediate Value Theorem
3. Exercises
# Antiderivatives (Indefinite Integral)
Antiderivatives, which are also referred to as indefinite integrals or primitive functions, is essentially the opposite of a derivative (hence the name). Mo... | github_jupyter |
# Introduction
This notebook generates a simple training/testing dataset showing icons of persons at different image locations.
# Check dependencies
```
import matplotlib
print(matplotlib.__version__)
import numpy as np
print(np.__version__)
import cv2
print(cv2.__version__)
import pickle
print(pickle.format_vers... | github_jupyter |
## The following analysis is meant to explore where it pays to go college.
### Introduction to the project
##### *The importance of a major is powerful.* Not only it can affect your life financially, but also it can help you to choose the right path to pursue. Considering the high cost of tuition no one would want to... | github_jupyter |
# Ternviz
Make a video of a turning structure from SMILES.
Checkout the Twitter bot [@ternviz](https://twitter.com/ternviz)!
```
# @title Install Required Packages
print("🐍Installing Miniconda")
! wget -q https://repo.anaconda.com/miniconda/Miniconda3-py37_4.8.2-Linux-x86_64.sh
! chmod +x Miniconda3-py37_4.8.2-Linu... | github_jupyter |
```
# PS2 - CE264
# importing the requried libraries
from collections import OrderedDict # For recording the model specification
import pandas as pd # For file input/output
import numpy as np # For vectorized math operations
import pylogit as pl # For MNL mo... | github_jupyter |
```
import pandas as pd
import numpy as np
from collections import Counter
```
## This notebook explains the theory behind microbial sourcetracking using a Gibb's sampler.
## The theory and examples are based on work detailed in [Knights et al. 2011](http://www.nature.com/nmeth/journal/v8/n9/abs/nmeth.1650.html): if... | github_jupyter |
```
import os
import sys
import glob
import pickle
import itertools
import random
from IPython.display import Image
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
from matplotlib.colors import ListedColormap
from scipy.stats import multivariate_normal
import numpy as np
import panda... | github_jupyter |
```
import numpy as np
import sys
sys.path.append('../../')
# Each Function are at different Part
import imregpoc
import cv2
import math
import VideoStiching
vobj =VideoStiching.VideoStiching('../../../../videoreader/1228/1228.avi')
vobj.load_data()
vobj.Optimization()
vobj.show_stitched('output_POC.mp4')
vobj.load_FP(... | github_jupyter |
# Step 2: Define Connection Masks
```
# This jupyter notebook gives the possibility to connect the same input to multiple nodes in the next layer.
# This is more memory intensive and I'd recommend starting with the alternative memory friendly notebook.
## Connectivity Matrices
# The connections between the layers are... | github_jupyter |
```
import os
from distutils.dir_util import copy_tree
import itertools
import scipy
from scipy import stats
import dask.dataframe as dd
import pandas as pd
import numpy as np
import random
import matplotlib.pyplot as plt
import time, pytz
from datetime import datetime
from matplotlib.ticker import MultipleLocator, Fix... | github_jupyter |
```
from PIL import Image
from pprint import pprint
import re
import pyocr
import pyocr.builders
import Levenshtein as lev
tools = pyocr.get_available_tools()
assert len(tools) > 0
tool = tools[0]
print(tool)
#'IMG_20180710_170326.jpg' - 10.07.2018 general
#'IMG_20180710_175215.jpg' - 9.07.2018 general
#'IMG_20180714_1... | github_jupyter |
# A quick, practical intro to the Jupyter Notebook
Notebooks consist of a **linear sequence of cells**. There are three basic cell types:
* **Code cells:** Input and output of live code that is run in the kernel
* **Markdown cells:** Narrative text with embedded LaTeX equations
* **Raw cells:** Unformatted text that ... | github_jupyter |
## Dataset analysis
This dataset is provided with metadata information such as weather conditions, solar conditions, dynamic objects present on annotated frames and present annotations for each frame. This notebooks shows how the metadata information can be used to statistically analyze the dataset.
```
import os
imp... | github_jupyter |
```
import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.ensemble import RandomForestClassifier
# Read in the data
#Data = pd.read_csv('Full_Data.csv', encoding = "ISO-8859-1")
#Data.head(1)
data = pd.read_csv('Full_Data.csv', encoding = "ISO-8859-1")
data.head(1)
train = data[da... | github_jupyter |
##### Copyright 2018 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 |
# 1. Introduction and flat files
**In this chapter, you'll learn how to import data into Python from all types of flat files, which are a simple and prevalent form of data storage. You've previously learned how to use NumPy and pandas—you will learn how to use these packages to import flat files and customize your impo... | github_jupyter |
# 02-04: Composite Design Pattern
### Type: Structural
### Scope: Object
### Symptoms: Hierarchial Data
## Intent
Composite design pattern is a structural design pattern which defines part-whole relationship between objects within a tree structure.
In a complex tree structure, it's a challenge to discriminate betwee... | github_jupyter |
```
import pandas as pd
import numpy as np
from scipy.stats import pearsonr
import openpyxl
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.utils import resample
from sklearn.preprocessing import StandardScaler, RobustScaler
from sklearn.model_selection import train_test_split
from imblearn.pipeli... | github_jupyter |
# Galaxy Classification with CNN (Pytorch)
Data:
https://www.kaggle.com/c/galaxy-zoo-the-galaxy-challenge
References:
1. https://pytorch.org/tutorials/beginner/transfer_learning_tutorial.html
2. https://pytorch.org/vision/stable/models.html
3. https://pytorch.org/tutorials/beginner/data_loading_tutorial.html
4... | github_jupyter |
# Days Between Dates
This lesson will focus on one problem: calculating the number of days between two dates.
This workspace is yours to use in whatever way is helpful. You might want to keep it open in a second tab as you go through the videos.
```
def isLeapYear(year):
if year % 400 == 0:
return 29
... | github_jupyter |
```
# Standard libraries
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colorbar
import seaborn as sns
# Third-party libraries
import camb
import pyhmcode as hmcode
# Seabornify
sns.set_theme(style='ticks')
# CAMB verbosity level
camb.set_feedback_level(0)
# Cosmological parameters
h = 0.7
omc ... | github_jupyter |
# Data Science Case Study | January 2021
## Problem Definition
The case study involves around the analysis and exploration of anomymous battery data. We will use this notebook to perform data exploration, find out pattens and relations, and define new attributes. In the second part, we will define a use-case for pred... | github_jupyter |
# 微分可能LUTモデルによるMNISTでの Auto Encoder 学習
Differentiable LUTモデルを用いて MNIST 画像の Auto Encoder を作成してみます。<br>
ネットワークモデルにはCNNを用いています。
バイナリであっても今のところある程度機能しており、一度 32ch まで圧縮した後に復元させています。
## 事前準備
```
import os
import numpy as np
import matplotlib.pyplot as plt
from tqdm.notebook import tqdm
import torch
import torchvision
impo... | github_jupyter |
```
#%matplotlib inline
import time
import datetime
import numpy as np
import pandas as pd
import pandas_market_calendars as mcal
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.finance import candlestick_ohlc, candlestick2_ohlc
import matplotlib.dates as mdates
import matplotlib.ticker as tick... | github_jupyter |
# Using *Kepler* Light Curve Products with Lightkurve
## Learning Goals
By the end of this tutorial, you will:
- Understand how NASA's *Kepler* Mission collected and released light curve data products.
- Be able to download and plot light curve files from the data archive using [Lightkurve](https://docs.lightkurve.o... | github_jupyter |
SOP040 - Upgrade pip in ADS Python sandbox
==========================================
Steps
-----
### Common functions
Define helper functions used in this notebook.
```
# Define `run` function for transient fault handling, hyperlinked suggestions, and scrolling updates on Windows
import sys
import os
import re
imp... | github_jupyter |
```
name = "2019-11-21-become-a-10x-programmer"
title = "Become a 10x programmer, lessons from academia and industry"
tags = "optimisation, profiling, testing, version control"
author = "Anthony De Gol"
from nb_tools import connect_notebook_to_post
from IPython.core.display import HTML
html = connect_notebook_to_post(... | github_jupyter |
```
%matplotlib inline
from IPython.core.display import HTML
HTML("""
<style>
.output_png {
display: table-cell;
text-align: center;
vertical-align: middle;
}
</style>
""")
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from scipy import integrate
from scipy imp... | github_jupyter |
```
# Erasmus+ ICCT project (2018-1-SI01-KA203-047081)
%matplotlib notebook
import control as c
import ipywidgets as w
import numpy as np
from IPython.display import display, HTML
import matplotlib.pyplot as plt
import matplotlib.animation as animation
# Toggle cell visibility
from IPython.display import HTML
tag =... | github_jupyter |
# Initialization
Welcome to the first assignment of "Improving Deep Neural Networks".
Training your neural network requires specifying an initial value of the weights. A well chosen initialization method will help learning.
If you completed the previous course of this specialization, you probably followed our ins... | github_jupyter |
# Understanding PCA behaviour
### June 2, 2019
#### Luis Da Silva
This notebook explores how the Principal Component Analysis works by making use of synthetic data.
```
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
def random_df(mx=0, sx=1, my=0, sy=1, n=... | github_jupyter |
```
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
import json
with open('/home/husein/alxlnet/topics.json') as fopen:
topics = set(json.load(fopen).keys())
list_topics = list(topics)
import xlnet
import numpy as np
import tensorflow as tf
from tqdm import tqdm
import model_utils
import random
import sent... | github_jupyter |
# Fourier Analysis, Wavelet Analysis, and Signal Processing
This note reviews basic operations for Fourier analysis and wavelet analysis, and demonstrate the Python implementation of the operations. The main reference is the wavelet paper by Torrence and Compo (1998), we will refer to it as TC98 later in the note.
Th... | github_jupyter |
# Riskfolio-Lib Tutorial:
<br>__[Financionerioncios](https://financioneroncios.wordpress.com)__
<br>__[Orenji](https://www.orenj-i.net)__
<br>__[Riskfolio-Lib](https://riskfolio-lib.readthedocs.io/en/latest/)__
<br>__[Dany Cajas](https://www.linkedin.com/in/dany-cajas/)__
<a href='https://ko-fi.com/B0B833SXD' target='... | github_jupyter |
## Hands-On Data Preprocessing in Python
Learn how to effectively prepare data for successful data analytics
AUTHOR: Dr. Roy Jafari
### Chapter 5: Data Visualization
#### Excercises
```
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
from ipywidgets import inter... | github_jupyter |
# Keras Data Loaders and Augmentator
<h1>Table of Contents<span class="tocSkip"></span></h1>
<div class="toc"><ul class="toc-item"><li><span><a href="#Image-Data-Generator" data-toc-modified-id="Image-Data-Generator-1"><span class="toc-item-num">1 </span>Image Data Generator</a></span></li><li><span><a href... | github_jupyter |
# Exercise2:房價預測模型
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://colab.research.google.com/github/taipeitechmmslab/MMSLAB-TF2/blob/master/Exercise/Exercise2.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />Run in Google Colab</a>
</td>
<td>
... | github_jupyter |
# **Dynamical learning of dynamics**
Christian Klos, Yaroslav Felipe Kalle Kossio, Sven Goedeke, Aditya Gilra, and Raoul-Martin Memmesheimer
*Neural Network Dynamics and Computation, Institute of Genetics, University of Bonn, Bonn, Germany.*
---
This notebook contains example code to create a network that dynamicall... | github_jupyter |
Welcome new ADAM user!
This notebook will guide you through a few ADAM features and validate that your system is configured correctly.
This guide will demonstate how to pull orbital data for a given asteroid and time frame from JPL Horizons and how to propogate that same orbit using ADAM. This program will also... | github_jupyter |
# Extracting Information with Selenium
*Curtis Miller*
Selenium is a good tool to choose for data extraction when the content of a webpage changes. JavaScript in particular changes the content of the DOM and so needs to be handled in a special way.
The webpage for the archive of [Pycoder's Weekly](http://pycoders.com... | github_jupyter |
<a href="https://colab.research.google.com/github/NeuromatchAcademy/course-content/blob/master/tutorials/W3D5_NetworkCausality/W3D5_Tutorial3.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# Tutorial 3: Simultaneous fitting/regression
**Week 3, Day... | github_jupyter |
```
import numpy as np
import pandas as pd
from numpy import genfromtxt
import matplotlib.pyplot as plt
data=pd.read_csv('Housedata.csv',index_col=0)
data.head()
categorical=['driveway','recroom','fullbase','gashw','airco','prefarea']
for col in categorical:
temp=data.loc[:,col]
c=temp.nunique()
temp=t... | github_jupyter |
# Functions
**Prerequisites**
- [Introduction](intro.ipynb)
- [Basics](basics.ipynb)
- [Collections](collections.ipynb)
- [Control Flow](control_flow.ipynb)
**Outcomes**
- Economic Production Functions
- Understand the basics of production functions in economics
- Functions
- Know how to... | github_jupyter |
## NLP Yelp Star Classification
**Columns**
stars: number of stars (1 to 5)
cool: number of likes on the review (0 or plus)
useful and funny =~ cool
```
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
file = "//home//vinicius//Data_Science//Noteboo... | github_jupyter |
```
%pylab inline
%load_ext autoreload
%autoreload 2
import matplotlib.pyplot as plt
import numpy as np
import numpy.random as npr
import sys
sys.path.append("../subjective-fits/")
import seaborn as sns
figsize(8,6)
mpl.rcParams['xtick.labelsize'] = 22
mpl.rcParams['ytick.labelsize'] = 22
plt.rc('axes', labelsize=22)
p... | github_jupyter |
# Genetic algorithms using `numpy`
In this demonstration, we will code up step-by-step, a simple GA for optimizing a trivial function with constraints. Further exploration in this example would be very useful for your project.
```
import numpy as np
# Do some Ipython black magic
from IPython.core.interactiveshell im... | github_jupyter |
# TV Script Generation
In this project, you'll generate your own [Seinfeld](https://en.wikipedia.org/wiki/Seinfeld) TV scripts using RNNs. You'll be using part of the [Seinfeld dataset](https://www.kaggle.com/thec03u5/seinfeld-chronicles#scripts.csv) of scripts from 9 seasons. The Neural Network you'll build will ge... | github_jupyter |
# Image Captioning with RNNs
In this exercise you will implement a vanilla recurrent neural networks and use them it to train a model that can generate novel captions for images.
```
# As usual, a bit of setup
import time, os, json
import numpy as np
import matplotlib.pyplot as plt
from cs231n.gradient_check import e... | github_jupyter |
## Day 2 - 1st activity
https://data-lessons.github.io/library-python/02-index-slice-subset/
```
import pandas as pd
articles_df = pd.read_csv('articles.csv')
print(articles_df.columns)
articles_df[['First_Author', 'DOI', 'ISSNs']].tail(5)
articles_df[['First_Author', 'DOI', 'ISSNs']].head(5)
articles_df['thkfdlsajfk... | github_jupyter |
```
cd /media/sf_datasets/Smarter\ Devices/BLUED_extracted/BLUED-TK/events/
import pandas as pd
import numpy as np
from sklearn.cross_validation import KFold,cross_val_score
from sklearn.neighbors import KNeighborsClassifier
import matplotlib.pyplot as plt
from sklearn.metrics import f1_score
from sklearn.model_selecti... | github_jupyter |
# Purpose
The purpose of this notebook is to experiment with converting pixel colors represented in the RGB (RedGreenBlue) like in the matplotlib numpy array to HSBK (hue, saturation, brightness, kelvin) values which are used as input for the LIFX Tiles
Goal is to take images directly from the Pillow library, convert... | github_jupyter |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.