code
stringlengths
2.5k
150k
kind
stringclasses
1 value
# Taylor problem 3.23 last revised: 04-Jan-2020 by Dick Furnstahl [furnstahl.1@osu.edu] **This notebook is almost ready to go, except that the initial conditions and $\Delta v$ are different from the problem statement and there is no statement to print the figure. Fix these and you're done!** This is a conservatio...
github_jupyter
``` import pandas as pd import numpy as np ``` # Distances ``` activator = "sgmd" mnist_sgmd = [] hands_sgmd = [] fashn_sgmd = [] for i in range(0, 10): dataset = 'mnist' df_cnn_relu0_1 = pd.read_csv(dataset + "/results/" + activator + "/cnn_K" + str(i) + ".csv") dataset = 'handsign_mnist' df_cnn_re...
github_jupyter
``` import os from pprint import pprint import torch import torch.nn as nn from transformers import BertForTokenClassification, BertTokenizer from transformers import AdamW from torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler from sklearn.model_selection import train_test_split impo...
github_jupyter
<a id='StartingPoint'></a> # ONNX classification example Sharing DL models between frameworks or programming languages is possible with Open Neural Network Exchange (ONNX for short). This notebook starts from an onnx model exported from MATLAB and uses it in Python. On MATLAB a GoogleNet model pre-trained on ImageNet...
github_jupyter
# Flux.pl The `Flux.pl` Perl script takes four input parameters: `Flux.pl [input file] [output file] [bin width (s)] [geometry base directory]` or, as invoked from the command line, `$ perl ./perl/Flux.pl [input file] [output file] [bin width (s)] [geometry directory]` ## Input Parameters * `[input file]` `Flux....
github_jupyter
# Character-level recurrent sequence-to-sequence model **Author:** [fchollet](https://twitter.com/fchollet)<br> **Date created:** 2017/09/29<br> **Last modified:** 2020/04/26<br> **Description:** Character-level recurrent sequence-to-sequence model. ## Introduction This example demonstrates how to implement a basic ...
github_jupyter
``` import numpy as np import tensorflow as tf import os import random from collections import defaultdict import pandas as pd import time def load_data_train(): user_movie = defaultdict(set) data=pd.read_csv('BRP_datas\\BRP_common_user_book\\common_user_book_19_1VS2.csv') num_user=len(pd.unique(data['user...
github_jupyter
**Note**: There are multiple ways to solve these problems in SQL. Your solution may be quite different from mine and still be correct. **1**. Connect to the SQLite3 database at `data/faculty.db` in the `notebooks` folder using the `sqlite` package or `ipython-sql` magic functions. Inspect the `sql` creation statement ...
github_jupyter
# Frequent opiate prescriber ``` import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns import preprocessors as pp sns.set(style="darkgrid") data = pd.read_csv('../data/prescriber-info.csv') data.head() ``` ## Variable Separation ``` uniq_cols = ['NPI'] cat_cols = list(data....
github_jupyter
# Priprava okolja ``` !pip install transformers !pip install sentencepiece import csv import torch from torch import nn from transformers import AutoTokenizer, AutoModel import pandas as pd from google.colab import drive import transformers import json from tqdm import tqdm from torch.utils.data import Dataset, DataL...
github_jupyter
``` import os import numpy as np import pandas as pd import gc ``` # To ensemble I used submissions from 8 public notebooks: * LB: 0.0225 - https://www.kaggle.com/lunapandachan/h-m-trending-products-weekly-add-test/notebook * LB: 0.0217 - https://www.kaggle.com/tarique7/hnm-exponential-decay-with-alternate-items/noteb...
github_jupyter
# The Shared Library with GCC When your program is linked against a shared library, only a small table is created in the executable. Before the executable starts running, **the operating system loads the machine code needed for the external functions** - a process known as **dynamic linking.** * Dynamic linkin...
github_jupyter
# Searching the UniProt database and saving fastas: This notebook is really just to demonstrate how Andrew finds the sequences for the datasets. <br> If you do call it from within our github repository, you'll probably want to add the fastas to the `.gitignore` file. ``` # Import bioservices module, to run remote U...
github_jupyter
# Validation report for dmu26_XID+PACS_COSMOS_20170303 The data product dmu26_XID+PACS_COSMOS_20170303, contains three files: 1. dmu26_XID+PACS_COSMOS_20170303.fits: The catalogue file 2. dmu26_XID+PACS_COSMOS_20170303_Bayes_pval_PACS100.fits: The Bayesian pvalue map 3. dmu26_XID+PACS_COSMOS_20170303_Bayes_pval_PACS1...
github_jupyter
# RNA World Hypothesis RNA is a simpler cousin of DNA. As you may know, RNA is widely thought to be the first self replicating life-form to arise perhaps around 4 billion years ago. One of the strongest arguments for this theory is that RNA is able to carry information in its nucleotides like DNA, and like protein, i...
github_jupyter
# Introduction In this post,we will talk about some of the most important papers that have been published over the last 5 years and discuss why they’re so important.We will go through different CNN Architectures (LeNet to DenseNet) showcasing the advancements in general network architecture that made these architectu...
github_jupyter
## Probalistic Confirmed COVID19 Cases- Denmark **Jorge: remember to reexecute the cell with the photo.** ### Table of contents [Initialization](#Initialization) [Data Importing and Processing](#Data-Importing-and-Processing) 1. [Kalman Filter Modeling: Case of Denmark Data](#1.-Kalman-Filter-Modeling:-Case-of-Denm...
github_jupyter
<a href="https://colab.research.google.com/github/Janani-harshu/Machine_Learning_Projects/blob/main/Covid19_death_prediction.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> Covid-19 is one of the deadliest viruses you’ve ever heard. Mutations in cov...
github_jupyter
## Dependencies ``` import json, warnings, shutil, glob from jigsaw_utility_scripts import * from scripts_step_lr_schedulers import * from transformers import TFXLMRobertaModel, XLMRobertaConfig from tensorflow.keras.models import Model from tensorflow.keras import optimizers, metrics, losses, layers SEED = 0 seed_ev...
github_jupyter
``` import pandas as pd import numpy as np import matplotlib as plt from shapely.geometry import Point, Polygon from sklearn.linear_model import LogisticRegression from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import KFold import zipfile import requests import os import shutil ...
github_jupyter
# Important installation This notebook requires unusual packages: `LightGBM`, `SHAP` and `LIME`. For installation, do: `conda install lightgbm lime shap` ## Initial classical imports ``` import os import numpy as np import pandas as pd import warnings warnings.simplefilter(action='ignore', category=Warning) import ...
github_jupyter
# Advanced RNNs <img src="https://raw.githubusercontent.com/GokuMohandas/practicalAI/master/images/logo.png" width=150> In this notebook we're going to cover some advanced topics related to RNNs. 1. Conditioned hidden state 2. Char-level embeddings 3. Encoder and decoder 4. Attentional mechanisms 5. Implementation ...
github_jupyter
### Supervised Machine Learning Models for Cross Species comparison of supporting cells ``` import numpy as np import pandas as pd import scanpy as sc import matplotlib.pyplot as plt import os import sys import anndata def MovePlots(plotpattern, subplotdir): os.system('mkdir -p '+str(sc.settings.figdir)+'/'+subp...
github_jupyter
# Nodejs MNIST model Deployment * Wrap a nodejs tensorflow model for use as a prediction microservice in seldon-core * Run locally on Docker to test ## Dependencies * ```pip install seldon-core``` * [Helm](https://github.com/kubernetes/helm) * [Minikube](https://github.com/kubernetes/minikube) * [S2I](https...
github_jupyter
<a href="https://colab.research.google.com/github/NeuromatchAcademy/course-content/blob/master/tutorials/W1D5_DimensionalityReduction/student/W1D5_Tutorial3.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # Neuromatch Academy: Week 1, Day 5, Tutoria...
github_jupyter
# Projection, Joining, and Sorting ## Setup ``` import ibis import os hdfs_port = os.environ.get('IBIS_WEBHDFS_PORT', 50070) hdfs = ibis.hdfs_connect(host='quickstart.cloudera', port=hdfs_port) con = ibis.impala.connect(host='quickstart.cloudera', database='ibis_testing', hdfs_client=hdfs) p...
github_jupyter
# Predicting Boston Housing Prices ## Using XGBoost in SageMaker (Hyperparameter Tuning) _Deep Learning Nanodegree Program | Deployment_ --- As an introduction to using SageMaker's High Level Python API for hyperparameter tuning, we will look again at the [Boston Housing Dataset](https://www.cs.toronto.edu/~delve/d...
github_jupyter
**Instructions:** 1. **For all questions after 10th, Please only use the data specified in the note given just below the question** 2. **You need to add answers in the same file i.e. PDS_UberDriveProject_Questions.ipynb' and rename that file as 'Name_Date.ipynb'.You can mention the date on which you will be uploading...
github_jupyter
``` import process_output from PIL import Image, ImageEnhance, ImageFilter import requests from io import BytesIO import imgkit import json def get_unsplash_url(client_id, query, orientation): root = 'https://api.unsplash.com/' path = 'photos/random/?client_id={}&query={}&orientation={}' search_url = r...
github_jupyter
# Robust Scaler - Experimento Este é um componante que dimensiona atributos usando estatísticas robustas para outliers. Este Scaler remove a mediana e dimensiona os dados de acordo com o intervalo quantil (o padrão é Amplitude interquartil). Amplitude interquartil é o intervalo entre o 1º quartil (25º quantil) e o 3º ...
github_jupyter
<a href="https://colab.research.google.com/github/ralsouza/python_fundamentos/blob/master/src/05_desafio/05_missao05.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ## **Missão: Analisar o Comportamento de Compra de Consumidores.** ### Nível de Difi...
github_jupyter
WINE CLASSIFIER ``` # Imports from io import StringIO import pandas as pd import spacy from cytoolz import * import numpy as np from IPython.display import display import seaborn as sns from sklearn.ensemble import RandomForestClassifier from sklearn.feature_selection import chi2 from sklearn.svm import LinearSVC fr...
github_jupyter
# Criminology in Portugal (2011) ## Introduction > In this _study case_, it will be analysed the **_crimes occurred_** in **_Portugal_**, during the civil year of **_2011_**. It will analysed all the _categories_ or _natures_ of this **_crimes_**, _building some statistics and making some filtering of data related to...
github_jupyter
``` !pip install torch torchvision !pip install wavio !pip install sounddevice from google.colab import drive drive.mount('/content/drive') !ls "/content/drive/My Drive/IMT Atlantique/Projet 3A /master/kitchen20" %cd /content/drive/My Drive/IMT Atlantique/Projet 3A /master/kitchen20 from envnet import EnvNet from kitc...
github_jupyter
``` from sklearn import * from sklearn.preprocessing import LabelEncoder from sklearn.preprocessing import StandardScaler from sklearn.datasets import load_iris from sklearn.ensemble import (RandomForestClassifier, ExtraTreesClassifier, AdaBoostClassifier) from sklearn.tree import Decision...
github_jupyter
##### Copyright 2021 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
<a href="https://colab.research.google.com/github/Shubham0Rajput/Feature-Detection-with-AKAZE/blob/master/AKAZE_code.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ``` #IMPORT FILES import matplotlib.pyplot as plt import cv2 #matplotlib inline #MO...
github_jupyter
## Programming for Data Analysis Project 2018 ### Patrick McDonald G00281051 #### Problem statement For this project you must create a data set by simulating a real-world phenomenon of your choosing. You may pick any phenomenon you wish – you might pick one that is of interest to you in your personal or professional...
github_jupyter
# Перечислимые типы (enums) ## 1. Базовые возможности ``` enum Color { White, // 0 Red, // 1 Green, // 2 Blue, // 3 Orange, // 4 } Color white = Color.White; Console.WriteLine(white); // White Color red = (Color)1; // Так можно приводить к типу перечисления Console.WriteLine(red...
github_jupyter
<center> <img src="https://gitlab.com/ibm/skills-network/courses/placeholder101/-/raw/master/labs/module%201/images/IDSNlogo.png" width="300" alt="cognitiveclass.ai logo" /> </center> # **Space X Falcon 9 First Stage Landing Prediction** ## Web scraping Falcon 9 and Falcon Heavy Launches Records from Wikipedia ...
github_jupyter
# Entities Recognition <div class="alert alert-info"> This tutorial is available as an IPython notebook at [Malaya/example/entities](https://github.com/huseinzol05/Malaya/tree/master/example/entities). </div> <div class="alert alert-warning"> This module only trained on standard language structure, so it is no...
github_jupyter
<a href="https://colab.research.google.com/github/Phantom-Ren/PR_TH/blob/master/FCM.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> <center> # 模式识别·第七次作业·模糊聚类(Fussy C Means) #### 纪泽西 17375338 #### Last Modified:26th,April,2020 </center> <table ...
github_jupyter
<img src="https://github.com/OpenMined/design-assets/raw/master/logos/OM/horizontal-primary-light.png" alt="he-black-box" width="600"/> # Homomorphic Encryption using Duet: Data Owner ## Tutorial 2: Encrypted image evaluation Welcome! This tutorial will show you how to evaluate Encrypted images using Duet and TenSE...
github_jupyter
# Shallow regression for vector data This script reads zip code data produced by **vectorDataPreparations** and creates different machine learning models for predicting the average zip code income from population and spatial variables. It assesses the model accuracy with a test dataset but also predicts the number to...
github_jupyter
# RNN Sentiment Classifier In this notebook, we use an RNN to classify IMDB movie reviews by their sentiment. [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/the-deep-learners/deep-learning-illustrated/blob/master/notebooks/rnn_sentiment_classifier...
github_jupyter
# Intro to Jupyter Notebooks ### `Jupyter` is a project for developing open-source software ### `Jupyter Notebooks` is a `web` application to create scripts ### `Jupyter Lab` is the new generation of web user interface for Jypyter ### But it is more than that #### It lets you insert and save text, equations & visuali...
github_jupyter
![qiskit_header.png](attachment:qiskit_header.png) # Qiskit Aqua: Vehicle Routing ## The Introduction Logistics is a major industry, with some estimates valuing it at USD 8183 billion globally in 2015. Most service providers operate a number of vehicles (e.g., trucks and container ships), a number of depots, where t...
github_jupyter
<a href="https://colab.research.google.com/github/JoseAugustoVital/Decision-Score-MarketPlace/blob/main/decision_score.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # ***UNIVERSIDADE FEDERAL DO MATO GROSSO DO SUL*** # Análise de dados para aumenta...
github_jupyter
# Introduction to geospatial vector data in Python ``` %matplotlib inline import pandas as pd import geopandas pd.options.display.max_rows = 10 ``` ## Importing geospatial data Geospatial data is often available from specific GIS file formats or data stores, like ESRI shapefiles, GeoJSON files, geopackage files, P...
github_jupyter
``` import os, json, sys, time, random import numpy as np import torch from easydict import EasyDict from math import floor from easydict import EasyDict from steves_utils.vanilla_train_eval_test_jig import Vanilla_Train_Eval_Test_Jig from steves_utils.torch_utils import get_dataset_metrics, independent_accuracy_as...
github_jupyter
## Computer Vision Learner [`vision.learner`](/vision.learner.html#vision.learner) is the module that defines the [`cnn_learner`](/vision.learner.html#cnn_learner) method, to easily get a model suitable for transfer learning. ``` from fastai.gen_doc.nbdoc import * from fastai.vision import * ``` ## Transfer learning...
github_jupyter
``` import pandas as pd ``` ## Formas de Criar uma lista ### Usando espaço e a função split ``` data = ['1 2 3 4'.split(), '5 6 7 8 '.split(), '9 10 11 12'.split(), '13 14 15 16'.split()] data ``` ## Passando int para cada elemento ### Com a função map ``` # map usa os parâmetros (function se...
github_jupyter
# Neural networks with PyTorch Deep learning networks tend to be massive with dozens or hundreds of layers, that's where the term "deep" comes from. You can build one of these deep networks using only weight matrices as we did in the previous notebook, but in general it's very cumbersome and difficult to implement. Py...
github_jupyter
# GA4GH Variation Representation Schema This notebook demonstrates the use of the VR schema to represent variation in APOE. Objects created in this notebook are saved at the end and used by other notebooks to demonstrate other features of the VR specification. ## APOE Variation rs7...
github_jupyter
``` import numpy as np import cv2 as cv import json """缩小图像,方便看效果 resize会损失像素,造成边缘像素模糊,不要再用于计算的原图上使用 """ def resizeImg(src): height, width = src.shape[:2] size = (int(width * 0.3), int(height * 0.3)) img = cv.resize(src, size, interpolation=cv.INTER_AREA) return img """找出ROI,用于分割原图 原图有四块区域,一个是地块区域,...
github_jupyter
``` """ Estimating the causal effect of sodium on blood pressure in a simulated example adapted from Luque-Fernandez et al. (2018): https://academic.oup.com/ije/article/48/2/640/5248195 """ import numpy as np import pandas as pd from sklearn.linear_model import LinearRegression def generate_data(n=1000, seed=0, b...
github_jupyter
# abc ``` doc_a = "Brocolli is good to eat. My brother likes to eat good brocolli, but not my mother." doc_b = "My mother spends a lot of time driving my brother around to baseball practice." doc_c = "Some health experts suggest that driving may cause increased tension and blood pressure." doc_d = "I often feel pressu...
github_jupyter
# McKinsey Data Scientist Hackathon link: https://datahack.analyticsvidhya.com/contest/mckinsey-analytics-online-hackathon-recommendation/?utm_source=sendinblue&utm_campaign=Download_The_Dataset_McKinsey_Analytics_Online_Hackathon__Recommendation_Design_is_now_Live&utm_medium=email slack:https://analyticsvidhya.slack...
github_jupyter
# Trax : Ungraded Lecture Notebook In this notebook you'll get to know about the Trax framework and learn about some of its basic building blocks. ## Background ### Why Trax and not TensorFlow or PyTorch? TensorFlow and PyTorch are both extensive frameworks that can do almost anything in deep learning. They offer a...
github_jupyter
<h1>Data Exploration</h1> <p>In this notebook we will perform a broad data exploration on the <code>Hitters</code> data set. Note that the aim of this exploration is not to be completely thorough; instead we would like to gain quick insights to help develop a first prototype. Upon analyzing the output of the prototype,...
github_jupyter
<a href="https://colab.research.google.com/github/choderalab/pinot/blob/master/scripts/adlala_mol_graph.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # import ``` ! rm -rf pinot ! git clone https://github.com/choderalab/pinot.git ! pip install dg...
github_jupyter
#### Libraries ``` %%javascript utils.load_extension('collapsible_headings/main') utils.load_extension('hide_input/main') utils.load_extension('autosavetime/main') utils.load_extension('execute_time/ExecuteTime') utils.load_extension('code_prettify/code_prettify') utils.load_extension('scroll_down/main') utils.load_e...
github_jupyter
<img src="images/Callysto_Notebook-Banner_Top_06.06.18.jpg"> ``` %%html <script src="https://cdn.geogebra.org/apps/deployggb.js"></script> ``` # Reflections of Graphs <img src="images/cat_fight.jpg" width=960 height=640> ## Introduction In the photo above, a kitten is looking at its reflection in a mirror. There ...
github_jupyter
``` from sklearn.datasets import load_iris, fetch_openml from sklearn.preprocessing import MinMaxScaler, normalize from sklearn.model_selection import train_test_split from scipy.spatial.distance import minkowski, cosine from sklearn.metrics import accuracy_score from collections import Counter import numpy as np impor...
github_jupyter
# Finding the Data We need to install [newsapi-python](https://github.com/mattlisiv/newsapi-python) package. We can do this by entering ! in the beginning of a cell to directly access to the system terminal. Using exclamation mark is an easy way to access system terminal and install required packages as well undertake...
github_jupyter
``` from sacred import Experiment import tensorflow as tf import threading import numpy as np import os import Datasets from Input import Input as Input from Input import batchgenerators as batchgen import Models.WGAN_Critic import Models.Unet import Utils import cPickle as pickle import Test import pickle dsd_train, ...
github_jupyter
# Hyperparameter Tuning with Amazon SageMaker and MXNet _**Creating a Hyperparameter Tuning Job for an MXNet Network**_ --- --- ## Contents 1. [Background](#Background) 1. [Setup](#Setup) 1. [Data](#Data) 1. [Code](#Code) 1. [Tune](#Train) 1. [Wrap-up](#Wrap-up) --- ## Background This example notebook focuses o...
github_jupyter
# Data Loading Tutorial ``` cd ../.. save_path = 'data/' from scvi.dataset import LoomDataset, CsvDataset, Dataset10X, AnnDataset import urllib.request import os from scvi.dataset import BrainLargeDataset, CortexDataset, PbmcDataset, RetinaDataset, HematoDataset, CbmcDataset, BrainSmallDataset, SmfishDataset ``` ## G...
github_jupyter
<h1> Explore and create ML datasets </h1> In this notebook, we will explore data corresponding to taxi rides in New York City to build a Machine Learning model in support of a fare-estimation tool. The idea is to suggest a likely fare to taxi riders so that they are not surprised, and so that they can protest if the c...
github_jupyter
# Wind Statistics ### Introduction: The data have been modified to contain some missing values, identified by NaN. Using pandas should make this exercise easier, in particular for the bonus question. You should be able to perform all of these operations without using a for loop or other looping construct. 1. The...
github_jupyter
**[Pandas Micro-Course Home Page](https://www.kaggle.com/learn/pandas)** --- # Introduction Maps allow us to transform data in a `DataFrame` or `Series` one value at a time for an entire column. However, often we want to group our data, and then do something specific to the group the data is in. We do this with the `...
github_jupyter
<a href="https://colab.research.google.com/github/jana0601/AA_Summer-school-LMMS/blob/main/Lab_Session_ToyModels.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ``` import numpy as np import matplotlib.pyplot as plt %matplotlib inline import scipy.l...
github_jupyter
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-59152712-8"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-59152712-8'); </script> # Indexed Expressions: Representing and manipulating tensor...
github_jupyter
<a href="https://colab.research.google.com/github/arfild/dw_matrix/blob/master/Day5.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ``` !pip install hyperopt import pandas as pd import numpy as np import os import datetime import tensorflow as tf f...
github_jupyter
``` import pandas as pd import numpy as np import matplotlib.backends.backend_tkagg import matplotlib.pylab as plt from astropy.io import fits from astropy import units as units import astropy.io.fits as pyfits from astropy.convolution import Gaussian1DKernel, convolve from extinction import calzetti00, apply, ccm89 fr...
github_jupyter
Os treinamentos das redes MLP e Resnet foram feitos com um batch de 64 imagens por epoca e 10 epocas de treinamento com o dataset Cifar10 #CNN ``` '''For Pre-activation ResNet, see 'preact_resnet.py'. Reference: [1] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun Deep Residual Learning for Image Recognition. a...
github_jupyter
``` import matplotlib.pyplot as plt import seaborn as sns from sklearn.linear_model import Ridge from sklearn.linear_model import Lasso from sklearn.neighbors import KNeighborsRegressor from sklearn.model_selection import GridSearchCV from sklearn.metrics import r2_score from sklearn.metrics import mean_squared_error ...
github_jupyter
# Modeling and Simulation in Python Chapter 6 Copyright 2017 Allen Downey License: [Creative Commons Attribution 4.0 International](https://creativecommons.org/licenses/by/4.0) ``` # Configure Jupyter so figures appear in the notebook %matplotlib inline # Configure Jupyter to display the assigned value after an as...
github_jupyter
``` %matplotlib inline # Importing standard Qiskit libraries and configuring account from qiskit import QuantumCircuit, execute, Aer, IBMQ from qiskit.compiler import transpile, assemble from qiskit.tools.jupyter import * from qiskit.visualization import * # Loading your IBM Q account(s) provider = IBMQ.load_account() ...
github_jupyter
# Availability Calculator This tool estimates the average device availability over a period of time. Double-click into the cells below, where it says `'here'`, and adjust the values as necessary. After setting configuration values, select `Kernel` > `Restart & Run All` from the menu. ``` from datetime import dateti...
github_jupyter
<a href="https://colab.research.google.com/github/TerrenceAm22/DS-Unit-2-Kaggle-Challenge/blob/master/LS_DS_223_assignment_checkpoint2.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> Lambda School Data Science *Unit 2, Sprint 2, Module 3* --- # C...
github_jupyter
``` import wget, json, os, math from pathlib import Path from string import capwords from pybtex.database import parse_string import pybtex.errors from mpcontribs.client import Client from bravado.exception import HTTPNotFound from pymatgen.core import Structure from pymatgen.ext.matproj import MPRester from tqdm.noteb...
github_jupyter
# DeepDreaming with TensorFlow >[Loading and displaying the model graph](#loading) >[Naive feature visualization](#naive) >[Multiscale image generation](#multiscale) >[Laplacian Pyramid Gradient Normalization](#laplacian) >[Playing with feature visualzations](#playing) >[DeepDream](#deepdream) This notebook demo...
github_jupyter
``` # reload packages %load_ext autoreload %autoreload 2 ``` ### Choose GPU ``` %env CUDA_DEVICE_ORDER=PCI_BUS_ID %env CUDA_VISIBLE_DEVICES=3 import tensorflow as tf gpu_devices = tf.config.experimental.list_physical_devices('GPU') if len(gpu_devices)>0: tf.config.experimental.set_memory_growth(gpu_devices[0], Tr...
github_jupyter
``` import sys sys.path.append('../scripts/') from robot import * from scipy.stats import multivariate_normal import random #追加 import copy class Particle: def __init__(self, init_pose, weight): self.pose = init_pose self.weight = weight def motion_update(self, nu, omega, time, noise_...
github_jupyter
``` # To add a new cell, type '# %%' # To add a new markdown cell, type '# %% [markdown]' # %% [markdown] # ## Import necessary dependencies import pandas as pd import numpy as np from matplotlib import pyplot as plt from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.feature_extraction.text imp...
github_jupyter
# Sentiment Identification ## BACKGROUND A large multinational corporation is seeking to automatically identify the sentiment that their customer base talks about on social media. They would like to expand this capability into multiple languages. Many 3rd party tools exist for sentiment analysis, however, they need h...
github_jupyter
# Feature Engineering ![](images/engineering-icon.jpeg) ## Objective Data preprocessing and engineering techniques generally refer to the addition, deletion, or transformation of data. The time spent on identifying data engineering needs can be significant and requires you to spend substantial time understanding ...
github_jupyter
``` from sklearn.cluster import KMeans from matplotlib import pyplot as plt import numpy as np import pandas as pd trueLables = pd.read_csv('bbcsport_classes.csv',delimiter=",", header=None).values print(trueLables.shape) terms = pd.read_csv('bbcsport_terms.csv',delimiter=",", header=None).values print(terms.shape) X =...
github_jupyter
ERROR: type should be string, got "https://keras.io/examples/structured_data/structured_data_classification_from_scratch/\n\nmudar nome das coisas. Editar como quero // para de servir de exemplo pra o futuro..\n\n```\nimport tensorflow as tf\nimport numpy as np\nimport pandas as pd\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\nimport pydot\nfile_url = \"http://storage.googleapis.com/download.tensorflow.org/data/heart.csv\"\ndataframe = pd.read_csv(file_url)\ndataframe.head()\nval_dataframe = dataframe.sample(frac=0.2, random_state=1337)\ntrain_dataframe = dataframe.drop(val_dataframe.index)\ndef dataframe_to_dataset(dataframe):\n dataframe = dataframe.copy()\n labels = dataframe.pop(\"target\")\n ds = tf.data.Dataset.from_tensor_slices((dict(dataframe), labels))\n ds = ds.shuffle(buffer_size=len(dataframe))\n return ds\n\n\ntrain_ds = dataframe_to_dataset(train_dataframe)\nval_ds = dataframe_to_dataset(val_dataframe)\n```\n\nfor x, y in train_ds.take(1):\n print(\"Input:\", x)\n print(\"Target:\", y)\n \n |||||| entender isto melhor\n\n```\ntrain_ds = train_ds.batch(32)\nval_ds = val_ds.batch(32)\nfrom tensorflow.keras.layers.experimental.preprocessing import Normalization\nfrom tensorflow.keras.layers.experimental.preprocessing import CategoryEncoding\nfrom tensorflow.keras.layers.experimental.preprocessing import StringLookup\n\n\ndef encode_numerical_feature(feature, name, dataset):\n # Create a Normalization layer for our feature\n normalizer = Normalization()\n\n # Prepare a Dataset that only yields our feature\n feature_ds = dataset.map(lambda x, y: x[name])\n feature_ds = feature_ds.map(lambda x: tf.expand_dims(x, -1))\n\n # Learn the statistics of the data\n normalizer.adapt(feature_ds)\n\n # Normalize the input feature\n encoded_feature = normalizer(feature)\n return encoded_feature\n\n\ndef encode_string_categorical_feature(feature, name, dataset):\n # Create a StringLookup layer which will turn strings into integer indices\n index = StringLookup()\n\n # Prepare a Dataset that only yields our feature\n feature_ds = dataset.map(lambda x, y: x[name])\n feature_ds = feature_ds.map(lambda x: tf.expand_dims(x, -1))\n\n # Learn the set of possible string values and assign them a fixed integer index\n index.adapt(feature_ds)\n\n # Turn the string input into integer indices\n encoded_feature = index(feature)\n\n # Create a CategoryEncoding for our integer indices\n encoder = CategoryEncoding(output_mode=\"binary\")\n\n # Prepare a dataset of indices\n feature_ds = feature_ds.map(index)\n\n # Learn the space of possible indices\n encoder.adapt(feature_ds)\n\n # Apply one-hot encoding to our indices\n encoded_feature = encoder(encoded_feature)\n return encoded_feature\n\n\ndef encode_integer_categorical_feature(feature, name, dataset):\n # Create a CategoryEncoding for our integer indices\n encoder = CategoryEncoding(output_mode=\"binary\")\n\n # Prepare a Dataset that only yields our feature\n feature_ds = dataset.map(lambda x, y: x[name])\n feature_ds = feature_ds.map(lambda x: tf.expand_dims(x, -1))\n\n # Learn the space of possible indices\n encoder.adapt(feature_ds)\n\n # Apply one-hot encoding to our indices\n encoded_feature = encoder(feature)\n return encoded_feature\n# Categorical features encoded as integers\nsex = keras.Input(shape=(1,), name=\"sex\", dtype=\"int64\")\ncp = keras.Input(shape=(1,), name=\"cp\", dtype=\"int64\")\nfbs = keras.Input(shape=(1,), name=\"fbs\", dtype=\"int64\")\nrestecg = keras.Input(shape=(1,), name=\"restecg\", dtype=\"int64\")\nexang = keras.Input(shape=(1,), name=\"exang\", dtype=\"int64\")\nca = keras.Input(shape=(1,), name=\"ca\", dtype=\"int64\")\n\n# Categorical feature encoded as string\nthal = keras.Input(shape=(1,), name=\"thal\", dtype=\"string\")\n\n# Numerical features\nage = keras.Input(shape=(1,), name=\"age\")\ntrestbps = keras.Input(shape=(1,), name=\"trestbps\")\nchol = keras.Input(shape=(1,), name=\"chol\")\nthalach = keras.Input(shape=(1,), name=\"thalach\")\noldpeak = keras.Input(shape=(1,), name=\"oldpeak\")\nslope = keras.Input(shape=(1,), name=\"slope\")\n\nall_inputs = [\n sex,\n cp,\n fbs,\n restecg,\n exang,\n ca,\n thal,\n age,\n trestbps,\n chol,\n thalach,\n oldpeak,\n slope,\n]\n\n# Integer categorical features\nsex_encoded = encode_integer_categorical_feature(sex, \"sex\", train_ds)\ncp_encoded = encode_integer_categorical_feature(cp, \"cp\", train_ds)\nfbs_encoded = encode_integer_categorical_feature(fbs, \"fbs\", train_ds)\nrestecg_encoded = encode_integer_categorical_feature(restecg, \"restecg\", train_ds)\nexang_encoded = encode_integer_categorical_feature(exang, \"exang\", train_ds)\nca_encoded = encode_integer_categorical_feature(ca, \"ca\", train_ds)\n\n# String categorical features\nthal_encoded = encode_string_categorical_feature(thal, \"thal\", train_ds)\n\n# Numerical features\nage_encoded = encode_numerical_feature(age, \"age\", train_ds)\ntrestbps_encoded = encode_numerical_feature(trestbps, \"trestbps\", train_ds)\nchol_encoded = encode_numerical_feature(chol, \"chol\", train_ds)\nthalach_encoded = encode_numerical_feature(thalach, \"thalach\", train_ds)\noldpeak_encoded = encode_numerical_feature(oldpeak, \"oldpeak\", train_ds)\nslope_encoded = encode_numerical_feature(slope, \"slope\", train_ds)\n\nall_features = layers.concatenate(\n [\n sex_encoded,\n cp_encoded,\n fbs_encoded,\n restecg_encoded,\n exang_encoded,\n slope_encoded,\n ca_encoded,\n thal_encoded,\n age_encoded,\n trestbps_encoded,\n chol_encoded,\n thalach_encoded,\n oldpeak_encoded,\n ]\n)\nx = layers.Dense(32, activation=\"relu\")(all_features)\nx = layers.Dropout(0.5)(x)\noutput = layers.Dense(1, activation=\"sigmoid\")(x)\nmodel = keras.Model(all_inputs, output)\nmodel.compile(\"adam\", \"binary_crossentropy\", metrics=[\"accuracy\"])\nmodel.fit(train_ds, epochs=50, validation_data=val_ds)\nsample = {\n \"age\": 60,\n \"sex\": 1,\n \"cp\": 1,\n \"trestbps\": 145,\n \"chol\": 233,\n \"fbs\": 1,\n \"restecg\": 2,\n \"thalach\": 150,\n \"exang\": 0,\n \"oldpeak\": 2.3,\n \"slope\": 3,\n \"ca\": 0,\n \"thal\": \"fixed\",\n}\n\ninput_dict = {name: tf.convert_to_tensor([value]) for name, value in sample.items()}\npredictions = model.predict(input_dict)\n\nprint(\n \"This particular patient had a %.1f percent probability \"\n \"of having a heart disease, as evaluated by our model.\" % (100 * predictions[0][0],)\n)\n```\n\n"
github_jupyter
## Dependencies ``` import warnings, json, random, os import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from sklearn.model_selection import KFold, StratifiedKFold from sklearn.metrics import mean_squared_error import tensorflow as tf import tensorflow.keras.layers as L impor...
github_jupyter
## PyCity Schools Analysis ##### Top and Bottom Performing Schools - The most immediate observation is that Charter schools populate the top 5 performing schools and District schools populate the bottom 5 performing schools for standardized test scores. - Overall, District schools had lower standardized test scores t...
github_jupyter
Greyscale ℓ1-TV Denoising ========================= This example demonstrates the use of class [tvl1.TVL1Denoise](http://sporco.rtfd.org/en/latest/modules/sporco.admm.tvl1.html#sporco.admm.tvl1.TVL1Denoise) for removing salt & pepper noise from a greyscale image using Total Variation regularization with an ℓ1 data fid...
github_jupyter
``` %matplotlib inline ``` # Out-of-core classification of text documents This is an example showing how scikit-learn can be used for classification using an out-of-core approach: learning from data that doesn't fit into main memory. We make use of an online classifier, i.e., one that supports the partial_fit metho...
github_jupyter
``` import pandas as pd import seaborn as sns %matplotlib inline ``` Como hay gente voluntariosa, pero que no deja de ser radical, tenemos que limpiar formatos dispares de documentos estatales ``` # Carta Marina 2015 data2015 = pd.read_csv('../data/raw/escuelas-elecciones-2015-cordoba.csv') data2015.head() ``` Sepa...
github_jupyter
# Basic objects A `striplog` depends on a hierarchy of objects. This notebook shows the objects and their basic functionality. - [Lexicon](#Lexicon): A dictionary containing the words and word categories to use for rock descriptions. - [Component](#Component): A set of attributes. - [Interval](#Interval): One elemen...
github_jupyter
# Import Modules ``` import warnings warnings.filterwarnings('ignore') from src import detect_faces, show_bboxes from PIL import Image import torch from torchvision import transforms, datasets import numpy as np import os ``` # Path Definition ``` dataset_path = '../Dataset/emotiw/' face_coordinates_directory = '....
github_jupyter
``` # This cell is added by sphinx-gallery !pip install mrsimulator --quiet %matplotlib inline import mrsimulator print(f'You are using mrsimulator v{mrsimulator.__version__}') ``` # Itraconazole, ¹³C (I=1/2) PASS ¹³C (I=1/2) 2D Phase-adjusted spinning sideband (PASS) simulation. The following is a simulation of...
github_jupyter
``` # !pip install plotly import pandas as pd import numpy as np from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler import keras from keras.models import Sequential from keras.layers import Dense, Dropout from sklearn.metr...
github_jupyter
# Lambda School Data Science - Logistic Regression Logistic regression is the baseline for classification models, as well as a handy way to predict probabilities (since those too live in the unit interval). While relatively simple, it is also the foundation for more sophisticated classification techniques such as neur...
github_jupyter