markdown
stringlengths
0
1.02M
code
stringlengths
0
832k
output
stringlengths
0
1.02M
license
stringlengths
3
36
path
stringlengths
6
265
repo_name
stringlengths
6
127
Convert from Radians to Degrees The above answers will be in radians, use the following code to convert to degrees.
#substitute x_c and x_i as needed z=c.phase(x_c) m.degrees(z) print("Angle in degrees =",m.degrees(z))
Angle in degrees = -81.07294513104007
MIT
Applications/ENGR 202 Solver.ipynb
smithrockmaker/ENGR213
Simple Circuit in Series
# For following three cells, if reactance is already given, replace "xind" or"xcap" with corresponding j value # Resistor value is overwritten from previous cells when changed here # Not all simple circuits will have all three components. Modify as needed. # Original formula - series_comb = r + ind + cap r = 100 ...
Series Rectangular Form = (100+6919.805079547168j)
MIT
Applications/ENGR 202 Solver.ipynb
smithrockmaker/ENGR213
Simple Parallel Circuit - Product/Sum
# Product sum rule works only with 2 components # Original Formula - prod_sum = res*cap/(res + cap) ind = 0 + xind*1j cap = 0 + xcap*1j res = 100 prod_sum = res*cap/(res + cap) print("Product/sum Rectangular Form =",prod_sum)
Product/sum Rectangular Form = (97.59201358307332-15.329717646080926j)
MIT
Applications/ENGR 202 Solver.ipynb
smithrockmaker/ENGR213
Simple Parallel Circuit
# Use as many components as necessary # Original formula - parallel_comb = 1/(1/res + 1/ind + 1/cap) ind = 0 + xind*1j cap = 0 + xcap*1j res = 100 parallel_comb = 1/(1/res + 1/ind + 1/cap) print("Parallel Rectangular Form =",parallel_comb)
Parallel Rectangular Form = (98.04620253923555-13.840607701931122j)
MIT
Applications/ENGR 202 Solver.ipynb
smithrockmaker/ENGR213
Current Solver
# Make sure to use the parallel cell that IS NOT product/sum # Copy and paste cur_ind or cur_cap sections as necessary to account for all components. Some code modifaction/addition may be required. # This cell useful as is for one of each component. # Once previous cells are complete, this will populate automatically E...
Z Polar = (99.01828242260899, -0.14023751838586943) Z Rectangular = (98.04620253923555-13.840607701931122j) Source Current = (0.1+0.014116413837030016j) Source Current, Polar = (0.1009914508244054, 0.14023751838586943) Angle = 8.035017932898603 Capacitor Current = (-0+0.015707963267948967j) Capacitor Cur...
MIT
Applications/ENGR 202 Solver.ipynb
smithrockmaker/ENGR213
Series-Parallel Circuits
# Organization cell for component values # Inductors z1 = 200*1j # Resistors z2 = 300 z3 = 270 #Capacitors z4 = -1500*1j # This cell is ambiguous with just z values to make it easy to modify. Keep track of z values. # Original Form of equation - parallel_react = 1/(1/z1+1/z2+1/(z3+z4)) parallel_react = 1/(1/z1+1/z...
Z Rectangular = (111.7846057266418+141.10138457782585j) Z Polar = (180.01499606210666, 0.9008118071374078)
MIT
Applications/ENGR 202 Solver.ipynb
smithrockmaker/ENGR213
TPU
AUTO = tf.data.experimental.AUTOTUNE # Detect hardware, return appropriate distribution strategy try: tpu = tf.distribute.cluster_resolver.TPUClusterResolver() # TPU detection. No parameters necessary if TPU_NAME environment variable is set. On Kaggle this is always the case. print('Running on TPU ', tpu.maste...
_____no_output_____
MIT
Image Classification/CGIAR Computer Vision for Crop Disease/recongratulationsyoure3iniclrworkshopchallenge1/model4.ipynb
ZindiAfrica/Computer-Vision
This notebook was prepared by [Donne Martin](https://github.com/donnemartin). Source and license info is on [GitHub](https://github.com/donnemartin/interactive-coding-challenges). Solution Notebook Problem: Find the highest product of three numbers in a list.* [Constraints](Constraints)* [Test Cases](Test-Cases)* [Al...
class Solution(object): def max_prod_three_nlogn(self, array): if array is None: raise TypeError('array cannot be None') if len(array) < 3: raise ValueError('array must have 3 or more ints') array.sort() product = 1 for item in array[-3:]: ...
_____no_output_____
Apache-2.0
online_judges/prod_three/prod_three_solution.ipynb
sophomore99/PythonInterective
Unit Test
%%writefile test_prod_three.py from nose.tools import assert_equal, assert_raises class TestProdThree(object): def test_prod_three(self): solution = Solution() assert_raises(TypeError, solution.max_prod_three, None) assert_raises(ValueError, solution.max_prod_three, [1, 2]) assert...
Success: test_prod_three
Apache-2.0
online_judges/prod_three/prod_three_solution.ipynb
sophomore99/PythonInterective
Unzipping and Zipping FilesAs you are probably aware, files can be compressed to a zip format. Often people use special programs on their computer to unzip these files, luckily for us, Python can do the same task with just a few simple lines of code. Create Files to Compress
# slashes may need to change for MacOS or Linux f = open("new_file.txt",'w+') f.write("Here is some text") f.close() # slashes may need to change for MacOS or Linux f = open("new_file2.txt",'w+') f.write("Here is some text") f.close()
_____no_output_____
MIT
4-assets/BOOKS/Jupyter-Notebooks/06-Unzipping-and-Zipping-Files-checkpoint.ipynb
impastasyndrome/Lambda-Resource-Static-Assets
Zipping FilesThe [zipfile library](https://docs.python.org/3/library/zipfile.html) is built in to Python, we can use it to compress folders or files. To compress all files in a folder, just use the os.walk() method to iterate this process for all the files in a directory.
import zipfile
_____no_output_____
MIT
4-assets/BOOKS/Jupyter-Notebooks/06-Unzipping-and-Zipping-Files-checkpoint.ipynb
impastasyndrome/Lambda-Resource-Static-Assets
Create Zip file first , then write to it (the write step compresses the files.)
comp_file = zipfile.ZipFile('comp_file.zip','w') comp_file.write("new_file.txt",compress_type=zipfile.ZIP_DEFLATED) comp_file.write('new_file2.txt',compress_type=zipfile.ZIP_DEFLATED) comp_file.close()
_____no_output_____
MIT
4-assets/BOOKS/Jupyter-Notebooks/06-Unzipping-and-Zipping-Files-checkpoint.ipynb
impastasyndrome/Lambda-Resource-Static-Assets
Extracting from Zip FilesWe can easily extract files with either the extractall() method to get all the files, or just using the extract() method to only grab individual files.
zip_obj = zipfile.ZipFile('comp_file.zip','r') zip_obj.extractall("extracted_content")
_____no_output_____
MIT
4-assets/BOOKS/Jupyter-Notebooks/06-Unzipping-and-Zipping-Files-checkpoint.ipynb
impastasyndrome/Lambda-Resource-Static-Assets
________ Using shutil libraryOften you don't want to extract or archive individual files from a .zip, but instead archive everything at once. The shutil library that is built in to python has easy to use commands for this:
import shutil
_____no_output_____
MIT
4-assets/BOOKS/Jupyter-Notebooks/06-Unzipping-and-Zipping-Files-checkpoint.ipynb
impastasyndrome/Lambda-Resource-Static-Assets
The shutil library can accept a format parameter, `format` is the archive format: one of "zip", "tar", "gztar", "bztar",or "xztar".
pwd directory_to_zip='C:\\Users\\Marcial\\Pierian-Data-Courses\\Complete-Python-3-Bootcamp\\12-Advanced Python Modules' # Creating a zip archive output_filename = 'example' # Just fill in the output_filename and the directory to zip # Note this won't run as is because the variable are undefined shutil.make_archive(outp...
_____no_output_____
MIT
4-assets/BOOKS/Jupyter-Notebooks/06-Unzipping-and-Zipping-Files-checkpoint.ipynb
impastasyndrome/Lambda-Resource-Static-Assets
Causal Inference In Statistics - A Primer 3.1 Interventions Bruno Gonçalves www.data4sci.com @bgoncalves, @data4sci
from collections import Counter from pprint import pprint import pandas as pd import numpy as np import matplotlib import matplotlib.pyplot as plt from CausalModel import CausalModel import watermark %load_ext watermark %matplotlib inline
_____no_output_____
MIT
3.1 - Interventions.ipynb
m5l14i11/Causality
We start by print out the versions of the libraries we're using for future reference
%watermark -n -v -m -g -iv
watermark 2.0.2 json 2.0.9 pandas 1.0.1 matplotlib 3.1.3 numpy 1.18.1 autopep8 1.5 Sun Oct 18 2020 CPython 3.7.3 IPython 6.2.1 compiler : Clang 4.0.1 (tags/RELEASE_401/final) system : Darwin release : 19.6.0 machine : x86_64 processor : i386 CPU cores : 8 interpreter: 64bit Git hash ...
MIT
3.1 - Interventions.ipynb
m5l14i11/Causality
Load default figure style
plt.style.use('./d4sci.mplstyle') colors = plt.rcParams['axes.prop_cycle'].by_key()['color']
_____no_output_____
MIT
3.1 - Interventions.ipynb
m5l14i11/Causality
Graph Surgery
G = CausalModel() G.add_causation('Ux', 'X') G.add_causation('Uy', 'Y') G.add_causation('Uz', 'Z') G.add_causation('Z', 'X') G.add_causation('Z', 'Y') G.pos = {'Z': (0, 1), 'X': (-1, 0), 'Y':(1, 0), 'Uz':(0, 2), 'Ux':(-1, 1), 'Uy': (1,1)} fig, ax = plt.subplots(1, figsize=(3, 2.5)) G.plot(ax=ax) G.save_model('dags/Pri...
_____no_output_____
MIT
3.1 - Interventions.ipynb
m5l14i11/Causality
Ex - GroupBy Introduction:GroupBy can be summarized as Split-Apply-Combine.Special thanks to: https://github.com/justmarkham for sharing the dataset and materials.Check out this [Diagram](http://i.imgur.com/yjNkiwL.png) Step 1. Import the necessary libraries
import pandas as pd
_____no_output_____
BSD-3-Clause
03_Grouping/Alcohol_Consumption/Exercise.ipynb
coderhh/pandas_exercises
Step 2. Import the dataset from this [address](https://raw.githubusercontent.com/justmarkham/DAT8/master/data/drinks.csv). Step 3. Assign it to a variable called drinks.
url = 'https://raw.githubusercontent.com/justmarkham/DAT8/master/data/drinks.csv' drinks = pd.read_csv(url) drinks
_____no_output_____
BSD-3-Clause
03_Grouping/Alcohol_Consumption/Exercise.ipynb
coderhh/pandas_exercises
Step 4. Which continent drinks more beer on average?
drinks.groupby('continent').beer_servings.mean()
_____no_output_____
BSD-3-Clause
03_Grouping/Alcohol_Consumption/Exercise.ipynb
coderhh/pandas_exercises
Step 5. For each continent print the statistics for wine consumption.
drinks.groupby('continent').wine_servings.describe()
_____no_output_____
BSD-3-Clause
03_Grouping/Alcohol_Consumption/Exercise.ipynb
coderhh/pandas_exercises
Step 6. Print the mean alcohol consumption per continent for every column
drinks.groupby('continent').mean()
_____no_output_____
BSD-3-Clause
03_Grouping/Alcohol_Consumption/Exercise.ipynb
coderhh/pandas_exercises
Step 7. Print the median alcohol consumption per continent for every column
drinks.groupby('continent').median()
_____no_output_____
BSD-3-Clause
03_Grouping/Alcohol_Consumption/Exercise.ipynb
coderhh/pandas_exercises
Step 8. Print the mean, min and max values for spirit consumption. This time output a DataFrame
drinks.groupby('continent').spirit_servings.agg(['mean', 'min', 'max'])
_____no_output_____
BSD-3-Clause
03_Grouping/Alcohol_Consumption/Exercise.ipynb
coderhh/pandas_exercises
Week 3, Day 1 (Dataset Preparation and Arrangement)> Welcome to first day (Week 3) of the McE-51069 course.- sticky_rank: 7- toc: true- badges: false- comments: false- categories: [deep_learning, computer_vision] You can download resources for today from this [link](https://github.com/ytu-cvlab/mce-51069-week3-day1/ar...
import pandas as pd import numpy as np import matplotlib.pyplot as plt import cv2 import math %matplotlib inline
_____no_output_____
Apache-2.0
_notebooks/2020-12-23-week3-day1.ipynb
ytu-cvlab/Resource-Blog
Pandas stores data in dataframe objects. We can assign columns to each to numpy array (or) list to create a dataframe.
#Create a dataframe names = ['Jack','Jean','Jennifer','Jimmy'] ages = np.array([23,22,24,21]) # print(type(names)) # print(type(ages)) df = pd.DataFrame({'name': names, 'age': ages, 'city': ['London', 'Berlin', 'New York', 'Sydney']},index=None) df.head() # df.style.hide_index(...
_____no_output_____
Apache-2.0
_notebooks/2020-12-23-week3-day1.ipynb
ytu-cvlab/Resource-Blog
Now, let's see some handy dataframe tricks.
df[['name','city']] df.info() # print(df.columns) # print(df.age)
<class 'pandas.core.frame.DataFrame'> RangeIndex: 4 entries, 0 to 3 Data columns (total 3 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 name 4 non-null object 1 age 4 non-null int32 2 city 4 non-null object dtypes: int32(1), object(2) memory usage...
Apache-2.0
_notebooks/2020-12-23-week3-day1.ipynb
ytu-cvlab/Resource-Blog
Now that we know how to create a dataframe, we can save the dataframe we created.
df.to_csv('Ages_and_cities.csv',index=False,header=True) df = pd.read_csv('Ages_and_cities.csv') df.head()
_____no_output_____
Apache-2.0
_notebooks/2020-12-23-week3-day1.ipynb
ytu-cvlab/Resource-Blog
Understanding your dataset In this section, we used [Iris flowers dataset](https://en.wikipedia.org/wiki/Iris_flower_data_set), which contains petal and sepal measurements of three species of Iris flowers. Three species of Iris flowers from the dataset ![](images/iris.png) Sepal vs Petal This dataset was introduced ...
df = pd.read_csv('iris_data.csv') df.head() # df.head(3) df.tail()
_____no_output_____
Apache-2.0
_notebooks/2020-12-23-week3-day1.ipynb
ytu-cvlab/Resource-Blog
Slicing data Now that we understand our dataset, let's prepare to seperate our data based on labels for unique visualization.
# df.loc[:3] df.loc[80:85,("sepal_length","variety")] # df.iloc[146:] # df.iloc[80:85,2:5] df.iloc[80:85,[0,4]] Se= df.loc[df.variety =='Setosa', :] Vc= df.loc[df.variety =='Versicolor', :] Vi= df.loc[df.variety =='Virginica', :] Vi.head()
_____no_output_____
Apache-2.0
_notebooks/2020-12-23-week3-day1.ipynb
ytu-cvlab/Resource-Blog
Feature visualization
df = pd.read_csv('iris_data.csv') # df.dtypes
_____no_output_____
Apache-2.0
_notebooks/2020-12-23-week3-day1.ipynb
ytu-cvlab/Resource-Blog
First, we will visualize each measurement with histograms to observe the output distribution for each class.
# df.hist("sepal.length",bins=15,edgecolor='black') plt.figure(figsize=(15,15)) plt.subplot(2, 2, 1) plt.hist(Se.sepal_length,bins=15,color="steelblue",edgecolor='black',alpha =0.4, label="Setosa") plt.hist(Vc.sepal_length,bins=15,color='red',edgecolor='black', alpha =0.3, label="Versicolor") plt.hist(Vi.sepal_length...
_____no_output_____
Apache-2.0
_notebooks/2020-12-23-week3-day1.ipynb
ytu-cvlab/Resource-Blog
Now, we will visualize multiple features with scatter plots to gain some more insights.
plt.figure(figsize=(15,15)) area = np.pi*20 plt.subplot(2, 2, 1) plt.scatter(Se.sepal_length,Se.sepal_width, s=area, c="steelblue", alpha=0.6, label="Setosa") plt.scatter(Vc.sepal_length,Vc.sepal_width, s=area, c="red", alpha=0.6, label="Versicolor") plt.scatter(Vi.sepal_length,Vi.sepal_width, s=area, c="blue", alpha...
_____no_output_____
Apache-2.0
_notebooks/2020-12-23-week3-day1.ipynb
ytu-cvlab/Resource-Blog
We can definitely see some blobs forming from these visualizations. "Setosa" class unsally stands out from the other two classes but the sepal width vs sepal length plot shows "versicolor" and "virginica" classes will more challenging to classify compared to "setosa" class. Training the model [Scikit-learn](https://sc...
from sklearn.model_selection import train_test_split from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import RandomForestClassifier from sklearn import metrics import seaborn as sns df = pd.read_csv('iris_data.csv') # df.dtypes df.tail() train_X, test_X, train_y, test_y = train_test_split(df[df.col...
_____no_output_____
Apache-2.0
_notebooks/2020-12-23-week3-day1.ipynb
ytu-cvlab/Resource-Blog
Model Evaluation Decision Tree classifier
print(metrics.classification_report(DT_predicted, test_y)) mat = metrics.confusion_matrix(test_y, DT_predicted) sns.heatmap(mat.T, square=True, annot=True, fmt='d', cbar=False) plt.xlabel('true label') plt.ylabel('predicted label');
_____no_output_____
Apache-2.0
_notebooks/2020-12-23-week3-day1.ipynb
ytu-cvlab/Resource-Blog
Ramdom Forest Classifier
print(metrics.classification_report(RF_predicted, test_y)) from sklearn.metrics import confusion_matrix import seaborn as sns mat = confusion_matrix(test_y, RF_predicted) sns.heatmap(mat.T, square=True, annot=True,fmt='d', cbar=False) plt.xlabel('true label') plt.ylabel('predicted label');
_____no_output_____
Apache-2.0
_notebooks/2020-12-23-week3-day1.ipynb
ytu-cvlab/Resource-Blog
[colab notebook](https://colab.research.google.com/github/jakevdp/PythonDataScienceHandbook/blob/master/notebooks/05.08-Random-Forests.ipynb) Feature Engineering When generating new features, the product between two features is usually not recommended to engineer unless it makes a magnification of the situation. Here,...
#Generate new features df = pd.read_csv('iris_data.csv') df['petal_hypotenuse'] = np.sqrt(df["petal_length"]**2+df["petal_width"]**2) df['petal_product']=df["petal_length"]*df["petal_width"] df.tail() Se= df.loc[df.variety =='Setosa', :] Vc= df.loc[df.variety =='Versicolor', :] Vi= df.loc[df.variety =='Virginica', :] ...
_____no_output_____
Apache-2.0
_notebooks/2020-12-23-week3-day1.ipynb
ytu-cvlab/Resource-Blog
Train with Engineered features Now, let's replace two petal features with two new features we generated.
df.head() df2 = df.loc[:,["sepal_length","sepal_width","petal_hypotenuse","petal_product","variety"]] df2.dtypes train_X, test_X, train_y, test_y = train_test_split(df2[df2.columns[0:4]].values, df2.variety.values, test_size=0.25) from sklearn.tree import DecisionTre...
_____no_output_____
Apache-2.0
_notebooks/2020-12-23-week3-day1.ipynb
ytu-cvlab/Resource-Blog
Data PreprocessingThis notebook shows
import pandas as pd import numpy as np import matplotlib.pyplot as plt import re import json import nltk from nltk.corpus import wordnet import sklearn import seaborn as sns import unicodedata import inflect nltk.download('punkt') nltk.download('wordnet') nltk.download('averaged_perceptron_tagger') nltk.download('stop...
[nltk_data] Downloading package punkt to /home/jovyan/nltk_data... [nltk_data] Package punkt is already up-to-date! [nltk_data] Downloading package wordnet to /home/jovyan/nltk_data... [nltk_data] Package wordnet is already up-to-date! [nltk_data] Downloading package averaged_perceptron_tagger to [nltk_data] /h...
MIT
notebooks/data_preprocessing.ipynb
SudoHead/movie-classifier
Load the data:
path = '../data/movies_metadata.csv' df = pd.read_csv(path) df = pd.concat([df['release_date'], df['title'], df['overview'], df['genres']], axis=1) # remove duplicates duplicate_rows = df[df.duplicated()] df.drop(duplicate_rows.index, inplace=True)
_____no_output_____
MIT
notebooks/data_preprocessing.ipynb
SudoHead/movie-classifier
Drop the NaN rows where either title or overview is NaN
# convert empty string to NaN df['overview'].replace('', np.nan, inplace=True) df.dropna(subset=['release_date', 'title', 'overview'], inplace=True) # the release date is no longer necessary, because NaN are cleared del df['release_date']
_____no_output_____
MIT
notebooks/data_preprocessing.ipynb
SudoHead/movie-classifier
Drop rows with no overview info or blank
reg_404 = "^not available|^no overview" overview_not_found = df['overview'].str.contains(reg_404, regex=True, flags=re.IGNORECASE) overview_blank = df['overview'].str.isspace() df.drop(df[overview_not_found].index, inplace=True) df.drop(df[overview_blank].index, inplace=True) df.head()
/opt/conda/lib/python3.7/site-packages/ipykernel_launcher.py:6: UserWarning: Boolean Series key will be reindexed to match DataFrame index.
MIT
notebooks/data_preprocessing.ipynb
SudoHead/movie-classifier
Transform column genre
def extract_genres(genres_str): genres_str = genres_str.replace("'", '\"') genres_json = json.loads(genres_str) genres_list = [] for elem in genres_json: genres_list.append(elem['name']) return genres_list # remove rows with no genres, since they don't provide any information df.drop(df[df['...
_____no_output_____
MIT
notebooks/data_preprocessing.ipynb
SudoHead/movie-classifier
Visualise movie genres' distribution
all_genres = sum(df['genres'], []) genre_types = set(all_genres) len(genre_types) all_genres = nltk.FreqDist(all_genres) # create dataframe all_genres_df = pd.DataFrame({'Genre': list(all_genres.keys()), 'Count': list(all_genres.values())}) g = all_genres_df.nlargest(columns="Count", n...
_____no_output_____
MIT
notebooks/data_preprocessing.ipynb
SudoHead/movie-classifier
Text Preprocessing
def to_lower(text): return text.lower() def remove_specials(sentence): sentence = sentence.replace('-', ' ') sentence = re.sub(r'[^\w\s]', '', sentence) return sentence def remove_stopwords(tokens): words = [] for word in tokens: if word not in nltk.corpus.stopwords.words('english'): ...
_____no_output_____
MIT
notebooks/data_preprocessing.ipynb
SudoHead/movie-classifier
Save the processed data:
# new_df.to_csv("../data/movies_data_ready.csv", index=False)
_____no_output_____
MIT
notebooks/data_preprocessing.ipynb
SudoHead/movie-classifier
Model Training
for a in alpha: for i in range(5000): for j in range(x.size): h[j]=theta[0]*1 + theta[1]*x[j] + theta[2]*np.power(x[j],2) + theta[3]*np.power(x[j],3) theta=theta+a*(y[j]-h[j])*np.array([1, x[j], np.power(x[j],2), np.power(x[j],3)]) if a==0.03: error[i]=np.sum(np.s...
_____no_output_____
MIT
Results/Jupyter/ML/ex1.ipynb
in2dblue/interactive-rl
Dataset Bug DetectionIn this example, we will demonstrate how to detect bugs in a data set using the public Airlines data set.
# Since we use the category_encoders library to perform binary encoding on some of the features in this demo, # we'll need to install it. !pip install category_encoders import pandas pandas.options.display.max_rows=5 # restrict to 5 rows on display df = pandas.read_csv("https://raw.githubusercontent.com/Devvrat53/Fli...
_____no_output_____
Apache-2.0
docs/notebooks/divergence/BugDetection.ipynb
FINRAOS/model-validation-toolkit
Prepare daily dataLet's assume that we run new data each day through our model. For simplicity we will just look at the last 10 days of data.
df_daily = df[df['month'] > 11] df_daily = df_daily[df_daily['day'] > 20] df_daily
_____no_output_____
Apache-2.0
docs/notebooks/divergence/BugDetection.ipynb
FINRAOS/model-validation-toolkit
Bug DetectionNow we want to find any bugs in any of our daily sets of data that we feed to our model.Note that we are performing binary encoding on the categorical columns (carrier, origin, and dest) so that we can pass the data to the variational estimation function directly. We are doing this for performance reasons...
import category_encoders as ce from mvtk.supervisor.utils import compute_divergence_crosstabs from mvtk.supervisor.divergence import calc_tv_knn columns = ['dep_time', 'sched_dep_time', 'dep_delay', 'arr_time', 'sched_arr_time', 'arr_delay', 'air_time', 'distance', 'hour', 'minute', 'carrier', 'origin', 'dest'] encod...
_____no_output_____
Apache-2.0
docs/notebooks/divergence/BugDetection.ipynb
FINRAOS/model-validation-toolkit
As you can see from the heatmap above, although there are some divergences between the days, there is nothing that is too alarming.Let's now update our data set to contain a "bug" in the "sched_dep_time" feature. For day 30, all of the values of that feature are null (which we are then translating to 0).
df_daily.loc[df_daily['day'] == 30, ['sched_dep_time']] = None
_____no_output_____
Apache-2.0
docs/notebooks/divergence/BugDetection.ipynb
FINRAOS/model-validation-toolkit
Below is the percentage of scheduled departure times that are empty per day in our updated daily data set
day = 21 for df_day in df_daily.groupby('day'): day_pct = df_day[1]['sched_dep_time'].value_counts(normalize=True, dropna=False) * 100 pct = day_pct.loc[day_pct.index.isnull()].values if (len(pct) == 0): pct = 0 else: pct = pct[0] print('Day ' + str(day) + ': ' + str(round(pct)) + '%...
_____no_output_____
Apache-2.0
docs/notebooks/divergence/BugDetection.ipynb
FINRAOS/model-validation-toolkit
Think BayesThis notebook presents example code and exercise solutions for Think Bayes.Copyright 2018 Allen B. DowneyMIT License: https://opensource.org/licenses/MIT
# Configure Jupyter so figures appear in the notebook %matplotlib inline # Configure Jupyter to display the assigned value after an assignment %config InteractiveShell.ast_node_interactivity='last_expr_or_assign' # import classes from thinkbayes2 from thinkbayes2 import Hist, Pmf, Suite, Beta import thinkplot import...
_____no_output_____
MIT
solutions/world_cup_soln.ipynb
chwebster/ThinkBayes2
Controllo di un braccio robotico con giunto flessibileUn collegamento di un braccio robotico è azionato da un motore elettrico tramite un giunto flessibile che si comporta come una molla torsionale. La dinamica del sistema può essere approssimata con un sistema lineare tempo invariante del terzo ordine in cui gli stat...
A = numpy.matrix('0 1 -1; -0.9 -0.09 0.09; 0.1 0.01 -0.01') B = numpy.matrix('0; 90; 0') C = numpy.matrix('0 0 1') D = numpy.matrix('0') sys_tf = control.tf(sss(A,B,C,D)) print(sys_tf)
3.886e-16 s^2 + 0.9 s + 9 ----------------------------- s^3 + 0.1 s^2 + s - 8.674e-19
BSD-3-Clause
ICCT_it/examples/04/.ipynb_checkpoints/SS-40-Controllo_di_un_braccio_robotico_con_giunto_flessibile-checkpoint.ipynb
ICCTerasmus/ICCT
con poli
import warnings # In order to suppress the warning BadCoefficient warnings.filterwarnings("ignore") print(numpy.round(sys_tf.pole(),3))
[-0.05+0.999j -0.05-0.999j 0. +0.j ]
BSD-3-Clause
ICCT_it/examples/04/.ipynb_checkpoints/SS-40-Controllo_di_un_braccio_robotico_con_giunto_flessibile-checkpoint.ipynb
ICCTerasmus/ICCT
e zeri
print(numpy.round(sys_tf.zero(),3),'.')
[-2.31613695e+15 -1.00000000e+01] .
BSD-3-Clause
ICCT_it/examples/04/.ipynb_checkpoints/SS-40-Controllo_di_un_braccio_robotico_con_giunto_flessibile-checkpoint.ipynb
ICCTerasmus/ICCT
Innanzitutto, si analizza il sistema per verificare se è controllabile e osservabile. La matrice di controllabilità $\mathcal{C}$ è
Ctrb = control.ctrb(A,B) display(Markdown(bmatrix(Ctrb))) # print(numpy.linalg.matrix_rank(Ctrb))
_____no_output_____
BSD-3-Clause
ICCT_it/examples/04/.ipynb_checkpoints/SS-40-Controllo_di_un_braccio_robotico_con_giunto_flessibile-checkpoint.ipynb
ICCTerasmus/ICCT
e ha rango pari a 3 quindi il sistema è controllabile. La matrice di osservabilità $\mathcal{O}$ è
Obsv = control.obsv(A,C) display(Markdown(bmatrix(Obsv))) # print(numpy.linalg.matrix_rank(Obsv))
_____no_output_____
BSD-3-Clause
ICCT_it/examples/04/.ipynb_checkpoints/SS-40-Controllo_di_un_braccio_robotico_con_giunto_flessibile-checkpoint.ipynb
ICCTerasmus/ICCT
e ha rango pari a 3 quindi il sistema è osservabile.Ciò potrebbe essere effettivamente dedotto dal fatto che il denominatore della funzione di trasferimento è del terzo ordine (uguale alla dimensione del vettore nello spazio degli stati). Design del regolatore Design del controllerDati i requisiti, si sa che si devono ...
# Preparatory cell X0 = numpy.matrix('0.0; 0.0; 0.0') K = numpy.matrix([8/15,-4.4,-4]) L = numpy.matrix([[23],[66],[107/3]]) Aw = matrixWidget(3,3) Aw.setM(A) Bw = matrixWidget(3,1) Bw.setM(B) Cw = matrixWidget(1,3) Cw.setM(C) X0w = matrixWidget(3,1) X0w.setM(X0) Kw = matrixWidget(1,3) Kw.setM(K) Lw = matrixWidget(3,...
_____no_output_____
BSD-3-Clause
ICCT_it/examples/04/.ipynb_checkpoints/SS-40-Controllo_di_un_braccio_robotico_con_giunto_flessibile-checkpoint.ipynb
ICCTerasmus/ICCT
Data Science and Business Analytics Intern @ The Sparks Foundation Author : Aniket M. Wazarkar Task 2 : Prediction using Unsupervised ML Dataset : Iris.csv (https://bit.ly/3kXTdox) Algorithm used here : K-Means Clustering Import Libraries
%matplotlib inline import matplotlib.pyplot as plt import pandas as pd import numpy as np from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.cluster import KMeans from sklearn.decomposition import PCA
_____no_output_____
Apache-2.0
Task #2 Prediction using Unsupervised ML.ipynb
aniketspeaks/Task-2-Prediction-using-Unsupervised-ML
Load Dataset
df=pd.read_csv('Iris.csv') df
_____no_output_____
Apache-2.0
Task #2 Prediction using Unsupervised ML.ipynb
aniketspeaks/Task-2-Prediction-using-Unsupervised-ML
K-Means is considered an unsupervised learning algorthm. This means you only need a features matrix. In the iris dataset, there are four features. In this notebook, the features matrix will only be two features as it is easier to visualize clusters in two dimensions. KMeans is a popular clustering algorithm that we can...
df.info() df.Species.unique() df["Species"].value_counts()
_____no_output_____
Apache-2.0
Task #2 Prediction using Unsupervised ML.ipynb
aniketspeaks/Task-2-Prediction-using-Unsupervised-ML
Arrange Data into Feature Matrix Use DataFrame.loc attribute to access a particular cell in the given Dataframe using the index and column labels.
features = ['PetalLengthCm','PetalWidthCm'] # Create features matrix x = df.loc[:, features].values x
_____no_output_____
Apache-2.0
Task #2 Prediction using Unsupervised ML.ipynb
aniketspeaks/Task-2-Prediction-using-Unsupervised-ML
class sklearn.preprocessing.LabelEncoder.Encode target labels with value between 0 and n_classes-1.
from sklearn import preprocessing le=preprocessing.LabelEncoder() df.Species=le.fit_transform(df.Species.values) df.Species y=df.Species y
_____no_output_____
Apache-2.0
Task #2 Prediction using Unsupervised ML.ipynb
aniketspeaks/Task-2-Prediction-using-Unsupervised-ML
Standardize the data Standardize features by removing the mean and scaling to unit varianceThe standard score of a sample x is calculated as:z = (x - u) / swhere u is the mean of the training samples or zero if with_mean=False, and s is the standard deviation of the training samples or one if with_std=False.
x=StandardScaler().fit_transform(x)
_____no_output_____
Apache-2.0
Task #2 Prediction using Unsupervised ML.ipynb
aniketspeaks/Task-2-Prediction-using-Unsupervised-ML
Plot data to estimate number of clusters
X=pd.DataFrame(x,columns=features) plt.figure(figsize=(6,5)) plt.scatter(X['PetalLengthCm'], X['PetalWidthCm']) plt.xlabel('petal length (cm)') plt.ylabel('petal width (cm)'); plt.title('K-Means Clustering')
_____no_output_____
Apache-2.0
Task #2 Prediction using Unsupervised ML.ipynb
aniketspeaks/Task-2-Prediction-using-Unsupervised-ML
Finding the optimum number of clusters for K-means clustering
# Finding the optimum number of clusters for k-means classification wcss = [] for i in range(1, 11): kmeans = KMeans(n_clusters = i, init = 'k-means++', max_iter = 300, n_init = 10, random_state = 0) kmeans.fit(x) wcss.append(kmeans.inertia_) # Plotting the results onto a line graph, ...
_____no_output_____
Apache-2.0
Task #2 Prediction using Unsupervised ML.ipynb
aniketspeaks/Task-2-Prediction-using-Unsupervised-ML
It is called 'The elbow method' from the above graph, the optimum clusters is where the elbow occurs. This is when the within cluster sum of squares (WCSS) doesn't decrease significantly with every iteration.From this we choose the number of clusters as **'3'**. K-Means Clustering
# Make an instance of KMeans with 3 clusters kmeans = KMeans(n_clusters=3, random_state=1) # Fit only on a features matrix kmeans.fit(x) # Get labels and cluster centroids labels = kmeans.labels_ centroids = kmeans.cluster_centers_ labels centroids
_____no_output_____
Apache-2.0
Task #2 Prediction using Unsupervised ML.ipynb
aniketspeaks/Task-2-Prediction-using-Unsupervised-ML
Visually Evaluate the clusters
colormap = np.array(['r', 'g', 'b']) plt.scatter(X['PetalLengthCm'], X['PetalWidthCm'], c=colormap[labels]) plt.scatter(centroids[:,0], centroids[:,1], s = 300, marker = 'x', c = 'k') plt.xlabel('petal length (cm)') plt.ylabel('petal width (cm)');
_____no_output_____
Apache-2.0
Task #2 Prediction using Unsupervised ML.ipynb
aniketspeaks/Task-2-Prediction-using-Unsupervised-ML
Visually Evaluate the clusters and compare the species
plt.figure(figsize=(10,4)) plt.subplot(1, 2, 1) plt.scatter(X['PetalLengthCm'], X['PetalWidthCm'], c=colormap[labels]) plt.scatter(centroids[:,0], centroids[:,1], s = 300, marker = 'x', c = 'k') plt.xlabel('petal length (cm)') plt.ylabel('petal width (cm)'); plt.title('K-Means Clustering (k = 3)') plt.subplot(1, 2, ...
_____no_output_____
Apache-2.0
Task #2 Prediction using Unsupervised ML.ipynb
aniketspeaks/Task-2-Prediction-using-Unsupervised-ML
They look pretty similar. Looks like KMeans picked up flower differences with only two features and not the labels. The colors are different in the two graphs simply because KMeans gives out a arbitrary cluster number and the iris dataset has an arbitrary number in the target column. PCA Projection in 2D The original...
pca = PCA(n_components=2) # Fit and transform the data principalComponents = pca.fit_transform(x) principalDf = pd.DataFrame(data = principalComponents, columns = ['principal component 1', 'principal component 2']) df=pd.read_csv('Iris.csv')
_____no_output_____
Apache-2.0
Task #2 Prediction using Unsupervised ML.ipynb
aniketspeaks/Task-2-Prediction-using-Unsupervised-ML
2D Projection
finalDf = pd.concat([principalDf, df[['Species']]], axis = 1) finalDf fig, ax = plt.subplots(nrows = 1, ncols = 1, figsize = (8,8)); targets = df.loc[:, 'Species'].unique() colors = ['r', 'g', 'b'] for target, color in zip(targets,colors): indicesToKeep = finalDf['Species'] == target ax.scatter(finalDf.loc[ind...
_____no_output_____
Apache-2.0
Task #2 Prediction using Unsupervised ML.ipynb
aniketspeaks/Task-2-Prediction-using-Unsupervised-ML
From the graph, it looks like the setosa class is well separated from the versicolor and virginica classes. Explained Varience The explained variance tells us how much information (variance) can be attributed to each of the principal components. This is important as while you can convert 4 dimensional space to 2 dimen...
pca.explained_variance_ratio_ sum(pca.explained_variance_ratio_)
_____no_output_____
Apache-2.0
Task #2 Prediction using Unsupervised ML.ipynb
aniketspeaks/Task-2-Prediction-using-Unsupervised-ML
Dynamics 365 Business Central Trouble Shooting Guide (TSG) - Performance analysis (overview) This notebook contains Kusto queries that can help getting to the root cause of a performance issue for an environment. Each section in the notebook contains links to the performance tuning guide on docs [aka.ms/bcperformance...
# load the KQLmagic module %reload_ext Kqlmagic # Connect to the Application Insights API %kql appinsights://appid='<add app id from the Application Insights portal>';appkey='<add API key from the Application Insights portal>'
_____no_output_____
MIT
samples/AppInsights/TroubleShootingGuides/Performance-overview-TSG.ipynb
dmc-dk/BCTech
2. Define filters This workbook is designed for troubleshooting a single environment. Please provide values for aadTenantId and environmentName:
aadTenantId = "<Add AAD tenant id here>" environmentName = "<add environment name here>"
_____no_output_____
MIT
samples/AppInsights/TroubleShootingGuides/Performance-overview-TSG.ipynb
dmc-dk/BCTech
Analyze performance Now you can run Kusto queries to look for possible root causes for performance issues. Either click **Run All** above to run all sections, or scroll down to the type of analysis you want to do and manually run queries Sessions Performance tuning guide: https://docs.microsoft.com/en-us/dynamics36...
%%kql let _aadTenantId = aadTenantId; let _environmentName = environmentName; traces | where 1==1 and customDimensions.aadTenantId == _aadTenantId and customDimensions.environmentName == _environmentName and customDimensions.eventId == 'RT0004' and timestamp > ago(7d) | extend clientType = tos...
_____no_output_____
MIT
samples/AppInsights/TroubleShootingGuides/Performance-overview-TSG.ipynb
dmc-dk/BCTech
Web service requests Performance tuning guide: https://docs.microsoft.com/en-us/dynamics365/business-central/dev-itpro/performance/performance-developerwriting-efficient-web-services Web service telemetry docs: https://docs.microsoft.com/en-us/dynamics365/business-central/dev-itpro/administration/telemetry-webservic...
%%kql let _aadTenantId = aadTenantId; let _environmentName = environmentName; traces | where 1==1 and customDimensions.aadTenantId == _aadTenantId and customDimensions.environmentName == _environmentName and customDimensions.eventId == 'RT0008' and timestamp > ago(7d) | extend category = tostr...
_____no_output_____
MIT
samples/AppInsights/TroubleShootingGuides/Performance-overview-TSG.ipynb
dmc-dk/BCTech
Data related Performance tuning guide: * [Efficient data access](https://docs.microsoft.com/en-us/dynamics365/business-central/dev-itpro/performance/performance-developerefficient-data-access) * [Avoid locking](https://docs.microsoft.com/en-us/dynamics365/business-central/dev-itpro/performance/performance-applicatio...
%%kql let _aadTenantId = aadTenantId; let _environmentName = environmentName; traces | where 1==1 and customDimensions.aadTenantId == _aadTenantId and customDimensions.environmentName == _environmentName and customDimensions.eventId == 'RT0005' and timestamp > ago(7d) | summarize count() by bi...
_____no_output_____
MIT
samples/AppInsights/TroubleShootingGuides/Performance-overview-TSG.ipynb
dmc-dk/BCTech
Company management Operations such as "copy company" can cause performance degradations if they are done when users are logged into the system. Read more in the performance tuning guide here: https://docs.microsoft.com/en-us/dynamics365/business-central/dev-itpro/performance/performance-applicationbe-cautious-with-t...
%%kql let _aadTenantId = aadTenantId; let _environmentName = environmentName; traces | where 1==1 and customDimensions.aadTenantId == _aadTenantId and customDimensions.environmentName == _environmentName and customDimensions.eventId in ('LC0001') and timestamp > ago(7d) | extend operation_typ...
_____no_output_____
MIT
samples/AppInsights/TroubleShootingGuides/Performance-overview-TSG.ipynb
dmc-dk/BCTech
Reports Learn more about how to write performant reports here in the performance tuning guide: https://docs.microsoft.com/en-us/dynamics365/business-central/dev-itpro/performance/performance-developerwriting-efficient-reports Report telemetry docs: https://docs.microsoft.com/en-us/dynamics365/business-central/dev-it...
%%kql let _aadTenantId = aadTenantId; let _environmentName = environmentName; traces | where 1==1 and customDimensions.aadTenantId == _aadTenantId and customDimensions.environmentName == _environmentName and customDimensions.eventId == 'RT0006' and timestamp > ago(7d) | extend clientType = tos...
_____no_output_____
MIT
samples/AppInsights/TroubleShootingGuides/Performance-overview-TSG.ipynb
dmc-dk/BCTech
Page views Page view telemetry docs: https://docs.microsoft.com/en-us/dynamics365/business-central/dev-itpro/administration/telemetry-page-view-trace KQL samples * https://github.com/microsoft/BCTech/blob/master/samples/AppInsights/KQL/RawData/PageViews.kql * https://github.com/microsoft/BCTech/blob/master/samples/A...
%%kql // Top 10 longest page times // let _aadTenantId = aadTenantId; let _environmentName = environmentName; pageViews | where 1==1 and customDimensions.aadTenantId == _aadTenantId // and customDimensions.environmentName == _environmentName | where timestamp > ago(7d) | extend objectId = tostring(c...
_____no_output_____
MIT
samples/AppInsights/TroubleShootingGuides/Performance-overview-TSG.ipynb
dmc-dk/BCTech
FloPy Creating a Complex MODFLOW 6 Model with FlopyThe purpose of this notebook is to demonstrate the Flopy capabilities for building a more complex MODFLOW 6 model from scratch. This notebook will demonstrate the capabilities by replicating the advgw_tidal model that is distributed with MODFLOW 6. Setup the Noteboo...
%matplotlib inline import sys import os import platform import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt # run installed version of flopy or add local path try: import flopy except: fpth = os.path.abspath(os.path.join('..', '..')) sys.path.append(fpth) import flopy print(sys...
_____no_output_____
CC0-1.0
examples/Notebooks/flopy3_mf6_B_complex-model.ipynb
gyanz/flopy
Create the MODFLOW 6 Input Files and Run the ModelOnce all the flopy objects are created, it is very easy to create all of the input files and run the model.
# change folder to save simulation #sim.simulation_data.mfpath.set_sim_path(run_folder) # write simulation to new location sim.write_simulation() # Print a list of the files that were created # in workspace print(os.listdir(workspace))
['intercell_flow_obs1.csv', 'riv_flowsA.csv', 'advgw_tidal.nam', 'advgw_tidal.ic', 'riv_flowsB.csv', 'advgw_tidal.dis.grb', 'recharge_rates_1.ts', 'advgw_tidal.sto', 'advgw_tidal.lst', 'tides.ts', 'advgw_tidal.cbb', 'advgw_tidal.ims', 'well-rates.ts', 'advgw_tidal.ghb', 'advgw_tidal.obs', 'advgw_tidal.riv.obs', 'ghb_fl...
CC0-1.0
examples/Notebooks/flopy3_mf6_B_complex-model.ipynb
gyanz/flopy
Run the SimulationWe can also run the simulation from the notebook, but only if the MODFLOW 6 executable is available. The executable can be made available by putting the executable in a folder that is listed in the system path variable. Another option is to just put a copy of the executable in the simulation folder...
# Run the simulation success, buff = sim.run_simulation() print('\nSuccess is: ', success)
FloPy is using the following executable to run the model: /Users/jdhughes/.local/bin/mf6 MODFLOW 6 U.S. GEOLOGICAL SURVEY MODULAR HYDROLOGIC MODEL VERSION 6.0.3 08/09/2018 MODFLOW 6 compiled Sep 24 2018 16:09:01 with GFORTRAN compiler (v...
CC0-1.0
examples/Notebooks/flopy3_mf6_B_complex-model.ipynb
gyanz/flopy
Post-Process Head ResultsPost-processing MODFLOW 6 results is still a work in progress. There aren't any Flopy plotting functions built in yet, like they are for other MODFLOW versions. So we need to plot the results using general Flopy capabilities. We can also use some of the Flopy ModelMap capabilities for MODFL...
# Read the binary head file and plot the results # We can use the existing Flopy HeadFile class because # the format of the headfile for MODFLOW 6 is the same # as for previous MODFLOW verions headfile = '{}.hds'.format(model_name) fname = os.path.join(workspace, headfile) hds = flopy.utils.binaryfile.HeadFile(fname) h...
_____no_output_____
CC0-1.0
examples/Notebooks/flopy3_mf6_B_complex-model.ipynb
gyanz/flopy
Post-Process FlowsMODFLOW 6 writes a binary grid file, which contains information about the model grid. MODFLOW 6 also writes a binary budget file, which contains flow information. Both of these files can be read using Flopy capabilities. The MfGrdFile class in Flopy can be used to read the binary grid file. The C...
# read the binary grid file fname = os.path.join(workspace, '{}.dis.grb'.format(model_name)) bgf = flopy.utils.mfgrdfile.MfGrdFile(fname) # data read from the binary grid file is stored in a dictionary bgf._datadict # Information from the binary grid file is easily retrieved ia = bgf._datadict['IA'] - 1 ja = bgf._data...
_____no_output_____
CC0-1.0
examples/Notebooks/flopy3_mf6_B_complex-model.ipynb
gyanz/flopy
Clustering text documents using k-meansAs an example we'll be using the 20 newsgroups dataset consists of 18000+ newsgroup posts on 20 topics. You can learn more about the dataset at http://qwone.com/~jason/20Newsgroups/
from sklearn.datasets import fetch_20newsgroups from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.preprocessing import Normalizer from sklearn import metrics import matplotlib.pyplot as plt from sklearn.cluster import KMeans, MiniBatchKMeans import numpy as np
_____no_output_____
MIT
jupyter_notebooks/machine_learning/ebook_mastering_ml_in_6_steps/Chapter_5_Code/Code/Document_Clustering.ipynb
manual123/Nacho-Jupyter-Notebooks
Load data
newsgroups_train = fetch_20newsgroups(subset='train') print(list(newsgroups_train.target_names))
['alt.atheism', 'comp.graphics', 'comp.os.ms-windows.misc', 'comp.sys.ibm.pc.hardware', 'comp.sys.mac.hardware', 'comp.windows.x', 'misc.forsale', 'rec.autos', 'rec.motorcycles', 'rec.sport.baseball', 'rec.sport.hockey', 'sci.crypt', 'sci.electronics', 'sci.med', 'sci.space', 'soc.religion.christian', 'talk.politics.gu...
MIT
jupyter_notebooks/machine_learning/ebook_mastering_ml_in_6_steps/Chapter_5_Code/Code/Document_Clustering.ipynb
manual123/Nacho-Jupyter-Notebooks
To keep it simple, let's filter only 3 topics. Assume that we do not know the topics, let's run clustering algorithm and examine the keywords of each clusters
categories = ['alt.atheism', 'comp.graphics', 'rec.motorcycles'] dataset = fetch_20newsgroups(subset='all', categories=categories, shuffle=True, random_state=2017) print("%d documents" % len(dataset.data)) print("%d categories" % len(dataset.target_names)) labels = dataset.target print("Extracting features from the...
2768 documents 3 categories Extracting features from the dataset using a sparse vectorizer n_samples: 2768, n_features: 35311
MIT
jupyter_notebooks/machine_learning/ebook_mastering_ml_in_6_steps/Chapter_5_Code/Code/Document_Clustering.ipynb
manual123/Nacho-Jupyter-Notebooks
LSA via SVDLatent Semantic Analysis (LSA) is a mathematical method that tries to bring out latent relationships within a collection of documents. Rather than looking at each document isolated from the others it looks at all the documents as a whole and the terms within them to identify relationships. Let's perform LSA...
from IPython.display import Image Image(filename='../Chapter 5 Figures/SVD.png', width=500) from sklearn.decomposition import TruncatedSVD # Lets reduce the dimensionality to 2000 svd = TruncatedSVD(2000) lsa = make_pipeline(svd, Normalizer(copy=False)) X = lsa.fit_transform(X) explained_variance = svd.explained_var...
Explained variance of the SVD step: 95%
MIT
jupyter_notebooks/machine_learning/ebook_mastering_ml_in_6_steps/Chapter_5_Code/Code/Document_Clustering.ipynb
manual123/Nacho-Jupyter-Notebooks
k-means clustering
from __future__ import print_function km = KMeans(n_clusters=3, init='k-means++', max_iter=100, n_init=1) # Scikit learn provides MiniBatchKMeans to run k-means in batch mode suitable for a very large corpus # km = MiniBatchKMeans(n_clusters=5, init='k-means++', n_init=1, init_size=1000, batch_size=1000) print("Clus...
Clustering sparse data with KMeans(algorithm='auto', copy_x=True, init='k-means++', max_iter=100, n_clusters=3, n_init=1, n_jobs=1, precompute_distances='auto', random_state=None, tol=0.0001, verbose=0) Top terms per cluster: Cluster 0: edu graphics university god subject lines organization com posting uk Clust...
MIT
jupyter_notebooks/machine_learning/ebook_mastering_ml_in_6_steps/Chapter_5_Code/Code/Document_Clustering.ipynb
manual123/Nacho-Jupyter-Notebooks
Hierarchical clustering
from sklearn.metrics.pairwise import cosine_similarity dist = 1 - cosine_similarity(X) from scipy.cluster.hierarchy import ward, dendrogram linkage_matrix = ward(dist) #define the linkage_matrix using ward clustering pre-computed distances fig, ax = plt.subplots(figsize=(8, 8)) # set size ax = dendrogram(linkage_matr...
_____no_output_____
MIT
jupyter_notebooks/machine_learning/ebook_mastering_ml_in_6_steps/Chapter_5_Code/Code/Document_Clustering.ipynb
manual123/Nacho-Jupyter-Notebooks
10 May 2017 - Lecture 2 JNB Code Along - WH Nixalo[Notebook](https://github.com/fastai/courses/blob/ed1fb08d86df277d2736972a1ff1ac39ea1ac733/deeplearning1/nbs/lesson2.ipynb) | Lecture[1:20:00](https://www.youtube.com/watch?v=e3aM6XTekJc) 1 Linear models with CNN features
# This is to point Python to my utils folder import sys; import os # DIR = %pwd sys.path.insert(1, os.path.join('../utils')) # Rather than importing everything manually, we'll make things easy # and load them all in utils.py, and just import them from there. import utils; reload(utils) from utils import * %matplotli...
Using Theano backend.
MIT
FAI_old/lesson2/lesson2_codealong.ipynb
WNoxchi/Kawkasos
1.1 IntroWe need to find a way to convert the imagenet predictions to a probability of being a cat or a dog, since that is what the Kaggle copmetition requires us to submit. We could use the imagenet hierarchy to download a list of all the imagenet categories in each of the dog and cat groups, and could then solve ou...
%matplotlib inline from __future__ import division, print_function import os, json from glob import glob import numpy as np import scipy from sklearn.preprocessing import OneHotEncoder from sklearn.metrics import confusion_matrix np.set_printoptions(precision=4, linewidth=100) from matplotlib import pyplot as plt impo...
_____no_output_____
MIT
FAI_old/lesson2/lesson2_codealong.ipynb
WNoxchi/Kawkasos
1.2 Linear models in kerasLet's forget the motivating example for a second a see how we can create a simple Linear model in Keras:Each of the ```Dense()``` layers is just a *linear* model, followed by a simple *activation function*.In a linear model each row is calculated as ```sum(row * weights)```, where weights nee...
# we'll create a random matrix w/ 2 columns; & do a MatMul to get our # y value using a vector [2, 3] & adding a constant of 1. x = random((30, 2)) y = np.dot(x, [2., 3.]) + 1. x[:5] y[:5]
_____no_output_____
MIT
FAI_old/lesson2/lesson2_codealong.ipynb
WNoxchi/Kawkasos
We can use kears to create a simple linear model (```Dense()``` - with no activation - in Keras) and optimize it using SGD to minimize mean squared error.
# Keras calls the Linear Model "Dense"; aka. "Fully-Connected" in other # libraries. # So when we go 'Dense' w/ an input of 2 columns, & output of 1 col, # we're defining a linear model that can go from the 2 col array above, to # the 1 col output of y above. # Sequential() is a way of building multiple-layer network...
_____no_output_____
MIT
FAI_old/lesson2/lesson2_codealong.ipynb
WNoxchi/Kawkasos
Above is everything Keras is doing behind the scenes.So, if we pass multiple layers to Keras via ```Sequential(..)```, we can start to build & optimize Deep Neural Networks.Before that, we can still use the single-layer LM to create a pretty decent entry to the dogs-vs-cats Kaggle competition. 1.3 Train Linear Model o...
# setup the directories os.mkdir('data') os.mkdir('data/dogscats') path = "data/dogscats/" model_path = path + 'models/' # if the path to our models DNE, make it if not os.path.exists(model_path): os.mkdir(model_path) # NOTE: os.mkdir(..) only works for a single folder # Also will throw error if dir already exis...
_____no_output_____
MIT
FAI_old/lesson2/lesson2_codealong.ipynb
WNoxchi/Kawkasos
We'll process as many images at a time as we can. This is a case of T&E to find the max batch size that doesn't cause a memory error.
batch_size = 100
_____no_output_____
MIT
FAI_old/lesson2/lesson2_codealong.ipynb
WNoxchi/Kawkasos