code
stringlengths
2.5k
150k
kind
stringclasses
1 value
# 基于Tensorflow的softmax回归 Tensorflow是近年来非常非常流行的一个分布式的机器学习框架,之前一直想学习但是一直被各种各样的事情耽搁着。这学期恰好选了“人工神经网络”这门课,不得不接触这个框架了。最开始依照书上的教程通过Anaconda来配置环境,安装tensorflow。结果tensorflow是安装好了但是用起来是真麻烦。最后卸载了Anaconda在裸机上用`pip install tensorflow`来安装,可是裸机上的python是3.6.3版本的,似乎不支持tensorflow,于是在电脑上安装了另一个版本的python才算解决了这个问题,哎!说多了都是泪。言归正传,现在通过一个softma...
github_jupyter
# Functional Python ## BProf Python course ### June 25-29, 2018 #### Judit Ács Python has 3 built-in functions that originate from functional programming. ## Map - `map` applies a function on each element of a sequence ``` def double(e): return e * 2 l = [2, 3, "abc"] list(map(double, l)) map(double, l) %%...
github_jupyter
``` #r "nuget:Microsoft.ML,1.4.0" #r "nuget:Microsoft.ML.AutoML,0.16.0" #r "nuget:Microsoft.Data.Analysis,0.1.0" using Microsoft.Data.Analysis; using XPlot.Plotly; using Microsoft.AspNetCore.Html; Formatter<DataFrame>.Register((df, writer) => { var headers = new List<IHtmlContent>(); headers.Add(th(i("index")))...
github_jupyter
# Matching Registry and PA State Business License Data ``` import pandas as pd import mwdsbe import mwdsbe.datasets.licenses as licenses import schuylkill as skool import time def drop_duplicates_by_date(df, date_column): df.sort_values(by=date_column, ascending=False, inplace=True) df = df.loc[~df.index.dupli...
github_jupyter
``` import pandas as pd from datetime import datetime, timedelta import pickle start_date = datetime(2018, 10, 16, 0, 0, 0) end_date = datetime(2018, 12, 31, 0, 0, 0) num_days = (end_date - start_date).days + 1 dfs = pd.DataFrame(index=range(num_days)) entries = [] for d in range(num_days): day = start_date + tim...
github_jupyter
``` import sys import gym import numpy as np import random import math from collections import defaultdict, deque import matplotlib.pyplot as plt %matplotlib inline import check_test from plot_utils import plot_values #create an instance of CliffWalking environment env = gym.make('CliffWalking-v0') print("Actions_spac...
github_jupyter
# *bienvenue sur notre page qui presentera la fonction traiter des differents suports robotiques mindstorm* ![lego1](img\lego1.jpg "lego mindstorm") ### Ici vous trouverez toute les information sur les briques de controle des lego Mindstorm EV3. la brique de controlle du EV3 est un mini aurdinateur sous linux avec u...
github_jupyter
``` import cv2 import numpy as np import os import math from scipy.spatial import distance as dist from collections import OrderedDict from scipy.optimize import linear_sum_assignment from kalman_utils.KFilter import * from filterpy.kalman import KalmanFilter, UnscentedKalmanFilter, MerweScaledSigmaPoints from filterpy...
github_jupyter
Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. ![Impressions](https://PixelServer20190423114238.azurewebsites.net/api/impressions/MachineLearningNotebooks/how-to-use-azureml/machine-learning-pipelines/intro-to-pipelines/aml-pipelines-publish-and-run-using-rest-endpoint.png)...
github_jupyter
## LIDAR to 2D grid map example This simple tutorial shows how to read LIDAR (range) measurements from a file and convert it to occupancy grid. Occupancy grid maps (_Hans Moravec, A.E. Elfes: High resolution maps from wide angle sonar, Proc. IEEE Int. Conf. Robotics Autom. (1985)_) are a popular, probabilistic approa...
github_jupyter
<a href="https://colab.research.google.com/github/DebjitHore/Complete-Data-Structures-and-Algorithms-in-Python/blob/main/Recursion_Udemy.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> Recursion- A way of solving a problem by having a function call ...
github_jupyter
# Settings/scenario management Capacity expansion modeling is often an exercise in exploring the difference between different technical, cost, or policy scenarios across a range of planning years, so PowerGenome has a built-in method for creating modified versions of a single baseline scenario. Within the settings fil...
github_jupyter
``` import pandas as pd import matplotlib.pyplot as plt import numpy as np import statistics import math from sklearn.linear_model import LinearRegression from scipy.optimize import curve_fit er_cas_100_data = pd.read_csv('proc_er_cas_100.csv') del er_cas_100_data['Unnamed: 0'] er_500_50_0012 = pd.read_csv('proc_er_5...
github_jupyter
``` from pymongo import MongoClient import pandas as pd import datetime client = MongoClient() characters = client.ck2.characters ``` This notebook tries to build a world tree by drawing and edge between every character in the save file with their father and mother. Running this code will generate a network with over ...
github_jupyter
# Pythonの基礎 ## データ型 ``` # [変数名] = [値] と書くと,その変数名を持った変数に値を代入できる.代入された値は後で利用したりすることができる. x = 1 # 整数 y = 2.1 # 実数 z = 2 * x + y # 四則演算 (×→*, ÷→/) print(z) # print(x)でxを表示.print(x, y, ...)ともかけて,xとyにスペースが入って出力される str1 = "これは文字列" str2 = 'これも文字列' str3 = """ このように書くと 複数行に渡る文字列 を表現できる """ str4 = ''' こちらでも 良い ''' str5 = str1 ...
github_jupyter
``` import numpy as np import itertools import math import scipy import matplotlib.pyplot as plt import matplotlib import matplotlib.patches as patches from matplotlib import animation from matplotlib import transforms from mpl_toolkits.axes_grid1 import make_axes_locatable import xarray as xr import dask from sklearn....
github_jupyter
``` # General from os import path from random import randrange from sklearn.model_selection import train_test_split, GridSearchCV #cross validation from sklearn.metrics import confusion_matrix, plot_confusion_matrix, make_scorer from sklearn.metrics import accuracy_score, roc_auc_score, balanced_accuracy_score from s...
github_jupyter
<img src="../../../images/qiskit_header.png" alt="Note: In order for images to show up in this jupyter notebook you need to select File => Trusted Notebook" align="middle"> # Accreditation protocol Accreditation Protocol (AP) is a protocol devised to characterize the reliability of noisy quantum devices.<br> Given a...
github_jupyter
# **Behavioral Cloning** --- **Behavioral Cloning Project** The goals / steps of this project are the following: * Use the simulator to collect data of good driving behavior * Build, a convolution neural network in Keras that predicts steering angles from images * Train and validate the model with a training and val...
github_jupyter
<a href="https://colab.research.google.com/github/ashraj98/rbf-sin-approx/blob/main/Lab2.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # Lab 2 ### Ashwin Rajgopal Start off by importing numpy for matrix math, random for random ordering of sample...
github_jupyter
``` import csv import numpy as np posts = [] path = 'data/Constraint_Train.csv' num_long_posts = 0 num_real = 0 with open(path, newline='', encoding='utf-8') as csvfile: spamreader = csv.reader(csvfile, delimiter=',', quotechar='\"') spamreader.__next__() # Skip header row for row in spamreader: ...
github_jupyter
To finish, check out: http://articles.adsabs.harvard.edu/cgi-bin/nph-iarticle_query?1992AJ....104.2213L&amp;data_type=PDF_HIGH&amp;whole_paper=YES&amp;type=PRINTER&amp;filetype=.pdf ``` # Third-party from astropy.io import ascii, fits import astropy.coordinates as coord import astropy.units as u from astropy.constants...
github_jupyter
# Final Checks for model ``` import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt df = pd.read_csv(f"D:/Docs/train_1.csv", encoding='mac_roman') ``` ## 1. Use ONLY compliance available columns ``` df = df[df['compliance'].notna()] df.shape df['fine_amount'] = df['fine_amount']...
github_jupyter
``` BRANCH = 'main' """ You can run either this notebook locally (if you have all the dependencies and a GPU) or on Google Colab. Instructions for setting up Colab are as follows: 1. Open a new Python 3 notebook. 2. Import this notebook from GitHub (File -> Upload Notebook -> "GITHUB" tab -> copy/paste GitHub URL) 3. ...
github_jupyter
# T<sub>2</sub> Ramsey Experiment This experiment serves as one of the series of experiments used to characterize a single qubit. Its purpose is to determine two of the qubit's properties: *Ramsey* or *detuning frequency* and $T_2\ast$. The rough frequency of the qubit was already determined previously. Here, we would...
github_jupyter
### Note * Instructions have been included for each segment. You do not have to follow them exactly, but they are included to help you think through the steps. ``` # Dependencies and Setup import pandas as pd # File to Load (Remember to Change These) file_to_load = "Resources/purchase_data.csv" # Read Purchasing Fil...
github_jupyter
``` import os import pandas as pd from sklearn.model_selection import StratifiedShuffleSplit from dimensionality_reduction import reduce_dimension import load_database from algorithms import * import warnings warnings.filterwarnings('ignore') database_name = os.environ['DATABASE'] n_components = int(os.environ['N_COMP...
github_jupyter
# Experimental data analysis on foil open area ## Brian Larsen, ISR-1 ## Data provided by Phil Fernandes, ISR-1 2016-9-14 The setup is a foil in its holder mounted to a foil holder meant to bock incident ions. The foil has a ~0.6mm hole in it to provide a baseline. The goal is to use the relative intensity of the witn...
github_jupyter
#1. Install Dependencies First install the libraries needed to execute recipes, this only needs to be done once, then click play. ``` !pip install git+https://github.com/google/starthinker ``` #2. Get Cloud Project ID To run this recipe [requires a Google Cloud Project](https://github.com/google/starthinker/blob/mast...
github_jupyter
# Project: Part of Speech Tagging with Hidden Markov Models --- ### Introduction Part of speech tagging is the process of determining the syntactic category of a word from the words in its surrounding context. It is often used to help disambiguate natural language phrases because it can be done quickly with high accu...
github_jupyter
# TensorFlow Tutorial Welcome to this week's programming assignment. Until now, you've always used numpy to build neural networks. Now we will step you through a deep learning framework that will allow you to build neural networks more easily. Machine learning frameworks like TensorFlow, PaddlePaddle, Torch, Caffe, Ke...
github_jupyter
<a href="https://colab.research.google.com/github/oonid/growth-hacking-with-nlp-sentiment-analysis/blob/master/create_dataset.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # Evaluate Amazon Video Games Review Dataset ``` # ndjson to handle newlin...
github_jupyter
# Project Description Another CV2 tutorial this one from https://pythonprogramming.net/loading-images-python-opencv-tutorial/ ``` #http://tsaith.github.io/record-video-with-python-3-opencv-3-on-osx.html import numpy as np import cv2 cap = cv2.VideoCapture(0) # Capture video from camera # Get the width and height...
github_jupyter
# Hierarchical Clustering Lab In this notebook, we will be using sklearn to conduct hierarchical clustering on the [Iris dataset](https://archive.ics.uci.edu/ml/datasets/iris) which contains 4 dimensions/attributes and 150 samples. Each sample is labeled as one of the three type of Iris flowers. In this exercise, we'l...
github_jupyter
``` import pandas as pd import seaborn as sns import matplotlib.pyplot as plt %matplotlib inline # import data from the github page of the book data = pd.read_csv('https://raw.githubusercontent.com/Develop-Packt/Exploring-Absenteeism-at-Work/master/data/Absenteeism_at_work.csv', sep=";") # print dimensionality of the...
github_jupyter
## 8.2 创建超链接 超链接指按内容链接,可以从一个文本内容指向文本其他内容或其他文件、网址等。超链接可以分为文本内链接、网页链接以及本地文件链接。LaTeX提供了`hyperref`宏包,可用于生成超链接。在使用时,只需在前导代码中申明宏包即可,即`\usepackage{hyperref}`。 ### 8.2.1 超链接类型 #### 文本内链接 在篇幅较大的文档中,查阅内容会比较繁琐,因此,往往会在目录中使用超链接来进行文本内容的快速高效浏览。可以使用`hyperref`宏包创建文本内超链接。 【**例8-4**】使用`\usepackage{hyperref}`创建一个简单的目录链接文本内容的例子。 ```t...
github_jupyter
``` import pandas as pd import numpy as np %matplotlib inline import matplotlib.pyplot as plt from sklearn.preprocessing import normalize import seaborn as sns # list of models # Commented few models because they produced very big results which interfere visualization models = [ # 'RandomForestRegressor', # ...
github_jupyter
``` suppressMessages(library("mc2d")) library("scales") library("ggplot2") library("gridExtra") ``` # Risk Study for REPLACE ME See the [ISO 27005 Risk Cookbook](http://www.businessofsecurity.com/docs/FAIR%20-%20ISO_IEC_27005%20Cookbook.pdf) for a more detailed explanation of this template. # Asset Define the asset...
github_jupyter
# Testing ARMA hidden semi-Markov models ``` import numpy as np import seaborn as sns import time from types import SimpleNamespace from bioslds import sources from bioslds.arma import Arma, make_random_arma from bioslds.arma_hsmm import sample_switching_models, ArmaHSMM from bioslds.plotting import FigureManager ``...
github_jupyter
``` from planaritychecker import PlanarityChecker from numpy.random import random, randint import networkx as nx from planarity.planarity_networkx import planarity %matplotlib inline ``` # Check $K_5$ and $K_{3,3}$ without one edge ``` almost_K5 = PlanarityChecker(5) graph_almost_K5 = nx.Graph() graph_almost_K5.add_n...
github_jupyter
``` from __future__ import print_function import os from netCDF4 import Dataset import requests from lxml import etree import matplotlib.pyplot as plt from owslib.wps import WebProcessingService, ComplexDataInput verify_ssl = True if 'DISABLE_VERIFY_SSL' not in os.environ else False def parseStatus(execute): o =...
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. # Supported radar data formats The binary encoding of many radar products is a major obstacle for many potential radar user...
github_jupyter
# Research ## Imports ``` import pandas as pd import pandas_datareader as dr from pandas_datareader import data as web import matplotlib.pyplot as plt from matplotlib import style import numpy as np import datetime import mplfinance as mpl import plotly.graph_objects as go import plotly import yfinance as yf ``` ## ...
github_jupyter
<h1>SUBSET SELECTION</h1> ``` import numpy as np import pandas as pd import matplotlib.pyplot as plt import scipy import sklearn import seaborn as sns import xlrd import time import statsmodels.api as sm data=pd.read_excel('Data/Mini Project EFSA.xlsx') data.rename(columns={'sex \n(0=M, 1=F)':'sex'}, inplace=True) dat...
github_jupyter
<div align="right"><i>COM418 - Computers and Music</i></div> <div align="right"><a href="https://people.epfl.ch/paolo.prandoni">Paolo Prandoni</a>, <a href="https://www.epfl.ch/labs/lcav/">LCAV, EPFL</a></div> <p style="font-size: 30pt; font-weight: bold; color: #B51F1F;">Non-Harmonic Distortion in a Quantized Sinusoi...
github_jupyter
# Large dataset testing --- Checking if the new large dataset class, which lazily loads batch files instead of diving a giant pre-loaded one, works well to train my models. ## Importing the necessary packages ``` import os # os handles directory/workspace changes import comet_ml ...
github_jupyter
**QC of ETL starting with GDC release 24 clinical tables** This notebook focuses on the QC of program **MMRF** data_category clinical This program has a total of five clinical tables present in this release Tables listed below --- - `isb-project-zero.GDC_Clinical_Data.rel24_clin_MMRF` - `isb-project-zero.GDC_Clini...
github_jupyter
``` #Libraries import warnings warnings.filterwarnings('ignore') import pandas as pd import numpy as np import os import re import json import string import matplotlib.pyplot as plt %matplotlib inline import plotly.express as px import plotly.graph_objects as go from tqdm.autonotebook import tqdm from functools import...
github_jupyter
``` #!/usr/bin/env python3 # -*- coding: utf-8 -*- #@author: Kelle Clark, Andrew Florian, Xinyu Xiong #Created on Tue Feb 4 10:05:49 2020 #CSCI 6040 Project 1 Text Generation #PHASE 3: Smoothing the Language Models for the Corpus #Various folders of .txt files were created in the CSCI6040 Team Project 1 folder #to b...
github_jupyter
[this doc on github](https://github.com/dotnet/interactive/tree/master/samples/notebooks/fsharp/Docs) # Object formatters ## Default formatting behaviors When you return a value or a display a value in a .NET notebook, the default formatting behavior is to try to provide some useful information about the object. If ...
github_jupyter
# MAT281 - Laboratorio N°06 ## Problema 01 <img src="./images/logo_iris.jpg" width="360" height="360" align="center"/> El **Iris dataset** es un conjunto de datos que contine una muestras de tres especies de Iris (Iris setosa, Iris virginica e Iris versicolor). Se midió cuatro rasgos de cada muestra: el largo y anch...
github_jupyter
# Polarization **Prerequisite: Basic Introduction** In this notebook parameterization of the polarization primitives and few methods derived from the primitives are presented. In particular, setting up of * General parameters * Current/voltage range * Current/voltage limits * Online display * Tolerance limits is ex...
github_jupyter
# Arrays There are several kinds of sequences in Python. A [list](lists) is one. However, the sequence type that we will use most in the class, is the array. The `numpy` package, abbreviated `np` in programs, provides Python programmers with convenient and powerful functions for creating and manipulating arrays. `...
github_jupyter
``` import pandas as pd, numpy as np import matplotlib.pyplot as plt %matplotlib inline from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor from sklearn.cross_validation import train_test_split from sklearn.grid_search import GridSearchCV import pandas as pd, numpy as np from sklearn.ensembl...
github_jupyter
# Checkpoint 2 ``` # imports. from datetime import datetime import matplotlib.pyplot as plt %matplotlib inline import numpy as np from scipy import integrate from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm import random plt.rcParams['figure.figsize'] = (10, 6) plt.rcParams['font.size'] = 16 # Constan...
github_jupyter
# Week 05, Part 1 ### Topic 1. For reference: about plotting polygons in R (we won't go over this, but it serves as reference) 1. Plotting normal distributions 1. Example: Manufacturing rulers 1. BACK TO SLIDES FOR PERCENTILES ``` # resize require(repr) options(repr.plot.width=8, repr.plot.height=8) ``` ## 1....
github_jupyter
``` import os,requests,json; from ipywidgets import IntProgress,HTML,VBox; from IPython.display import display; r = requests.get( 'http://dz_gs:8080/geoserver/rest/settings/contact' ,auth=('admin','nhdplus') ); if r.status_code != 200 or r.json()["contact"]["contactOrganization"] != 'NHDPlusInABox': raise E...
github_jupyter
# <center>Introduction on Using Python to access GeoNet's GNSS data In this notebook we will learn how to get data from one GNSS(Global Navigation Satellite System) station. By the end of this tutorial you will have make a graph like the one below. <img src="plot.png"> ## &nbsp;Table of contents ### 1. Introduction #...
github_jupyter
``` import keras import tensorflow as tf print(keras.__version__) print(tf.__version__) import numpy as np import pandas as pd from sklearn.feature_extraction.text import CountVectorizer from sklearn.model_selection import train_test_split from sklearn.metrics import classification_report,confusion_matrix NGRAMS = 2 S...
github_jupyter
# Principal Componenet Analysis (PCA) The PCA algorithm is a dimensionality reduction algorithm which works really well for datasets which have correlated columns. It combines the features of X in linear combination such that the new components capture the most information of the data. The PCA model is implemented in...
github_jupyter
# Deploy and perform inference on Model Package from AWS Marketplace This notebook provides you instructions on how to deploy and perform inference on model packages from AWS Marketplace object detection model. This notebook is compatible only with those object detection model packages which this notebook is linked ...
github_jupyter
# Timeseries Ce notebook présente quelques étapes simples pour une série temporelle. La plupart utilise le module [statsmodels.tsa](https://www.statsmodels.org/stable/tsa.html#module-statsmodels.tsa). ``` from jyquickhelper import add_notebook_menu add_notebook_menu() %matplotlib inline ``` ## Données Les données s...
github_jupyter
# ETL Processes Use this notebook to develop the ETL process for each of your tables before completing the `etl.py` file to load the whole datasets. ``` import os import glob import psycopg2 import pandas as pd from sql_queries import * conn = psycopg2.connect("host=127.0.0.1 dbname=studentdb user=student password=stu...
github_jupyter
<a href="https://cognitiveclass.ai"><img src = "https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/Logos/organization_logo/organization_logo.png" width = 400> </a> This notebook is designed to run in a IBM Watson Studio default runtime (NOT the Watson Studio Apache Spark Runtime as the de...
github_jupyter
``` # Copyright 2020 IITK EE604A Image Processing. All Rights Reserved. # # Licensed under the MIT License. Use and/or modification of this code outside of EE604 must reference: # # © IITK EE604A Image Processing # https://github.com/ee604/ee604_assignments # # Author: Shashi Kant Gupta, Chiranjeev Prachand and Prof ...
github_jupyter
# A simple notebook to do MIRI coordinate transforms. # Some functionality depends on having the JWST pipeline and/or pysiaf module installed ``` import numpy as np import pdb as pdb from astropy.modeling import models from asdf import AsdfFile from jwst import datamodels from jwst.assign_wcs import miri import pysia...
github_jupyter
##### Copyright 2019 The TensorFlow Hub Authors. Licensed under the Apache License, Version 2.0 (the "License"); ``` # Copyright 2019 The TensorFlow Hub Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. ...
github_jupyter
# Sample grouping We are going to linger into the concept of sample groups. As in the previous section, we will give an example to highlight some surprising results. This time, we will use the handwritten digits dataset. ``` from sklearn.datasets import load_digits digits = load_digits() data, target = digits.data, d...
github_jupyter
# OSMnx + igraph for faster performance Author: [Geoff Boeing](https://geoffboeing.com/) NetworkX is ubiquitous, easy to use, and sufficiently fast for most use cases. But it can be slow for analyzing very large graphs because it is pure Python, trading off speed for ease of use. Fortunately, converting OSMnx-created...
github_jupyter
<a href="https://colab.research.google.com/github/harnalashok/deeplearning-sequences/blob/main/tf%20data%20API.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> ``` #Last amended: 12th March, 2021 # My folder: harnalashok/github/deeplearning-sequence...
github_jupyter
# Zebrafish Double coiling model ### Below is the block of code to run double coiling models INITIALIZE - Run before running the models to set the parameters ``` %matplotlib inline ### FIRST, run this code to set the simulation parameters. Then select from the codes below to run different models #Declare the durati...
github_jupyter
``` !pip install pandas-summary import pandas as pd # pip install pandas_summary from pandas_summary import DataFrameSummary ``` # Competencia de Kaggle [ir a Kaggle](https://www.kaggle.com/c/rossmann-store-sales/data) [3er puesto](https://github.com/entron/entity-embedding-rossmann) # Métrica de la competencia $...
github_jupyter
<a href="https://colab.research.google.com/github/hlab-repo/purity-and-danger/blob/master/Immigration.ipynb" target="_parent"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a> # Creating a Model for Immigration and Outsider Language This notebook starts with a baseline syst...
github_jupyter
``` """Udacity - Self-Driving Engineer Nanodegree Project 1: Finding Lane Lines on the Road Nikko Sadural""" import matplotlib.pyplot as plt import matplotlib.image as mpimg import numpy as np import cv2 import math from moviepy.editor import VideoFileClip from IPython.display import HTML %matplotlib inline def grays...
github_jupyter
``` # basic import sys import os # common import numpy as np import pandas as pd import xarray as xr import matplotlib.pyplot as plt from datetime import datetime, timedelta from sklearn.cluster import KMeans import pickle import warnings warnings.filterwarnings('ignore') from IPython.display import Image #lib from l...
github_jupyter
``` import numpy as np import matplotlib.pyplot as plt ``` # Parte 1: Iteração de Rayleigh Vimos que podemos iterar um vetor $v$ pela matriz $A$, obtendo a sequência de vetores $A^nv$, por multiplicações sucessivas, e que isso permite encontrar um autovetor. ## Questão 1 Implemente uma função `itera(A,v,tol,debug)`...
github_jupyter
# Homework 1: Classification With Naive Bayes ## Problem 1: Diabetes Classification Points: 40 A famous collection of data on whether a patient has diabetes, known as the Pima Indians dataset, and originally owned by the National Institute of Diabetes and Digestive and Kidney Diseases can be found at Kaggle. Downloa...
github_jupyter
<a rel="license" href="http://creativecommons.org/licenses/by/4.0/"><img alt="Creative Commons License" style="border-width:0" src="https://i.creativecommons.org/l/by/4.0/88x31.png" /></a><br /><span xmlns:dct="http://purl.org/dc/terms/" property="dct:title"><b>The Knapsack Problem</b></span> by <a xmlns:cc="http://cre...
github_jupyter
**Title**: Upload kaggle chest X-Ray. **Date**: 12-Oct-2020 **Description**: Pneumonia accounts for over 15% of all deaths of children under 5 years old internationally. Advanced detection of pneumonia could save thousands of lives a year. In 2018 the RSNA Pneumonia Detection Challenge was posted on Kaggle,...
github_jupyter
``` #import libraries import requests from datetime import datetime as dt from datetime import timedelta import pandas as pd # get events from n days ago iso = 887 #Pike I changed this to Yemen limit = 400 api_url = 'https://api.acleddata.com/acled/read?terms=accept&iso={}'.format(iso) print (api_url, type(api_url)) #...
github_jupyter
``` from lenslikelihood.power_spectra import * mass_function_model = 'shethTormen' normalization = 'As' pivot_string = '01' pivot = 0.1 structure_formation_interp_As = load_interpolated_mapping(mass_function_model, pivot_string) import numpy as np import matplotlib.pyplot as plt import matplotlib.cm as cm import os ...
github_jupyter
# Content: 1. [Definitions](#1.-Definitions) 2. [The root finding problem](#2.-The-root-finding-problem) 3. [Fixed point iteration](#3.-Fixed-point-iteration) >3.1 [The cobweb diagram](#3.1-The-cobweb-diagram) >3.2 [Fixed point iteration theorem](#3.2-Fixed-point-iteration-theorem) >3.3 [The code](#3.3-The-code) ...
github_jupyter
# 第二十三讲 微分方程和$e^{At}$ ## 微分方程$\frac{du}{dt} = Au$ 现有一阶(First-order)微分方程组:$\left\{\begin{matrix} \frac{du_1}{dt} & = & -u_1 & + 2u_2\\ \frac{du_2}{dt} & = & u_1 & -2u_2 \end{matrix}\right.$,其中初始状态 $u(0) = \begin{bmatrix}u_1 \\ u_2 \end{bmatrix} = \begin{bmatrix} 1 \\ 0 \end{bmatrix}$,现在我们需要求解方程的一般形式 $u(t)$。 首先,通过微分方...
github_jupyter
Project No.: 3 Time Taken: 3 days Difficulty: Intermediate. This is the toughest dataset I've worked with. Learnt a lot. Still a long way to go... Would love it if you left a comment with advice on where I could have improved, what you liked/disliked about my work, or any thing else. And if you like it, please giv...
github_jupyter
``` !git clone https://github.com/huggingface/transformers.git %cd transformers !pwd !git reset --hard 52f44dd !cp ./examples/token-classification/run_ner.py ../ %cd .. #!wget https://raw.githubusercontent.com/huggingface/transformers/master/examples/token-classification/run_ner.py !wget https://raw.githubusercontent.c...
github_jupyter
# Artificial Intelligence Nanodegree ## Convolutional Neural Networks --- In this notebook, we train a CNN on augmented images from the CIFAR-10 database. ### 1. Load CIFAR-10 Database ``` import keras from keras.datasets import cifar10 # load the pre-shuffled train and test data (x_train, y_train), (x_test, y_te...
github_jupyter
``` import os, json, sys, time, random import numpy as np import torch from easydict import EasyDict from math import floor from easydict import EasyDict from steves_utils.vanilla_train_eval_test_jig import Vanilla_Train_Eval_Test_Jig from steves_utils.torch_utils import get_dataset_metrics, independent_accuracy_as...
github_jupyter
# Introducing Scikit-Learn There are several Python libraries which provide solid implementations of a range of machine learning algorithms. One of the best known is [Scikit-Learn](http://scikit-learn.org), a package that provides efficient versions of a large number of common algorithms. Scikit-Learn is characterized...
github_jupyter
``` # Import Dependencies import numpy as np import pandas as pd from pathlib import Path # Processing Libraries from sklearn.preprocessing import StandardScaler, LabelEncoder # Models from sklearn.linear_model import LogisticRegression from sklearn.ensemble import RandomForestClassifier ``` ### Predictions I believ...
github_jupyter
``` given = """ Grey BOTTOM BOTTOM 4 Grey BOTTOM BOTTOM 2 Grey RIGHT RIGHT 2 Grey LEFT LEFT 2 BLACK RIGHT RIGHT 2 Grey LEFT LEFT 2 BLACK RIGHT RIGHT 2 Grey EMPTY EMPTY 4 Grey LEFT LEFT 3 BLACK TOP TOP 1 BLACK EMPTY EMPTY 5 Grey TOP TOP 3 Grey RIGHT RIGHT 5 Grey BOTTOM BOTTOM 5 Grey BOTTOM BOTTOM 2 BLACK EMPTY EMPTY 3 B...
github_jupyter
# Demonstration of integrating POI Points to OSM road network 1. Use anyway you like to get the sample [POI data](https://assets.onemap.sg/shp/supermarkets.zip) consisting of supermarkets from [OneMap SG](https://www.onemap.sg/). 2. Use [OSMnx](https://osmnx.readthedocs.io/en/stable/index.html) to download the pedestri...
github_jupyter
``` import numpy as np import pandas as pd import scipy import scipy.stats import verdict import matplotlib.pyplot as plt ``` # Parameters ``` sample_number = 0 ``` # Load Mock Data ``` # Load using my preferred wrapper for hdf5 files. data = verdict.Dict.from_hdf5( './data/synthetic_data/sample{}/observers_file.h5...
github_jupyter
``` from google.colab import drive drive.mount('/content/drive') # from google.colab import drive # drive.mount('/content/drive') !pwd path = '/content/drive/MyDrive/Research/AAAI/cifar_new/k_001/sixth_run1_' import torch.nn as nn import torch.nn.functional as F import pandas as pd import numpy as np import matplotlib...
github_jupyter
``` # These are all the modules we'll be using later. Make sure you can import them # before proceeding further. from __future__ import print_function import numpy as np import tensorflow as tf from six.moves import cPickle as pickle from six.moves import range # The folder when dumped big 3D array has been stored from...
github_jupyter
## Fitting a diagonal covariance Gaussian mixture model to text data In a previous assignment, we explored k-means clustering for a high-dimensional Wikipedia dataset. We can also model this data with a mixture of Gaussians, though with increasing dimension we run into two important issues associated with using a full...
github_jupyter
# Example notebook for the functions contained in cry_file_readwrite.py ### Crystal_input class ``` from crystal_functions.file_readwrite import Crystal_input ``` #### Create a crystal input object from blocks ``` geom_block = ['MGO BULK - GEOMETRY TEST\n', 'CRYSTAL\n', '0 0 0\n', ...
github_jupyter
# Text Data Explanation Benchmarking: Emotion Multiclass Classification This notebook demonstrates how to use the benchmark utility to benchmark the performance of an explainer for text data. In this demo, we showcase explanation performance for partition explainer on an Emotion Multiclass Classification model. The me...
github_jupyter
# Mapas Autorganizados (SOM) <img src="../img/som_1.jpg" width="500"> Se toma un conjunto de datos multidimensional los cuales se pueden mostrar como un mapa bidimensional. El objetivo del **SOM** es reducir las columnas y quedarnos solo con las que nos aporten más info. O lo que es lo mismo, reducir lo máximo la dim...
github_jupyter
# Unsupervised outliers detection (event detection) ``` import drama as drm import numpy as np import matplotlib.pylab as plt from matplotlib import gridspec from drama.outlier_finder import grid_run_drama from keras.datasets import mnist %matplotlib inline n_try = 5 # MNIST dataset (x_train, y_train), (x_test, y_...
github_jupyter
# Further information ## What are the differences between recursion and iteration? When giving instructions to a computer it is possible to use recursion to directly implement a common mathematical definition. For example consider the following sequence: $$ \left\{\begin{array}{l} a_1 = 1\\ a_{n + 1}= 3a...
github_jupyter