code stringlengths 2.5k 150k | kind stringclasses 1
value |
|---|---|
# Analyzing data with Pandas
First a little setup. Importing the pandas library as ```pd```
```
import pandas as pd
```
Set some helpful display options. Uncomment the boilerplate in this cell.
```
%matplotlib inline
pd.set_option("max_columns", 150)
pd.set_option('max_colwidth',40)
pd.options.display.float_format ... | github_jupyter |
<div>
<img src="https://drive.google.com/uc?export=view&id=1vK33e_EqaHgBHcbRV_m38hx6IkG0blK_" width="350"/>
</div>
#**Artificial Intelligence - MSc**
##CS6462 - PROBABILISTIC AND EXPLAINABLE AI
###CS6462_Etivity_1a
###Author: Enrique Naredo
##Rolling a Die
Code in the cells are only hints and you must verify it... | github_jupyter |
```
import requests
from matplotlib import pyplot as plt
from bs4 import BeautifulSoup
def gasoline_price():
"""Gets current gasoline price in Swedish Krona"""
try:
page = requests.get('https://www.globalpetrolprices.com/Sweden/gasoline_prices/')
soup = BeautifulSoup(page.content, 'html.parser')... | github_jupyter |
## Face and Facial Keypoint detection
After you've trained a neural network to detect facial keypoints, you can then apply this network to *any* image that includes faces. The neural network expects a Tensor of a certain size as input and, so, to detect any face, you'll first have to do some pre-processing.
1. Detect... | github_jupyter |
# K-Naive Bayes
code by xbwei, adapted for use by daviscj & mathi2ma.
## Import and Prepare the Data
[pandas](https://pandas.pydata.org/) provides excellent data reading and querying module,[dataframe](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html), which allows you to import structure... | github_jupyter |
```
import numpy as np
import functools
from sklearn.base import BaseEstimator, ClusterMixin, TransformerMixin
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.svm import SVC
from clustering_by_classif... | github_jupyter |
```
library(caret, quiet=TRUE);
library(base64enc)
library(httr, quiet=TRUE)
```
# Build a Model
```
set.seed(1960)
create_model = function() {
model <- train(Species ~ ., data = iris, method = "ctree2")
return(model)
}
# dataset
model = create_model()
# pred <- predict(model, as.matrix(iris[, -5]) ... | github_jupyter |
<a href="https://colab.research.google.com/github/ferdouszislam/pytorch-practice/blob/main/cnn_cifar10.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
```
import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transf... | github_jupyter |
# Python Data Types and Markdown
This tutorial covers the very basics of Python and Markdown.
> Because this file is saved on GitHub, you should feel free to change whatever you want in this file and even try to break it. Breaking code and then trying to fix it again is a fantastic way to learn how code works—AS LONG... | github_jupyter |
<a href="https://colab.research.google.com/github/cocoisland/DS-Unit-1-Sprint-4-Statistical-Tests-and-Experiments/blob/master/module2-sampling-confidence-intervals-and-hypothesis-testing/LS_DS_142_Sampling_Confidence_Intervals_and_Hypothesis_Testing.ipynb" target="_parent"><img src="https://colab.research.google.com/as... | github_jupyter |
# Predicting NYC Taxi Fares with RAPIDS
Process 380 million rides in NYC from 2015-2017.
RAPIDS is a suite of GPU accelerated data science libraries with APIs that should be familiar to users of Pandas, Dask, and Scikitlearn.
This notebook focuses on showing how to use cuDF with Dask & XGBoost to scale GPU DataFrame ... | github_jupyter |
<img align="left" src="https://lever-client-logos.s3.amazonaws.com/864372b1-534c-480e-acd5-9711f850815c-1524247202159.png" width=200>
<br></br>
<br></br>
## *Data Science Unit 4 Sprint 3 Assignment 1*
# Recurrent Neural Networks and Long Short Term Memory (LSTM)
 this page as a jupyterlab notebook from: [Lab24](http://54.243.252.9/engr-1330-webroot/8-Labs/Lab24/Lab24.ipynb)
___
# <font color=green>Laboratory 24:... | github_jupyter |
# Instructor Turn Get Home Tweets
```
!pip install tweepy
# Dependencies
import json
import tweepy
# Import Twitter API Keys
from config import consumer_key, consumer_secret, access_token, access_token_secret
# Setup Tweepy API Authentication
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_to... | github_jupyter |
```
#importing modules
import os
import codecs
import numpy as np
import string
import pandas as pd
```
# **Data Preprocessing**
```
#downloading and extracting the files on colab server
import urllib.request
urllib.request.urlretrieve ("https://archive.ics.uci.edu/ml/machine-learning-databases/20newsgroups-mld/20_ne... | github_jupyter |
# 예외 처리
It is likely that you have raised Exceptions if you have
typed all the previous commands of the tutorial. For example, you may
have raised an exception if you entered a command with a typo.
Exceptions are raised by different kinds of errors arising when executing
Python code. In your own code, you may also ca... | 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 |
# Convolutional Neural Networks
---
In this notebook, we train a **CNN** to classify images from the CIFAR-10 database.
The images in this database are small color images that fall into one of ten classes; some example images are pictured below.
<img src='notebook_ims/cifar_data.png' width=70% height=70% />
### Test... | github_jupyter |
```
```
# INTRODUCTION TO UNSUPERVISED LEARNING
Unsupervised learning is the training of a machine using information that is neither classified nor labeled and allowing the algorithm to act on that information without guidance. Here the task of the machine is to group unsorted information according to similarit... | github_jupyter |
# Perceptron
__The Perceptron is a linear machine learning algorithm for binary classification tasks.__
It may be considered one of the first and one of the simplest types of artificial neural networks. It is definitely not “deep” learning but is an important building block.
Like logistic regression, it can quickly ... | github_jupyter |
```
%load_ext rpy2.ipython
%matplotlib inline
from fbprophet import Prophet
import pandas as pd
from matplotlib import pyplot as plt
import logging
logging.getLogger('fbprophet').setLevel(logging.ERROR)
import warnings
warnings.filterwarnings("ignore")
df = pd.read_csv('../examples/example_wp_log_peyton_manning.csv')
m... | github_jupyter |
### Demonstration of `flopy.utils.get_transmissivities` method
for computing open interval transmissivities (for weighted averages of heads or fluxes)
In practice this method might be used to:
* compute vertically-averaged head target values representative of observation wells of varying open intervals (including va... | github_jupyter |
```
import pandas as pd
import warnings
warnings.filterwarnings('ignore')
# Dependencies for interaction with database:
from sqlalchemy import create_engine
from sqlalchemy.orm import Session
# Machine Learning dependencies:
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import StandardSca... | 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 |
```
import math
import numpy as np
import pandas as pd
```
### Initial conditions
```
initial_rating = 400
k = 100
things = ['Malted Milk','Rich Tea','Hobnob','Digestive']
```
### Elo Algos
```
def expected_win(r1, r2):
"""
Expected probability of player 1 beating player 2
if player 1 has rating 1 (r1)... | github_jupyter |
##### 1. Dates (사건일자)
: timestamp of the crime incident
##### 2. Category (범죄유형 - 종속변수)
: category of the crime incident (only in train.csv). This is the target variable you are going to predict.
##### 3. Descript (범죄 세부정보)
: detailed description of the crime incident (only in train.csv)
##### 4. DayOfWeek (요일)
: the d... | github_jupyter |
# Low level API
## Prerequisites
- Understanding the gammapy data workflow, in particular what are DL3 events and instrument response functions (IRF).
- Understanding of the data reduction and modeling fitting process as shown in the [analysis with the high level interface tutorial](analysis_1.ipynb)
## Context
Thi... | github_jupyter |
# Benchmark FRESA.CAD BSWIMS final Script
This algorithm implementation uses R code and a Python library (rpy2) to connect with it, in order to run the following it is necesary to have installed both on your computer:
- R (you can download in https://www.r-project.org/) <br>
- install rpy2 by <code> pip install rpy2... | github_jupyter |
This notebook contains an implementation of the third place result in the Rossman Kaggle competition as detailed in Guo/Berkhahn's [Entity Embeddings of Categorical Variables](https://arxiv.org/abs/1604.06737).
The motivation behind exploring this architecture is it's relevance to real-world application. Much of our f... | github_jupyter |
```
from math import inf
from collections import Counter
from collections import OrderedDict
```
# 1.Codigo de norving
```
"""
Spelling Corrector in Python 3; see http://norvig.com/spell-correct.html
Copyright (c) 2007-2016 Peter Norvig
MIT license: www.opensource.org/licenses/mit-license.php
"""
#######... | github_jupyter |
<a href="https://colab.research.google.com/github/sokrypton/ColabFold/blob/main/verbose/alphafold_noTemplates_noMD.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
#AlphaFold
```
#################
# WARNING
#################
# - This notebook is in... | github_jupyter |
```
# default_exp first_steps
```
# First Steps
> API details.
```
#hide
from nbdev.showdoc import *
import os
os.listdir("/home/alois")
os.walk("$HOME")
for item in os.walk(("$HOME")):
print(item)
```
Apparently this does not work. So use the next try:
```
from os import listdir
from os.path import isfile, j... | github_jupyter |
# Data Structures
## Pandas
```
import pandas as pd
```
### Preparation
```
# create dataframe with specific column names
corpus_df = pd.DataFrame(columns=['id', 'userurl', 'source', 'title', 'description', 'content', 'keywords'])
# append one row, fill by column name
corpus_df = corpus_df.append(
... | github_jupyter |
# Fancy Indexing
In the previous sections, we saw how to access and modify portions of arrays using simple indices `(arr[0])`, `slices(arr[:5])`, and Boolean masks `(arr[arr > 0])`. In this section, we'll llok at another style of array indexing, known as *fancy indexing*. Fancy indexing islike the simple indexing we'v... | github_jupyter |
# mlrose Tutorial Examples - Genevieve Hayes
## Overview
mlrose is a Python package for applying some of the most common randomized optimization and search algorithms to a range of different optimization problems, over both discrete- and continuous-valued parameter spaces. This notebook contains the examples used in ... | github_jupyter |
```
import os
import numpy as np
import tensorflow.keras as keras
from sklearn.metrics import roc_auc_score
import matplotlib.pyplot as plt
import pickle
from tqdm.notebook import tqdm
import pandas as pd
import seaborn as sns
from src.models.train_model import MonteCarloDropout, MCLSTM
model_name = r"merged-ce-mc.h5"
... | github_jupyter |
#### Copyright 2018 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 writin... | github_jupyter |
<!--NAVIGATION-->
_______________
Este documento puede ser utilizado de forma interactiva en las siguientes plataformas:
- [Google Colab](https://colab.research.google.com/github/masdeseiscaracteres/ml_course/blob/master/material/05_random_forests.ipynb)
- [MyBinder](https://mybinder.org/v2/gh/masdeseiscaracteres/ml... | github_jupyter |
```
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
% matplotlib inline
```
### Loading Training Transactions Data
```
tr_tr = pd.read_csv('data/train_transaction.csv', index_col='TransactionID')
print('Rows :', tr_tr.shape[0],' Columns : ',tr_tr.shape... | github_jupyter |
```
midifile = 'data/chopin-fantaisie.mid'
import time
import copy
import subprocess
from abc import abstractmethod
import numpy as np
import midi # Midi file parser
from midipattern import MidiPattern
from distorter import *
from align import align_frame_to_frame, read_align, write_align
MidiPattern.MIDI_DEVICE = 2
... | github_jupyter |
# SciPy를 이용한 최적화
- fun: 2.0
hess_inv: array([[ 0.5]])
jac: array([ 0.])
message: 'Optimization terminated successfully.'
nfev: 9 # SciPy는 Sympy가 아니라서, Symbolic을 활용하지 못하기에 수치 미분을 함 - 1위치에서 3번 계산됨 nit가 2 이라는거는 2번 뛰엇나느 것이며, 3곳에서 9번함수를돌림..
nit: 2
njev: 3
status: 0
success: True
x: ... | github_jupyter |
[Table of Contents](./table_of_contents.ipynb)
# Probabilities, Gaussians, and Bayes' Theorem
```
from __future__ import division, print_function
%matplotlib inline
#format the book
import book_format
book_format.set_style()
```
## Introduction
The last chapter ended by discussing some of the drawbacks of the Discr... | github_jupyter |
```
%load_ext autotime
import os
from bs4 import BeautifulSoup
import urllib
import urllib.request
import requests
folder_path = os.getcwd()
# data-tags are the tags used for explaining the conditions of using the
# content in the weblink
file_name = '\\data_tags.txt'
file_path = folder_path + file_name
url_link = in... | github_jupyter |
# 1- Business Understanding
The aim of this notebook is to create a model that will be able to find out which users might buy a product after seeing a promotion, have a targeted marketing campain, and thus, make more profits.
We should understand the features V1 through V7 without knowing what does each feature induc... | 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 |
```
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
import math as m
%matplotlib inline
import torch
import torchvision
import torchvision.transforms as transforms
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import random
from torch.utils.data import... | github_jupyter |
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License.

# Reinforcement Learning in A... | github_jupyter |
```
import csv
import tensorflow as tf
import numpy as np
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
!wget --no-check-certificate \
https://storage.googleapis.com/laurencemoroney-blog.appspot.com/bbc-text.csv \
-O /tmp/bbc-text.cs... | github_jupyter |
# Libraries and setup variables
```
from IPython.core.display import display, HTML
display(HTML("<style>.container { width:100% !important; }</style>"))
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from utils import *
%matplotlib inline
sns.set()
```
### Loading the ... | github_jupyter |
# Learning to play connect 4 using minimax Deep Q-learning
In this notebook we will train a reinforcement learning (RL) agent using minimax deep Q-learning on a classic game: Connect 4.
In Connect 4, your objective is to get 4 of your checkers in a row horizontally, vertically, or diagonally on the game board before ... | github_jupyter |
<a href="https://colab.research.google.com/github/NeuromatchAcademy/course-content-dl/blob/main/tutorials/W1D2_LinearDeepLearning/student/W1D2_Tutorial3.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# Tutorial 3: Deep linear neural networks
**Week... | github_jupyter |
# Credit Corp's Consumer Lending Segment
Note: All numbers are in the form of $'000 unless otherwise stated
Let's import some libraries first...
```
import pandas
from pandas.plotting import scatter_matrix
from sklearn import datasets
from sklearn import model_selection
from sklearn import linear_model
# models
fr... | 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 numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.metrics import confusion_matrix
fashion_mnist = tf.keras.datasets.fashion_mnist
(X_train_full, y_train_full), (X_test, y_test) = fashion_mnist.load_data()
plt.figure()
for k in range(9):
plt.subplot(3,3,k... | github_jupyter |
# Learning Tree-augmented Naive Bayes (TAN) Structure from Data
In this notebook, we show an example for learning the structure of a Bayesian Network using the TAN algorithm. We will first build a model to generate some data and then attempt to learn the model's graph structure back from the generated data.
For comp... | github_jupyter |
**This notebook is an exercise in the [Intermediate Machine Learning](https://www.kaggle.com/learn/intermediate-machine-learning) course. You can reference the tutorial at [this link](https://www.kaggle.com/alexisbcook/introduction).**
---
As a warm-up, you'll review some machine learning fundamentals and submit you... | github_jupyter |
<a href="https://colab.research.google.com/github/magenta/ddsp/blob/master/ddsp/colab/demos/timbre_transfer.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
##### Copyright 2020 Google LLC.
Licensed under the Apache License, Version 2.0 (the "Licens... | github_jupyter |
# Підручник: Основні засоби приватного глибинного навчання
Ласкаво просимо до вступного підручника PySyft щодо збереження конфіденційності, децентралізованого глибинного навчання. Ця серія зошитів - покрокове керівництво для ознайомлення з новими інструментами та прийомами, необхідними для глибинного навчання на секре... | github_jupyter |
<img src="images/usm.jpg" width="480" height="240" align="left"/>
# MAT281 - Laboratorio N°06
## Objetivos de la clase
* Reforzar los conceptos básicos del E.D.A..
## Contenidos
* [Problema 01](#p1)
## Problema 01
<img src="./images/logo_iris.jpg" width="360" height="360" align="center"/>
El **Iris dataset** es ... | github_jupyter |
```
import pandas as pd
df_all = pd.read_csv("48648_88304_bundle_archive/alldata.csv")
df_all = df_all.loc[df_all['location'].notnull()]
df_all
df_all['location'] = [x.strip().split(',', maxsplit=1)[0] for x in df_all['location']]
df_all['location'].value_counts()[:10]
df_all_location_lat_lon = {
'New York':[40.71,... | github_jupyter |
```
import pandas as pd
import numpy as np
np.__version__
```
## Predicting diabetes using machine learning
```
# Import all the tools we need
# Regular EDA and plotting libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
# Models from Scikit... | github_jupyter |
# 2017 Open Data Day Hackathon at Mobile Web Ghana
### Open Tender Contracts Awarded by Ministry of Health
After investigating the dataset for this small project, I realised that the data wasn't scraped well. The dataset has many empty rows. This limited the scope of the project as it cannot answer all questions I ha... | github_jupyter |
```
import numpy as np
import copy
from sklearn import preprocessing
import tensorflow as tf
from tensorflow import keras
import os
import pandas as pd
from matplotlib import pyplot as plt
from numpy.random import seed
np.random.seed(2095)
data = pd.read_excel('Dataset/CardiacPrediction.xlsx')
data.drop(['SEQN','Annual... | github_jupyter |
# Summarization with blurr
> blurr is a libray I started that integrates huggingface transformers with the world of fastai v2, giving fastai devs everything they need to train, evaluate, and deploy transformer specific models. In this article, I provide a simple example of how to use blurr's new summarization capabili... | github_jupyter |
# Importing libraries
```
import nltk
import glob
import os
import numpy as np
import string
import pickle
from gensim.models import Doc2Vec
from gensim.models.doc2vec import LabeledSentence
from tqdm import tqdm
from sklearn import utils
from sklearn.svm import LinearSVC
from sklearn.neural_network import MLPClassifi... | github_jupyter |
# Lab 2: Object-Oriented Python
## Overview
After have covered rules, definitions, and semantics, we'll be playing around with actual classes, writing a fair chunk of code and building several classes to solve a variety of problems.
Recall our starting definitions:
- An *object* has identity
- A *name* is a referen... | github_jupyter |
## KITTI Object Detection finetuning
### This notebook is used to lunch the finetuning of FPN on KITTI object detection benchmark, the code fetches COCO weights for weight initialization
```
data_path = "../datasets/KITTI/data_object_image_2/training"
import detectron2
from detectron2.utils.logger import setup_logger
... | github_jupyter |
# SP LIME
## Regression explainer with boston housing prices dataset
```
from sklearn.datasets import load_boston
import sklearn.ensemble
import sklearn.linear_model
import sklearn.model_selection
import numpy as np
from sklearn.metrics import r2_score
np.random.seed(1)
#load example dataset
boston = load_boston()
... | github_jupyter |
## Dependencies
```
import random, os, warnings, math, glob
import numpy as np
import pandas as pd
import tensorflow as tf
import tensorflow.keras.layers as L
import tensorflow.keras.backend as K
from tensorflow.keras import Model
from transformers import TFAutoModelForSequenceClassification, TFAutoModel, AutoTokenize... | github_jupyter |
**This notebook is an exercise in the [Feature Engineering](https://www.kaggle.com/learn/feature-engineering) course. You can reference the tutorial at [this link](https://www.kaggle.com/ryanholbrook/target-encoding).**
---
# Introduction #
In this exercise, you'll apply target encoding to features in the [*Ames*](... | github_jupyter |
# Practice: Basic Statistics I: Averages
For this practice, let's use the Boston dataset.
```
# Import the numpy package so that we can use the method mean to calculate averages
import numpy as np
# Import the load_boston method
from sklearn.datasets import load_boston
# Import pandas, so that we can work with the d... | github_jupyter |
## Homework: Multilingual Embedding-based Machine Translation (7 points)
**In this homework** **<font color='red'>YOU</font>** will make machine translation system without using parallel corpora, alignment, attention, 100500 depth super-cool recurrent neural network and all that kind superstuff.
But even without para... | github_jupyter |
# 第2章 スカラー移流方程式(数値計算法の基礎)
## 2.2 [3] 空間微分項に対する1次精度風上差分の利用
```
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
```
(1) $\Delta t = 0.05, \Delta x = 0.1$
初期化
```
c = 1
dt = 0.05
dx = 0.1
jmax = 21
nmax = 6
x = np.linspace(0, dx * (jmax - 1), jmax)
q = np.zeros(jmax)
for j in range(jmax):
... | github_jupyter |
```
from functools import wraps
import time
def show_args(function):
@wraps(function)
def wrapper(*args, **kwargs):
print('hi from decorator - args:')
print(args)
result = function(*args, **kwargs)
print('hi again from decorator - kwargs:')
print(kwargs)
retu... | github_jupyter |
```
import os
import sys
from pathlib import Path
import pandas as pd
import numpy as np
import torch as T
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import Dataset, DataLoader
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
%config InlineBackend.figure_form... | github_jupyter |
```
import nltk
from nltk import word_tokenize, pos_tag
from nltk.corpus import indian
X3= nltk.corpus.indian
X3_marathi_sent = X3.tagged_sents('marathi.pos')
marathi_numbers = [chr(0x0966), chr(0x0967), chr(0x0968), chr(0x0969), chr(0x096A),
chr(0x096B), chr(0x096C), chr(0x096D), chr(0x096E), chr(0... | github_jupyter |
### 實作簡單的乘法與加法層反向傳播
```
# coding: utf-8
class MulLayer:
def __init__(self):
self.x = None
self.y = None
def forward(self, x, y):
self.x = x
self.y = y
out = x * y
return out
def backward(self, dout):
dx = dout * self.y
dy =... | github_jupyter |
> # Using fast "kmc kmer counter" to create kmers and count them per sequence.
> ***
> kmc is an external tool (exe app) that needs to be downloaded.
> It is a very efficient tool for data preprocessing, famous in bio-informatics.
> * link to download https://github.com/refresh-bio/KMC
> ## Attention!
> The ***kme... | github_jupyter |
```
import pysam
import time
import pickle
import os
from collections import defaultdict
#==========================================================================================================
fa_folder = "/oak/stanford/groups/arend/Xin/AssemblyProj/reference_align_2/Software_Xin/Aquila/source" #The path of the... | github_jupyter |
```
%load_ext autoreload
%autoreload 2
import os
os.getcwd()
import sys, glob, shutil
os.chdir(os.path.dirname(os.getcwd()))
os.getcwd()
import cv2
import numpy as np
import matplotlib.pyplot as plt
import keras
import os
import time
import pickle
import tensorflow as tf
from src import models
from src.utils.image imp... | github_jupyter |
<a href="https://colab.research.google.com/github/yukinaga/object_detection/blob/main/section_3/03_exercise.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
# 演習
RetinaNetで、物体の領域を出力する`regression_head`も訓練対象に加えてみましょう。
モデルを構築するコードに、追記を行なってください。
## 各設... | github_jupyter |
```
from keras.datasets import mnist
import numpy as np
(x_train, _), (x_test, _) = mnist.load_data()
print(x_train.shape, x_test.shape)
# alternative reshape
x_train = x_train.astype('float32') / 255.
x_test = x_test.astype('float32') / 255.
x_train = np.reshape(x_train, (len(x_train), 28, 28, 1)) # adapt this if us... | github_jupyter |
<a href="https://colab.research.google.com/github/DannyML-DSC/Hash-analytics/blob/master/Pandas.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
```
#authenticatiopn script in gcp
!apt-get install -y -qq software-properties-common python-software-pro... | github_jupyter |
# ZSL target-shift: synthetic data generation
<br>
```
import pickle
import numpy as np
import os, sys
import csv
```
-----------
### Synthetic data generation.
```
num_feat = 5
num_attr = 2
cov_matrix = np.eye(num_feat) # a common cov mat for all distributions.
means = []
for i in range(num_attr):
x = np.rand... | github_jupyter |
```
#question 2
def add_chars(w1, w2):
"""
Return a string containing the characters you need to add to w1 to get w2.
You may assume that w1 is a subsequence of w2.
>>> add_chars("owl", "howl")
'h'
>>> add_chars("want", "wanton")
'on'
>>> add_chars("rat", "radiate")
'diae'
>>> ... | github_jupyter |
### Лекция 7. Исключения
https://en.cppreference.com/w/cpp/language/exceptions
https://en.cppreference.com/w/cpp/error
https://apprize.info/c/professional/13.html
<br />
##### Зачем нужны исключения
Для обработки исключительных ситуаций.
Как вариант - обработка ошибок.
<br />
###### Как пользоваться исключения... | github_jupyter |
```
# fundamentals
import os, sys
import numpy as np
import pandas as pd
from calendar import monthrange, month_name
import scipy.stats as stats
import datetime
import imp
import scipy.io as sio
import pickle as pkl
# plotting libraries and setup
from matplotlib.colors import BoundaryNorm
import matplotlib.pyplot as p... | github_jupyter |
```
import numpy as np
from sklearn.datasets import load_iris
# Loading the dataset
iris = load_iris()
X_raw = iris['data']
y_raw = iris['target']
# Isolate our examples for our labeled dataset.
n_labeled_examples = X_raw.shape[0]
training_indices = np.random.randint(low=0, high=len(X_raw)+1, size=3)
# Defining the ... | github_jupyter |
```
import collections
import pickle
import os
import numpy as np
import pandas as pd
import tensorflow as tf
tf.config.experimental.list_physical_devices('GPU')
```
# Utils
```
image_size=(54,128)
def savepickle(fname,*args):
with open(fname+"_pk","wb") as f:
pickle.dump(args,f)
def loadpickle... | github_jupyter |
```
import pandas as pd
import numpy as np
import os
from sklearn.metrics import mean_squared_error, mean_absolute_error
import matplotlib.pyplot as plt
import pickle
import random
import train
from model import NNModelEx
pd.set_option('display.max_columns', 999)
# For this model, the data preprocessing part is alread... | github_jupyter |
```
import numpy as np
import pandas as pd
from sklearn.preprocessing import LabelEncoder
import matplotlib.pyplot as plt
ir= pd.read_csv("C:\\Users\\dhima\\anaconda3\\6th Week\\Iris.csv")
ir1=ir.copy()
ir1
ir1.isnull().sum()
y_true=ir1['Species']
y_true
```
# Ques 1. Apply PCA and select first two directions to conv... | github_jupyter |
```
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline
credit_df = pd.read_csv('German Credit Data.csv')
credit_df
credit_df.info()
X_features = list(credit_df.columns)
X_features.remove('status')
X_features
encoded_df = pd.get_dummies(credit_df[X_features],d... | github_jupyter |
# Caculation of Barotropic Streamfunction
```
%matplotlib inline
import matplotlib.pyplot as plt
import cosima_cookbook as cc
from mpl_toolkits.basemap import Basemap, shiftgrid
import numpy as np
import pandas as pd
import netCDF4 as nc
from joblib import Memory
memory = Memory(cachedir='/g/data1/v45/cosima-cookbook... | github_jupyter |
# Comparing Training and Test and Parking and Sensor Datasets
```
import sys
import pandas as pd
import numpy as np
import datetime as dt
import time
import matplotlib.pyplot as plt
sys.path.append('../')
from common import reorder_street_block, process_sensor_dataframe, get_train, \
feat_eng, add_... | github_jupyter |
This notebook is part of the $\omega radlib$ documentation: https://docs.wradlib.org.
Copyright (c) $\omega radlib$ developers.
Distributed under the MIT License. See LICENSE.txt for more info.
# Export a dataset in GIS-compatible format
In this notebook, we demonstrate how to export a gridded dataset in GeoTIFF and... | github_jupyter |
# FAO Economic and Employment Stats
Two widgets for the 'People' tab.
- No of people employed full time (```forempl``` x 1000)
- ...of which are female (```femempl``` x 1000)
- Net USD generate by forest ({```usdrev``` - ```usdexp```} x 1000)
- GDP in USD in 2012 (```gdpusd2012``` x 1000) **NOTE: GDP in year=9999**
... | github_jupyter |
<a href="https://colab.research.google.com/github/African-Quant/FOREX_RelativeStrengthOscillator/blob/main/Oanda_RelativeStrength_NJ.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a>
```
#@title Installation
!pip install git+https://github.com/yhilpis... | github_jupyter |
```
import numpy as np
import tensorflow as tf
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score
import json
import pickle
from sklearn.externals import joblib
import sys
sys.path.append('../src/')
from TFExpMachine import TFExpMachine, simple_batcher
```
# Load data (see m... | github_jupyter |
```
pip install holidays
import numpy as np
import pandas as pd
import seaborn as sns
import datetime
import ast
import holidays
def load_dataset():
df = pd.read_csv('https://drive.google.com/uc?id=1XzXWsdWV_w95wyCrzaMQT3T-8X6hoAEE',dtype='unicode')
return df
```
Columns to be dropped:
1. belongs_to_collection
2... | github_jupyter |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.