code
stringlengths
2.5k
150k
kind
stringclasses
1 value
# Import libraries and packages ``` import folium import numpy as np import pandas as pd import seaborn as sns from geopy.geocoders import Nominatim from matplotlib import pyplot as plt from scipy import stats from sklearn.linear_model import LinearRegression from sklearn.pipeline import Pipeline from sklearn.prepro...
github_jupyter
``` # Import required modules import pandas as pd import numpy as np from sklearn.model_selection import train_test_split, GridSearchCV from sklearn.ensemble import AdaBoostClassifier, GradientBoostingClassifier, BaggingClassifier, RandomForestClassifier, VotingClassifier from sklearn.tree import DecisionTreeClassifie...
github_jupyter
# 序列模型和注意机制 Sequence Models & Attention Mechanism ## 1. 常见的序列到序列架构 Various sequence to sequence architectures ### 1.1 基本模型 Basic Models ![Sequence to sequence model.png](img/Sequence to sequence model.png) ![Image captioning.png](img/Image captioning.png) ### 1.2 挑选概率最高的句子 Picking the most likely sentence 序列到序列的机...
github_jupyter
# Predicting movie ratings One of the most common uses of big data is to predict what users want. This allows Google to show you relevant ads, Amazon to recommend relevant products, and Netflix to recommend movies that you might like. This lab will demonstrate how we can use Apache Spark to recommend movies to a user....
github_jupyter
# Table widgets in the napari viewer Before we talk about tables and widgets in napari, let's create a viewer, a simple test image and a labels layer: ``` import numpy as np import napari import pandas from napari_skimage_regionprops import regionprops_table, add_table, get_table viewer = napari.Viewer() viewer.add_im...
github_jupyter
# Regresión con Redes Neuronales Empleando diferentes *funciones de pérdida* y *funciones de activación* las **redes neuronales** pueden resolver efectivamente problemas de **regresión.** En esta libreta se estudia el ejemplo de [California Housing](http://www.spatial-statistics.com/pace_manuscripts/spletters_ms_dir/s...
github_jupyter
## First ML project ``` import pandas as pd housing = pd.read_csv("data.csv") housing.head() housing.info() housing['AGE'].value_counts() housing.describe() %matplotlib inline import matplotlib.pyplot as plt housing.hist(bins=50, figsize=(20,15)) import numpy as np def split_train_test(data , test_ratio): np.rando...
github_jupyter
``` conda install pandas conda install numpy conda install matplotlib pip install plotly import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns import plotly.express as px from scipy import stats import warnings warnings.filterwarnings("ignore") df = pd.read_csv("insurance.csv") d...
github_jupyter
``` import os import numpy as np import pandas as pd import matplotlib.pyplot as plt %matplotlib inline data_path = '../results/results.csv' df = pd.read_csv(data_path, delimiter='\t') ray = df['Ray_et_al'].to_numpy() matrixreduce = df['MatrixREDUCE'].to_numpy() rnacontext = df['RNAcontext'].to_numpy() deepbind = df['D...
github_jupyter
## Fish classification In this notebook the fish classification is done. We are going to classify in four classes: Tuna fish (TUNA), LAG, DOL and SHARK. The detector will save the cropped image of a fish. Here we will take this image and we will use a CNN to classify it. In the original Kaggle competition there are s...
github_jupyter
# Uptake of carbon, heat, and oxygen Plotting a global map of carbon, heat, and oxygen uptake ``` from dask.distributed import Client client = Client("tcp://10.32.15.112:32829") client %matplotlib inline import xarray as xr import intake import numpy as np from cmip6_preprocessing.preprocessing import read_data fro...
github_jupyter
<a href="https://colab.research.google.com/github/wel51x/DS-Unit-1-Sprint-4-Statistical-Tests-and-Experiments/blob/master/Winston_Lee_DS_Unit_1_Sprint_Challenge_4.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # Data Science Unit 1 Sprint Challenge...
github_jupyter
## Getting the Data from Kaggle Using the Kaggle API ``` #!kaggle competitions download -c titanic # Unzip the folder #!unzip 'titanic.zip' -d data/titanic/ ``` # Setup ``` # Load the train file to pandas import pandas as pd import numpy as np import missingno as msno from collections import Counter import re impor...
github_jupyter
### Halo check Plot halos to see if halofinders work well ``` #import os #base = os.path.abspath('/home/hoseung/Work/data/05427/') #base = base + '/' # basic parameters # Directory, file names, snapshots, scale, npix base = '/home/hoseung/Work/data/05427/' cluster_name = base.split('/')[-2] frefine= 'refine_params.t...
github_jupyter
# Chapter 12 *Modeling and Simulation in Python* Copyright 2021 Allen Downey License: [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-nc-sa/4.0/) ``` # check if the libraries we need are installed try: import pint except ImportError: !pip in...
github_jupyter
``` import pandas as pd import matplotlib.pyplot as plt ``` ## Counting missing rows with left join The Movie Database is supported by volunteers going out into the world, collecting data, and entering it into the database. This includes financial data, such as movie budget and revenue. If you wanted to know which mov...
github_jupyter
**Chapter 19 – Training and Deploying TensorFlow Models at Scale** _This notebook contains all the sample code in chapter 19._ <table align="left"> <td> <a href="https://colab.research.google.com/github/ageron/handson-ml2/blob/master/19_training_and_deploying_at_scale.ipynb" target="_parent"><img src="https://c...
github_jupyter
# Data pre-processing for Azure Data Explorer <img src="https://github.com/Azure/azure-kusto-spark/raw/master/kusto_spark.png" style="border: 1px solid #aaa; border-radius: 10px 10px 10px 10px; box-shadow: 5px 5px 5px #aaa"/> We often see customer scenarios where historical data has to be migrated to Azure Data Explo...
github_jupyter
# WGAN with MNIST (or Fashion MNIST) * `Wasserstein GAN`, [arXiv:1701.07875](https://arxiv.org/abs/1701.07875) * Martin Arjovsky, Soumith Chintala, and L ́eon Bottou * This code is available to tensorflow version 2.0 * Implemented by [`tf.keras.layers`](https://www.tensorflow.org/versions/r2.0/api_docs/python/tf/...
github_jupyter
# Artificial Neural Networks ## About this notebook This notebook kernel was created to help you understand more about machine learning. I intend to create tutorials with several machine learning algorithms from basic to advanced. I hope I can help you with this data science trail. For any information, you can conta...
github_jupyter
``` from keras.models import Sequential from keras.layers import Dense from keras.callbacks import TensorBoard from keras.layers import * import numpy from sklearn.model_selection import train_test_split #ignoring the first row (header) # and the first column (unique experiment id, which I'm not using here) dataset ...
github_jupyter
# **Jupyer Bridge and RCy3** You can open this notebook in the Google Colab from Github directly (File -> Open notebook -> Github). Also you can download this notebook and upload it to the Google Colab (File -> Open notebook -> Upload). <font color='red'> You do not need to run installation and getting started sect...
github_jupyter
# Keras MNIST Model Deployment * Wrap a Tensorflow MNIST python model for use as a prediction microservice in seldon-core * Run locally on Docker to test * Deploy on seldon-core running on minikube ## Dependencies * [Helm](https://github.com/kubernetes/helm) * [Minikube](https://github.com/kubernetes/minik...
github_jupyter
``` import pandas as pd import numpy as np import datetime import string from collections import Counter from scipy.sparse import hstack, csr_matrix from nltk.tokenize import RegexpTokenizer, word_tokenize from nltk import ngrams from sklearn.svm import LinearSVC from sklearn.naive_bayes import MultinomialNB from sklea...
github_jupyter
<table class="ee-notebook-buttons" align="left"> <td><a target="_blank" href="https://github.com/giswqs/earthengine-py-notebooks/tree/master/Image/canny_edge_detector.ipynb"><img width=32px src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" /> View source on GitHub</a></td> <td><a target="_blank" hr...
github_jupyter
# Gaussian Mixture Model ``` !pip install tqdm torchvision tensorboardX from __future__ import print_function import torch import torch.utils.data import numpy as np import matplotlib.pyplot as plt from matplotlib import cm from mpl_toolkits.mplot3d import Axes3D seed = 0 torch.manual_seed(seed) if torch.cuda.is_av...
github_jupyter
# Evaluate text-image search app with Flickr 8k dataset > Create labeled data, text processor and evaluate with Vespa python API - toc: true - badges: true - comments: true - categories: [text_image_search, clip_model, vespa, flicker8k] This post creates a labeled dataset out of the Flicker 8k image-caption dataset,...
github_jupyter
# Import libraries ``` import pandas as pd import numpy as np from sklearn.ensemble import RandomForestRegressor from sklearn.metrics import r2_score from sklearn.metrics import mean_absolute_error from sklearn.model_selection import train_test_split from sklearn.model_selection import GridSearchCV import matplotlib.p...
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
``` import os import pandas as pd filePath = os.path.join(os.getcwd(), 'hindi_corpus_2012_12_19', 'Hi_Newspapers.txt') data = pd.read_csv(filePath, delimiter='\t', names=['source', 'date', 'unnamed_1', 'unnamed_2', 'text']) filePath2 = os.path.join(os.getcwd(), 'hindi_corpus_2012_12_19', 'Hi_Blogs.txt') data2 = pd.read...
github_jupyter
# Locality Sensitive Hashing Locality Sensitive Hashing (LSH) provides for a fast, efficient approximate nearest neighbor search. The algorithm scales well with respect to the number of data points as well as dimensions. In this assignment, you will * Implement the LSH algorithm for approximate nearest neighbor searc...
github_jupyter
<a href="https://colab.research.google.com/github/gdg-ml-team/ioExtended/blob/master/Lab_2.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ``` !pip install -q tensorflow_hub from __future__ import absolute_import, division, print_function import ma...
github_jupyter
# e-magyar elemzés --- (2021. 04. 16.) Mittelholcz Iván ## 1. Az e-magyar használata Az elemzendő szöveg: ``` !cat orkeny.txt ``` Az e-magyar legfrissebb verziójának letöltése: ``` !docker pull mtaril/emtsv:latest ``` Az *orkeny.txt* elemzése, az eredmény kiírása az *orkény.tsv* fájlba: ``` !docker run --rm -...
github_jupyter
<a href="https://practicalai.me"><img src="https://raw.githubusercontent.com/practicalAI/images/master/images/rounded_logo.png" width="100" align="left" hspace="20px" vspace="20px"></a> <img src="https://raw.githubusercontent.com/practicalAI/images/master/images/02_Numpy/numpy.png" width="200" vspace="30px" align="rig...
github_jupyter
**This notebook is an exercise in the [Introduction to Machine Learning](https://www.kaggle.com/learn/intro-to-machine-learning) course. You can reference the tutorial at [this link](https://www.kaggle.com/dansbecker/underfitting-and-overfitting).** --- ## Recap You've built your first model, and now it's time to op...
github_jupyter
``` import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns sns.set(color_codes=True) # makes inline plots to have better quality %config InlineBackend.figure_format = 'svg' # Set the default style plt.style.use("seaborn") ``` ### Read the data and rename columns ``` df = pd.read...
github_jupyter
``` import pandas as pd import numpy as np import emoji import pickle import cv2 import matplotlib.pyplot as plt import os sentiment_data = pd.read_csv("../../resource/Emoji_Sentiment_Ranking/Emoji_Sentiment_Data_v1.0.csv") sentiment_data.head() def clean(x): x = x.replace(" ", "-").lower() return str(x) senti...
github_jupyter
``` import pandas as pd df=pd.read_excel("D:/DATA SCIENCE NOTE/AirQualityUCI.xlsx") df df.columns df.keys() df.shape df.describe() df["RH"].max() df["RH"].min() len(df.loc[df["RH"]==-200]) df["T"].min() df["T"].max() df["CO(GT)"].min() df["CO(GT)"].max() #REplace-200 by nan value of the dataset import numpy as np df.re...
github_jupyter
# Importing the data ``` from pandas import read_csv #Let's us read in the comma-separated text file import matplotlib.pyplot as plt #Our go-to module for plotting data = read_csv('data.csv') fig = plt.figure() ax = fig.add_subplot(1, 1, 1) ax.scatter(data['red_pos_X'], data['red_pos_Y'] , color = 'red', edgecol...
github_jupyter
# Computing the Bayesian Hilbert Transform-DRT In this tutorial example, we will show how the developed BHT-DRT method works using a simple ZARC model. The equivalent circuit consists one ZARC model, *i.e*., a resistor in parallel with a CPE element. ``` # import the libraries import numpy as np from math import pi, ...
github_jupyter
``` from functools import reduce import numpy as np import pandas as pd from pandas.tseries.offsets import DateOffset from sklearn.preprocessing import StandardScaler from sklearn.ensemble import RandomForestRegressor from sklearn.ensemble import RandomForestClassifier from xgboost import XGBClassifier from xgboost imp...
github_jupyter
<i>Recommendation Systems</i><br> -- Author by : * Nub-T * D. Johanes ``` !wget http://files.grouplens.org/datasets/movielens/ml-latest-small.zip import os import zipfile CUR_DIR = os.path.abspath(os.path.curdir) movie_zip = zipfile.ZipFile(CUR_DIR + '/ml-latest-small.zip') movie_zip.extractall() import panda...
github_jupyter
<a href="https://colab.research.google.com/github/KorstiaanW/masakhane-mt/blob/master/KorstiaanW_tn_en_Baseline.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # Masakhane - Reverse Machine Translation for African Languages (Using JoeyNMT) > ## NB ...
github_jupyter
# Python Data Science > Dataframe Wrangling with Pandas Kuo, Yao-Jen from [DATAINPOINT](https://www.datainpoint.com/) ``` import requests import json from datetime import date from datetime import timedelta ``` ## TL; DR > In this lecture, we will talk about essential data wrangling skills in `pandas`. ## Essenti...
github_jupyter
``` import numpy as np ## ahora veremos como mostrar la forma de los arrays creados con numpy # creando un array 3D arr_3d = np.zeros((3,3,3)) # y lo imprimimos print(arr_3d) # vemos su forma print("la forma es: {}".format(arr_3d.shape)) # ahora veremos como convertir una lista de python a un array en numpy # prim...
github_jupyter
Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. # Part 1: Training Tensorflow 2.0 Model on Azure Machine Learning Service ## Overview of the part 1 This notebook is Part 1 (Preparing Data and Model Training) of a two part workshop that demonstrates an end-to-end workflow usi...
github_jupyter
# Introduction &copy; Harishankar Manikantan, maintained on GitHub at [hmanikantan/ECH60](https://github.com/hmanikantan/ECH60) and published under an [MIT license](https://github.com/hmanikantan/ECH60/blob/master/LICENSE). Return to [Course Home Page](https://hmanikantan.github.io/ECH60/) **[Context and Scope](#scop...
github_jupyter
# Softmax 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.* This exercise is ...
github_jupyter
# __Proposal__ We are facing a serious situation of COVID-19 pandemic, for which governments have implemented contingency plans with various effectiveness. We are trying to create a database for further analysis of the effectiveness of the contingency plans and measures governments have chosen. # __Finding Data__ So...
github_jupyter
<a href="https://colab.research.google.com/github/thecodinguru/DS-Unit-2-Linear-Models/blob/master/Copy_of_LS_DS_213_assignment.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 1, Module 3* --- # Ridge Re...
github_jupyter
### Importing the required modules/packages ``` import numpy as np import matplotlib.pyplot as plt import pandas as pd import re import nltk import string import scipy as sp from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestClassifier from nltk.corpus import stopwords from ...
github_jupyter
## Week 2-2 - Visualizing General Social Survey data Your mission is to analyze a data set of social attitudes by turning it into vectors, then visualizing the result. ### 1. Choose a topic and get your data We're going to be working with data from the General Social Survey, which asks Americans thousands of questio...
github_jupyter
``` import numpy as np import pandas as pd from sklearn.model_selection import train_test_split from sklearn import preprocessing from sklearn.ensemble import RandomForestClassifier from sklearn import svm from sklearn.metrics import precision_score, recall_score import matplotlib.pyplot as plt #reading train.csv data ...
github_jupyter
# Extracting training data from the ODC <img align="right" src="../../Supplementary_data/dea_logo.jpg"> * [**Sign up to the DEA Sandbox**](https://docs.dea.ga.gov.au/setup/sandbox.html) to run this notebook interactively from a browser * **Compatibility:** Notebook currently compatible with the `DEA Sandbox` environm...
github_jupyter
``` import numpy as np import pandas as pd import matplotlib from matplotlib import pyplot as plt %matplotlib inline ``` ## Read in the data *I'm using pandas* ``` data = pd.read_csv('bar.csv') data ``` ## Here is the default bar chart from python ``` f,ax = plt.subplots() ind = np.arange(len(data)) # the x loc...
github_jupyter
Advanced Lane Finding Project === ### Run the code in the cell below to extract object points and image points for camera calibration. ``` # Code block: Import # Import all necessary libraries import numpy as np import cv2 import glob import matplotlib.pyplot as plt import pickle import matplotlib.image as mpimg %m...
github_jupyter
``` import sys sys.path.append('../src') import numpy as np import pandas as pd import matplotlib.pyplot as plt import plotly.graph_objects as go import plotly.express as px pd.set_option('display.max_rows', None) import datetime from plotly.subplots import make_subplots from covid19.config import covid_19_data data ...
github_jupyter
# **MITRE ATT&CK PYTHON CLIENT**: Data Sources ------------------ ## Goals: * Access ATT&CK data sources in STIX format via a public TAXII server * Learn to interact with ATT&CK data all at once * Explore and idenfity patterns in the data retrieved * Learn more about ATT&CK data sources ## 1. ATT&CK Python Client Ins...
github_jupyter
# Introduction to Band Ratios & Spectral Features The BandRatios project explore properties of band ratio measures. Band ratio measures are an analysis measure in which the ratio of power between frequency bands is calculated. By 'spectral features' we mean features we can measure from the power spectra, such as pe...
github_jupyter
``` %matplotlib inline import os, sys import nibabel as nb import numpy as np from nipype import Node, Workflow from nipype.interfaces.fsl import SliceTimer, MCFLIRT, Smooth, ExtractROI import pandas as pd import matplotlib.pyplot as plt from scipy import stats from sklearn.utils import shuffle import glob import sh...
github_jupyter
``` # Environ import scipy as scp import tensorflow as tf from scipy.stats import gamma import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.neighbors import KernelDensity import random import multiprocessing as mp import psutil import pickle import os import re import time # import data...
github_jupyter
# Bayesian Curve Fitting ### Overview The predictive distribution resulting from a Baysian treatment of polynominal curve fittting using an $M = 9$ polynominal, with the fixed parameters $\alpha = 5×10^{-3}$ and $\beta = 11.1$ (Corresponding to known noise variance), in which the red curve denotes the mean of the pred...
github_jupyter
``` ''' setting before run. every notebook should include this code. ''' import os os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID" os.environ["CUDA_VISIBLE_DEVICES"]="0" import sys _r = os.getcwd().split('/') _p = '/'.join(_r[:_r.index('gate-decorator-pruning')+1]) print('Change dir from %s to %s' % (os.getcwd(), _p)) o...
github_jupyter
# When To Stop Fuzzing In the past chapters, we have discussed several fuzzing techniques. Knowing _what_ to do is important, but it is also important to know when to _stop_ doing things. In this chapter, we will learn when to _stop fuzzing_ – and use a prominent example for this purpose: The *Enigma* machine that w...
github_jupyter
# Cavity flow with Navier-Stokes The final two steps will both solve the Navier–Stokes equations in two dimensions, but with different boundary conditions. The momentum equation in vector form for a velocity field v⃗ is: $$ \frac{\partial \overrightarrow{v}}{\partial t} + (\overrightarrow{v} \cdot \nabla ) \overri...
github_jupyter
``` import numpy as np import pandas as pd import os import matplotlib.pyplot as plt from TutorML.decomposition import LFM def load_movielens(train_path, test_path, basedir=None): if basedir: train_path = os.path.join(basedir,train_path) test_path = os.path.join(basedir,test_path) col_names = ['...
github_jupyter
# Continuous Control --- You are welcome to use this coding environment to train your agent for the project. Follow the instructions below to get started! ### 1. Start the Environment Run the next code cell to install a few packages. This line will take a few minutes to run! ``` !pip -q install ./python ``` The...
github_jupyter
# Example 10.2: Non-Ideal Rankine Cycle *John F. Maddox, Ph.D., P.E.<br> University of Kentucky - Paducah Campus<br> ME 321: Engineering Thermodynamics II<br>* ## Problem Statement A Rankine cycle operates with water as the working fluid with a turbine inlet pressure of 3 MPa, a condenser pressure of 15 kPa, and no s...
github_jupyter
# Setup ``` from warnings import simplefilter simplefilter(action='ignore', category=FutureWarning) from tensorflow.keras import backend as K from tensorflow.keras.models import Model, load_model, clone_model from tensorflow.keras.utils import to_categorical from tensorflow.keras.layers import Activation from sklear...
github_jupyter
Here is a simple example of file IO: ``` #Write a file out_file = open("test.txt", "w") out_file.write("This Text is going to out file\nLook at it and see\n") out_file.close() #Read a file in_file = open("test.txt", "r") text = in_file.read() in_file.close() print(text) ``` The output and the contents of the file t...
github_jupyter
Uses `langevin-survival.cpp` with `INPUT_DATA_FILE` flag to compute 2D MFPT from a file generated by `exp-data-diffus-analysis.ipynb`. The file contains $(x,y)$ positions, with only free diffusion phases, separated by `NaN`s when reset occurs. Parameters ($D$, $\sigma$, FPS, $T_\text{res}$...) are contained in the asso...
github_jupyter
# Identify sectors expected to perform well in near future > Find out beaten down sectors that are showing signs of reversal. - badges: true - categories: [personal-finance] Here I find out the sectors that are delivering diminishing returns i.e. returns are decreasing on lower time frames compared to higher time fr...
github_jupyter
``` import pandas as pd import numpy as np from sklearn import * import matplotlib.pyplot as plt %matplotlib inline df = pd.read_csv("/data/credit-default.csv") df.head() df.info() df.default.value_counts()/len(df) target = "default" y = np.where(df[target] == 2, 1, 0) #outcome variable X = df.copy() #feature matrix de...
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
# DataJoint U24 - Workflow DeepLabCut ## Introduction This notebook gives a brief overview and introduces some useful DataJoint tools to facilitate the exploration. + DataJoint needs to be configured before running this notebook, if you haven't done so, refer to the [01-Configure](./01-Configure.ipynb) notebook. + I...
github_jupyter
``` # accessing documentation with ? # We can use help function to understand the documentation print(help(len)) # or we can use the ? operator len? # The notation works for objects also L = [1,2,4,5] L.append? L? # This will also work for functions that we create ourselves, the ? returns the doc string in the funct...
github_jupyter
``` import matplotlib.pyplot as plt from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.cluster import KMeans from sklearn.decomposition import PCA from sklearn.manifold import TSNE from pathlib import Path import pandas as pd import numpy as np random_state = 100 all_txt_files =[] for file in Pat...
github_jupyter
# Imports ``` from nltk.corpus import stopwords from nltk.tokenize import word_tokenize from pymongo import MongoClient import csv import matplotlib.pyplot as plt import pandas as pd import seaborn as sns import spacy import tweepy ``` # Help-Functions ``` def open_csv(csv_address): '''Loading CSV document with ...
github_jupyter
``` import os import numpy as np import itertools import matplotlib.pyplot as plt import pandas as pd from sklearn.utils import shuffle from sklearn.preprocessing import MinMaxScaler from sklearn.model_selection import train_test_split from tensorflow import keras from tensorflow.keras import layers from sklearn.metric...
github_jupyter
# Data Prep of Chicago Food Inspections Data This notebook reads in the food inspections dataset containing records of food inspections in Chicago since 2010. This dataset is freely available through healthdata.gov, but must be provided with the odbl license linked below and provided within this repository. This note...
github_jupyter
# 灰色关联分析法 Grey Relational Analysis FinCreWorld & xyfJASON ## 1 简述 > 参考资料:[数学建模笔记——评价类模型之灰色关联分析 - 小白的文章 - 知乎](https://zhuanlan.zhihu.com/p/161536409) 灰色关联分析的研究对象是一个系统,系统的发展受多个因素的影响,我们想知道这些因素中哪些影响大、哪些影响小。 如果把系统和因素都量化为数值,那么我们研究的就是多个序列的关联程度,或者换句话说,这些序列的**曲线几何形状的相似程度**。形状越相似,说明关联度越高。我们只需要量化各个因素的曲线 $\{x_i\}$ 与系统的曲线 $\{x...
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
# Traitement des données en tables [Vidéo d'accompagnement 2](https://vimeo.com/534400395) Dans cette section, nous supposons disposer d'une table de n-uplets nommés (à l'aide de dictionnaires) et donc de la forme: ```python [ {"descr1": "val1", "descr2": "val2",...}, {"descr1": "val'1", ...}, ... ] ```...
github_jupyter
# Markov Decision Process (MDP) # Discounted Future Return $$R_t = \sum^{T}_{k=0}\gamma^{t}r_{t+k+1}$$ $$R_0 = \gamma^{0} * r_{1} + \gamma^{1} * r_{2} = r_{1} + \gamma^{1} * r_{2}\ (while\ T\ =\ 1) $$ $$R_1 = \gamma^{1} * r_{2} =\ (while\ T\ =\ 1) $$ $$so,\ R_0 = r_{1} + R_1$$ Higher $\gamma$ stands for lower disco...
github_jupyter
<img src="../figures/HeaDS_logo_large_withTitle.png" width="300"> <img src="../figures/tsunami_logo.PNG" width="600"> [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Center-for-Health-Data-Science/PythonTsunami/blob/intro/Numbers_and_operators/Numb...
github_jupyter
This notebook accompanies the Whisper Connected Fracture Analysis note. ``` from pathlib import Path import geopandas as gpd import pandas as pd import numpy as np from shapely.geometry import LineString from pyfracman.data import clean_columns from pyfracman.fab import parse_fab_file from pyfracman.frac_geo import ...
github_jupyter
# Generate AIBL cohort dataset and residuals files in hdf5 format ``` # Import data from Excel sheet import pandas as pd df = pd.read_excel('aibl_ptdemog_final.xlsx', sheet_name='aibl_ptdemog_final') #print(df) sid = df['RID'] grp = df['DXCURREN'] age = df['age'] sex = df['PTGENDER(1=Female)'] tiv = df['Total'] # TIV ...
github_jupyter
``` import numpy as np import matplotlib.pyplot as plt import pandas as pd %matplotlib inline import sklearn sklearn.set_config(print_changed_only=True) ``` ## Automatic Feature Selection ### Univariate statistics ``` from sklearn.datasets import load_breast_cancer from sklearn.feature_selection import SelectPercenti...
github_jupyter
### EXP: Pilote2 QC rating - **Aim:** Test reliability of quality control (QC) of brain registration ratings between two experts raters (PB: Pierre Bellec, YB: Yassine Benahajali) based on the first drafted qc protocol on the zooniverse platform ( ref: https://www.zooniverse.org/projects/simexp/brain-match ). - **Exp...
github_jupyter
[![img/pythonista.png](img/pythonista.png)](https://www.pythonista.io) # Áreas en *D3.js*. ## Inicialización de *D3.js* en la *notebook*. La siguiente celda permite habilitar *D3.js* dentro de esta *notebook* y debe de ser ejecutada siempre antes que cualquier otra celda. **Advertencia:** En caso de no inicializar...
github_jupyter
# Lekcja 5-6: Listy ## Spis treści <a href="#1">1. Co to jest lista?</a> - <a href="#1.1">1.1. Rzut oka z góry - kolekcje w Pythonie</a> - <a href="#1.1_b1">Kolekcje</a> - <a href="#1.1_b2">Typy</a> - <a href="#1.1_b3">Cechy charakterystyczne kolekcji</a> - <a href="#1.2">1.2. Twor...
github_jupyter
### Objective of the session * datetime objects ``` # Use pythons datetime: from datetime import datetime now = datetime.now() # checking for the current datetime print(now) # now I am trying to put my own datetime t1 = datetime.now() t2 = datetime(1970, 1, 1) ...
github_jupyter
``` import os from os.path import join import numpy as np import pandas as pd from scipy.stats import linregress import matplotlib.pyplot as plt %matplotlib inline from plotting_functions import cm2inch ``` # Estimates ### Load individual estimates (in sample fits) multiplicative ``` parameters = ['v', 'gamma', ...
github_jupyter
<a href="https://colab.research.google.com/github/mrdbourke/tensorflow-deep-learning/blob/main/05_transfer_learning_in_tensorflow_part_2_fine_tuning.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # 05. Transfer Learning with TensorFlow Part 2: Fine...
github_jupyter
``` # This notebook demonstrates using bankroll to load positions across brokers # and highlights some basic portfolio rebalancing opportunities based on a set of desired allocations. # # The default portfolio allocation is described (with comments) in notebooks/Rebalance.example.ini. # Copy this to Rebalance.ini in th...
github_jupyter
# 1. Event approach ## Reading the full stats file ``` import numpy import pandas full_stats_file = '/Users/irv033/Downloads/data/stats_example.csv' df = pandas.read_csv(full_stats_file) def date_only(x): """Chop a datetime64 down to date only""" x = numpy.datetime64(x) return numpy.datetime64(...
github_jupyter
# The effect of steel casing in AEM data Figures 4, 5, 6 in Kang et al. (2020) are generated using this ``` # core python packages import numpy as np import scipy.sparse as sp import matplotlib.pyplot as plt from matplotlib.colors import LogNorm from scipy.constants import mu_0, inch, foot import ipywidgets import pr...
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 torch.backends...
github_jupyter
## 2-3. 量子フーリエ変換 この節では、量子アルゴリズムの中でも最も重要なアルゴリズムの一つである量子フーリエ変換について学ぶ。 量子フーリエ変換はその名の通りフーリエ変換を行う量子アルゴリズムであり、様々な量子アルゴリズムのサブルーチンとしても用いられることが多い。 (参照:Nielsen-Chuang 5.1 `The quantum Fourier transform`) ※なお、最後のコラムでも多少述べるが、回路が少し複雑である・入力状態を用意することが難しいといった理由から、いわゆるNISQデバイスでの量子フーリエ変換の実行は難しいと考えられている。 ### 定義 まず、$2^n$成分の配列 $\...
github_jupyter
# Lab 2: cleaning operations practice with the Adult dataset In this lab, we will practice what we learned in the clearning operations lab, but now we use a larger dataset, __Adult__, which we already used in the previous lab . We start by loading the data as we have done before, as well as the necessary libraries. We ...
github_jupyter