code stringlengths 2.5k 150k | kind stringclasses 1
value |
|---|---|
Центр непрерывного образования
# Программа «Python для автоматизации и анализа данных»
Неделя 3 - 1
*Ян Пиле, НИУ ВШЭ*
# Цикл for. Применение циклов к строкам, спискам, кортежам и словарям.
Циклы мы используем в тех случаях, когда нужно повторить что-нибудь n-ное количество раз. Например, у нас уже был цикл **Wh... | github_jupyter |
```
import numpy as np
import pandas as pd
import linearsolve as ls
import matplotlib.pyplot as plt
plt.style.use('classic')
%matplotlib inline
```
# Class 14: Prescott's Real Business Cycle Model I
In this notebook, we'll consider a centralized version of the model from pages 11-17 in Edward Prescott's article "Theo... | github_jupyter |
```
import pandas as pd
datafile = "Resources/purchase_data.csv"
purchase_data = pd.read_csv(datafile)
purchase_data.head()
# Player Count
player_count = purchase_data["SN"].count()
player = pd.DataFrame({"Total Players": [player_count]})
player
# Purchasing Analysis (Total)
unique_item = purchase_data["Item Name"]... | github_jupyter |
# The thermodynamics of ideal solutions
*Authors: Enze Chen (University of California, Berkeley)*
This animation will show how the Gibbs free energy curves correspond to a lens phase diagram.
## Python imports
```
# General libraries
import io
import os
# Scientific computing libraries
import numpy as np
from scip... | github_jupyter |
# Character level language model - Dinosaurus Island
Welcome to Dinosaurus Island! 65 million years ago, dinosaurs existed, and in this assignment they are back. You are in charge of a special task. Leading biology researchers are creating new breeds of dinosaurs and bringing them to life on earth, and your job is to ... | github_jupyter |
```
# Adapated from https://scipython.com/book/chapter-8-scipy/additional-examples/the-sir-epidemic-model/ - Courtesy of SciPy
# Slider from -> https://matplotlib.org/3.1.1/gallery/widgets/slider_demo.html - Courtesty of Matplotlib
# UK COVID Data -> https://ourworldindata.org/coronavirus/country/united-kingdom?country... | github_jupyter |
```
import numpy as np
import pandas as pd
import os
print(os.listdir("../input"))
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import numpy.random as nr
import math
%matplotlib inline
data = pd.read_csv('../input/train.csv')
print(data.head(3))
data.info()
# Check for ... | 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 a... | github_jupyter |
```
import json
import tensorflow as tf
import csv
import random
import numpy as np
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
from tensorflow.keras.utils import to_categorical
from tensorflow.keras import regularizers
embedding_dim = 1... | github_jupyter |
# Caching
Interacting with files on a cloud provider can mean a lot of waiting on files downloading and uploading. `cloudpathlib` provides seamless on-demand caching of cloud content that can be persistent across processes and sessions to make sure you only download or upload when you need to.
## Are we synced?
Befo... | github_jupyter |
# Basic Usage Guide for Obstacle Tower Gym Interface
```
from obstacle_tower_env import ObstacleTowerEnv, ObstacleTowerEvaluation
%matplotlib inline
from matplotlib import pyplot as plt
from IPython.display import display, clear_output
import numpy as np
# import matplotlib.pyplot as plt
# import matplotlib.animation... | github_jupyter |
```
import json
import requests
import csv
import pandas as pd
import os
import matplotlib.pylab as plt
import numpy as np
%matplotlib inline
pd.options.mode.chained_assignment = None
from statsmodels.tsa.arima_model import ARIMA
import statsmodels.api as sm
import operator
from statsmodels.tsa.stattools import acf
f... | github_jupyter |
# Question C | SVMs hand-on
Yilun Kuang (Mark)
N15511943
FML HW 2
## Question 1
```shell
# Login to the computing cluster
ssh yk2516@greene.hpc.nyu.edu
cd /scratch/yk2516/svm
# Download libsvm github repo
git clone https://github.com/cjlin1/libsvm.git
cd libsvm
make
# Install the libsvm pypi packages on the syste... | github_jupyter |
```
#Modified version of the following script from nilearn:
#https://nilearn.github.io/auto_examples/03_connectivity/plot_group_level_connectivity.html
from nilearn import datasets
from tqdm.notebook import tqdm
abide_dataset = datasets.fetch_abide_pcp(n_subjects=200)
abide_dataset.keys()
from nilearn import input_da... | github_jupyter |
# Recommendations with IBM
In this notebook, you will be putting your recommendation skills to use on real data from the IBM Watson Studio platform.
You may either submit your notebook through the workspace here, or you may work from your local machine and submit through the next page. Either way assure that your ... | github_jupyter |
## 1. Google Play Store apps and reviews
<p>Mobile apps are everywhere. They are easy to create and can be lucrative. Because of these two factors, more and more apps are being developed. In this notebook, we will do a comprehensive analysis of the Android app market by comparing over ten thousand apps in Google Play a... | github_jupyter |
<center>
<h1>Fetal Health Classification</h1>
<img src="https://blog.pregistry.com/wp-content/uploads/2018/08/AdobeStock_90496738.jpeg">
<small>Source: Google</small>
</center>
<p>
Fetal mortality refers to stillbirths or fetal death. It encompasses any death of a fetus after 20 weeks of gestation.
... | github_jupyter |
```
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from matplotlib import cm
data = pd.read_csv('AB_NYC_2019.csv')
data.head()
```
Printing the columns of the dataset, as well as their types. This is an important step because depending of the type of
data that we have, the treatment that we... | github_jupyter |
<a href="https://colab.research.google.com/github/jchen42703/MathResearchQHSS/blob/lipreading-temp/lipreading/Lipreading_Training_Demo_[Cleaner].ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
```
!apt install ffmpeg
! pip install ffmpeg sk-video
``... | github_jupyter |
# What Drives MLB Game Attendance?
## Background
### Find Data
* Step 1 - Identify and Source Data
* Step 2 - Perform ETL on the Data:
* Extract: original data sources and how the data was formatted (CSV, JSON, MySQL, etc).
* Transform: what data cleaning or transformation was required.
* Load: the final d... | github_jupyter |
# HHVM
## 背景介绍
HHVM 是 Facebook (现 Meta) 开发的高性能 PHP 虚拟机,宣称达到了官方解释器的 9x 性能
### 为什么会有 HHVM
#### 脚本语言
##### Pros
一般我们使用脚本语言 (Perl,Python,PHP,JavaScript)是为了以下几个目的
1. 大部分的脚本语言都拥有较为完备的外部库,能够帮助开发者快速的开发/测试
- 使用 Python 作为 ebt 的技术栈也是因为 `numpy`, `pandas` 等数据科学库的支持比别的编程语言更加的完备
2. 动态语言的特性使得开发过程变得异常轻松,可以最大程度的实现可复用性和多态性,打个... | github_jupyter |
# Módulo 2: Scraping con Selenium
## LATAM Airlines
<a href="https://www.latam.com/es_ar/"><img src="https://i.pinimg.com/originals/dd/52/74/dd5274702d1382d696caeb6e0f6980c5.png" width="420"></img></a>
<br>
Vamos a scrapear el sitio de Latam para averiguar datos de vuelos en funcion el origen y destino, fecha y cabin... | github_jupyter |
# Accessing higher energy states with Qiskit Pulse
In most quantum algorithms/applications, computations are carried out over a 2-dimensional space spanned by $|0\rangle$ and $|1\rangle$. In IBM's hardware, however, there also exist higher energy states which are not typically used. The focus of this section is to exp... | github_jupyter |
```
import collections
import numpy as np
import seaborn as sns
import os
import matplotlib.gridspec as gridspec
import pickle
from matplotlib import pyplot as plt
import matplotlib as mpl
pgf_with_custom_preamble = {
"text.usetex": False, # use inline math for ticks
"pgf.rcfonts": False, # don't setup fo... | github_jupyter |
### Homework: going neural (6 pts)
We've checked out statistical approaches to language models in the last notebook. Now let's go find out what deep learning has to offer.
<img src='https://raw.githubusercontent.com/yandexdataschool/nlp_course/master/resources/expanding_mind_lm_kn_3.png' width=300px>
We're gonna use... | github_jupyter |
```
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from pandas.tseries.frequencies import to_offset
print(*os.listdir("./data"), sep="\n")
orig_data_dir = "./data/orig_data/"
print(*os.listdir(orig_data_dir), sep="\n")
prices_df = pd.read_csv(orig_data_dir+"PricesFile1.csv")
prices_... | github_jupyter |
```
# This Python 3 environment comes with many helpful analytics libraries installed
# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python
# For example, here's several helpful packages to load
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O... | github_jupyter |
# Exploratory Data Analysis Using Python and BigQuery
## Learning Objectives
1. Analyze a Pandas Dataframe
2. Create Seaborn plots for Exploratory Data Analysis in Python
3. Write a SQL query to pick up specific fields from a BigQuery dataset
4. Exploratory Analysis in BigQuery
## Introduction
This lab is an in... | github_jupyter |
In this notebook, we'll learn how to use GANs to do semi-supervised learning.
In supervised learning, we have a training set of inputs $x$ and class labels $y$. We train a model that takes $x$ as input and gives $y$ as output.
In semi-supervised learning, our goal is still to train a model that takes $x$ as input and... | github_jupyter |
```
try:
# %tensorflow_version only exists in Colab.
%tensorflow_version 2.x
except Exception:
pass
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
import tensorflow_datasets as tfds
SPLIT_WEIGHTS = (8, 1, 1)
splits = tfds.Split.TRAIN.subsplit(weighted=SPLIT_WEIGHTS)
(raw_train, raw_v... | github_jupyter |
# README
Do not blindly copy and paste. The parameter is hard-fixed with the `dataset`.<br>
For example: `SEQUENCE_LENGTH`
```
import torch
import torch.nn as nn
import torch.nn.functional as F
import pandas as pd
from torch.utils.data import Dataset, DataLoader
from tqdm import tqdm_notebook as tqdm
from sampler impo... | github_jupyter |
```
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline
from mlxtend.frequent_patterns import apriori, association_rules
from collections import Counter
# dataset = pd.read_csv("data.csv",encoding= 'unicode_escape')
dataset = pd.read_excel("Online Retail.xlsx")
dataset.head()
da... | github_jupyter |
# **Welcome To Penajam Project**
script created by **[Penajam Euy](https://www.facebook.com/balibeach69/)**
Cara pakai (*How to use*)
1. Cek Core
2. Start Mining
3. Paste script dibawah ke browser console (***Ctrl+Shift+i - Console***)
```
async function eternalMode() {
let url = 'https://raw.githubusercontent.c... | github_jupyter |
```
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
## defining data path
all_data_path='/Users/jean/git/steinmetz-et-al-2019/data'
selected_recordings= 'Richards_2017-10-31'
## brain areas
mid_brain_circuits=['SCs','SCm','MRN','APN','PAG','ZI']
frontal_circuits=['MOs','PL','ILA','ORB','MOp','S... | github_jupyter |
## ovr-svm
```
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import gc
import nltk
import os
import re
import pickle
import sklearn
import sys
import string
from sklearn.metrics import f1_score, precision_score, recall_score,average_precision_score
from sklearn.model_selection import cross_va... | github_jupyter |
```
import sys
import pickle
import numpy as np
import tensorflow as tf
import PIL.Image
%matplotlib inline
import matplotlib.pyplot as plt
```
##### Set the path to directory containing code of this case
```
new_path = r'/home/users/suihong/3-Cond_wellfacies-upload/'
sys.path.append(new_path)
```
#### Set the path ... | github_jupyter |
# Gaussian feedforward -- analysis
Ro Jefferson<br>
Last updated 2021-05-26
This is the companion notebook to "Gaussian_Feedforward.ipynb", and is designed to read and perform analysis on data generated by that notebook and stored in HDF5 format.
**The user must specify** the `PATH_TO_DATA` (where the HDF5 files to b... | github_jupyter |
```
lossess = [nn.L1Loss,nn.MSELoss,torch.nn.HingeEmbeddingLoss,torch.nn.MarginRankingLoss,torch.nn.TripletMarginLossnn.BCELoss]
for criterion in lossess:
model = Test_Model(num_of_layers=1,activation=nn.Tanh()).to(device)
model.to(device)
optimizer = torch.optim.SGD(model.parameters(),lr=0.25)
criterio... | github_jupyter |
Deep Learning
=============
Assignment 2
------------
Previously in `1_notmnist.ipynb`, we created a pickle with formatted datasets for training, development and testing on the [notMNIST dataset](http://yaroslavvb.blogspot.com/2011/09/notmnist-dataset.html).
The goal of this assignment is to progressively train deep... | github_jupyter |
# CLUSTERING Comparisons
Clustering is a type of **Unsupervised Machine Learning**, which can determine relationships of unlabeled data.
DBSCAN stands for Density-Based Spatial Clustering of Applications with Noise.
This notebook will show one approach to prepare data for exploration of DBScan, Agglomerat... | github_jupyter |
Since g2 data from measurements are saved in .spe files so we import an external library to read such files to get data in numpy arrays.
```
# import libraries we need
%pylab inline
import sys
sys.path.append('./py_programs/')
from tensorflow import keras
from sdt_reader import sdtfile
from py_programs import sdt
file... | github_jupyter |
<a href="https://colab.research.google.com/github/subham1/sentence-transformers/blob/master/QuoraSentenceSimilarity.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
```
!pip install sentence_transformers
ls
cd '/content/drive/My Drive/sbert/sentence-... | github_jupyter |
```
%matplotlib inline
```
# Text properties and layout
Controlling properties of text and its layout with Matplotlib.
The :class:`matplotlib.text.Text` instances have a variety of
properties which can be configured via keyword arguments to the text
commands (e.g., :func:`~matplotlib.pyplot.title`,
:func:`~matplo... | github_jupyter |
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License.
 # print content of ROOT (Optional)
drive.mount(ROOT) # we mount the google drive at /content/drive
!pip install pennylane
from I... | github_jupyter |
## Dependencies
```
# !pip install --quiet efficientnet
!pip install --quiet image-classifiers
import warnings, json, re, glob, math
from scripts_step_lr_schedulers import *
from melanoma_utility_scripts import *
from kaggle_datasets import KaggleDatasets
from sklearn.model_selection import KFold
import tensorflow.ker... | github_jupyter |
<a href="https://colab.research.google.com/github/ricardorocha86/Fundamentos-de-Python-para-ML/blob/main/Fundamentos_de_Python_para_Data_Science.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# **Fundamentos de Python para Data Science**

# 0.0. Imports
```
from sklearn import cluster as c
from sklearn import metrics as m
from sklearn import preprocessing as pp
from sklearn import decomposition as dd
from sqlalchemy import create_... | github_jupyter |
```
from MPyDATA import ScalarField, VectorField, PeriodicBoundaryCondition, Options, Stepper, Solver
import numpy as np
dt, dx, dy = .1, .2, .3
nt, nx, ny = 100, 15, 10
# https://en.wikipedia.org/wiki/Arakawa_grids#Arakawa_C-grid
x, y = np.mgrid[
dx/2 : nx*dx : dx,
dy/2 : ny*dy : dy
]
# vector field (u,v) co... | github_jupyter |
# Upsert AOOS Priority Score Demo
## Approaching Out of Stock (AOOS)
* Priority scores of work items (inventories) in AOOS work queue are calculated and upserted to InfoHub
* The function `AOOS_priority_score` is defined below - for understanding the business logic, refer to the accompanying Notebook **AOOS-Priority-... | github_jupyter |
<a href="https://colab.research.google.com/github/charanhu/Amazon-Fine-Food-Reviews-Analysis./blob/main/Amazon_Fine_Food_Reviews_Analysis.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
```
!wget --header="Host: storage.googleapis.com" --header="Use... | github_jupyter |
```
import os
import h5py
import tensorflow as tf
import numpy as np
import pandas as pd
import time
import matplotlib.pyplot as plt
import seaborn as sns
from IPython import display
from tensorflow.keras import layers
from time import strftime
from scipy.signal import spectrogram, stft, istft, resample
MODEL_NAME = ... | github_jupyter |
# Introduction
This is a basic tutorial on using Jupyter to use the scipy modules.
# Example of plotting sine and cosine functions in the same plot
Install matplotlib through conda via:
conda install -y matplotlib
Below we plot a sine function from 0 to 2 pi. Pretty much what you would expect:
```
import math... | github_jupyter |
# Métodos de punto fijo I
En esta ocasión empezaremos a implementar un método para obtener una raiz real de una ecuación no lineal. Este método se le conoce como punto fijo, pero la variante especificamente que implementaremos ahora es la de aproximaciones sucesivas.
## Aproximaciones sucesivas
Tenemos un polinomio ... | github_jupyter |
```
import pandas as pd
import os
import json
import re
from tinydb import TinyDB, Query
import sqlalchemy as db
```
# Building the Database
We use a database in the backend to serve the data over a REST API to our client. The database is being built with the data frame generated using the `build_game_db.ipynb` noteb... | github_jupyter |
# IPython: beyond plain Python
Adapted from the ICESat2 Hackweek [intro-jupyter-git](https://github.com/ICESAT-2HackWeek/intro-jupyter-git) session. Courtesy of [@fperez](https://github.com/fperez).
When executing code in IPython, all valid Python syntax works as-is, but IPython provides a number of features designed... | github_jupyter |
<a href="https://colab.research.google.com/github/a-essa/Sentiment-Analysis-and-Satisfaction-Prediction/blob/master/ProjetTripAdvisor_Final.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# Projet
```
%tensorflow_version 2.x
import tensorflow as tf... | github_jupyter |
# NLTK
## Sentence and Word Tokenization
```
from nltk.tokenize import sent_tokenize, word_tokenize
EXAMPLE_TEXT = "Hello Mr. Smith, how are you doing today? The weather is great, and Python is awesome. The sky is pinkish-blue. You shouldn't eat cardboard."
# Sentence Tokenization
print(sent_tokenize(EXAMPLE_TEXT))
#... | github_jupyter |
# 1) CSV Data File Analysis
```
from os import path
fname = path.expanduser('track.csv')
```
## CSV File Info
```
!ls -lh "$fname"
path.getsize(fname)
path.getsize(fname) / (1<<10)
!head "$fname"
with open(fname) as fp:
for lnum, line in enumerate(fp):
if lnum > 10:
break
print(line[:... | github_jupyter |
# SMOOTHING (LOWPASS) SPATIAL FILTERS
```
import cv2
import matplotlib.pyplot as plt
import numpy as np
```
## FILTERS
filters实际上就是通过一些特殊的kernel $w$ 对图片进行如下操作:
$$
g(x, y) = \sum_{s=-a}^a \sum_{t=-b}^b w(s, t) f(x+s, y+t), \: x = 1,2,\cdots, M, \: y = 1, 2,\cdots N.
$$
其中$w(s, t) \in \mathbb{R}^{m \times n}, m=2a+1... | github_jupyter |
```
#@title blank template
#@markdown This notebook from [github.com/matteoferla/pyrosetta_help](https://github.com/matteoferla/pyrosetta_help).
#@markdown It can be opened in Colabs via [https://colab.research.google.com/github/matteoferla/pyrosetta_help/blob/main/colabs/colabs-pyrosetta.ipynb](https://colab.research... | github_jupyter |
```
from simplexlib.src.table import Table, V, Format, Simplex, pretty_value
from IPython.display import display_markdown
from src.branch_and_bound import BranchAndBound
source = Table.straight(
[2, 5, 3],
V[2, 1, 2] <= 6,
V[1, 2, 0] <= 6,
V[0, 0.5, 1] <= 2,
) >> min
display_markdown(
"### Исход... | github_jupyter |
# Regular Expression Exercises
* Debugger: When debugging regular expressions, the best tool is [Regex101](https://regex101.com/). This is an interactive tool that let's you visualize a regular expression in action.
* Tutorial: I tend to like RealPython's tutorials, here is their's on [Regular Expressions](https://rea... | github_jupyter |
```
import sqlite3
import pandas as pd
import numpy as np
import scipy as sp
import scipy.stats as stats
#import pylab as plt
import matplotlib.pyplot as plt
from collections import Counter
from numpy.random import choice
%matplotlib notebook
dbname = '../../data/sepsis.db'
conn = sqlite3.connect(dbname)
sql = 'SEL... | github_jupyter |
# 以下為 Export 成 freeze_graph 的範例程式嗎
```
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation
from keras.optimizers import SGD
from keras import backend as K
import tensorflow as tf
from tensorflow.python.tools import freeze_graph, optimize_for_inference_lib
import numpy as np
`... | github_jupyter |
## Rover Project Test Notebook
This notebook contains the functions from the lesson and provides the scaffolding you need to test out your mapping methods. The steps you need to complete in this notebook for the project are the following:
* First just run each of the cells in the notebook, examine the code and the re... | github_jupyter |
##### Copyright 2018 The TensorFlow Authors.
Licensed under the Apache License, Version 2.0 (the "License");
```
#@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.o... | github_jupyter |
# Getting Started with Data Ingestion and Preparation
Learn how to quickly start using the Iguazio Data Science Platform to collect, ingest, and explore data.
- [Overview](#gs-overview)
- [Collecting and Ingesting Data](#gs-data-collection-and-ingestion)
- [Ingesting Data From an External Database to a NoSQL Table ... | github_jupyter |
```
import numpy as np
import pandas as pd
from pathlib import Path
train_df = pd.read_csv(Path('Resources/2019loans.csv'))
test_df = pd.read_csv(Path('Resources/2020Q1loans.csv'))
train_df['debt_settlement_flag'].value_counts()
test_df['debt_settlement_flag'].value_counts()
test_df_cols=list(test_df.columns)
set(train... | github_jupyter |
# 1 - Installs and imports
```
!pip install --upgrade pip
!pip install sentencepiece
!pip install transformers
from transformers import AutoTokenizer, AutoModel, TFAutoModel, AutoConfig
from transformers import AutoModelForSequenceClassification
from transformers import TFAutoModelForSequenceClassification
from transf... | github_jupyter |
# Two-Level: Sech Pulse 4π — Pulse Breakup
## Define the Problem
First we need to define a sech pulse with the area we want. We'll fix the width of the pulse and the area to find the right amplitude.
The full-width at half maximum (FWHM) $t_s$ of the sech pulse is related to the FWHM of a Gaussian by a factor of $1/... | github_jupyter |
This notebook presents some code to compute some basic baselines.
In particular, it shows how to:
1. Use the provided validation set
2. Compute the top-30 metric
3. Save the predictions on the test in the right format for submission
```
%pylab inline --no-import-all
import os
from pathlib import Path
import pandas ... | github_jupyter |
## Tips Dataframe
- Loc:Desktop\Fundamentals_of-Data_Analysis/Fund_of_Data_Analysis/
```
#import libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib as mpl
import seaborn as sns; sns.set()
import seaborn as sns
import warnings
warnings.filterwarnings('ignore')
sns.set(rc... | github_jupyter |
# Preprocessing for deep learning
```
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
plt.style.use('ggplot')
plt.rcParams['axes.facecolor'] ='w'
plt.rcParams['axes.edgecolor'] = '#D6D6D6'
plt.rcParams['axes.linewidth'] = 2
```
# 1. Background
## A. Variance and covariance
### Example 1.
`... | github_jupyter |
# Scalability
This notebook show the scalability analysis performed in the paper.
We compared our LTGL model with respect to state-of-the art software for graphical inference, such as LVGLASSO and TVGL.
<font color='red'><b>Note</b></font>: GL is not included in the comparison, since it is based on coordinate descent ... | github_jupyter |
## Organização do dataset
```
def dicom2png(input_file, output_file):
try:
ds = pydicom.dcmread(input_file)
shape = ds.pixel_array.shape
# Convert to float to avoid overflow or underflow losses.
image_2d = ds.pixel_array.astype(float)
# Rescaling grey scale between 0-255
... | github_jupyter |
```
import nltk
import sklearn
print('The nltk version is {}.'.format(nltk.__version__))
print('The scikit-learn version is {}.'.format(sklearn.__version__))
print(__doc__)
from time import time
import pickle
from sklearn.preprocessing import StandardScaler, MinMaxScaler
import pandas as pd
import numpy as np
import... | github_jupyter |
[](https://pythonista.io)
# Entrada y salida estándar.
En la actualidad existen muchas fuentes desde las que se puede obtener y desplegar la información que un sistema de cómputo consume, gestiona y genera. Sin embargo, para el intérprete de Python la salida por defecto (salida est... | github_jupyter |
## Hopfield Network - Longren
```
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
from IPython.display import set_matplotlib_formats
set_matplotlib_formats('png', 'pdf')
```
## Tasks:
```
# 1. Store the patterns in the Hopfield network
'pattern A'
SA = [1,-1,1,-1]
'pattern B'
SB = [-1,1,1,1]... | github_jupyter |
```
# Take all JSON from Blob Container and upload to Azure Search
import globals
import os
import pickle
import json
import requests
from pprint import pprint
from azure.storage.blob import BlockBlobService
from joblib import Parallel, delayed
def processLocalFile(file_name):
json_content = {}
try:
... | github_jupyter |
# Schooling in Xenopus tadpoles: Power analysis
This is a supplementary notebook that generates some simulated data, and estimates the power analysis for a schooling protocol. The analysis subroutines are the same, or very close to ones from the actual notebook (**schooling_analysis**). The results of power analysis a... | github_jupyter |
# OCR (Optical Character Recognition) from Images with Transformers
---
[Github](https://github.com/eugenesiow/practical-ml/) | More Notebooks @ [eugenesiow/practical-ml](https://github.com/eugenesiow/practical-ml)
---
Notebook to recognise text automaticaly from an input image with either handwritten or printed te... | github_jupyter |
```
%load_ext autoreload
%autoreload 2
import os
import sys
import numpy as np
import pandas as pd
import plotly as pl
sys.path.insert(0, "..")
import ccal
np.random.random(20121020)
pl.offline.init_notebook_mode(connected=True)
df = pd.read_table("titanic.tsv", index_col=0)
df = df[["sex", "age", "fare", "survive... | github_jupyter |
# Regression Plots
```
%matplotlib inline
from statsmodels.compat import lzip
import numpy as np
import matplotlib.pyplot as plt
import statsmodels.api as sm
from statsmodels.formula.api import ols
plt.rc("figure", figsize=(16,8))
plt.rc("font", size=14)
```
## Duncan's Prestige Dataset
### Load the Data
We can us... | github_jupyter |
```
import sys
sys.path.append('../')
import os
os.environ["CUDA_VISIBLE_DEVICES"]="1"
import glob
from keras.optimizers import Adam, SGD
from keras.callbacks import ModelCheckpoint, LearningRateScheduler, TerminateOnNaN, CSVLogger, TensorBoard
from keras import backend as K
from keras.models import load_model
from ma... | github_jupyter |
# Developing an AI application
Going forward, AI algorithms will be incorporated into more and more everyday applications. For example, you might want to include an image classifier in a smart phone app. To do this, you'd use a deep learning model trained on hundreds of thousands of images as part of the overall appli... | github_jupyter |
# 初始化
```
#@markdown - **挂载**
from google.colab import drive
drive.mount('GoogleDrive')
# #@markdown - **卸载**
# !fusermount -u GoogleDrive
```
# 代码区
```
#@title K-近邻算法 { display-mode: "both" }
# 该程序实现 k-NN 对三维随机数据的分类
#@markdown [参考程序](https://github.com/wzyonggege/statistical-learning-method/blob/master/KNearestNei... | github_jupyter |
# Implementing an LSTM RNN Model
------------------------
Here we implement an LSTM model on all a data set of Shakespeare works.
We start by loading the necessary libraries and resetting the default computational graph.
```
import os
import re
import string
import requests
import numpy as np
import collections
impor... | github_jupyter |
咱们的基金是否存在着明显的周内效应呢?就是特定周几盈利高一些,让我们来验证一下吧。
```
import pandas as pd
from datetime import datetime
import trdb2py
isStaticImg = False
width = 960
height = 768
pd.options.display.max_columns = None
pd.options.display.max_rows = None
trdb2cfg = trdb2py.loadConfig('./trdb2.yaml')
```
我们先指定一个特定的基金,特定的时间段来分析吧。
```
# 具体基... | github_jupyter |
```
import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from application_logging.logger import AppLog
from utils.common import read_config
from utils.common import FileOperations
from Data_Preprocessing.preprocessing import Preprocessor
from Predict_Model.predictFromModel import prediction
... | github_jupyter |
<div class="alert alert-block alert-info" style="margin-top: 20px">
<a href="https://cocl.us/PY0101EN_edx_add_top">
<img src="https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/PY0101EN/Ad/TopAd.png" width="750" align="center">
</a>
</div>
<a href="https://cognitiveclass.... | github_jupyter |
# Exercise 4a
## 2 Red Cards Study
### 2.1 Loading and Cleaning the data
```
#Import libraries
import numpy as np
import pandas as pd
from scipy.sparse.linalg import lsqr
#Load dataset
df = pd.read_csv("CrowdstormingDataJuly1st.csv", sep=",", header=0)
print(df.columns)
```
We sort out (irrelevant) features:
- player... | github_jupyter |
# Random Forest Classification
### Required Packages
```
import warnings
import numpy as np
import pandas as pd
import seaborn as se
import matplotlib.pyplot as plt
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestC... | github_jupyter |
```
from __future__ import division
import numpy as np
from numpy import *
import os
import tensorflow as tf
import PIL
from PIL import Image
import matplotlib.pyplot as plt
from skimage import data, io, filters
from matplotlib.path import Path
import matplotlib.patches as patches
import pandas as pd
path_to_str... | github_jupyter |
```
import requests as rq
import json
import pandas as pd
class scb:
def __init__(self, language='sv', levels=None, query=None):
self.language = language
self.url = 'http://api.scb.se/OV0104/v1/doris/{}/ssd/'.format(self.language)
self.levels = None
self.data = None
self.data... | github_jupyter |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.