code
stringlengths
2.5k
150k
kind
stringclasses
1 value
``` import qiskit import numpy as np, matplotlib.pyplot as plt import sys sys.path.insert(1, '../') import qtm.base, qtm.constant, qtm.nqubit, qtm.onequbit, qtm.fubini_study num_qubits = 3 num_layers = 2 psi = 2*np.random.rand(2**num_qubits)-1 psi = psi / np.linalg.norm(psi) qc_origin = qiskit.QuantumCircuit(num_qubits...
github_jupyter
# Predictive Maintenance using Machine Learning on Sagemaker *Part 3 - Timeseries data preparation* ## Initialization --- Directory structure to run this notebook: ``` nasa-turbofan-rul-lstm | +--- data | | | +--- interim: intermediate data we can manipulate and process | | | \--- raw: *immutable* data downloa...
github_jupyter
# О вероятности попасть под удар фигуры, поставленной случайным образом на шахматную доску На шахматную доску случайным образом поставлены две фигуры. С какой вероятностью первая фигура бьёт вторую? В данном ноутбуке представлен расчёт этой вероятности для каждой шахматной фигуры как функции от размера доски. Рассмотр...
github_jupyter
# Collaborative Filtering on Google Analytics Data ### Learning objectives 1. Prepare the user-item matrix and use it with WALS. 2. Train a `WALSMatrixFactorization` within TensorFlow locally and on AI Platform. 3. Visualize the embedding vectors with principal components analysis. ## Overview This notebook demonstra...
github_jupyter
``` import numpy as np from resonance.nonlinear_systems import SingleDoFNonLinearSystem ``` To apply arbitrary forcing to a single degree of freedom linear or nonlinear system, you can do so with `SingleDoFNonLinearSystem` (`SingleDoFLinearSystem` does not support arbitrary forcing...yet). Add constants, a generalize...
github_jupyter
# Fit $k_{ij}$ and $r_c^{ABij}$ interactions parameter of Ethanol and CPME This notebook has te purpose of showing how to optimize the $k_{ij}$ and $r_c^{ABij}$ for a mixture with induced association. First it's needed to import the necessary modules ``` import numpy as np from sgtpy import component, mixture, saft...
github_jupyter
# BAYES CLASSIFIERS For any classifier $f:{X \to Y}$, it's prediction error is: $P(f(x) \ne Y) = \mathbb{E}[ \mathbb{1}(f(X) \ne Y)] = \mathbb{E}[\mathbb{E}[ \mathbb{1}(f(X) \ne Y)|X]]$ For each $x \in X$, $$\mathbb{E}[ \mathbb{1}(f(X) \ne Y)|X = x] = \sum\limits_{y \in Y} P(Y = y|X = x) \cdot \mathbb{1}(f(x) \ne...
github_jupyter
# Mini Project: Temporal-Difference Methods In this notebook, you will write your own implementations of many Temporal-Difference (TD) methods. While we have provided some starter code, you are welcome to erase these hints and write your code from scratch. ### Part 0: Explore CliffWalkingEnv Use the code cell below...
github_jupyter
<a href="https://colab.research.google.com/github/elizabethts/DS-Unit-1-Sprint-1-Dealing-With-Data/blob/master/LS_DS_114_Making_Data_backed_Assertions.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # Lambda School Data Science - Making Data-backed ...
github_jupyter
``` import numpy as np import pandas_datareader as pdr import datetime as dt import pandas as pd import matplotlib.pyplot as plt start = dt.datetime(2012, 6, 1) end = dt.datetime(2022, 3, 9) stock = ['fb'] stock_data = pdr.get_data_yahoo(stock, start, end) pair = ['snap'] pair_data = pdr.get_data_yahoo(pair, start, e...
github_jupyter
# Convolutional Neural Networks --- In this notebook, we train a **CNN** to classify images from the CIFAR-10 database. The images in this database are small color images that fall into one of ten classes; some example images are pictured below. <img src='notebook_ims/cifar_data.png' width=70% height=70% /> ### Test...
github_jupyter
``` #hide #skip ! [ -e /content ] && pip install -Uqq fastai # upgrade fastai on colab #default_exp data.core #export from fastai.torch_basics import * from fastai.data.load import * #hide from nbdev.showdoc import * ``` # Data core > Core functionality for gathering data The classes here provide functionality for ...
github_jupyter
<img src="images/logo.jpg" style="display: block; margin-left: auto; margin-right: auto;" alt="לוגו של מיזם לימוד הפייתון. נחש מצויר בצבעי צהוב וכחול, הנע בין האותיות של שם הקורס: לומדים פייתון. הסלוגן המופיע מעל לשם הקורס הוא מיזם חינמי ללימוד תכנות בעברית."> # <span style="text-align: right; direction: rtl; float: r...
github_jupyter
``` import os import json import pickle import random from collections import defaultdict, Counter from indra.literature.adeft_tools import universal_extract_text from indra.databases.hgnc_client import get_hgnc_name, get_hgnc_id from adeft.discover import AdeftMiner from adeft.gui import ground_with_gui from adeft.m...
github_jupyter
# Identificar Perfil de Consumo de Clientes de uma Instituição Financeira ## Uma breve introdução Uma Instituição Financeira X tem o interesse em identificar o perfil de gastos dos seus clientes. Identificando os clientes certos, eles podem melhorar a comunicação dos ativos promocionais, utilizar com mais eficiência ...
github_jupyter
##### Copyright 2019 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
## Fundamentals, introduction to machine learning The purpose of these guides is to go a bit deeper into the details behind common machine learning methods, assuming little math background, and teach you how to use popular machine learning Python packages. In particular, we'll focus on the Numpy and PyTorch libraries...
github_jupyter
# Check Environment This notebook checks that you have correctly created the environment and that all packages needed are installed. ## Environment The next command should return a line like (Mac/Linux): /<YOUR-HOME-FOLDER>/anaconda/envs/ztdl/bin/python or like (Windows 10): C:\\<YOUR-HOME-FOLDER>\\Anacond...
github_jupyter
## Preprocessing ``` # Import our dependencies from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler import pandas as pd import tensorflow as tf # Import and read the charity_data.csv. import pandas as pd application_df = pd.read_csv("charity_data.csv") application_df...
github_jupyter
# The Graph Data Access In this notebook, we read in the data that was generated and saved as a csv from the [TheGraphDataSetCreation](TheGraphDataSetCreation.ipynb) notebook. Goals of this notebook are to obtain: * Signals, states, event and sequences * Volatility metrics * ID perceived shocks (correlated with an...
github_jupyter
``` import pandas as pd import numpy as np import pickle BASEDIR_MIMIC = '/Volumes/MyData/MIMIC_data/mimiciii/1.4' def get_note_events(): n_rows = 100000 icd9_code = pd.read_csv(f"{BASEDIR_MIMIC}/DIAGNOSES_ICD.csv", index_col = None) # create the iterator noteevents_iterator = pd.read_csv( f"{...
github_jupyter
# Recurrent Neural Networks ``` import pandas as pd import numpy as np %matplotlib inline import matplotlib.pyplot as plt ``` ## Time series forecasting ``` df = pd.read_csv('../data/cansim-0800020-eng-6674700030567901031.csv', skiprows=6, skipfooter=9, engine='python') df.head() fr...
github_jupyter
# Handwritten Digits Classifier with Improved Accuracy using Data Augmentation In previous steps, we trained a model that could recognize handwritten digits using the MNIST dataset. We were able to achieve above 98% accuracy on our validation dataset. However, when you deploy the model in an Android app and test it, y...
github_jupyter
<a href="https://colab.research.google.com/github/ilexistools/ebralc2021/blob/main/nltk_treinar_etiquetador.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ``` ``` # Treinar um etiquetador morfossintático Para realizar a etiquetagem morfossintátic...
github_jupyter
# An example of an optimal pruning based routing algorithm - based on a simple graph and Dijkstra's algorithm with concave cost function - Create a simple graph with multiple edge's attributes¶ - weight = w_ij - concave = c_ij where i,j is nodes ``` import networkx as nx import matplotlib.pyplot as plt ``` ##...
github_jupyter
# Machine Learning Engineer Nanodegree ## Introduction and Foundations ## Project: Titanic Survival Exploration In 1912, the ship RMS Titanic struck an iceberg on its maiden voyage and sank, resulting in the deaths of most of its passengers and crew. In this introductory project, we will explore a subset of the RMS Ti...
github_jupyter
# Make Corner Plots of Posterior Distributions This file allows me to quickly and repeatedly make the cornor plot to examin the results of the MCMC analsys ``` import numpy as np import matplotlib.pyplot as plt import matplotlib import pandas as pd from astropy.table import Table import corner # import seaborn matplo...
github_jupyter
``` import pandas as pd import sqlite3 conn = sqlite3.connect('database.sqlite') query = "SELECT * FROM sqlite_master" df_schema = pd.read_sql_query(query, conn) df_schema.tbl_name.unique() df_schema.head(20) cur = conn.cursor() cur.execute('''SELECT * from pragma_table_info("Player_Attributes")''' ) rows = cur.fet...
github_jupyter
# Importing the libraries ``` %pip install tensorflow import pandas as pd import matplotlib.pyplot as plt import numpy as np import tensorflow as tf import seaborn as sns ``` # Importing The Dataset ``` dataset = pd.read_csv("../input/framingham-heart-study-dataset/framingham.csv") ``` # Analysing The Data ``` dat...
github_jupyter
# Reinforcement Learning page 441<br> For details, see - https://github.com/ageron/handson-ml/blob/master/16_reinforcement_learning.ipynb, - https://gym.openai.com, - http://www0.cs.ucl.ac.uk/staff/d.silver/web/Teaching.html, - https://www.jstor.org/stable/24900506?seq=1#metadata_info_tab_contents, - http://book.python...
github_jupyter
# Dynamic Recurrent Neural Network. TensorFlow implementation of a Recurrent Neural Network (LSTM) that performs dynamic computation over sequences with variable length. This example is using a toy dataset to classify linear sequences. The generated sequences have variable length. ## RNN Overview <img src="http://co...
github_jupyter
``` import sys, os sys.path.append(os.path.abspath('../..')) from tqdm.notebook import tqdm import math import gym import torch import torch.optim as optim from torch.utils.tensorboard import SummaryWriter from collections import deque from networks.dqn_atari import MC_DQN from utils.memory import RankedReplayMemory,...
github_jupyter
# **Exploratory Analysis** First of all, let's import some useful libraries that will be used in the analysis. ``` import numpy as np import pandas as pd import matplotlib.pyplot as plt ``` Now, the dataset stored in drive needs to be retieved. I am using google colab for this exploration with TPU hardware accelerat...
github_jupyter
# Laboratorio 7 ``` import numpy as np import pandas as pd import matplotlib.pyplot as plt import altair as alt from sklearn import datasets, linear_model from sklearn.metrics import mean_squared_error, r2_score alt.themes.enable('opaque') %matplotlib inline ``` En este laboratorio utilizaremos los mismos datos de ...
github_jupyter
``` import radical.analytics as ra import radical.pilot as rp import radical.utils as ru import radical.entk as re import os from glob import glob import numpy as np from matplotlib import pyplot as plt from matplotlib import cm import csv import pandas as pd import json import matplotlib as mpl mpl.rcParams['text.uset...
github_jupyter
# Running, Debugging, Testing & Packaging ``` !code ./1-helloconnectedworld ``` Let's look at the key parts of our app: **package.json** This defines all contributions: commands, context menus, UI, everything! ```json "activationEvents": [ // Use "*" to start on application start. If contributing comm...
github_jupyter
# Convolutional Autoencoder Sticking with the MNIST dataset, let's improve our autoencoder's performance using convolutional layers. Again, loading modules and the data. ``` %matplotlib inline import numpy as np import tensorflow as tf import matplotlib.pyplot as plt from tensorflow.examples.tutorials.mnist import i...
github_jupyter
Practice geospatial aggregations in geopandas before writing them to .py files ``` %load_ext autoreload %autoreload 2 import sys sys.path.append('../utils') import wd_management wd_management.set_wd_root() import geopandas as gp import pandas as pd import requests res = requests.get('https://services5.arcgis.com/GfwWN...
github_jupyter
<a href="https://colab.research.google.com/github/prateekjoshi565/Fine-Tuning-BERT/blob/master/Fine_Tuning_BERT_for_Spam_Classification.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # Install Transformers Library ``` !pip install transformers imp...
github_jupyter
# WeatherPy ---- #### 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 time import rando...
github_jupyter
<a href="https://colab.research.google.com/github/jorge23amury/daa_2021_1/blob/master/4_diciembre1358.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ``` """ Array2D """ class Array2D: def __init__(self,rows, cols, value): self.__cols ...
github_jupyter
# Run hacked AlphaFold2 on the designed bound states ### Imports ``` %load_ext lab_black # Python standard library from glob import glob import os import socket import sys # 3rd party library imports import dask import matplotlib.pyplot as plt import pandas as pd import pyrosetta import numpy as np import scipy impo...
github_jupyter
<a href="https://colab.research.google.com/github/parshwa1999/Map-Segmentation/blob/master/ResNet_RoadTest.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # Segmentation of Road from Satellite imagery ## Importing Libraries ``` import warnings war...
github_jupyter
``` import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.data import DataLoader from torchvision import datasets, transforms from torchvision.utils import make_grid import numpy as np import pandas as pd from sklearn.metrics import confusion_matrix import matplotlib.pyplot as plt %matplo...
github_jupyter
## Homework 4 Today we'll start by reproducing the DQN and then try improving it with the tricks we learned on the lecture: * Target networks * Double q-learning * Prioritized experience replay * Dueling DQN * Bootstrap DQN ``` import matplotlib.pyplot as plt import numpy as np %matplotlib inline # If you are runni...
github_jupyter
``` # installing keras !pip install keras # installing opencv !pip install opencv-python # installing opencv full package !pip install opencv-contrib-python import cv2 from keras.models import load_model import numpy as np face_detect = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') def face_dete...
github_jupyter
``` # (c) amantay from https://github.com/AmantayAbdurakhmanov/misc/blob/master/Geabox-Yearn.ipynb import json import os from dotenv import load_dotenv from web3 import Web3 from multicall import Call, Multicall load_dotenv() # add this line RPC_Endpoint = os.getenv('RPC_NODE') GearboxAddressProvider = Web3.toChecks...
github_jupyter
``` #!/usr/bin/env python import matplotlib.pyplot as plt import matplotlib.colors as colors import matplotlib.tri as tri from mpl_toolkits.axes_grid1.anchored_artists import AnchoredSizeBar from matplotlib import ticker, cm import numpy as np from numpy import ma import csv degree_sign= u'\N{DEGREE SIGN}' CSV_FILE_PA...
github_jupyter
__mlmachine - GroupbyImputer, KFoldEncoder, and Skew Correction__ <br><br> Welcome to Example Notebook 2. If you're new to mlmachine, check out [Example Notebook 1](https://github.com/petersontylerd/mlmachine/blob/master/notebooks/mlmachine_part_1.ipynb). <br><br> Check out the [GitHub repository](https://github.com/pe...
github_jupyter
``` # default_exp analysis ``` # Tools to analyze the results of Gate simulations ``` #hide from nbdev.showdoc import * ``` ## Dependencies ``` #export import pandas as pd import uproot as rt import awkward as ak from scipy.stats import moyal import matplotlib.pyplot as plt import numpy as np import math from scip...
github_jupyter
# 序列到序列学习(seq2seq) 在`seq2seq`中, 特定的“&lt;eos&gt;”表示序列结束词元。 一旦输出序列生成此词元,模型就会停止预测。 在循环神经网络解码器的初始化时间步,有两个特定的设计决定: 首先,特定的“&lt;bos&gt;”表示序列开始词元,它是解码器的输入序列的第一个词元。 其次,使用循环神经网络编码器最终的隐状态来初始化解码器的隐状态。 这种设计将输入序列的编码信息送入到解码器中来生成输出序列的。 在其他一些设计中 :cite:`Cho.Van-Merrienboer.Gulcehre.ea.2014`, 编码器最终的隐状态在每一个时间步都作为解码器的输入序列的一部分。 类似于 :`lang...
github_jupyter
# Now You Code 2: Character Frequency Write a program to input some text (a word or a sentence). The program should create a histogram of each character in the text and it's frequency. For example the text `apple` has a frequency `a:1, p:2, l:1, e:1` Some advice: - build a dictionary of each character where the char...
github_jupyter
## Deep face recognition with Keras, Dlib and OpenCV Face recognition identifies persons on face images or video frames. In a nutshell, a face recognition system extracts features from an input face image and compares them to the features of labeled faces in a database. Comparison is based on a feature similarity metr...
github_jupyter
``` dtypes = { 'MachineIdentifier': 'category', 'ProductName': 'category', 'EngineVersion': 'category', 'AppVersion': 'category', ...
github_jupyter
``` import pytorch_lightning as pl import torch.nn as nn import torch.nn.functional as F from torch import optim from torch.utils.data import DataLoader, random_split from torch.utils.data.distributed import DistributedSampler import numpy as np import pandas as pd import torch as torch from pathlib import Path impor...
github_jupyter
``` import numpy as np import nibabel as nb import matplotlib.pyplot as plt # helper function to plot 3D NIfTI def plot_slice (fname): # Load image img = nb.load (fname) data = img.get_data () # cut in the middle of brain cut = int (data.shape[-1]/2) + 10 # plot data plt.imsh...
github_jupyter
# Mapping water extent and rainfall using WOfS and CHIRPS * **Products used:** [wofs_ls](https://explorer.digitalearth.africa/products/wofs_ls), [rainfall_chirps_monthly](https://explorer.digitalearth.africa/products/rainfall_chirps_monthly) ## Background The United Nations have prescribed 17 "Sustainable Developme...
github_jupyter
# Overview 1. Project Instructions & Prerequisites 2. Learning Objectives 3. Data Preparation 4. Create Categorical Features with TF Feature Columns 5. Create Continuous/Numerical Features with TF Feature Columns 6. Build Deep Learning Regression Model with Sequential API and TF Probability Layers 7. Evaluating Potent...
github_jupyter
<font size ='3'>*First, let's read in the data and necessary libraries*<font/> ``` import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from mypy import print_side_by_side from mypy import display_side_by_side #https://stackoverflow.com/a/44923103/8067752 %matplotlib inline pd....
github_jupyter
# Appendix Hao Lu 04/04/2020 In this notebook, we simulated EEG data with the method described in the paper by Bharadwaj and Shinn-Cunningham (2014) and analyzed the data with the toolbox proposed in the same paper. The function was modifed so the values of thee variables within the function can be extracted and stu...
github_jupyter
# Statistics ## Introduction In this chapter, you'll learn about how to do statistics with code. We already saw some statistics in the chapter on probability and random processes: here we'll focus on computing basic statistics and using statistical tests. We'll make use of the excellent [*pingouin*](https://pingouin-...
github_jupyter
``` import tensorflow as tf import numpy as np import matplotlib.pyplot as plt from matplotlib.pyplot import savefig import cv2 np.set_printoptions(threshold=np.inf) num_images = 3670 dataset = [] for i in range(1, num_images+1): img = cv2.imread("color_images/color_" +str(i) +".jpg" ) dataset.append(np.array...
github_jupyter
# CarND Object Detection Lab Let's get started! ``` import tensorflow as tf import numpy as np import matplotlib.pyplot as plt from PIL import Image from PIL import ImageDraw from PIL import ImageColor import time from scipy.stats import norm %matplotlib inline plt.style.use('ggplot') ``` ## MobileNets [*MobileNet...
github_jupyter
``` import sys import json sys.path.insert(0, "../") print(sys.path) import pymongo #31470/5/1 import sys import json import cobrakbase import cobrakbase.core.model import cobra import logging #from cobra.core import Gene, Metabolite, Model, Reaction #from pyeda import * #from pyeda.inter import * #from pyeda.boolalg i...
github_jupyter
``` import matplotlib.pyplot as plt import pandas as pd import numpy as np from sklearn.linear_model import LogisticRegression from sklearn import metrics from sklearn.metrics import classification_report, confusion_matrix, f1_score from sklearn.metrics import make_scorer, f1_score, accuracy_score, recall_score, precis...
github_jupyter
``` # importing import tensorflow as tf import matplotlib.pyplot as plt import os # loading images path_dir = "/content/drive/MyDrive/Dataset/malariya_cell_data_set/cell_images/" loaded = 0 path = path_dir+"Uninfected/" uninfected_list = os.listdir(path) path = path_dir + "Parasitized" infected_list = os.listdir(path...
github_jupyter
# Using Neural Network Formulations in OMLT In this notebook we show how OMLT can be used to build different optimization formulations of neural networks within Pyomo. It specifically demonstrates the following examples:<br> 1.) A neural network with smooth sigmoid activation functions represented using full-space and...
github_jupyter
# transmissibility-based TPA: FRF based In this example a numerical example is used to demonstrate a FRF based TPA example. ``` import pyFBS import numpy as np import pandas as pd import matplotlib.pyplot as plt from matplotlib import cm from matplotlib.colors import LogNorm %matplotlib inline ``` ## Example datase...
github_jupyter
``` import warnings warnings.simplefilter(action='ignore', category=FutureWarning) import pandas as pd import numpy as np import sklearn.metrics pd.reset_option('all') # 84575189_0_6365692015941409487 -> no matches at all data = pd.read_csv('/Users/summ7t/dev/novartis/table-linker/SemTab2019/embedding_evaluation_file...
github_jupyter
# Homework 5: Problems ## Due Wednesday 28 October, before class ### PHYS 440/540, Fall 2020 https://github.com/gtrichards/PHYS_440_540/ ## Problems 1&2 Complete Chapters 1 and 2 in the *unsupervised learning* course in Data Camp. The last video (and the two following code examples) in Chapter 2 are off topic, but...
github_jupyter
### Dataset Source: About this file Boston House Price dataset ### columns: * CRIM per capita crime rate by town * ZN proportion of residential land zoned for lots over 25,000 sq.ft. * INDUS proportion of non-retail business acres per town * CHAS Charles River dummy variable (= 1 if tract bounds rive...
github_jupyter
# 第5章 計算機を作る ## 5.1.2 スタックマシン ``` def calc(expression: str): # 空白で分割して字句にする tokens = expression.split() stack = [] for token in tokens: if token.isdigit(): # 数値はスタックに push する stack.append(int(token)) continue # 数値でないなら,演算子として処理する x = sta...
github_jupyter
# Week 3 - Ungraded Lab: Data Labeling Welcome to the ungraded lab for week 3 of Machine Learning Engineering for Production. In this lab, you will see how the data labeling process affects the performance of a classification model. Labeling data is usually a very labor intensive and costly task but it is of great im...
github_jupyter
# A Whirlwind Tour of Python *Jake VanderPlas, Summer 2016* These are the Jupyter Notebooks behind my O'Reilly report, [*A Whirlwind Tour of Python*](http://www.oreilly.com/programming/free/a-whirlwind-tour-of-python.csp). The full notebook listing is available [on Github](https://github.com/jakevdp/WhirlwindTourOfPy...
github_jupyter
``` epochs = 5 ``` # Example - Simple Vertically Partitioned Split Neural Network - <b>Alice</b> - Has model Segment 1 - Has the handwritten Images - <b>Bob</b> - Has model Segment 2 - Has the image Labels Based on [SplitNN - Tutorial 3](https://github.com/OpenMined/PySyft/blob/master/examples/tu...
github_jupyter
## 1-3. 複数量子ビットの記述 ここまでは1量子ビットの状態とその操作(演算)の記述について学んできた。この章の締めくくりとして、$n$個の量子ビットがある場合の状態の記述について学んでいこう。テンソル積がたくさん出てきてややこしいが、コードをいじりながら身につけていってほしい。 $n$個の**古典**ビットの状態は$n$個の$0,1$の数字によって表現され、そのパターンの総数は$2^n$個ある。 量子力学では、これらすべてのパターンの重ね合わせ状態が許されているので、$n$個の**量子**ビットの状態$|\psi \rangle$はどのビット列がどのような重みで重ね合わせになっているかという$2^n$個の複素確率振幅で記...
github_jupyter
# Evaluation of a Pipeline and its Components [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/deepset-ai/haystack/blob/master/tutorials/Tutorial5_Evaluation.ipynb) To be able to make a statement about the quality of results a question-answering pip...
github_jupyter
``` %matplotlib inline from __future__ import print_function, unicode_literals import sys, os import seaborn as sns import numpy as np import matplotlib from matplotlib import pyplot as plt from pygaarst import raster sys.path.append('../firedetection/') import landsat8fire as lfire sns.set(rc={'image.cmap': 'gist_heat...
github_jupyter
# Finding fraud patterns with FP-growth # Data Collection and Investigation ``` import pandas as pd # Input data files are available in the "../input/" directory df = pd.read_csv('D:/Python Project/Credit Card Fraud Detection/benchmark dataset/Test FP-Growth.csv') # printing the first 5 columns for data visualizati...
github_jupyter
``` import pandas as pd import sqlite3 import datetime def main(): data_list = [("ml-latest-small/", "small_output/", "small"), ("ml-20m/", "20M_output/","20M")] for item in data_list: start_time = datetime.datetime.now() process_data(item[0], item[1]) end_tim...
github_jupyter
``` %cd .. %ls import pandas as pd import datetime import numpy as np # xls to csv xls = pd.read_excel(u'107年 竹苗空品區/107年新竹站_20190315.xls', index_col=0) xls.to_csv('107年 竹苗空品區/107年新竹站_20190315.csv', encoding='big5') train = pd.read_csv('107年 竹苗空品區/107年新竹站_20190315.csv', encoding='big5', index_col = False) train.iloc[26]...
github_jupyter
``` ### MODULE 1 ### Basic Modeling in scikit-learn ``` ``` ### Seen vs. unseen data # The model is fit using X_train and y_train model.fit(X_train, y_train) # Create vectors of predictions train_predictions = model.predict(X_train) test_predictions = model.predict(X_test) # Train/Test Errors train_error = mae(y_tr...
github_jupyter
# Goals ### Learn how to change train validation splits # Table of Contents ## [0. Install](#0) ## [1. Load experiment with defaut transforms](#1) ## [2. Reset Transforms andapply new transforms](#2) <a id='0'></a> # Install Monk - git clone https://github.com/Tessellate-Imaging/monk_v1.git - cd monk_v...
github_jupyter
``` import pandas as pd import numpy as np import numpy.random as nr import matplotlib.pyplot as plt import matplotlib.pyplot as plt import sklearn from sklearn.ensemble import RandomForestClassifier import catboost as cat from catboost import CatBoostClassifier from sklearn import preprocessing import sklearn.model_se...
github_jupyter
# Dataproc - Submit Hadoop Job ## Intended Use A Kubeflow Pipeline component to submit a Apache Hadoop MapReduce job on Apache Hadoop YARN in Google Cloud Dataproc service. ## Run-Time Parameters: Name | Description :--- | :---------- project_id | Required. The ID of the Google Cloud Platform project that the cluste...
github_jupyter
# Random Variables :label:`sec_random_variables` In :numref:`sec_prob` we saw the basics of how to work with discrete random variables, which in our case refer to those random variables which take either a finite set of possible values, or the integers. In this section, we develop the theory of *continuous random var...
github_jupyter
# Capstone Project - Madiun Cafe Location ## Introduction / business problem i am looking to open a cafe in Madiun City, **the question is**, where is the best location for open new cafe? **The background of the problem** it is not worth setting up a cafe in the close promixity of existing ones. because the location ...
github_jupyter
<div> <img src="https://drive.google.com/uc?export=view&id=1vK33e_EqaHgBHcbRV_m38hx6IkG0blK_" width="350"/> </div> #**Artificial Intelligence - MSc** This notebook is designed specially for the module ET5003 - MACHINE LEARNING APPLICATIONS Instructor: Enrique Naredo ###ET5003_BayesianNN © All rights reserved to t...
github_jupyter
# 函数 - 函数可以用来定义可重复代码,组织和简化 - 一般来说一个函数在实际开发中为一个小功能 - 一个类为一个大功能 - 同样函数的长度不要超过一屏 Python中的所有函数实际上都是有返回值(return None), 如果你没有设置return,那么Python将不显示None. 如果你设置return,那么将返回出return这个值. ``` def HJN(): print('Hello') return 1000 b=HJN() print(b) HJN def panduan(number): if number % 2 == 0: print('O') e...
github_jupyter
``` import tensorflow as tf import os import pickle import numpy as np CIFAR_DIR = "./../../cifar-10-batches-py" print(os.listdir(CIFAR_DIR)) def load_data(filename): """read data from data file.""" with open(filename, 'rb') as f: data = pickle.load(f, encoding='bytes') return data[b'data'], da...
github_jupyter
``` import pandas as pd import numpy as np X_raw = pd.read_csv("/Users/joejohns/data_bootcamp/GitHub/final_project_nhl_prediction/Data/Shaped_Data/data_bet_stats_mp.csv") ##note it is against, for .. then sometimes *by itself* stat% = for/(for+against); stat%_against would be 1-stat% ##basic features to add: ##pp % ##...
github_jupyter
# Linear Regression We will implement a linear regression model by using the Keras library. ``` %matplotlib inline import matplotlib.pyplot as plt import pandas as pd import numpy as np ``` ## Data set: Weight and height Active Drive and read the csv file with the weight and height data ``` df = pd.read_csv('/cont...
github_jupyter
``` print(__doc__) from time import time import numpy as np import matplotlib.pyplot as plt %matplotlib inline from sklearn import metrics from sklearn.cluster import KMeans from sklearn.datasets import load_digits from sklearn.decomposition import PCA from sklearn.preprocessing import scale np.random.seed(42) digit...
github_jupyter
# Training vs validation loss [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/parrt/fundamentals-of-deep-learning/blob/main/notebooks/3.train-test-diabetes.ipynb) By [Terence Parr](https://explained.ai). This notebook explores how to use a validat...
github_jupyter
# Simple Attack In this notebook, we will examine perhaps the simplest possible attack on an individual's private data and what the OpenDP library can do to mitigate it. ## Loading the data The vetting process is currently underway for the code in the OpenDP Library. Any constructors that have not been vetted may st...
github_jupyter
``` import tensorflow as tf import h5py import shutil import numpy as np from torch.utils.data import DataLoader import keras from tqdm.notebook import tqdm from keras.models import Sequential from keras.layers import Dense, Flatten, Conv3D, Dropout, MaxPooling3D,MaxPooling2D from keras.utils import to_categorical from...
github_jupyter
© 2018 Suzy Beeler and Vahe Galstyan. This work is licensed under a [Creative Commons Attribution License CC-BY 4.0](https://creativecommons.org/licenses/by/4.0/). All code contained herein is licensed under an [MIT license](https://opensource.org/licenses/MIT) This exercise was generated from a Jupyter notebook. You...
github_jupyter
# 1. Python and notebook basics In this first chapter, we will cover the very essentials of Python and notebooks such as creating a variable, importing packages, using functions, seeing how variables behave in the notebook etc. We will see more details on some of these topics, but this very short introduction will the...
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
# Classifying Fashion-MNIST Now it's your turn to build and train a neural network. You'll be using the [Fashion-MNIST dataset](https://github.com/zalandoresearch/fashion-mnist), a drop-in replacement for the MNIST dataset. MNIST is actually quite trivial with neural networks where you can easily achieve better than 9...
github_jupyter