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
Gym Crowdedness Analysis with PCA > Objective : To **predict** how crowded a university gym would be at a given time of day (and some other features, including weather) > Data Decription : The dataset consists of 26,000 people counts (about every 10 minutes) over one year. The dataset also contains information abo...
import numpy as np # linear algebra import pandas as pd import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline df=pd.read_csv(r'C:\Users\kusht\OneDrive\Desktop\Excel-csv\PCA analysis.csv') #Replace it with your path where the data file is stored df.head()
_____no_output_____
MIT
Gym Crowd Analysis/Gym Crowd Analysis with PCA (ToDo Template).ipynb
abhisngh/Data-Science
**TASK : Print the `info()` of the dataset**
### START CODE HERE (~ 1 Line of code) ### END CODE
_____no_output_____
MIT
Gym Crowd Analysis/Gym Crowd Analysis with PCA (ToDo Template).ipynb
abhisngh/Data-Science
**TASK : Describe the dataset using `describe()`**
### START CODE HERE (~ 1 Line of code) ### END CODE
_____no_output_____
MIT
Gym Crowd Analysis/Gym Crowd Analysis with PCA (ToDo Template).ipynb
abhisngh/Data-Science
**TASK : Convert temperature in farenheit into celsius scale using the formula `Celsius=(Fahrenheit-32)* (5/9)`**
### START CODE HERE (~1 Line of code) ### END CODE
_____no_output_____
MIT
Gym Crowd Analysis/Gym Crowd Analysis with PCA (ToDo Template).ipynb
abhisngh/Data-Science
**TASK : Convert the timestamp into hours in 12 h format as its currently in seconds and drop `date` coulmn**
### START CODE HERE: (~ 1 Line of code) ### END CODE
_____no_output_____
MIT
Gym Crowd Analysis/Gym Crowd Analysis with PCA (ToDo Template).ipynb
abhisngh/Data-Science
`2` Exploratory Data Analysis `2.1` Uni-Variate and Bi-Variate Analysis - **Pair Plots** **TASK : Use `pairplot()` to make different pair scatter plots of the entire dataframe**
### START CODE HERE : ### END CODE
_____no_output_____
MIT
Gym Crowd Analysis/Gym Crowd Analysis with PCA (ToDo Template).ipynb
abhisngh/Data-Science
**TASK: Now analyse scatter plots between `number_people` and all other attributes using a `for loop` to properly know what are the ideal conditions for people to come to the gym**
### START CODE HERE ### END CODE
_____no_output_____
MIT
Gym Crowd Analysis/Gym Crowd Analysis with PCA (ToDo Template).ipynb
abhisngh/Data-Science
**Analyse the plots and understand :**1. **At what time , temperature , week of the day more people come in?** 2. **Whether people like to come to the gym in a holiday or a weekend or they prefer to come to gym during working days?** 3. **Which month is most preferable for people to come to the gym?** - *...
### START CODE HERE : ### END CODE
_____no_output_____
MIT
Gym Crowd Analysis/Gym Crowd Analysis with PCA (ToDo Template).ipynb
abhisngh/Data-Science
`2.2` Correlation Matrix **TASK : Plot a correlation matrix and make it more understandable using `sns.heatmap`**
### START CODE HERE : ### END CODE HERE
_____no_output_____
MIT
Gym Crowd Analysis/Gym Crowd Analysis with PCA (ToDo Template).ipynb
abhisngh/Data-Science
**Analyse the correlation matrix and understand the different dependencies of attributes on each other** `3.` Processing : `3.1` One hot encoding :One hot encoding certain attributes to not give any ranking/priority to any instance **TASK: One Hot Encode following attributes `month` , `hour` , `day of week`**
## YOU CAN USE EITHER get_dummies() OR OneHotEncoder() ### START CODE HERE : ### END CODE
_____no_output_____
MIT
Gym Crowd Analysis/Gym Crowd Analysis with PCA (ToDo Template).ipynb
abhisngh/Data-Science
`3.2` Feature Scaling :Some attributes ranges are ver different compared to other values and during PCA implementation this might give a problem thus you need to standardise some of the attributes **TASK: Using `StandardScaler()` , standardise `temperature` and `timestamp`**
## You can use two individual scalers one for temperature and other for timestamp ## you can use an array type data=df.values and standradise data then split data into X and y from sklearn.preprocessing import StandardScaler ### START CODE HERE : (Replace places having '#' with the code) data=df.values scaler1 = Standa...
_____no_output_____
MIT
Gym Crowd Analysis/Gym Crowd Analysis with PCA (ToDo Template).ipynb
abhisngh/Data-Science
`4.` Splitting the dataset : **TASK : Split the dataset into dependent and independent variables and name them y and X respectively**
### START CODE HERE : ### END CODE
_____no_output_____
MIT
Gym Crowd Analysis/Gym Crowd Analysis with PCA (ToDo Template).ipynb
abhisngh/Data-Science
**TASK : Split the X ,y into training and test set**
from sklearn.model_selection import train_test_split ### START CODE HERE : ### END CODE
_____no_output_____
MIT
Gym Crowd Analysis/Gym Crowd Analysis with PCA (ToDo Template).ipynb
abhisngh/Data-Science
`5.` Principal Component Analysis Principal component analysis (PCA) is a technique for reducing the dimensionality of such datasets, increasing interpretability but at the same time minimizing information loss. It does so by creating new uncorrelated variables that successively maximize variance. **How does it work? ...
from sklearn.decomposition import PCA ### START CODE HERE : (Replace spaces having '#' with the code) pca = PCA() pca.fit_transform(#) ### END CODE
_____no_output_____
MIT
Gym Crowd Analysis/Gym Crowd Analysis with PCA (ToDo Template).ipynb
abhisngh/Data-Science
**TASK : Get covariance using `get_covariance()`**
### START CODE HERE (~ 1 line of code) ### END CODE HERE
_____no_output_____
MIT
Gym Crowd Analysis/Gym Crowd Analysis with PCA (ToDo Template).ipynb
abhisngh/Data-Science
**TASK : Get explained variance using `explained_variance_ratio`**
### START CODE HERE : ### END CODE
_____no_output_____
MIT
Gym Crowd Analysis/Gym Crowd Analysis with PCA (ToDo Template).ipynb
abhisngh/Data-Science
**TASK : Plot a bar graph of `explained variance`**
# you can use plt.bar() ### START CODE HERE : (Replace spaces having '#' with the code) with plt.style.context('dark_background'): plt.figure(figsize=(15,12)) plt.bar(range(49), '#', alpha=0.5, align='center', label='individual explained variance') plt.ylabel('#') plt.xlabel('#') plt.l...
_____no_output_____
MIT
Gym Crowd Analysis/Gym Crowd Analysis with PCA (ToDo Template).ipynb
abhisngh/Data-Science
**Analyse the plot and estimate how many componenets you want to keep** **TASK : Make a `PCA()` object with n_components =20 and fit-transform in the dataset (X) and assign to a new variable `X_new`**
### START CODE HERE : ### END CODE
_____no_output_____
MIT
Gym Crowd Analysis/Gym Crowd Analysis with PCA (ToDo Template).ipynb
abhisngh/Data-Science
Now , `X_new` is the dataset for PCA **TASK : Get Covariance using `get_covariance`**
### START CODE HERE (~1 Line of code) ### END CODE
_____no_output_____
MIT
Gym Crowd Analysis/Gym Crowd Analysis with PCA (ToDo Template).ipynb
abhisngh/Data-Science
**TASK : Get the explained variance using `explained_variance_ratio`**
### START CODE HERE : ### END CODE
_____no_output_____
MIT
Gym Crowd Analysis/Gym Crowd Analysis with PCA (ToDo Template).ipynb
abhisngh/Data-Science
**TASK : Plot bar plot of `exlpained variance`**
# You can use plt.bar() ### START CODE HERE: ### END CODE
_____no_output_____
MIT
Gym Crowd Analysis/Gym Crowd Analysis with PCA (ToDo Template).ipynb
abhisngh/Data-Science
`6.` Modelling : Random Forest To understand Random forest classifier , lets first get a brief idea about Decision Trees in general. Decision Trees are very intuitive and at everyone have used this knowingly or unknowingly at some point . Basically the model keeps sorting them into categories forming a large tree by r...
# Establish model from sklearn.ensemble import RandomForestRegressor model = RandomForestRegressor() # Try different numbers of n_estimators and print the scores # You can use a variable estimators = np.arrange(10,200,10) and then a for loop to take all the values of estimators ### START CODE HERE : (Replace spaces ha...
_____no_output_____
MIT
Gym Crowd Analysis/Gym Crowd Analysis with PCA (ToDo Template).ipynb
abhisngh/Data-Science
**TASK : Make a plot between `n_estimator` and `scores` to properly get the best number of estimators**
## Use plt.plot ### START CODE HERE : ### END CODE HERE
_____no_output_____
MIT
Gym Crowd Analysis/Gym Crowd Analysis with PCA (ToDo Template).ipynb
abhisngh/Data-Science
`6.2` Random Forest With PCA **TASK : Split the your dataset with PCA into training and testing set using `train_test_split`**
from sklearn.model_selection import train_test_split ### START CODE HERE : ### END CODE
_____no_output_____
MIT
Gym Crowd Analysis/Gym Crowd Analysis with PCA (ToDo Template).ipynb
abhisngh/Data-Science
**TASK : Make a random forest model called `model_pca` and fit it into the new X_train and y_train and then print out the random forest scores for dataset with PCA applied to it**
# Establish model from sklearn.ensemble import RandomForestRegressor model_pca = RandomForestRegressor() # You can use different number of estimators # # You can use a variable estimators = np.arrange(10,200,10) and then a for loop to take all the values of estimators ### START CODE HERE : ### END CODE
_____no_output_____
MIT
Gym Crowd Analysis/Gym Crowd Analysis with PCA (ToDo Template).ipynb
abhisngh/Data-Science
**TASK : Make a plot between `n_estimator` and `score` and find the best parameter**
# you can use plt.plot ### START CODE HERE : ### END CODE
_____no_output_____
MIT
Gym Crowd Analysis/Gym Crowd Analysis with PCA (ToDo Template).ipynb
abhisngh/Data-Science
Performance programming We've spent most of this course looking at how to make code readable and reliable. For research work, it is often also important that code is efficient: that it does what it needs to do *quickly*. It is very hard to work out beforehand whether code will be efficient or not: it is essential to *...
def mandel1(position, limit=50): value = position while abs(value) < 2: limit -= 1 value = value**2 + position if limit < 0: return 0 return limit xmin = -1.5 ymin = -1.0 xmax = 0.5 ymax = 1.0 resolution = 300 xstep = (xmax - xmin) / resolution ...
_____no_output_____
CC-BY-3.0
ch08performance/010intro.ipynb
jack89roberts/rsd-engineeringcourse
We will learn this lesson how to make a version of this code which works Ten Times faster:
import numpy as np def mandel_numpy(position,limit=50): value = position diverged_at_count = np.zeros(position.shape) while limit > 0: limit -= 1 value = value**2+position diverging = value * np.conj(value) > 4 first_diverged_this_time = np.logical_and(diverging, diverged_at_...
50.9 ms ± 10.8 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
CC-BY-3.0
ch08performance/010intro.ipynb
jack89roberts/rsd-engineeringcourse
Note we get the same answer:
sum(sum(abs(data_numpy - data1)))
_____no_output_____
CC-BY-3.0
ch08performance/010intro.ipynb
jack89roberts/rsd-engineeringcourse
Matplotlib ( Matplotlib Pt. 3) Plot Appearence in Matplotlib
import matplotlib.pyplot as plt %matplotlib inline import numpy as np x = np.linspace(0,5,11) # We go from 0 to 5 and grab 11 points which are linearly spaced. y = x ** 2 fig = plt.figure() # Add a set of axes to the figure. ax = fig.add_axes([0,0,1,1]) # To add color to the plot there are multiple ways like directly t...
_____no_output_____
BSD-3-Clause
08. Data Visualization - Matplotlib/.ipynb_checkpoints/8.2 Matplotlib Pt 3-checkpoint.ipynb
CommunityOfCoders/ML_Workshop_Teachers
Linewidth and Line Style
fig = plt.figure() ax = fig.add_axes([0,0,1,1]) ax.plot(x,y,color='#008080') # Default Line width # 5 times the linewidth fig = plt.figure() ax = fig.add_axes([0,0,1,1]) ax.plot(x,y,color='#008080',lw=5)#A shorthand is used here for linewidth which is lw # To get transparency on the plotted line we can pass the alpha ...
_____no_output_____
BSD-3-Clause
08. Data Visualization - Matplotlib/.ipynb_checkpoints/8.2 Matplotlib Pt 3-checkpoint.ipynb
CommunityOfCoders/ML_Workshop_Teachers
Markers* Markers are used when we have just a few number of data points.
# Say we have x an array of len(x) data points. x len(x) # Say if we wanted to mark where those 11 points occured on the plot. fig = plt.figure() ax = fig.add_axes([0,0,1,1]) ax.plot(x,y,color='#008080',lw=3,marker='o',markersize=15,markerfacecolor='yellow', markeredgewidth=3,markeredgecolor='black')
_____no_output_____
BSD-3-Clause
08. Data Visualization - Matplotlib/.ipynb_checkpoints/8.2 Matplotlib Pt 3-checkpoint.ipynb
CommunityOfCoders/ML_Workshop_Teachers
More examples on line and marker styles
fig, ax = plt.subplots(figsize=(12,6)) ax.plot(x, x+1, color="red", linewidth=0.25) ax.plot(x, x+2, color="red", linewidth=0.50) ax.plot(x, x+3, color="red", linewidth=1.00) ax.plot(x, x+4, color="red", linewidth=2.00) # possible linestype options ‘-‘, ‘–’, ‘-.’, ‘:’, ‘steps’ ax.plot(x, x+5, color="green", lw=3, line...
_____no_output_____
BSD-3-Clause
08. Data Visualization - Matplotlib/.ipynb_checkpoints/8.2 Matplotlib Pt 3-checkpoint.ipynb
CommunityOfCoders/ML_Workshop_Teachers
Control over axis appearance* In this section we will look at controlling axis sizing properties in a matplotlib figure.
# Say we wanted to show the plot between 0 and 1 on the x-axis fig = plt.figure() ax = fig.add_axes([0,0,1,1]) ax.plot(x,y,color='#008080',lw=3,ls='--') # Say we wanted to show the plot between 0 and 1 on the x-axis fig = plt.figure() ax = fig.add_axes([0,0,1,1]) ax.plot(x,y,color='#008080',lw=3,ls='--', marker...
_____no_output_____
BSD-3-Clause
08. Data Visualization - Matplotlib/.ipynb_checkpoints/8.2 Matplotlib Pt 3-checkpoint.ipynb
CommunityOfCoders/ML_Workshop_Teachers
Plot Range* We can configure the ranges of the axes using the set_ylim and set_xlim methods in the axis object, or axis('tight') for automatically getting \"tightly fitted\" axes ranges:
fig, axes = plt.subplots(1, 3, figsize=(12, 4)) axes[0].plot(x, x**2, label = 'X squaraed',color='red') axes[0].plot(x, x**3,label='X cube',color='green') axes[0].set_title("default axes ranges") axes[1].plot(x, x**2, label = 'X squaraed',color='red') axes[1].plot(x, x**3,label='X cube',color='green') axes[1].axis('...
_____no_output_____
BSD-3-Clause
08. Data Visualization - Matplotlib/.ipynb_checkpoints/8.2 Matplotlib Pt 3-checkpoint.ipynb
CommunityOfCoders/ML_Workshop_Teachers
Special Plot Types* There are many specialized plots we can create, such as barplots, histograms, scatter plots, and much more. Most of these type of plots we will actually create using seaborn, a statistical plotting library for Python. But here are a few examples of these type of plots:
# Scatter plot plt.scatter(x,y) # Histrogram from random import sample data = sample(range(1, 1000), 100) plt.hist(data) data = [np.random.normal(0, std, 100) for std in range(1, 4)] # rectangular box plot plt.boxplot(data,vert=True,patch_artist=True);
_____no_output_____
BSD-3-Clause
08. Data Visualization - Matplotlib/.ipynb_checkpoints/8.2 Matplotlib Pt 3-checkpoint.ipynb
CommunityOfCoders/ML_Workshop_Teachers
--- 2. Select subsets from our dataset---
from digits.data import matimport from digits.data import select dataroot='../../data/thomas/artcorr/' imp = matimport.Importer(dataroot=dataroot)
_____no_output_____
MIT
data/Selecting.ipynb
eegdigits/notebooks
With `imp.open()` we can use HDF5 references to our samples and targets datasets without using up initial memory. The `samples` and `targets` objects are attached to the `store` attribute.In this notebook we will load the samples and targets from the file right away.
imp.open('3131.h5') samples = imp.store.samples targets = imp.store.targets 670*16 print(select.getsessionnames(samples)) for sess in select.getsessionnames(samples): print(samples.xs(sess, level='session').shape[0])
['01', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16'] 632 650 652 652 683 687 669 658 610 672 609
MIT
data/Selecting.ipynb
eegdigits/notebooks
The functions in `digits.data.select` will provide a high level abstraction for subselecting and pruning the large dataset, specific to the studies parameters. For instance: column-wise+ select only sampling points from a time window with `select.fromtimerange(samples, min, max)`+ select all sampling points from a name...
print(select.getchannelnames(samples)) print(select.getsessionnames(samples)) print(select.getpresentationnames(samples)) print(select.getsessionnames(samples))
['01', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16']
MIT
data/Selecting.ipynb
eegdigits/notebooks
The level/index names can be display with `head()` quite nicely:
samples.head()
_____no_output_____
MIT
data/Selecting.ipynb
eegdigits/notebooks
Now for the selection:
print(samples.shape) print(select.getsessionnames(samples)) samples, targets = select.fromsessionlist(samples, targets, ['14', '15']) samples.shape samples = select.fromchannellist(samples, ['C1', 'C2']) print(samples.shape) samples = select.fromtimerange(samples, 't_0200', 't_0201') print(samples.shape) samples, targe...
\begin{tabular}{llllrrrr} \toprule & & & & C1 & & C2 & \\ & & & & t\_0200 & t\_0201 & t\_0200 & t\_0201 \\ subject & session & trial & presentation & & & & \\ \midrule 3131 & 14 & 2 & 1 & -7.291202...
MIT
data/Selecting.ipynb
eegdigits/notebooks
DAT210x - Programming with Python for DS Module5- Lab3
import pandas as pd from datetime import timedelta import matplotlib.pyplot as plt import matplotlib matplotlib.style.use('ggplot') # Look Pretty
_____no_output_____
MIT
Module5/Module5 - Lab3.ipynb
azharmgh/pyrepo
A convenience function for you to use:
def clusterInfo(model): print("Cluster Analysis Inertia: ", model.inertia_) print('------------------------------------------') for i in range(len(model.cluster_centers_)): print("\n Cluster ", i) print(" Centroid ", model.cluster_centers_[i]) print(" #Samples ", (model.l...
_____no_output_____
MIT
Module5/Module5 - Lab3.ipynb
azharmgh/pyrepo
CDRs A [call detail record](https://en.wikipedia.org/wiki/Call_detail_record) (CDR) is a data record produced by a telephone exchange or other telecommunications equipment that documents the details of a telephone call or other telecommunications transaction (e.g., text message) that passes through that facility or de...
df1 = pd.read_csv('Datasets/CDR.csv') df1 = df1.dropna() df1['CallDate'] = pd.to_datetime(df1['CallDate'], 'coerce') df1['CallTime'] = pd.to_timedelta(df1['CallTime']) df1['Duration'] = pd.to_timedelta(df1['Duration']) df1.dtypes
_____no_output_____
MIT
Module5/Module5 - Lab3.ipynb
azharmgh/pyrepo
Create a unique list of the phone number values (people) stored in the `In` column of the dataset, and save them in a regular python list called `unique_numbers`. Manually check through `unique_numbers` to ensure the order the numbers appear is the same order they (uniquely) appear in your dataset:
# .. your code here .. unique_numbers = df1.In.unique().tolist() unique_numbers
_____no_output_____
MIT
Module5/Module5 - Lab3.ipynb
azharmgh/pyrepo
Using some domain expertise, your intuition should direct you to know that people are likely to behave differently on weekends vs on weekdays: On Weekends1. People probably don't go into work1. They probably sleep in late on Saturday1. They probably run a bunch of random errands, since they couldn't during the week1. T...
print("Examining person: ", unique_numbers[0])
Examining person: 4638472273
MIT
Module5/Module5 - Lab3.ipynb
azharmgh/pyrepo
Create a slice called `user1` that filters to only include dataset records where the `In` feature (user phone number) is equal to the first number on your unique list above:
# .. your code here .. user1 = df1[df1['In'] == unique_numbers[0]] user1
_____no_output_____
MIT
Module5/Module5 - Lab3.ipynb
azharmgh/pyrepo
Alter your slice so that it includes only Weekday (Mon-Fri) values:
# .. your code here .. pm5 = pd.to_timedelta('17:00:00') am730 = pd.to_timedelta('07:30:00') #user2 = user1[(((user1['DOW'] == 'Sat') | (user1['DOW'] == 'Sun')) & ((user1['CallTime'] > am1) & (user1['CallTime'] < am4)))] user2 = user1 user1 = user1[(((user1['DOW'] == 'Mon') | (user1['DOW'] == 'Tue') | (user1['DOW'] == ...
_____no_output_____
MIT
Module5/Module5 - Lab3.ipynb
azharmgh/pyrepo
The idea is that the call was placed before 5pm. From Midnight-730a, the user is probably sleeping and won't call / wake up to take a call. There should be a brief time in the morning during their commute to work, then they'll spend the entire day at work. So the assumption is that most of the time is spent either at w...
# .. your code here ..
_____no_output_____
MIT
Module5/Module5 - Lab3.ipynb
azharmgh/pyrepo
Plot the Cell Towers the user connected to
# .. your code here .. %matplotlib notebook fig = plt.figure() ax = fig.add_subplot(111) ax.scatter(user1.TowerLon,user1.TowerLat, c='g', marker='o', alpha=0.2) ax.set_title('Weedkay Calls (7:30am - 5pm)') plt.show() from sklearn.cluster import KMeans def doKMeans(data, num_clusters=0): # TODO: Be sure to only fe...
_____no_output_____
MIT
Module5/Module5 - Lab3.ipynb
azharmgh/pyrepo
Let's tun K-Means with `K=3` or `K=4`. There really should only be a two areas of concentration. If you notice multiple areas that are "hot" (multiple areas the user spends a lot of time at that are FAR apart from one another), then increase K=5, with the goal being that all centroids except two will sweep up the annoy...
model = doKMeans(user1, 4)
[[ 32.84579692 -96.81976265] [ 32.89970164 -96.91026779] [ 32.87348968 -96.85115015] [ 32.911583 -96.892222 ]]
MIT
Module5/Module5 - Lab3.ipynb
azharmgh/pyrepo
Print out the mean `CallTime` value for the samples belonging to the cluster with the LEAST samples attached to it. If our logic is correct, the cluster with the MOST samples will be work. The cluster with the 2nd most samples will be home. And the `K=3` cluster with the least samples should be somewhere in between the...
midWayClusterIndices = clusterWithFewestSamples(model) midWaySamples = user1[midWayClusterIndices] print(" Its Waypoint Time: ", midWaySamples.CallTime.mean())
Cluster With Fewest Samples: 3 Its Waypoint Time: 0 days 07:44:31.892341
MIT
Module5/Module5 - Lab3.ipynb
azharmgh/pyrepo
Let's visualize the results! First draw the X's for the clusters:
fig1 = plt.figure() ax1 = fig1.add_subplot(111) ax1.scatter(model.cluster_centers_[:,1], model.cluster_centers_[:,0], s=169, c='r', marker='x', alpha=0.8, linewidths=2) ax1.set_title('Weekday Calls Centroids') plt.show() clusterInfo(model) users_phones = [2068627935,2894365987,1559410755,3688089071] def examineNumber(...
Examining person: 2894365987 Cluster Analysis Inertia: 0.00584613804294 ------------------------------------------ Cluster 0 Centroid [ 32.717667 -96.875194] #Samples 141 Cluster 1 Centroid [ 32.72174109 -96.89194104] #Samples 2705 Cluster 2 Centroid [ 32.741889 -96.857611] #S...
MIT
Module5/Module5 - Lab3.ipynb
azharmgh/pyrepo
2894365987 is the closest so far
examineNumber(df1,users_phones[2],4) examineNumber(df1,users_phones[3],4) def getClusterSamples(df, number, num_clusters): print("getting cluster for person: ", number) user = df[df['In'] == number] pm5 = pd.to_timedelta('17:00:00') am730 = pd.to_timedelta('07:30:00') user = user[(((user['DOW'] == '...
examining user : 4638472273 getting cluster for person: 4638472273 Cluster With Fewest Samples: 1 Avg time : 0 days 07:44:01.395089 examining user : 1559410755 getting cluster for person: 1559410755 Cluster With Fewest Samples: 0 Avg time : 0 days 07:49:46.609049 examining user : 4931532174 getti...
MIT
Module5/Module5 - Lab3.ipynb
azharmgh/pyrepo
Yapay Öğrenmeye Giriş IAli Taylan Cemgil Parametrik Regresyon, Parametrik Fonksyon Oturtma Problemi (Parametric Regression, Function Fitting)Verilen girdi ve çıktı ikilileri $x, y$ için parametrik bir fonksyon $f$ oturtma problemi. Parametre $w$ değerlerini öyle bir seçelim ki $$y \approx f(x; w)$$$x$: Girdi (Input)$y...
import matplotlib.pyplot as plt import numpy as np %matplotlib inline from __future__ import print_function from ipywidgets import interact, interactive, fixed import ipywidgets as widgets import matplotlib.pylab as plt from IPython.display import clear_output, display, HTML x = np.array([8.0 , 6.1 , 11., 7., 9., ...
_____no_output_____
MIT
matkoy2021-1.ipynb
atcemgil/notes
Rasgele Arama
x = np.array([8.0 , 6.1 , 11., 7., 9., 12. , 4., 2., 10, 5, 3]) y = np.array([6.04, 4.95, 5.58, 6.81, 6.33, 7.96, 5.24, 2.26, 8.84, 2.82, 3.68]) def hata(y, x, w): N = len(y) f = x*w[1]+w[0] e = y-f return np.sum(e*e)/2 w = np.array([0, 0]) E = hata(y, x, w) for e in range(1000): ...
999 6.88573142353
MIT
matkoy2021-1.ipynb
atcemgil/notes
Gerçek veri: Türkiyedeki araç sayıları
%matplotlib inline import scipy as sc import numpy as np import pandas as pd import matplotlib as mpl import matplotlib.pylab as plt df_arac = pd.read_csv(u'data/arac.csv',sep=';') df_arac[['Year','Car']] #df_arac BaseYear = 1995 x = np.matrix(df_arac.Year[0:]).T-BaseYear y = np.matrix(df_arac.Car[0:]).T/1000000. pl...
_____no_output_____
MIT
matkoy2021-1.ipynb
atcemgil/notes
Örnek 1, devam: Modeli Öğrenmek* Öğrenmek: parametre kestirimi $w = [w_0, w_1]$* Genelde model veriyi hatasız açıklayamayacağı için her veri noktası için bir hata tanımlıyoruz:$$e_i = y_i - f(x_i; w)$$* Toplam kare hata $$E(w) = \frac{1}{2} \sum_i (y_i - f(x_i; w))^2 = \frac{1}{2} \sum_i e_i^2$$* Toplam kare hatayı $w...
from itertools import product BaseYear = 1995 x = np.matrix(df_arac.Year[0:]).T-BaseYear y = np.matrix(df_arac.Car[0:]).T/1000000. # Setup the vandermonde matrix N = len(x) A = np.hstack((np.ones((N,1)), x)) left = -5 right = 15 bottom = -4 top = 6 step = 0.05 W0 = np.arange(left,right, step) W1 = np.arange(bottom,t...
_____no_output_____
MIT
matkoy2021-1.ipynb
atcemgil/notes
Modeli Nasıl Kestirebiliriz? Fikir: En küçük kare hata (Gauss 1795, Legendre 1805)* Toplam hatanın $w_0$ ve $w_1$'e göre türevini hesapla, sıfıra eşitle ve çıkan denklemleri çöz\begin{eqnarray}\left(\begin{array}{c}y_0 \\ y_1 \\ \vdots \\ y_{N-1} \end{array}\right)\approx\left(\begin{array}{cc}1 & x_0 \\ 1 & x_1 \\ \v...
# Solving the Normal Equations # Setup the Design matrix N = len(x) A = np.hstack((np.ones((N,1)), x)) #plt.imshow(A, interpolation='nearest') # Solve the least squares problem w_ls,E,rank,sigma = np.linalg.lstsq(A, y) print('Parametreler: \nw0 = ', w_ls[0],'\nw1 = ', w_ls[1] ) print('Toplam Kare Hata:', E/2) f = n...
Parametreler: w0 = [[ 4.13258253]] w1 = [[ 0.20987778]] Toplam Kare Hata: [[ 37.19722385]]
MIT
matkoy2021-1.ipynb
atcemgil/notes
Polinomlar Parabol\begin{eqnarray}\left(\begin{array}{c}y_0 \\ y_1 \\ \vdots \\ y_{N-1} \end{array}\right)\approx\left(\begin{array}{ccc}1 & x_0 & x_0^2 \\ 1 & x_1 & x_1^2 \\ \vdots \\ 1 & x_{N-1} & x_{N-1}^2 \end{array}\right) \left(\begin{array}{c} w_0 \\ w_1 \\ w_2\end{array}\right)\end{eqnarray} $K$ derecesind...
x = np.array([10, 8, 13, 9, 11, 14, 6, 4, 12, 7, 5]) N = len(x) x = x.reshape((N,1)) y = np.array([8.04, 6.95, 7.58, 8.81, 8.33, 9.96, 7.24, 4.26, 10.84, 4.82, 5.68]).reshape((N,1)) #y = np.array([9.14, 8.14, 8.74, 8.77, 9.26, 8.10, 6.13, 3.10, 9.13, 7.26, 4.74]).reshape((N,1)) #y = np.array([7.46, 6.77, 12.74, 7.11, 7...
_____no_output_____
MIT
matkoy2021-1.ipynb
atcemgil/notes
About https://www.kaggle.com/uladzimirkapeika/feature-engineering-lightgbm-top-1https://zhuanlan.zhihu.com/p/145969470 Version 1.0 Libraries> Check your versions
import pandas as pd import numpy as np from itertools import product import sklearn from sklearn.preprocessing import LabelEncoder from sklearn.linear_model import LinearRegression from sklearn.neighbors import KNeighborsRegressor from sklearn.ensemble import RandomForestRegressor import lightgbm as lgb import calendar...
numpy 1.20.1 pandas 1.2.3 seaborn 0.11.1 sklearn 0.24.1 lightgbm 3.2.0
MIT
{{cookiecutter.project_slug}}/notebooks/02_sj_salse_predict_ml.ipynb
juforg/cookiecutter-ds-py3tkinter
**Load data**
test = pd.read_csv('../data/0_raw/sales/test.csv.gz') sales = pd.read_csv('../data/0_raw/sales/sales_train.csv.gz', encoding='UTF-8') # sales = pd.read_csv('https://storage.googleapis.com/kaggle-competitions-data/kaggle-v2/8587/868304/compressed/sales_train.csv.zip?GoogleAccessId=web-data@kaggle-161607.iam.gserviceacco...
214200 2935849 60 22170 84 item_name item_id \ 0 ! ВО ВЛАСТИ НАВАЖДЕНИЯ (ПЛАСТ.) D 0 1 !ABBYY FineReader 12 Professional Edition Full... 1 2 ***В ЛУЧАХ СЛАВЫ (UNV) D 2 3 ***ГОЛУБАЯ ВОЛНА (Univ) ...
MIT
{{cookiecutter.project_slug}}/notebooks/02_sj_salse_predict_ml.ipynb
juforg/cookiecutter-ds-py3tkinter
**Create dataset** Remove outliers
sns.boxplot(x=sales.item_cnt_day) sns.boxplot(x=sales.item_price) train = sales[(sales.item_price < 100000) & (sales.item_price > 0)] train = train[sales.item_cnt_day < 1001]
/Users/songjie/.local/share/virtualenvs/snp_mvp-8ex0mMfN/lib/python3.7/site-packages/ipykernel_launcher.py:2: UserWarning: Boolean Series key will be reindexed to match DataFrame index.
MIT
{{cookiecutter.project_slug}}/notebooks/02_sj_salse_predict_ml.ipynb
juforg/cookiecutter-ds-py3tkinter
Detect same shops
print(shops[shops.shop_id.isin([0, 57])]['shop_name']) print(shops[shops.shop_id.isin([1, 58])]['shop_name']) print(shops[shops.shop_id.isin([40, 39])]['shop_name']) train.loc[train.shop_id == 0, 'shop_id'] = 57 test.loc[test.shop_id == 0, 'shop_id'] = 57 train.loc[train.shop_id == 1, 'shop_id'] = 58 test.loc[test.sho...
_____no_output_____
MIT
{{cookiecutter.project_slug}}/notebooks/02_sj_salse_predict_ml.ipynb
juforg/cookiecutter-ds-py3tkinter
Simple train dataset
index_cols = ['shop_id', 'item_id', 'date_block_num'] df = [] for block_num in train['date_block_num'].unique(): cur_shops = train.loc[sales['date_block_num'] == block_num, 'shop_id'].unique() cur_items = train.loc[sales['date_block_num'] == block_num, 'item_id'].unique() df.append(np.array(list(product(*...
_____no_output_____
MIT
{{cookiecutter.project_slug}}/notebooks/02_sj_salse_predict_ml.ipynb
juforg/cookiecutter-ds-py3tkinter
Add test
test['date_block_num'] = 34 test['date_block_num'] = test['date_block_num'].astype(np.int8) test['shop_id'] = test['shop_id'].astype(np.int8) test['item_id'] = test['item_id'].astype(np.int16) df = pd.concat([df, test], ignore_index=True, sort=False, keys=index_cols) df.fillna(0, inplace=True)
_____no_output_____
MIT
{{cookiecutter.project_slug}}/notebooks/02_sj_salse_predict_ml.ipynb
juforg/cookiecutter-ds-py3tkinter
Feature engineering **Shop features*** City of a shop* City coords* Country part (0-4) based on the map
shops['city'] = shops['shop_name'].apply(lambda x: x.split()[0].lower()) shops.loc[shops.city == '!якутск', 'city'] = 'якутск' shops['city_code'] = LabelEncoder().fit_transform(shops['city']) coords = dict() coords['якутск'] = (62.028098, 129.732555, 4) coords['адыгея'] = (44.609764, 40.100516, 3) coords['балашиха'] =...
_____no_output_____
MIT
{{cookiecutter.project_slug}}/notebooks/02_sj_salse_predict_ml.ipynb
juforg/cookiecutter-ds-py3tkinter
**Item features*** Item category* More common item category
map_dict = { 'Чистые носители (штучные)': 'Чистые носители', 'Чистые носители (шпиль)' : 'Чистые носители', 'PC ': 'Аксессуары', 'Служебные': 'Служебные ' } items = pd.merge(items, item_cats, on='item_category_id') items['item_category'] = items['item_catego...
_____no_output_____
MIT
{{cookiecutter.project_slug}}/notebooks/02_sj_salse_predict_ml.ipynb
juforg/cookiecutter-ds-py3tkinter
**Date features*** Weekends count (4 or 5)* Number of days in a month
def count_days(date_block_num): year = 2013 + date_block_num // 12 month = 1 + date_block_num % 12 weeknd_count = len([1 for i in calendar.monthcalendar(year, month) if i[6] != 0]) days_in_month = calendar.monthrange(year, month)[1] return weeknd_count, days_in_month, month map_dict = {i: count_day...
_____no_output_____
MIT
{{cookiecutter.project_slug}}/notebooks/02_sj_salse_predict_ml.ipynb
juforg/cookiecutter-ds-py3tkinter
**Interaction features*** Item is new* Item was bought in this shop before
first_item_block = df.groupby(['item_id'])['date_block_num'].min().reset_index() first_item_block['item_first_interaction'] = 1 first_shop_item_buy_block = df[df['date_block_num'] > 0].groupby(['shop_id', 'item_id'])['date_block_num'].min().reset_index() first_shop_item_buy_block['first_date_block_num'] = first_shop_i...
_____no_output_____
MIT
{{cookiecutter.project_slug}}/notebooks/02_sj_salse_predict_ml.ipynb
juforg/cookiecutter-ds-py3tkinter
**Basic lag features**
def lag_feature(df, lags, col): tmp = df[['date_block_num','shop_id','item_id',col]] for i in lags: shifted = tmp.copy() shifted.columns = ['date_block_num','shop_id','item_id', col+'_lag_'+str(i)] shifted['date_block_num'] += i df = pd.merge(df, shifted, on=['date_block_num','sh...
_____no_output_____
MIT
{{cookiecutter.project_slug}}/notebooks/02_sj_salse_predict_ml.ipynb
juforg/cookiecutter-ds-py3tkinter
**Target encoding**
#Add target encoding for items for last 3 months item_id_target_mean = df.groupby(['date_block_num','item_id'])['item_cnt_month'].mean().reset_index().rename(columns={"item_cnt_month": "item_target_enc"}, errors="raise") df = pd.merge(df, item_id_target_mean, on=['date_block_num','item_id'], how='left') df['item_targ...
_____no_output_____
MIT
{{cookiecutter.project_slug}}/notebooks/02_sj_salse_predict_ml.ipynb
juforg/cookiecutter-ds-py3tkinter
Extra interaction features
#For new items add avg category sales for last 3 months item_id_target_mean = df[df['item_first_interaction'] == 1].groupby(['date_block_num','item_category_code'])['item_cnt_month'].mean().reset_index().rename(columns={ "item_cnt_month": "new_item_cat_avg"}, errors="raise") df = pd.merge(df, item_id_target_mean, ...
_____no_output_____
MIT
{{cookiecutter.project_slug}}/notebooks/02_sj_salse_predict_ml.ipynb
juforg/cookiecutter-ds-py3tkinter
Add sales for the last three months for similar item (item with id = item_id - 1;kinda tricky feature, but increased the metric significantly)
def lag_feature_adv(df, lags, col): tmp = df[['date_block_num','shop_id','item_id',col]] for i in lags: shifted = tmp.copy() shifted.columns = ['date_block_num','shop_id','item_id', col+'_lag_'+str(i)+'_adv'] shifted['date_block_num'] += i shifted['item_id'] -= 1 df = pd....
_____no_output_____
MIT
{{cookiecutter.project_slug}}/notebooks/02_sj_salse_predict_ml.ipynb
juforg/cookiecutter-ds-py3tkinter
Remove data for the first three months
df.fillna(0, inplace=True) df = df[(df['date_block_num'] > 2)] df.head() df.columns #Save dataset df.drop(['ID'], axis=1, inplace=True, errors='ignore') df.to_pickle('../output/models/sales_df.pkl')
_____no_output_____
MIT
{{cookiecutter.project_slug}}/notebooks/02_sj_salse_predict_ml.ipynb
juforg/cookiecutter-ds-py3tkinter
Train model
df = pd.read_pickle('../output/models/sales_df.pkl') df.info() X_train = df[df.date_block_num < 33].drop(['item_cnt_month'], axis=1) Y_train = df[df.date_block_num < 33]['item_cnt_month'] X_valid = df[df.date_block_num == 33].drop(['item_cnt_month'], axis=1) Y_valid = df[df.date_block_num == 33]['item_cnt_month'] X_tes...
_____no_output_____
MIT
{{cookiecutter.project_slug}}/notebooks/02_sj_salse_predict_ml.ipynb
juforg/cookiecutter-ds-py3tkinter
Stacking didn't work for me. I'd tried 2 approaches:1. XGBoost + CatBoost + LightGBM at the first level and LinearRegression/LightGBM at the second level1. LinearRegression + LightGBM + RandomForest at the first level and LinearRegression/LightGBM at the second level
test = pd.read_csv('../data/0_raw/sales/test.csv.gz') Y_test = gbm.predict(X_test[feature_name]).clip(0, 20) submission = pd.DataFrame({ "ID": test.index, "item_cnt_month": Y_test }) submission.to_csv('../output/gbm_submission.csv', index=False)
_____no_output_____
MIT
{{cookiecutter.project_slug}}/notebooks/02_sj_salse_predict_ml.ipynb
juforg/cookiecutter-ds-py3tkinter
Displaying Surfacespy3Dmol supports the following surface types:* VDW - van der Waals surface* MS - molecular surface* SES - solvent excluded surface* SAS - solvent accessible surface
import py3Dmol
_____no_output_____
Apache-2.0
1-3D-visualization/4-Surfaces.ipynb
NicholasAKovacs/mmtf-workshop
Add surfaceIn the structure below (HLA complex with antigen peptide pVR), we add a solvent excluded surface (SES) to the heavy chain to highlight the binding pocket for the antigen peptide (rendered as spheres).
viewer = py3Dmol.view(query='pdb:5XS3') heavychain = {'chain':'A'} lightchain = {'chain':'B'} antigen = {'chain':'C'} viewer.setStyle(heavychain,{'cartoon':{'color':'blue'}}) viewer.setStyle(lightchain,{'cartoon':{'color':'yellow'}}) viewer.setStyle(antigen,{'sphere':{'colorscheme':'orangeCarbon'}}) viewer.addSurfac...
_____no_output_____
Apache-2.0
1-3D-visualization/4-Surfaces.ipynb
NicholasAKovacs/mmtf-workshop
NETWORK = "https://nvlabs-fi-cdn.nvidia.com/stylegan2-ada-pytorch/pretrained/ffhq.pkl" STEPS = 300 FPS = 30 FREEZE_STEPS = 30
_____no_output_____
MIT
StyleGAN2.ipynb
patprem/FaceMorphing
Upload Starting ImageChoose your starting image.
import os from google.colab import files uploaded = files.upload() if len(uploaded) != 1: print("Upload exactly 1 file for source.") else: for k, v in uploaded.items(): _, ext = os.path.splitext(k) os.remove(k) SOURCE_NAME = f"source{ext}" open(SOURCE_NAME, 'wb').write(v)
_____no_output_____
MIT
StyleGAN2.ipynb
patprem/FaceMorphing
Also, choose your ending image.
uploaded = files.upload() if len(uploaded) != 1: print("Upload exactly 1 file for target.") else: for k, v in uploaded.items(): _, ext = os.path.splitext(k) os.remove(k) TARGET_NAME = f"target{ext}" open(TARGET_NAME, 'wb').write(v)
_____no_output_____
MIT
StyleGAN2.ipynb
patprem/FaceMorphing
Install SoftwareSome software must be installed into Colab, for this notebook to work. We are specificially using these technologies:* [Training Generative Adversarial Networks with Limited Data](https://arxiv.org/abs/2006.06676)Tero Karras, Miika Aittala, Janne Hellsten, Samuli Laine, Jaakko Lehtinen, Timo Aila* [One...
!wget http://dlib.net/files/shape_predictor_5_face_landmarks.dat.bz2 !bzip2 -d shape_predictor_5_face_landmarks.dat.bz2 import sys !git clone https://github.com/NVlabs/stylegan2-ada-pytorch.git !pip install ninja sys.path.insert(0, "/content/stylegan2-ada-pytorch")
fatal: destination path 'stylegan2-ada-pytorch' already exists and is not an empty directory. Requirement already satisfied: ninja in /usr/local/lib/python3.7/dist-packages (1.10.2.3)
MIT
StyleGAN2.ipynb
patprem/FaceMorphing
Preprocess Images for Best StyleGAN ResultsThe following are helper functions for the preprocessing.
import cv2 import numpy as np from PIL import Image import dlib detector = dlib.get_frontal_face_detector() predictor = dlib.shape_predictor('shape_predictor_5_face_landmarks.dat') def find_eyes(img): gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) rects = detector(gray, 0) if len(rects) == 0: raise ValueEr...
_____no_output_____
MIT
StyleGAN2.ipynb
patprem/FaceMorphing
The following will preprocess and crop your images. If you receive an error indicating multiple faces were found, try to crop your image better or obscure the background. If the program does not see a face, then attempt to obtain a clearer and more high-resolution image.
from matplotlib import pyplot as plt import cv2 image_source = cv2.imread(SOURCE_NAME) if image_source is None: raise ValueError("Source image not found") image_target = cv2.imread(TARGET_NAME) if image_target is None: raise ValueError("Source image not found") cropped_source = crop_stylegan(image_source) cr...
_____no_output_____
MIT
StyleGAN2.ipynb
patprem/FaceMorphing
Convert Source to a GANFirst, we convert the source to a GAN latent vector. This process will take several minutes.
cmd = f"python /content/stylegan2-ada-pytorch/projector.py --save-video 0 --num-steps 1000 --outdir=out_source --target=cropped_source.png --network={NETWORK}" !{cmd}
Loading networks from "https://nvlabs-fi-cdn.nvidia.com/stylegan2-ada-pytorch/pretrained/ffhq.pkl"... Computing W midpoint and stddev using 10000 samples... Setting up PyTorch plugin "bias_act_plugin"... Done. Setting up PyTorch plugin "upfirdn2d_plugin"... Done. step 1/1000: dist 0.64 loss 24569.53 step 2/1000: ...
MIT
StyleGAN2.ipynb
patprem/FaceMorphing
Convert Target to a GANNext, we convert the target to a GAN latent vector. This process will also take several minutes.
cmd = f"python /content/stylegan2-ada-pytorch/projector.py --save-video 0 --num-steps 1000 --outdir=out_target --target=cropped_target.png --network={NETWORK}" !{cmd}
Loading networks from "https://nvlabs-fi-cdn.nvidia.com/stylegan2-ada-pytorch/pretrained/ffhq.pkl"... Computing W midpoint and stddev using 10000 samples... Setting up PyTorch plugin "bias_act_plugin"... Done. Setting up PyTorch plugin "upfirdn2d_plugin"... Done. step 1/1000: dist 0.55 loss 24569.43 step 2/1000: ...
MIT
StyleGAN2.ipynb
patprem/FaceMorphing
With the conversion complete, lets have a look at the two GANs.
img_gan_source = cv2.imread('/content/out_source/proj.png') img = cv2.cvtColor(img_gan_source, cv2.COLOR_BGR2RGB) plt.imshow(img) plt.title('source-gan') plt.show() img_gan_target = cv2.imread('/content/out_target/proj.png') img = cv2.cvtColor(img_gan_target, cv2.COLOR_BGR2RGB) plt.imshow(img) plt.title('target-gan') p...
_____no_output_____
MIT
StyleGAN2.ipynb
patprem/FaceMorphing
Build the VideoThe following code builds a transition video between the two latent vectors previously obtained.
import torch import dnnlib import legacy import PIL.Image import numpy as np import imageio from tqdm.notebook import tqdm lvec1 = np.load('/content/out_source/projected_w.npz')['w'] lvec2 = np.load('/content/out_target/projected_w.npz')['w'] network_pkl = "https://nvlabs-fi-cdn.nvidia.com/stylegan2-ada-pytorch/pretr...
_____no_output_____
MIT
StyleGAN2.ipynb
patprem/FaceMorphing
Download your VideoIf you made it through all of these steps, you are now ready to download your video.
from google.colab import files files.download("movie.mp4")
_____no_output_____
MIT
StyleGAN2.ipynb
patprem/FaceMorphing
k-Nearest Neighbor (kNN) exercise*Complete and hand in this completed worksheet (including its outputs and any supporting code outside of the worksheet) with your assignment submission. For more details see the [assignments page](http://vision.stanford.edu/teaching/cs231n/assignments.html) on the course website.*The k...
# Run some setup code for this notebook. import random import numpy as np from cs231n.data_utils import load_CIFAR10 import matplotlib.pyplot as plt # This is a bit of magic to make matplotlib figures appear inline in the notebook # rather than in a new window. %matplotlib inline plt.rcParams['figure.figsize'] = (10....
_____no_output_____
MIT
assignment1/knn.ipynb
meijun/cs231n-assignment
We would now like to classify the test data with the kNN classifier. Recall that we can break down this process into two steps: 1. First we must compute the distances between all test examples and all train examples. 2. Given these distances, for each test example we find the k nearest examples and have them vote for t...
# Open cs231n/classifiers/k_nearest_neighbor.py and implement # compute_distances_two_loops. # Test your implementation: dists = classifier.compute_distances_two_loops(X_test) print dists.shape # We can visualize the distance matrix: each row is a single test example and # its distances to training examples plt.imshow...
_____no_output_____
MIT
assignment1/knn.ipynb
meijun/cs231n-assignment
**Inline Question 1:** Notice the structured patterns in the distance matrix, where some rows or columns are visible brighter. (Note that with the default color scheme black indicates low distances while white indicates high distances.)- What in the data is the cause behind the distinctly bright rows?- What causes the ...
# Now implement the function predict_labels and run the code below: # We use k = 1 (which is Nearest Neighbor). y_test_pred = classifier.predict_labels(dists, k=1) # Compute and print the fraction of correctly predicted examples num_correct = np.sum(y_test_pred == y_test) accuracy = float(num_correct) / num_test print...
Got 137 / 500 correct => accuracy: 0.274000
MIT
assignment1/knn.ipynb
meijun/cs231n-assignment
You should expect to see approximately `27%` accuracy. Now lets try out a larger `k`, say `k = 5`:
y_test_pred = classifier.predict_labels(dists, k=5) num_correct = np.sum(y_test_pred == y_test) accuracy = float(num_correct) / num_test print 'Got %d / %d correct => accuracy: %f' % (num_correct, num_test, accuracy)
Got 139 / 500 correct => accuracy: 0.278000
MIT
assignment1/knn.ipynb
meijun/cs231n-assignment
You should expect to see a slightly better performance than with `k = 1`.
# Now lets speed up distance matrix computation by using partial vectorization # with one loop. Implement the function compute_distances_one_loop and run the # code below: dists_one = classifier.compute_distances_one_loop(X_test) # To ensure that our vectorized implementation is correct, we make sure that it # agrees ...
Two loop version took 25.608644 seconds One loop version took 49.357512 seconds No loop version took 0.393901 seconds
MIT
assignment1/knn.ipynb
meijun/cs231n-assignment
Cross-validationWe have implemented the k-Nearest Neighbor classifier but we set the value k = 5 arbitrarily. We will now determine the best value of this hyperparameter with cross-validation.
num_folds = 5 k_choices = [1, 3, 5, 8, 10, 12, 15, 20, 50, 100] X_train_folds = [] y_train_folds = [] ################################################################################ # TODO: # # Split up the training data into folds. After splittin...
Got 141 / 500 correct => accuracy: 0.282000
MIT
assignment1/knn.ipynb
meijun/cs231n-assignment
Function call parameter rules and unpackingPython functions have the following four forms when declaring parameters:1. Without default value: `def func(a): pass`1. With default value: `def func(a, b = 1): pass`1. Arbitrary position parameters: `def func(a, b = 1, *c): pass`1. Arbitrary key parameter: `def func(a, b = ...
def func(a, b = 1): pass func(a = "G", 20) # SyntaxError
_____no_output_____
MIT
Notebooks/Arguments-and-Unpacking.ipynb
gtavasoli/PyTips
Another rule is position parameter priority:
def func(a, b = 1): pass func(20, a = "G") # TypeError: Repeat assignment to parameter a
_____no_output_____
MIT
Notebooks/Arguments-and-Unpacking.ipynb
gtavasoli/PyTips
**The safest way is to use all keyword parameters.** Arbitrary ParametersAny parameter can accept any number of parameters, where the form of `*a` represents any number of **positional parameters**, and `**d` represents any number of **keyword parameters**:
def concat(*lst, sep = "/"): return sep.join((str(i) for i in lst)) print(concat("G", 20, "@", "Hz", sep = ""))
G20@Hz
MIT
Notebooks/Arguments-and-Unpacking.ipynb
gtavasoli/PyTips
The syntax of the above `def concat(*lst, sep = "/")` was proposed by [PEP 3102](https://www.python.org/dev/peps/pep-3102/) and implemented after **Python 3.0**. The keyword function here must be clearly specified and cannot be inferred by position:
print(concat("G", 20, "-")) # Not G-20
G/20/-
MIT
Notebooks/Arguments-and-Unpacking.ipynb
gtavasoli/PyTips