text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
# Cat Dog Classification ## 1. 下载数据 我们将使用包含猫与狗图片的数据集。它是Kaggle.com在2013年底计算机视觉竞赛提供的数据集的一部分,当时卷积神经网络还不是主流。可以在以下位置下载原始数据集: `https://www.kaggle.com/c/dogs-vs-cats/data`。 图片是中等分辨率的彩色JPEG。看起来像这样: ![cats_vs_dogs_samples](https://s3.amazonaws.com/book.keras.io/img/ch5/cats_vs_dogs_samples.jpg) 不出所料,2013年的猫狗大战的Kaggle比赛是由使用卷...
github_jupyter
# Widget Events In this lecture we will discuss widget events, such as button clicks! ## Special events The `Button` is not used to represent a data type. Instead the button widget is used to handle mouse clicks. The `on_click` method of the `Button` can be used to register a function to be called when the button is...
github_jupyter
# Broadcast Variables We already saw so called *broadcast joins* which is a specific impementation of a join suitable for small lookup tables. The term *broadcast* is also used in a different context in Spark, there are also *broadcast variables*. ### Origin of Broadcast Variables Broadcast variables where introduce...
github_jupyter
# Sudoku This tutorial includes everything you need to set up decision optimization engines, build constraint programming models. When you finish this tutorial, you'll have a foundational knowledge of _Prescriptive Analytics_. >This notebook is part of the **[Prescriptive Analytics for Python](https://rawgit.com/IB...
github_jupyter
# RadarCOVID-Report ## Data Extraction ``` import datetime import json import logging import os import shutil import tempfile import textwrap import uuid import matplotlib.pyplot as plt import matplotlib.ticker import numpy as np import pandas as pd import pycountry import retry import seaborn as sns %matplotlib in...
github_jupyter
## Dragon Real Estate - Price Predictor ``` import pandas as pd housing = pd.read_csv("data.csv") housing.head() housing.info() housing['CHAS'].value_counts() housing.describe() %matplotlib inline # # For plotting histogram # import matplotlib.pyplot as plt # housing.hist(bins=50, figsize=(20, 15)) ``` ## Train-Test ...
github_jupyter
# Replacing scalar values I In this exercise, we will replace a list of values in our dataset by using the .replace() method with another list of desired values. We will apply the functions in the poker_hands DataFrame. Remember that in the poker_hands DataFrame, each row of columns R1 to R5 represents the rank of eac...
github_jupyter
``` import tensorflow as tf import numpy as np import matplotlib.pyplot as plt def plot_series(time, series, format="-", start=0, end=None): plt.plot(time[start:end], series[start:end], format) plt.xlabel("Time") plt.ylabel("Value") plt.grid(True) !wget --no-check-certificate \ https://raw.g...
github_jupyter
<a href="https://colab.research.google.com/github/christianadriano/PCA_AquacultureSystem/blob/master/PCA_KMeans_All_Piscicultura.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ``` import pandas as pd #tables for data wrangling import numpy as np #b...
github_jupyter
``` import torch as t import torchvision as tv import numpy as np import time ``` # 不是逻辑回归 ``` # 超参数 EPOCH = 5 BATCH_SIZE = 100 DOWNLOAD_MNIST = True # 下过数据的话, 就可以设置成 False N_TEST_IMG = 10 # 到时候显示 5张图片看效果, 如上图一 class DNN(t.nn.Module): def __init__(self): super(DNN, self).__init__() ...
github_jupyter
## Dependencies ``` import os import sys import cv2 import shutil import random import warnings import numpy as np import pandas as pd import seaborn as sns import multiprocessing as mp import matplotlib.pyplot as plt from tensorflow import set_random_seed from sklearn.utils import class_weight from sklearn.model_sele...
github_jupyter
``` import numpy as np import pandas as pd from matplotlib import pyplot as plt from tqdm import tqdm %matplotlib inline from torch.utils.data import Dataset, DataLoader import torch import torchvision import torch.nn as nn import torch.optim as optim from torch.nn import functional as F device = torch.device("cuda" i...
github_jupyter
<a href="https://colab.research.google.com/github/AliaksandrSiarohin/first-order-model/blob/master/demo.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # Demo for paper "First Order Motion Model for Image Animation" To try the demo, press the 2 play...
github_jupyter
# Installing Tensorflow We will creat an environment for tensorflow that will activate every time we use th package ### NOTE: it will take some time! ``` %pip install --upgrade pip %pip install tensorflow==2.5.0 ``` #### If you see the message below, restart the kernel please from the panel above (Kernels>restart)!...
github_jupyter
# Time Series Analysis 1 In the first lecture, we are mainly concerned with how to manipulate and smooth time series data. ``` %matplotlib inline import matplotlib.pyplot as plt import os import time import numpy as np import pandas as pd ! python3 -m pip install --quiet gmaps import gmaps import gmaps.datasets ``` ...
github_jupyter
## BERT model for MITMovies Dataset I was going to make this repository a package with setup.py and everything but because of my deadlines and responsibilities at my current workplace I haven't got the time to do that so I shared the structure of the project in README.md file. ``` # If any issues open the one that giv...
github_jupyter
``` # Import common packages and create database connection import pandas as pd import sqlite3 as db conn = db.connect('Db-IMDB.db') ``` 1.List all the directors who directed a 'Comedy' movie in a leap year. (You need to check that the genre is 'Comedy’ and year is a leap year) Your query should return director name,...
github_jupyter
``` !pip install torchvision==0.2.2 !pip install https://download.pytorch.org/whl/cu100/torch-1.1.0-cp36-cp36m-linux_x86_64.whl !pip install typing !pip install opencv-python !pip install slackweb !pip list | grep torchvision !pip list | grep torch # import cv2 import audioread import logging import os import random im...
github_jupyter
Python programmers will often suggest that there many ways the language can be used to solve a particular problem. But that some are more appropriate than others. The best solutions are celebrated as Idiomatic Python and there are lots of great examples of this on StackOverflow and other websites. A sort of sub-langu...
github_jupyter
# 讀取字典 ``` import pandas as pd import numpy as np import os filepath = '/Volumes/backup_128G/z_repository/Yumin_data/玉敏_俄羅斯課本的研究' file_dic = '華語八千詞(內含注音字型檔)/Chinese_8000W_20190515_v1.xlsx' book_file = '實用漢語教科書2010_生詞表.xlsx' to_file = 'processed/chinese_8000Words_results.xlsx' # write_level_doc = '{0}/{1}'.format(fil...
github_jupyter
# The Great Pyramid This is an estimate of the number of people needed to raise stones to the top of the [great pyramid](https://en.wikipedia.org/wiki/Great_Pyramid_of_Giza) using basic physics, such as force, energy, and power. It relies solely on reasonable estimates of known dimensions of the great pyramid and typi...
github_jupyter
# Time series analysis and visualization ``` # Hide all warnings import warnings warnings.simplefilter('ignore') import numpy as np import pandas as pd %matplotlib inline import matplotlib.pyplot as plt import statsmodels as sm import statsmodels.api from tqdm import tqdm from pylab import rcParams # Run-Control (...
github_jupyter
<center> <img src="../../img/ods_stickers.jpg"> ## Открытый курс по машинному обучению <center>Автор материала: Ефремова Дина (@ldinka). # <center>Исследование возможностей BigARTM</center> ## <center>Тематическое моделирование с помощью BigARTM</center> #### Интро BigARTM — библиотека, предназначенная для тематиче...
github_jupyter
# SIR-X This notebook exemplifies how Open-SIR can be used to fit the SIR-X model by [Maier and Dirk (2020)](https://science.sciencemag.org/content/early/2020/04/07/science.abb4557.full) to existing data and make predictions. The SIR-X model is a standard generalization of the Susceptible-Infectious-Removed (SIR) mode...
github_jupyter
# Huggingface SageMaker-SDK - BERT Japanese QA example 1. [Introduction](#Introduction) 2. [Development Environment and Permissions](#Development-Environment-and-Permissions) 1. [Installation](#Installation) 2. [Permissions](#Permissions) 3. [Uploading data to sagemaker_session_bucket](#Uploading-data-...
github_jupyter
``` from google.colab import drive drive.mount('gdrive') %cd /content/gdrive/My\ Drive/colab from __future__ import print_function import json import keras import pickle import os.path from keras.datasets import cifar10 from keras.preprocessing.image import ImageDataGenerator from keras.models import Sequential from ke...
github_jupyter
``` # -*- coding: utf-8 -*- # This work is part of the Core Imaging Library (CIL) developed by CCPi # (Collaborative Computational Project in Tomographic Imaging), with # substantial contributions by UKRI-STFC and University of Manchester. # Licensed under the Apache License, Version 2.0 (the "License"); # ...
github_jupyter
# Isolated skyrmion in confined helimagnetic nanostructure **Authors**: Marijan Beg, Marc-Antonio Bisotti, Weiwei Wang, Ryan Pepper, David Cortes-Ortuno **Date**: 26 June 2016 (Updated 24 Jan 2019) This notebook can be downloaded from the github repository, found [here](https://github.com/computationalmodelling/fidi...
github_jupyter
``` import os import numpy as np import pandas as pd import matplotlib.pyplot as plt %matplotlib inline ``` ## 1. 加载并可视化数据 ``` path = 'LogiReg_data.txt' pdData = pd.read_csv(path, header=None, names=['Exam 1', 'Exam 2', 'Admitted']) pdData.head() pdData.shape positive = pdData[pdData['Admitted'] == 1] negative = p...
github_jupyter
##### Copyright 2020 The TensorFlow Authors. ``` #@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ...
github_jupyter
# VIME: Self/Semi Supervised Learning for Tabular Data # Setup ``` import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns import tensorflow as tf import umap from sklearn.metrics import (average_precision_score, mean_squared_error, roc_auc_score) from...
github_jupyter
``` JSON_PATH = 'by-article-train_attn-data.json' from json import JSONDecoder data = JSONDecoder().decode(open(JSON_PATH).read()) word = 'Sponsored' hyper_count = dict() main_count = dict() for i, article in enumerate(data): if word in article['normalizedText'][-1]: energies = [e for w, e in article['acti...
github_jupyter
``` import detectron2 from detectron2.utils.logger import setup_logger setup_logger() import numpy as np import random from detectron2.engine import DefaultPredictor from detectron2.config import get_cfg from detectron2.utils.visualizer import Visualizer from detectron2.data import MetadataCatalog from detectron2.m...
github_jupyter
# Amazon SageMaker로 다중 노드들 간 분산 RL을 이용해 Roboschool 에이전트 훈련 --- 이 노트북은 `rl_roboschool_ray.ipynb` 의 확장으로, Ray와 TensorFlow를 사용한 강화 학습의 수평(horizontal) 스케일링을 보여줍니다. ## 해결해야 할 Roboschool 문제 선택 Roboschool은 가상 로봇 시스템에 대한 RL 정책을 훈련시키는 데 주로 사용되는 [오픈 소스](https://github.com/openai/roboschool/tree/master/roboschool) 물리 시뮬레이터입니다. ...
github_jupyter
``` import pickle import os import numpy as np from tqdm.notebook import tqdm from quchem_ibm.exp_analysis import * def dict_of_M_to_list(M_dict, PauliOP): P_Qubit_list, _ = zip(*(list(*PauliOP.terms.keys()))) list_of_M_bitstrings=None for bit_string, N_obtained in M_dict.items(): ...
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"); { display-mode: "form" } # you may not use this file except in compliance with the License. # You may obtain a copy of the License at...
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> # Generating C code for the right-hand sides of Maxwell's e...
github_jupyter
``` import numpy as np import pandas as pd import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.autograd import Variable import matplotlib.pyplot as plt %matplotlib inline data_raw = pd.read_csv('../input/sign_mnist_train.csv', sep=",") test_data_raw = pd.read_csv(...
github_jupyter
# Remuestreo Bootstrap Entre los métodos inferenciales que permiten cuantificar el grado de confianza que se puede tener de un estadı́sitico, y saber cuán acertados son los resultados sobre los parámetros de la población, se encuentran las técnias de remuestreo. Estas técnicas tienen la ventaja de que no necesitan da...
github_jupyter
# Data Bootcamp: Demography We love demography, specifically the dynamics of population growth and decline. You can drill down seemingly without end, as this [terrific graphic](http://www.bloomberg.com/graphics/dataview/how-americans-die/) about causes of death suggests. We take a look here at the UN's [populat...
github_jupyter
# Model understanding and interpretability In this colab, we will - Will learn how to interpret model results and reason about the features - Visualize the model results ``` import time # We will use some np and pandas for dealing with input data. import numpy as np import pandas as pd # And of course, we need tens...
github_jupyter
#**Exploratory Data Analysis** ### Setting Up Environment ``` import numpy as np import pandas as pd import matplotlib.pyplot as plt import matplotlib.style as style import seaborn as sns from scipy.stats import pointbiserialr from scipy.stats import pearsonr from scipy.stats import chi2_contingency from sklearn.impu...
github_jupyter
``` import warnings import sys sys.path.insert(0, '../src') import numpy as np import pandas as pd import matplotlib.pyplot as plt from felix_ml_tools import macgyver as mg from preprocess import * from sklearn.linear_model import LassoCV, Lasso warnings.filterwarnings('ignore') pd.set_option("max_columns", None) pd.s...
github_jupyter
``` import pandas as pd from pandas import DataFrame import numpy as np import matplotlib.pyplot as plt import seaborn as sns from datetime import datetime, timedelta from statsmodels.tsa.arima_model import ARIMA from statsmodels.tsa.statespace.sarimax import SARIMAX from statsmodels.graphics.tsaplots import plot_acf, ...
github_jupyter
``` # Install a pip package in the current Jupyter kernel import sys !{sys.executable} -m pip install pip install python-slugify !{sys.executable} -m pip install pip install bs4 !{sys.executable} -m pip install pip install lxml import requests, random, logging, urllib.request, json from bs4 import BeautifulSoup from tq...
github_jupyter
# Introduction to Python > Defining Functions with Python Kuo, Yao-Jen ## TL; DR > In this lecture, we will talk about defining functions with Python. ## Encapsulations ## What is encapsulation? > Encapsulation refers to one of two related but distinct notions, and sometimes to the combination thereof: > 1. A l...
github_jupyter
<br><br><font color="gray">DOING COMPUTATIONAL SOCIAL SCIENCE<br>MODULE 10 <strong>PROBLEM SETS</strong></font> # <font color="#49699E" size=40>MODULE 10 </font> # What You Need to Know Before Getting Started - **Every notebook assignment has an accompanying quiz**. Your work in each notebook assignment will serve ...
github_jupyter
# A Câmara de Vereadores e o COVID-19 Você também fica curioso(a) para saber o que a Câmara de Vereadores de Feira de Santana fez em relação ao COVID-19? O que discutiram? O quão levaram a sério o vírus? Vamos responder essas perguntas e também te mostrar como fazer essa análise. Vem com a gente! Desde o início do an...
github_jupyter
# 12 - Beginner Exercises * Conditional Statements ## 🍼 🍼 🍼 1.Create a Python program that receive a number from the user and determines if a given integer is even or odd. ``` # Write your own code in this cell n = ``` ## 🍼🍼 2.Write a Python code that would read any integer day number and show the day's na...
github_jupyter
``` import matplotlib.pyplot as plt import numpy as np import pandas as pd %config InlineBackend.figure_format='retina' dir_cat = './' #vit_df = pd.read_csv(dir_cat+'gz2_vit_09172021_0000_predictions.csv') #resnet_df = pd.read_csv(dir_cat+'gz2_resnet50_A_predictions.csv') df = pd.read_csv(dir_cat+'gz2_predictions.csv')...
github_jupyter
# Intro to Reinforcement Learning Reinforcement learning requires us to model our problem using the following two constructs: * An agent, the thing that makes decisions. * An environment, the world which encodes what decisions can be made, and the impact of those decisions. The environment contains all the possibl...
github_jupyter
# Analysis of Microglia data ``` # Setup import warnings warnings.filterwarnings("ignore") import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import numpy as np from sccoda.util import comp_ana as mod from sccoda.util import cell_composition_data as dat from sccoda.model import other_models as...
github_jupyter
# A project that shows the law of large numbers ``` import matplotlib.pyplot as plt import numpy as np import pandas as pd ``` # **Generating a population of random numbers** ``` # Creating 230,000 random numbers in a 1/f distribution randint = np.logspace(np.log10(0.001),np.log10(100),230000) fdist = np.zeros(2...
github_jupyter
# GLM: Robust Regression with Outlier Detection **A minimal reproducable example of Robust Regression with Outlier Detection using Hogg 2010 Signal vs Noise method.** + This is a complementary approach to the Student-T robust regression as illustrated in Thomas Wiecki's notebook in the [PyMC3 documentation](http://py...
github_jupyter
# Demystifying Neural Networks --- # Exercises - ANN Weights We will generate matrices that can be used as an ANN. You can generate matrices with any function from `numpy.random`. You can provide a tuple to the `size=` parameter to get an array of that shape. For example, `np.random.normal(0, 1, (3, 6))` generate...
github_jupyter
# Document Processing with AutoML and Vision API ## Problem Statement Formally the brief for this Open Project could be stated as follows: Given a collection of varying pdf/png documents containing similar information, create a pipeline that will extract relevant entities from the documents and store the entities in a...
github_jupyter
First we need to download the dataset. In this case we use a datasets containing poems. By doing so we train the model to create its own poems. ``` from datasets import load_dataset dataset = load_dataset("poem_sentiment") print(dataset) ``` Before training we need to preprocess the dataset. We tokenize the entries ...
github_jupyter
``` import numpy as np import pandas as pd import torch import torch.nn as nn from Utils import load from Utils import generator from Utils import metrics from train import * from prune import * from Layers import layers from torch.nn import functional as F import torch.nn as nn def fc(input_shape, nonlinearity=nn.ReLU...
github_jupyter
``` import numpy as np from matplotlib import pyplot def flux(psi_l, psi_r, C): return .5 * (C + abs(C)) * psi_l + \ .5 * (C - abs(C)) * psi_r def upwind(psi, i, C): return psi[i] - flux(psi[i ], psi[i+one], C[i]) + \ flux(psi[i-one], psi[i ], C[i-one]) def C_corr(C, nx, psi...
github_jupyter
``` from urllib.request import urlopen from bs4 import BeautifulSoup html = urlopen('http://en.wikipedia.org/wiki/Kevin_Bacon') bs = BeautifulSoup(html, 'html.parser') for link in bs.find_all('a'): if 'href' in link.attrs: print(link.attrs['href']) ``` ## Retrieving Articles Only ``` from urllib.request...
github_jupyter
``` import hail as hl ``` # *set up dataset* ``` # read in the dataset Zan produced # metadata from Alicia + sample QC metadata from Julia + densified mt from Konrad # no samples or variants removed yet mt = hl.read_matrix_table('gs://african-seq-data/hgdp_tgp/hgdp_tgp_dense_meta_preQC.mt') # 211358784 snps & 4151...
github_jupyter
<a name="top"></a> <div style="width:1000 px"> <div style="float:right; width:98 px; height:98px;"> <img src="https://raw.githubusercontent.com/Unidata/MetPy/master/metpy/plots/_static/unidata_150x150.png" alt="Unidata Logo" style="height: 98px;"> </div> <h1>Advanced Pythonic Data Analysis</h1> <h3>Unidata Python Wor...
github_jupyter
``` # Copyright 2020 Google LLC # # 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 writi...
github_jupyter
# Prepare Dataset for Model Training and Evaluating # Amazon Customer Reviews Dataset https://s3.amazonaws.com/amazon-reviews-pds/readme.html ## Schema - `marketplace`: 2-letter country code (in this case all "US"). - `customer_id`: Random identifier that can be used to aggregate reviews written by a single author....
github_jupyter
# Time Series Cross Validation ``` import pandas as pd import numpy as np #suppress ARIMA warnings import warnings warnings.filterwarnings('ignore') ``` Up till now we have used a single validation period to select our best model. The weakness of that approach is that it gives you a sample size of 1 (that's better ...
github_jupyter
##### Copyright 2018 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
# Exploratory data analysis Exploratory data analysis is an important part of any data science projects. According to [Forbs](https://www.forbes.com/sites/gilpress/2016/03/23/data-preparation-most-time-consuming-least-enjoyable-data-science-task-survey-says/?sh=67e543e86f63), it accounts for about 80% of the work of ...
github_jupyter
# TensorFlow Fold Quick Start TensorFlow Fold is a library for turning complicated Python data structures into TensorFlow Tensors. ``` # boilerplate import random import tensorflow as tf sess = tf.InteractiveSession() import tensorflow_fold as td ``` The basic elements of Fold are *blocks*. We'll start with some blo...
github_jupyter
<table class="ee-notebook-buttons" align="left"> <td><a target="_blank" href="https://github.com/giswqs/earthengine-py-notebooks/tree/master/Image/connected_pixel_count.ipynb"><img width=32px src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" /> View source on GitHub</a></td> <td><a target="_blank" ...
github_jupyter
# Experimental Mathimatics: Chronicle of Matlab code - 2008 - 2015 ##### Whereas the discovery of Chaos, Fractal Geometry and Non-Linear Dynamical Systems falls outside the domain of analytic function in mathematical terms the path to discovery is taken as experimental computer-programming. ##### Whereas existing di...
github_jupyter
<a href="https://colab.research.google.com/github/DJCordhose/ux-by-tfjs/blob/master/notebooks/click-sequence-model.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # Training on Sequences of Clicks on the Server Make sure to run this from top to bot...
github_jupyter
### Introduction This is an instruction set for running SQUID simulations using a handful of packages writen in python 3. Each package is created around a SQUID model and includes a solver and some utilities to use the solver indirectly to produce more complicated output. This tutorial will walk through using the **n...
github_jupyter
# Week 2: Tackle Overfitting with Data Augmentation Welcome to this assignment! As in the previous week, you will be using the famous `cats vs dogs` dataset to train a model that can classify images of dogs from images of cats. For this, you will create your own Convolutional Neural Network in Tensorflow and leverage ...
github_jupyter
**Author**: _Pradip Kumar Das_ **License:** https://github.com/PradipKumarDas/Competitions/blob/main/LICENSE **Profile & Contact:** [LinkedIn](https://www.linkedin.com/in/daspradipkumar/) | [GitHub](https://github.com/PradipKumarDas) | [Kaggle](https://www.kaggle.com/pradipkumardas) | pradipkumardas@hotmail.com (Emai...
github_jupyter
# SESSIONS ARE ALL YOU NEED ### Workshop on e-commerce personalization This notebook showcases with working code the main ideas of our ML-in-retail workshop from June lst, 2021 at MICES (https://mices.co/). Please refer to the README in the repo for a bit of context! While the code below is (well, should be!) fully f...
github_jupyter
We sometimes want to know where a value is in an array. ``` import numpy as np ``` By "where" we mean, which element contains a particular value. Here is an array. ``` arr = np.array([2, 99, -1, 4, 99]) arr ``` As you know, we can get element using their *index* in the array. In Python, array indices start at zer...
github_jupyter
``` # from utils import * import tensorflow as tf import os import sklearn.datasets import numpy as np import re import collections import random from sklearn import metrics import jieba # 写入停用词 with open(r'stopwords.txt','r',encoding='utf-8') as f: english_stopwords = f.read().split('\n') def separate_dataset(trai...
github_jupyter
# Base dos dados Base dos Dados is a Brazilian project of consolidation of datasets in a common repository with easy to follow codes. Download *clean, integrated and updated* datasets in an easy way through SQL, Python, R or CLI (Stata in development). With Base dos Dados you have freedom to: - download whole tables...
github_jupyter
##### Copyright 2018 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
## MIDI Generator ``` ## Uncomment command below to kill current job: #!neuro kill $(hostname) import random import sys import subprocess import torch sys.path.append('../midi-generator') %load_ext autoreload %autoreload 2 import IPython.display as ipd from model.dataset import MidiDataset from utils.load_model imp...
github_jupyter
# Sandbox - Tutorial ## Building a fiber bundle A [fiber bundle](https://github.com/3d-pli/fastpli/wiki/FiberModel) consit out of multiple individual nerve fibers. A fiber bundle is a list of fibers, where fibers are represented as `(n,4)-np.array`. This makes desining individually fiber of any shape possible. Howev...
github_jupyter
# Effect of House Characteristics on Their Prices ## by Lubomir Straka ## Investigation Overview In this investigation, I wanted to look at the key characteristics of houses that could be used to predict their prices. The main focus was on three aspects: above grade living area representing space characteristics, ov...
github_jupyter
``` import pickle with open('ldaseq1234.pickle', 'rb') as f: ldaseq = pickle.load(f) print(ldaseq.print_topic_times(topic=0)) topicdis = [[0.04461942257217848, 0.08583100499534332, 0.0327237321141309, 0.0378249089831513, 0.08521717043434086, 0.03543307086614173, 0.054356108712217424, 0.04057658115...
github_jupyter
``` %load_ext notexbook %texify ``` # PyTorch `nn` package ### `torch.nn` Computational graphs and autograd are a very powerful paradigm for defining complex operators and automatically taking derivatives; however for large neural networks raw autograd can be a bit too low-level. When building neural networks we fr...
github_jupyter
## 13.2 유가증권시장 12개월 모멘텀 최근 투자 기간 기준으로 12개월 모멘텀 계산 날짜 구하기 ``` from pykrx import stock import FinanceDataReader as fdr df = fdr.DataReader(symbol='KS11', start="2019-11") start = df.loc["2019-11"] end = df.loc["2020-09"] df.loc["2020-11"].head() start start_date = start.index[0] end_date = end.index[-1] print(start_dat...
github_jupyter
``` import numpy import pandas as pd import sqlite3 import os from pandas.io import sql from tables import * import re import pysam import matplotlib import matplotlib.image as mpimg import seaborn import matplotlib.pyplot %matplotlib inline def vectorizeSequence(seq): # the order of the letters is not arbitrary. ...
github_jupyter
The following latitude and longitude formats are supported by the `output_format` parameter: * Decimal degrees (dd): 41.5 * Decimal degrees hemisphere (ddh): "41.5° N" * Degrees minutes (dm): "41° 30′ N" * Degrees minutes seconds (dms): "41° 30′ 0″ N" You can split a column of geographic coordinates into one column f...
github_jupyter
<h2> 25ppm - somehow more features detected than at 4ppm... I guess because more likely to pass over the #scans needed to define a feature </h2> Enough retcor groups, loads of peak insertion problem (1000's). Does that mean data isn't centroided...? ``` import time import pandas as pd import seaborn as sns import mat...
github_jupyter
<h1>REGIONE CAMPANIA</h1> Confronto dei dati relativi ai decessi registrati dall'ISTAT e i decessi causa COVID-19 registrati dalla Protezione Civile Italiana con i decessi previsti dal modello predittivo SARIMA. <h2>DECESSI MENSILI REGIONE CAMPANIA ISTAT</h2> Il DataFrame contiene i dati relativi ai decessi mensili ...
github_jupyter
## 1. Inspecting transfusion.data file <p><img src="https://assets.datacamp.com/production/project_646/img/blood_donation.png" style="float: right;" alt="A pictogram of a blood bag with blood donation written in it" width="200"></p> <p>Blood transfusion saves lives - from replacing lost blood during major surgery or a ...
github_jupyter
# A Table based Q-Learning Reinforcement Agent in A Grid World This is a simple example of a Q-Learning agent. The Q function is a table, and each decision is made by sampling the Q-values for a particular state thermally. ``` import numpy as np import random import gym %matplotlib inline %config InlineBackend.figur...
github_jupyter
# Binary classification with Support Vector Machines (SVM) ``` %matplotlib inline import numpy as np import matplotlib.pyplot as plt import ipywidgets as widgets from sklearn.linear_model import LogisticRegression from sklearn.svm import LinearSVC, SVC from ipywidgets import interact, interactive, fixed from numpy.ran...
github_jupyter
We saw in this [journal entry](http://wiki.noahbrenowitz.com/doku.php?id=journal:2018-10:day-2018-10-24#run_110) that multiple-step trained neural network gives a very imbalanced estimate, but the two-step trained neural network gives a good answer. Where do these two patterns disagree? ``` %matplotlib inline import m...
github_jupyter
# ACS Download ## ACS TOOL STEP 1 -> SETUP : #### Uses: csa2tractcrosswalk.csv, VitalSignsCensus_ACS_Tables.xlsx #### Creates: ./AcsDataRaw/ ./AcsDataClean/ ### Import Modules & Construct Path Handlers ``` import os import sys import pandas as pd pd.set_option('display.expand_frame_repr', False) pd.set_option('...
github_jupyter
# Logarithmic Regularization: Dataset 1 ``` # Import libraries and modules import numpy as np import pandas as pd import xgboost as xgb from xgboost import plot_tree from sklearn.metrics import r2_score, classification_report, confusion_matrix, \ roc_curve, roc_auc_score, plot_c...
github_jupyter
<img src="logos/Icos_cp_Logo_RGB.svg" align="right" width="400"> <br clear="all" /> # Visualization of average footprints For questions and feedback contact ida.storm@nateko.lu.se To use the tool, <span style="background-color: #FFFF00">run all the Notebook cells</span> (see image below). <img src="network_charac...
github_jupyter
``` Copyright 2021 IBM Corporation 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 http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, softwa...
github_jupyter
``` import pandas as pd import numpy as np import scanpy as sc import os from sklearn.cluster import KMeans from sklearn.cluster import AgglomerativeClustering from sklearn.metrics.cluster import adjusted_rand_score from sklearn.metrics.cluster import adjusted_mutual_info_score from sklearn.metrics.cluster import homog...
github_jupyter
# Analytic center computation using a infeasible start Newton method # The set-up ``` import numpy as np import pandas as pd import accpm import accpm from IPython.display import display %load_ext autoreload %autoreload 1 %aimport accpm ``` $\DeclareMathOperator{\domain}{dom} \newcommand{\transpose}{\text{T}} \newco...
github_jupyter
``` import fluentpy as _ ``` These are solutions for the Advent of Code puzzles of 2018 in the hopes that this might inspire the reader how to use the fluentpy api to solve problems. See https://adventofcode.com/2018/ for the problems. The goal of this is not to produce minimal code or neccessarily to be as clear as...
github_jupyter