text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
# SPM12 scripting in a Jupyter notebook with an Octave kernel
This is a [Jupyter notebook](https://jupyter.org/) running an [Octave kernel](https://github.com/Calysto/octave_kernel) on [Binder](https://mybinder.org/), which allows cloud-based computation using SPM12 and Matlab scripts. It is therefore a reproducible e... | github_jupyter |
# Interactive time series with time slice retrieval
This notebook shows you how to use interactive plots to select time series for different locations and retrieve the imagery that corresponds with different points on a time series
```
%pylab notebook
from __future__ import print_function
import datacube
import xarra... | github_jupyter |
# Ungraded Lab: Class Activation Maps with Fashion MNIST
In this lab, you will see how to implement a simple class activation map (CAM) of a model trained on the [Fashion MNIST dataset](https://github.com/zalandoresearch/fashion-mnist). This will show what parts of the image the model was paying attention to when deci... | github_jupyter |
# Rotation matrix and mahalanobis distance
It is possible to rotate N dimensional dataset into a space. Since mahalanobis distance uses this background information, then this space will have an impact to distance calculations.
Firstly, we shall clear away old variables.
```
rm(list=ls())
```
Load additional librari... | github_jupyter |
<a href="https://colab.research.google.com/github/Peischlili/ComputerVision_WebScraper/blob/main/Yolo3_detection.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
**Import dependences**
```
import os
import struct
import numpy as np
from keras.layers... | github_jupyter |
# Autoregressive Integrated Moving Average with Explanatory Variable (ARIMAX)
The <a href="https://en.wikipedia.org/wiki/Autoregressive_integrated_moving_average">ARIMA</a> model is a generalisation of an ARMA model that can be applied to non-stationary time series.
The ARIMAX model is an extended version of ARIMA th... | github_jupyter |
```
# When you submit this code in Coding Ninjas it raises TLE for last two test cases. Do you know why?
# Exactly swapping takes most of the time
# // Refer the optimised code which is written below of this code//
class Node:
def __init__(self, data):
self.data = data
self.next = None
def length(... | github_jupyter |
<a href="https://colab.research.google.com/github/jonkrohn/ML-foundations/blob/master/notebooks/2-linear-algebra-ii.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# Linear Algebra II: Matrix Operations
This topic, *Linear Algebra II: Matrix Operat... | github_jupyter |
```
%load_ext autoreload
%autoreload 2
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import gpplot as gpp
import anchors
from poola import core as pool
import core_functions as fns
gpp.set_aesthetics(palette='Set2')
```
## Functions
```
#QC
def add_guide_seq_col(df, guide_col = 'sgRNA'... | github_jupyter |
# <center> In-class Assignment 1 </center>
**Task 1. Word game**
You need to write a program for a word game.
The first player think about a word and save it using input() function and only lowercase letters.
The second player provides new words in the same format. In total, the user needs to make 15 moves (name 1... | github_jupyter |
```
# import sys
from gp_sinkhorn.SDE_solver import solve_sde_RK
from gp_sinkhorn.MLE_drift import *
from gp_sinkhorn.utils import plot_trajectories_2
import copy
import torch
import math
import numpy as np
from celluloid import Camera
from IPython.display import HTML
import matplotlib.pyplot as plt
```
# Dataset... | github_jupyter |
```
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import seaborn as sns
from sklearn.neighbors import KNeighborsClassifier
from IPython.display import Image
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_curve, auc, plot_precision_recall_curve, plot_roc_cur... | github_jupyter |
Probability theory is a cornerstone for machine learning. We can think of quantum states as probability distributions with certain properties that make them different from our classical notion of probabilities. Contrasting these properties is an easy and straightforward introduction to the most basic concepts we need i... | github_jupyter |
```
from stonks.data.data_reader import MktDataReader
from stonks.backtest.backtest import BackTester
from stonks.backtest.strategy.constant_equal_weights import EqualWeightsStrategy
import functools
import math
import backtrader as bt
import backtrader.feeds as btfeeds
tickers = [
'AAPL', # Apple -> tech
'TSL... | github_jupyter |
```
import pandas as pd
import numpy as np
from matplotlib import pylab
bioresponse = pd.read_csv('bioresponse.csv', header=0)
bioresponse.head()
from sklearn.ensemble import RandomForestClassifier
import xgboost as xgb
from sklearn.model_selection import cross_val_score
bio_target = bioresponse.Activity.values
del bi... | github_jupyter |
## RF
```
# import xgboost as xgb
from sklearn.ensemble import RandomForestClassifier
from rsnautils import *
pkls = L(path_pred.glob('*_tta.pkl'))
fn = pkls[0]
def read_preds(fn):
preds,targs = fn.load()
df = pd.DataFrame(preds.numpy())
df.columns = [':'.join([fn.stem[:-4], c]) for c in htypes]
return... | github_jupyter |
# BLU03 - Learning Notebook - Part 3 of 3 - Web scraping
## 1. Introduction
In the context of data wrangling, we've already talked about three data sources: files, databases and public APIs.
Now it's time to delve into the Web!
As we all know, there is a huge amount of data in the Web. Whenever we search something ... | github_jupyter |
```
import tensorflow as tf
import glob
import nibabel as nib
import os
import time
import pandas as pd
import numpy as np
from mricode.utils import log_textfile
from mricode.utils import copy_colab
tf.__version__
tf.test.is_gpu_available()
path_output = './'
path_tfrecords = '/data2/res64/down/'
path_csv = '/data2/... | github_jupyter |
```
#API request to get data
import requests as req
url = 'http://api.tvmaze.com/schedule?country=US'
resp = req.get(url)
response = resp.text
type(response)
#Convert str datatype of response to list since json_normalize function from pandas
#requires JSON array i.e. list of records
import json
data = json.loads(respon... | github_jupyter |
```
# import necessary packages
import os
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import seaborn as sns
import plotly.express as px
import geopandas as gpd
from descartes import PolygonPatch
from tqdm import tqdm
df = pd.read_csv("data/full_run_3.zip",skiprows=6)
#remove all the columns t... | github_jupyter |
```
from datetime import datetime
import mxnet as mx
from mxnet import autograd, gluon, init, nd
from mxnet.gluon import nn, rnn, utils as gutils
import numpy as np
import pandas as pd
import sys
from tqdm import tqdm
from data import load_data
from net import EXAM
from eval import evaluate
# params
ctx = [mx.cpu(0)]
... | github_jupyter |
# ECIP Models for Software Defect Prediction Dataset
## Import
```
from imblearn.over_sampling import RandomOverSampler
from imblearn.over_sampling import SMOTE
from imblearn.under_sampling import RandomUnderSampler
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split
fr... | github_jupyter |
ERROR: type should be string, got "https://towardsdatascience.com/logistic-regression-using-python-sklearn-numpy-mnist-handwriting-recognition-matplotlib-a6b31e2b166a\n\n## Sigmoid\n\n```\nimport numpy as np\nimport matplotlib.pyplot as pl\ndef sigmoid(z):\n return 1 / (1 + np.exp(-z))\n\nsigmoid(757)\nfrom sklearn.datasets import load_digits\ndigits = load_digits() # 8x8 = 64 pixels -- Very clean Dataset\n```\n\n#### Now that you have the dataset loaded you can use the commands below\n\n```\ndigits.keys()\n# Print to show there are 1797 images (8 by 8 images for a dimensionality of 64)\nprint(\"Image Data Shape\" , digits.data.shape)\n# Print to show there are 1797 labels (integers from 0–9)\nprint(\"Label Data Shape\", digits.target.shape)\ndigits.data.shape\ndigits.keys()\nimport pandas as pd\n\ndf = pd.DataFrame(data= np.c_[digits['data'], digits['target']])\ndf\ncuatro = df.iloc[4]\nk = np.reshape(cuatro[:64].values, (8,8))\nplt.imshow(k, cmap=plt.cm.gray)\ndigits.target\n#y = a + b1X1 + b2X2 + b... + b64*X64\ndigits.target[0:50]\nimport numpy as np \nimport matplotlib.pyplot as plt\nplt.figure(figsize=(20,2))\nfor index, (image, label) in enumerate(zip(digits.data[0:5], digits.target[0:5])):\n plt.subplot(1, 5, index + 1)\n plt.imshow(np.reshape(image, (8,8)), cmap=plt.cm.gray)\n plt.title('Training: ' + str(label), fontsize = 20)\n```\n\n### Splitting Data into Training and Test Sets (Digits Dataset)\n\n```\nfrom sklearn.model_selection import train_test_split\nx_train, x_test, y_train, y_test = train_test_split(digits.data, digits.target, test_size=0.15, random_state=0)\nx_train.shape\nfrom sklearn.linear_model import LogisticRegression\n# all parameters not specified are set to their defaults\nlogisticRegr = LogisticRegression()\nlogisticRegr.fit(x_train, y_train)\nprint(y_train[:5])\n```\n\n### To predict\n\n```\nlogisticRegr.predict(x_train[:5])\nx_train[:5].shape\nx_test.shape\ny_test[:5]\nplt.figure(figsize=(20,2))\nfor index, (image, label) in enumerate(zip(x_test[0:5], y_test[0:5])):\n plt.subplot(1, 5, index + 1)\n plt.imshow(np.reshape(image, (8,8)), cmap=plt.cm.gray)\n plt.title('Test: ' + str(label), fontsize = 20)\nplt.rcParams['figure.figsize'] = 20 , 2\nfirst_test_image = x_test[0]\nplt.imshow(np.reshape(first_test_image, (8,8)), cmap=plt.cm.gray)\nx_test[0].shape\n# Returns a NumPy Array\n# Predict for One Observation (image)\nlogisticRegr.predict(x_test[0].reshape(1, -1))\nmax(logisticRegr.predict_proba(x_test[0].reshape(1, -1))[0])\ny_test[0:10]\nlogisticRegr.predict(x_test[0:10])\n```\n\n### Probabilities\n\n```\nx_test[:1].shape\nlogisticRegr.predict_proba(x_test[:1])\nsum(logisticRegr.predict_proba(x_test[0:1])[0])\nlogisticRegr.classes_\nmax(logisticRegr.predict_proba(x_test[0:1])[0])\n```\n\n### Measuring Model Performance (Digits Dataset)\n\n```\n# Use score method to get accuracy of model\nscore = logisticRegr.score(x_train, y_train)\nscore\n# Use score method to get accuracy of model\nscore = logisticRegr.score(x_test, y_test)\nprint(score * 100, \"%\")\nx_test.shape\n10 / 1 \n1000 / 10\n```\n\n### Matriz de confusión\n\nEje horizontal: falso negativo\n\nEje vertical: falso positivo\n\n```\nimport sklearn.metrics as metrics\npredictions = logisticRegr.predict(x_test)\ncm = metrics.confusion_matrix(y_test, predictions)\nprint(cm)\nimport seaborn as sns\n\nplt.figure(figsize=(8,8))\nsns.heatmap(cm, annot=True, fmt=\".1f\", linewidths=.5, square = True, cmap = 'Blues_r')\nplt.ylabel('Actual label')\nplt.xlabel('Predicted label')\nall_sample_title = 'Accuracy Score: {0}'.format(score)\nplt.title(all_sample_title, size = 15)\ndf2 = pd.DataFrame(data=digits['data'])\ndf2.shape\ny = df[64]\ny\ny.values.reshape(-1, 1).shape\ny_pred.shape\ndigits.target.shape\n# Yo ya estoy contento con mi modelo:\n\n# Ahora entreno el modelo con todos los datos que tengo\n# Entreno el modelo con todos los datos\nlogisticRegr.fit(df2, y.values)\n\n# Predecimos con todos los datos que tenemos\ny_pred = logisticRegr.predict(df2)\n# Calculamos cuánto de bien ha entrenado con nuestros datos\nlogisticRegr.score(df2, y.values)\n```\n\n" | github_jupyter |
In this notebook, we aim to recover the convergence map $\kappa$ from the observed shear $\gamma$.
The shear map can be obtained by the Kaiser-Squires transformation: $\gamma = \mathrm{TFP}^* \kappa$, where
<ul>
<li>$\mathrm{T}$ is a Non-equispaced Discrete Fourier Transform, so not necessarily invertible,</li>
... | github_jupyter |
# NEURAL NETWORKS
This notebook covers the neural network algorithms from chapter 18 of the book *Artificial Intelligence: A Modern Approach*, by Stuart Russel and Peter Norvig. The code in the notebook can be found in [learning.py](https://github.com/aimacode/aima-python/blob/master/learning.py).
Execute the below c... | github_jupyter |
# Operators
Operators are special symbols in Python that carry out arithmetic or logical computation. The value that the operator operates on is called the operand.
# Operator Types
1. Arithmetic operators
2. Comparison (Relational) operators
3. Logical (Boolean) operators
4. Bitwise operators
5. Assignment ... | github_jupyter |
## **Python Object Oriented Programming**
Python is a multi-paradigm programming language. It supports different programming approaches. One of the popular approaches to solve a programming problem is by creating objects. This is known as **Object-Oriented Programming (OOP)**
**An object has two characteristics:**
-... | github_jupyter |
### Summery
<pre>
Author : Anjana Tiha
Project Name : Detection of Pneumonia from Chest X-Ray Images using Convolutional Neural Network,
and Transfer Learning.
Description : 1. Detected Pneumonia from Chest X-Ray images by retraining pretrained model “InceptionV3”
... | github_jupyter |
----
<img src="../../../files/refinitiv.png" width="20%" style="vertical-align: top;">
# Data Library for Python
----
## Content layer - Estimates - Actuals KPI
This notebook demonstrates how to retrieve Estimates.
I/B/E/S (Institutional Brokers' Estimate System) delivers a complete suite of Estimates content with ... | github_jupyter |
# Multiclass Support Vector Machine exercise
*Complete and hand in this completed worksheet (including its outputs and any supporting code outside of the worksheet) with your assignment submission. For more details see the [assignments page](http://vision.stanford.edu/teaching/cs231n/assignments.html) on the course we... | github_jupyter |
```
#Retrieving dataset from Google Drive
MODE = "MOUNT"
from google.colab import drive
drive.mount._DEBUG = False
if MODE == "MOUNT":
drive.mount('/content/drive', force_remount=True)
elif MODE == "UNMOUNT":
try:
drive.flush_and_unmount()
except ValueError:
pass
from keras.models import Sequential, Model... | github_jupyter |
```
import azureml.core
from azureml.core import Workspace
ws = Workspace.from_config()
# Get the default datastore
default_ds = ws.get_default_datastore()
default_ds.upload_files(files=['./Data/borrower.csv', './Data/loan.csv'], # Upload the diabetes csv files in /data
target_path='creditrisk... | github_jupyter |
# 自動機械学習 Automated Machine Learning による品質管理モデリング & モデル解釈 (リモート高速実行)
製造プロセスから採取されたセンサーデータと検査結果のデータを用いて、品質管理モデルを構築します。
- Python SDK のインポート
- Azure ML service Workspace への接続
- Experiment の作成
- データの準備
- 計算環境の準備
- 自動機械学習の事前設定
- モデル学習と結果の確認
- モデル解釈
## 1. 事前準備
### Python SDK のインポート
Azure Machine Learning service の Python SD... | github_jupyter |
```
%load_ext autoreload
%autoreload 2
%matplotlib inline
import numpy as np
import xarray as xr
import matplotlib.pyplot as plt
plt.style.use(['seaborn-ticks', 'seaborn-talk'])
import seaborn as sns
import cartopy.crs as ccrs
```
# Setup
```
from dask.distributed import Client, progress
from dask_kubernetes impor... | github_jupyter |
# Artificial Intelligence Nanodegree
## Convolutional Neural Networks
---
In your upcoming project, you will download pre-computed bottleneck features. In this notebook, we'll show you how to calculate VGG-16 bottleneck features on a toy dataset. Note that unless you have a powerful GPU, computing the bottleneck f... | github_jupyter |
### Wikiart: Metric Anaylsis of different GANs
```
import numpy as np
import matplotlib.pyplot as plt
from google.colab import drive
from numpy import genfromtxt
```
### Mount Google Drive
```
# mount drive
drive.mount('/content/drive')
```
### Import results
```
# regular dc gan
is_dcgan_style = genfromtxt('/con... | github_jupyter |
```
import cv2
img=cv2.imread('0.jpeg')
# initilization of window
cv2.namedWindow('IMAGE',0)
cv2.imshow('IMAGE',img)
cv2.imwrite('output.jpeg',img)
cv2.waitKey()
cv2.destroyAllWindows()
#access and understand pixel data
import cv2
import numpy as np
img=cv2.imread('0.jpeg')
print(img)
print(type(img))
print(len(img))... | github_jupyter |
# General Information
This notebook demonstrates how the `fastai_sparse` library can be used in semantic segmentation tasks using the example of the [ShapeNet Core55](https://shapenet.cs.stanford.edu/iccv17/) 3D semantic segmentation solution presented in [SparseConvNet example](https://github.com/facebookresearch/Spa... | github_jupyter |
# Alignments
This notebook analyzes page alignments and prepares metrics for final use.
## Setup
We begin by loading necessary libraries:
```
from pathlib import Path
import pandas as pd
import xarray as xr
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import gzip
import pickle
import bin... | github_jupyter |

In the next step, our third agile sprint, we’ll extend our chart pages into full-blown reports. In this step, charts become interactive, static pages become dynamic, and our data becomes explorable through networks of linked, related entities with tables and charts. These are... | github_jupyter |
[](https://pythonista.mx)
# Palabras reservadas, nombres y el espacio de nombres.
## Palabras reservadas de Python.
Las palabras reservadas (keywords) corresponden a los nombres de las declaraciones que el intérprete de Python incluye por defecto. No se deben utilizar dichas palab... | github_jupyter |
```
import csv
import copy
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
np.random.seed(0)
pd.set_option('display.max_rows', None)
```
## Overview
This notebook simulates the spread of an infection within a community that serves as a collection of private spaces (houses) an... | github_jupyter |
# Reproducibility
```
import torch
my_seed=19951008
torch.manual_seed(my_seed)
import numpy as np
np.random.seed(my_seed)
from tqdm import tqdm
#torch.set_deterministic(True)
```
# Import libraries
```
import json
from sklearn.preprocessing import LabelEncoder
import sys
## These two should correspond to the path wh... | github_jupyter |
# Using TensorFlow Scripts in SageMaker - Quickstart
Starting with TensorFlow version 1.11, you can use SageMaker's TensorFlow containers to train TensorFlow scripts the same way you would train outside SageMaker. This feature is named **Script Mode**.
This example uses
[Multi-layer Recurrent Neural Networks (LSTM,... | github_jupyter |
## Quantitative QC by CV calculation
The data used in this notebook is lymphocyte data for one patient's B cells and T cells. We use this data to show the proteome variation between the cell types. Here, we calculate CVs to show the quality of the data.
After calculating CVs, we calculate Spearman correlation among re... | github_jupyter |
# Apartado 6 - Import
- Import modulos
- Abrir ficheros
------------------------------------------------------------------
## Import modulos
[HELP](https://realpython.com/python-modules-packages/)
```
import mi_modulo
suma = mi_modulo.suma_2(a=2, b=6)
print(suma)
resta = mi_modulo.resta_2(a=7, b=6)
resta
from mi... | github_jupyter |
<h1 align="center"> Machine learning-based prediction of early recurrence in glioblastoma patients: a glance towards precision medicine <br><br> [Statistical Analysis]</h1>
<h2>[1] Library</h2>
```
# OS library
import os
import sys
import argparse
import random
from math import sqrt
# Analysis
import numpy as np
imp... | github_jupyter |
This quickstart guide explains how to join two tables A and B using Jaccard similarity measure. First, you need to import the required packages as follows (if you have installed **py_stringsimjoin** it will automatically install the dependencies **py_stringmatching** and **pandas**):
```
# Import libraries
import py_s... | github_jupyter |
Now you want to improve your previous solution by removing the stop words from the corpus. The idea is you only want to add terms that are not in the `stop_words` list to the `bag_of_words` array.
Requirements:
1. Move all your previous codes from `main.ipynb` to the cell below.
1. Improve your solution by ignoring s... | github_jupyter |
```
# Build an autoencoder for dimensionaltiy reduction
#
# Model attributes: use dataset API to avoid feed dict
import tensorflow as tf
from tensorflow.data import Dataset as Ds
import pandas as pd
import numpy as np
from sklearn.utils import shuffle
from sklearn.model_selection import train_test_split
data = pd.re... | github_jupyter |
# First Example using QuantLib
*Copyright (c) 2015 Matthias Groncki*
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice,
this list of conditions... | github_jupyter |
```
%matplotlib inline
```
PyTorch: 새 autograd Function 정의하기
----------------------------------------
$y=\sin(x)$ 을 예측할 수 있도록, $-\pi$ 부터 $\pi$ 까지
유클리드 거리(Euclidean distance)를 최소화하도록 3차 다항식을 학습합니다.
다항식을 $y=a+bx+cx^2+dx^3$ 라고 쓰는 대신 $y=a+b P_3(c+dx)$ 로 다항식을 적겠습니다.
여기서 $P_3(x)=rac{1}{2}\left(5x^3-3x
ight)$ 은 3차
`르장드르 다... | github_jupyter |
### Visualizing Action Classes Learned with RGB Flow Models
This notebook is adapted from the original DeepDraw notebook. In particular, this notebook generates RGB images from action recognition models trained on RGB frames. The output is a image refelecting the knowledge in the model of a specific action class.
---... | github_jupyter |
<a href="https://colab.research.google.com/github/DarekGit/automl/blob/master/efficientdet/faces_test_EfficientDet_D4.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# Test of EfficientDet with Faces datasets
<table align="left"><td>
<a target... | github_jupyter |
This notebook provides code to reproduce the primary figures and tables in the paper
> Ping Liu, Joshua Guberman, Libby Hemphill, and Aron Culotta. "Forecasting the presence and intensity of hostility on Instagram using linguistic and social features." In *Proceedings of the Twelfth International AAAI Conference on We... | github_jupyter |
```
import numpy as np
import pandas as pd
import torch
import torchvision
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms, utils
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from matplotlib import pyplot as plt
%matplotlib inline
from scipy.st... | github_jupyter |
```
%matplotlib inline
import pandas as pd
import numpy as np
import scipy.stats
import matplotlib.pyplot as plt
```
# Bootstrapping (Nonparametric Inference)
- *random sampling with replacement*
- resampling technique to simulate drawing new samples (where repeating experiments is not feasible or possible)
- typical... | github_jupyter |
# [WIP] Creating New Tests
How to implement a new QC test in CoTeDe?
### Objective:
Show how to extend CoTeDe by creating new QC checks.
CoTeDe contains a collection of checks to evaluate the quality of the data. The user can define the parameters for each test such as changing the acceptable threshold of the spike c... | github_jupyter |
```
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import matplotlib.pyplot as plt # this is used for the plot the graph
import seaborn as sns # used for plot interactive graph.
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model imp... | 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 |
<img src="../Pierian-Data-Logo.PNG">
<br>
<strong><center>Copyright 2019. Created by Jose Marcial Portilla.</center></strong>
# Linear Regression with PyTorch
In this section we'll use PyTorch's machine learning model to progressively develop a best-fit line for a given set of data points. Like most linear regression ... | github_jupyter |
# Predicting Housing Prices using Tensorflow + Cloud AI Platform
This notebook will show you how to create a tensorflow model, train it on the cloud in a distributed fashion across multiple CPUs or GPUs and finally deploy the model for online prediction. We will demonstrate this by building a model to predict housing ... | github_jupyter |
## Hyperparameter Tuning in SageMaker
```
!pip install torchvision
import sagemaker
from sagemaker.tuner import (
IntegerParameter,
CategoricalParameter,
ContinuousParameter,
HyperparameterTuner,
)
sagemaker_session = sagemaker.Session()
bucket = sagemaker_session.default_bucket()
prefix = "sagemaker... | github_jupyter |
### 1.1 Loading libraries
```
import scipy.misc
import random
import numpy as np
import scipy
```
### 1.2 Load data
```
xs = []
ys = []
#read data.txt
with open("driving_dataset/data.txt") as f:
for line in f:
xs.append("driving_dataset/" + line.split()[0])
#the paper by Nvidia uses the inverse ... | github_jupyter |
## Big O Notation & Algorithm Analysis
### An algorithm can be thought of a procedure or formula to solve a particular problem. The question is, which algorithm to use to solve a specific problem when there exist multiple solutions to the problem?
### Big O Notation
- a statistical measure, used to describe the compl... | github_jupyter |
```
%matplotlib inline
%reload_ext autoreload
%autoreload 2
```
## Translation files
```
from fastai.text import *
```
French/English parallel texts from http://www.statmt.org/wmt15/translation-task.html . It was created by Chris Callison-Burch, who crawled millions of web pages and then used *a set of simple heuri... | github_jupyter |
# Programming Exercise 4: Neural Networks Learning
## Introduction
In this exercise, you will implement the backpropagation algorithm for neural networks and apply it to the task of hand-written digit recognition. Before starting on the programming exercise, we strongly recommend watching the video lectures and comp... | github_jupyter |
# Predicting Numeric Outcomes with Linear Regression
**Aim**: The aim of this notebook is to predict the amount of a mobile transaction (numeric outcome) given all the other features in the dataset.
## Table of contents
1. Linear Regression in 2-Dimensions
2. Linear Regression to predict transaction amount
3. Model ... | github_jupyter |
## Introduction
Underpinning all of the prediction techniques are models which assume "repeat" or "near-repeat" victimisation: the tendancy for one crime event at a location to give rise to an increased risk of other events at the same, or similar, locations in the future.
Missing from most of these models is an anal... | github_jupyter |
https://scipython.com/blog/visualizing-a-vector-field-with-matplotlib/
```
import numpy as np
import k3d
def E(q, r0, x, y, z):
"""Return the electric field vector E=(Ex,Ey,Ez) due to charge q at r0."""
den = np.hypot(x-r0[0], y-r0[1], z-r0[2])**3
return q * (x - r0[0]) / den, q * (y - r0[1]) / den, q * (z... | github_jupyter |
[Money Creation Examples](http://www.siebenbrunner.com/moneycreation/) > **Example 7**:
# Lending in Central Bank Digital Currency
We present two possible implementations of a Central Bank Digital Currency (CBDC) in which loans are denoted in CBDC. As discussed in the paper, there is an alternative way to implement CBD... | github_jupyter |
<a href="http://cocl.us/pytorch_link_top">
<img src="https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/DL0110EN/notebook_images%20/Pytochtop.png" width="750" alt="IBM Product " />
</a>
<img src="https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/DL0110EN... | github_jupyter |
```
import pandas as pd
import numpy as np
import pyarrow as pa
import pyarrow.parquet as pq
from fastparquet import ParquetFile
import os
# from ctakes_xml import CtakesXmlParser
# from sklearn.feature_extraction.text import TfidfVectorizer
from stringdist import levenshtein_norm as lev_norm
# import matplotlib
# %ma... | github_jupyter |
# Dynamic Programming
Dynamic Programming is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of subproblems, so that we do not have to re-compute them when ne... | github_jupyter |
# Advanced Lists
In this series of lectures we will be diving a little deeper into all the methods available in a list object. These aren't officially "advanced" features, just methods that you wouldn't typically encounter without some additional exploring. It's pretty likely that you've already encountered some of th... | github_jupyter |
# Simulating a random variable
The objective of this notebook is to give a feeling of what a random variable is. We will do this by the mean of simulations.
First we will simulate the experiment of tossing a coin. Then we will simulate the rolling of a die.
We will build *histograms* using the outcome of these two e... | github_jupyter |

<font size=3 color="midnightblue" face="arial">
<h1 align="center">Escuela de Ciencias Básicas, Tecnología e Ingeniería</h1>
</font>
<font size=3 color="navy" face="arial">
<h1 align="center">ECBTI</h1>
</font>
<font size=2 color="darkor... | github_jupyter |
# Variational classification
In this page, we introduce variational algorithms, then describe and implement variational quantum [classifier](gloss:classifier) and discuss variational training.
## Variational algorithms
Variational algorithms were introduced in 2014, with the variational [eigensolver](gloss:eigensolv... | github_jupyter |
# Tutorial for loading Final Testing competition data
To start with this competition, you will need to download the data for the two tasks, sleep cassette and motor imagery (MI). You could either handle them yourself, downloading them from here:
- Sleep final test data :
https://figshare.com/articles/dataset/finalSle... | github_jupyter |
# Creating your own light curves using custom aperture photometry
## Learning Goals
By the end of this tutorial, you will:
* Understand how to use aperture photometry to turn a series of two-dimensional images into a one-dimensional time series.
* Be able to determine the most useful aperture for photometry on a _Ke... | github_jupyter |
# Amostragem
## Carregamento da base de dados
```
import pandas as pd
import random
import numpy as np
dataset = pd.read_csv('census.csv')
dataset.shape
dataset.head()
dataset.tail()
```
## Amostragem aleatória simples
```
df_amostra_aleatoria_simples = dataset.sample(n = 100, random_state = 1)
df_amostra_aleatoria... | github_jupyter |
<!--<badge>--><a href="https://colab.research.google.com/github/huggingface/workshops/blob/main/mlops-world/dynamic-quantization.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a><!--</badge>-->
# Dynamic Quantization with Hugging Face Optimum
In this... | github_jupyter |
# Optimization
Marcos Duarte
> “If there occur some changes in nature, the amount of action necessary for this change must be as small as possible.” Maupertuis (sec XVIII).
## Definition
Optimization is the process of finding the best value from possible alternatives with regards to a certain criteria [Wikipedia]... | github_jupyter |
This file extracts features from the images using the CNN and computes cluster-level aggregations.
<br>
<br>
Written by Jatin Mathur
<br>
5/2020
```
import os
import numpy as np
import pandas as pd
from tqdm.notebook import tqdm
import pickle
import torch
import torch.nn as nn
import torch.optim as optim
import torch... | github_jupyter |
```
!pip install numpy==1.16.1
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
import matplotlib.pyplot as plt
import keras
from keras.models import Model, Sequential
from keras.layers import Dense, GlobalAveragePooling2D, Input, Embedding, Bidi... | github_jupyter |
```
# Import most generic modules
import importlib
import pathlib
import os
import sys
from datetime import datetime
from IPython.display import display, Markdown
import warnings
warnings.filterwarnings("ignore")
module_path = os.path.abspath(os.path.join("../.."))
if module_path not in sys.path:
sys.path.append(... | github_jupyter |
# 参数管理
我们首先关注具有单隐藏层的多层感知机
```
import mindspore
import numpy as np
from mindspore import nn
from mindspore import Tensor
net = nn.SequentialCell([nn.Dense(4, 8), nn.ReLU(), nn.Dense(8, 1)])
X = Tensor(np.random.rand(2, 4), mindspore.float32)
net(X)
```
参数访问
```
print(net[2].parameters_dict())
```
目标参数
```
print(t... | github_jupyter |
# k-Nearest Neighbor (kNN) exercise
*Complete and hand in this completed worksheet (including its outputs and any supporting code outside of the worksheet) with your assignment submission. For more details see the [assignments page](http://vision.stanford.edu/teaching/cs231n/assignments.html) on the course website.*
... | 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 |
```
#@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 agreed to in writing, software
# distributed u... | github_jupyter |
# On this notebook the test and training sets will be defined.
```
# Basic imports
import os
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import datetime as dt
import scipy.optimize as spo
import sys
%matplotlib inline
%pylab inline
pylab.rcParams['figure.figsize'] = (20.0, 10.0)
%load_ext... | github_jupyter |
# Lecture 7
## Training / Test dataset and Normalization
<hr/>
```
import numpy as np
import tensorflow as tf
x_data = [[1, 2, 1], [1, 3, 2], [1, 3, 4], [1, 5, 5], [1, 7, 5], [1, 2, 5], [1, 6, 6], [1, 7, 7]]
y_data = [[0, 0, 1], [0, 0, 1], [0, 0, 1], [0, 1, 0], [0, 1, 0], [0, 1, 0], [1, 0, 0], [1, 0, 0]]
# Evaluati... | github_jupyter |
### Model features
- augmentation (6 image generated)
```
NAME = 'augmentation'
import sys
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import cv2
import random
from tqdm import tqdm
from matplotlib import pyplot as plt
from sklearn.model_selection import t... | github_jupyter |
# Setup
**For full setup read all 'NOTE:' comments and that should be enough**
# NOTE: ctrl+shift+I and paste it to console
function ConnectButton(){
console.log("Connect pushed");
document.querySelector("#top-toolbar > colab-connect-button").shadowRoot.querySelector("#connect").click()
}
setInterval(Connect... | github_jupyter |
```
try:
import openmdao.api as om
import dymos as dm
except ImportError:
!python -m pip install openmdao[notebooks]
!python -m pip install dymos[docs]
import openmdao.api as om
import dymos as dm
```
# Multibranch Trajectory
This example demonstrates the use of a Trajectory to encapsulate a
s... | github_jupyter |
# Bias, Interpretability, and Risk in ML
In part due to its close connection with mathematics, AI systems have a reputation of being more objective and less biased than humans. In this section I want to caution against this view. Many AI systems have been shown to both adopt and amplify existing societal biases.
Bias... | github_jupyter |
## Overview of Windowing Functions
Let us get an overview of Windowing Functions using Spark.
* These are available as part of SQL in most of the traditional databases.
* In some databases they are also known as Analytical Functions.
Let us start spark context for this Notebook so that we can execute the code provi... | github_jupyter |
```
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import nltk
import string
from nltk.corpus import stopwords
from nltk.tokenize import RegexpTokenizer
from nltk.stem import WordNetLemmatizer
from nltk.stem.porter import PorterStemmer
url = 'http://destroyblackmagic.com/q... | github_jupyter |
# Exercise 4: Introduction to Object-Oriented Programming
We used Python so far for relatively simple scripting with the addition of an occasional function. Generally, we have been following what is called a **procedural programming** style: we define functions that combine several steps into a procedure that can be c... | github_jupyter |
# Fingerprints
In this notebook I will be exclusively looking at the QM9 dataset.
### QM9 dataset
QM9 provides quantum chemical properties for a relevant, consistent, and comprehensive chemical space of small organic molecules. This dataset consists of 130,831 molecules with 12 regression targets.
```
import os ... | github_jupyter |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.