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 |
|---|---|---|---|---|---|
Check Accuracy | from sklearn import svm
clf = svm.SVC(kernel='rbf')
clf.fit(X_train_SVM, y_train_SVM)
yhat = clf.predict(X_test_SVM)
yhat [0:5]
from sklearn.metrics import f1_score, jaccard_similarity_score
f1_acc = f1_score(y_test_SVM, yhat, average='weighted')
jaccard_acc = jaccard_similarity_score(y_test_SVM, yhat)
f1_acc, jacc... | _____no_output_____ | MIT | Coursera/IBM Python 01/Course02/ML Python Sharing.ipynb | brianshen1990/KeepLearning |
Logistic Regression Datset train and testJust use the K-Nearest one | from sklearn.linear_model import LogisticRegression
from sklearn.metrics import confusion_matrix
LR = LogisticRegression(C=0.01, solver='liblinear').fit(X_train,y_train)
yhat = LR.predict(X_test)
yhat_prob = LR.predict_proba(X_test)
yhat, yhat_prob | _____no_output_____ | MIT | Coursera/IBM Python 01/Course02/ML Python Sharing.ipynb | brianshen1990/KeepLearning |
Accuaracy | from sklearn.metrics import jaccard_similarity_score
jaccard_similarity_score(y_test, yhat)
from sklearn.metrics import log_loss
log_loss(y_test, yhat_prob) | _____no_output_____ | MIT | Coursera/IBM Python 01/Course02/ML Python Sharing.ipynb | brianshen1990/KeepLearning |
Model Evaluation using Test set | from sklearn.metrics import jaccard_similarity_score
from sklearn.metrics import f1_score
from sklearn.metrics import log_loss | _____no_output_____ | MIT | Coursera/IBM Python 01/Course02/ML Python Sharing.ipynb | brianshen1990/KeepLearning |
First, download and load the test set: | !wget -O loan_test.csv https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/ML0101ENv3/labs/loan_test.csv | --2020-05-22 15:47:37-- https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/ML0101ENv3/labs/loan_test.csv
Resolving s3-api.us-geo.objectstorage.softlayer.net (s3-api.us-geo.objectstorage.softlayer.net)... 67.228.254.196
Connecting to s3-api.us-geo.objectstorage.softlayer.net (s3-api.us-geo... | MIT | Coursera/IBM Python 01/Course02/ML Python Sharing.ipynb | brianshen1990/KeepLearning |
Load Test set for evaluation | test_df = pd.read_csv('loan_test.csv')
test_df.head() | _____no_output_____ | MIT | Coursera/IBM Python 01/Course02/ML Python Sharing.ipynb | brianshen1990/KeepLearning |
Prepare data | test_df['due_date'] = pd.to_datetime(test_df['due_date'])
test_df['effective_date'] = pd.to_datetime(test_df['effective_date'])
test_df['dayofweek'] = test_df['effective_date'].dt.dayofweek
test_df['weekend'] = test_df['dayofweek'].apply(lambda x: 1 if (x>3) else 0)
test_df.head()
test_df['Gender'].replace(to_replace=... | _____no_output_____ | MIT | Coursera/IBM Python 01/Course02/ML Python Sharing.ipynb | brianshen1990/KeepLearning |
K-Nearest | neigh = KNeighborsClassifier(n_neighbors = 7).fit(X_train,y_train)
yhat=neigh.predict(test_Feature)
K_f1_acc = f1_score(test_y, yhat, average='weighted')
k_jaccard_acc = jaccard_similarity_score(test_y, yhat)
K_f1_acc, k_jaccard_acc | /opt/conda/envs/Python36/lib/python3.6/site-packages/sklearn/metrics/classification.py:1143: UndefinedMetricWarning: F-score is ill-defined and being set to 0.0 in labels with no predicted samples.
'precision', 'predicted', average, warn_for)
| MIT | Coursera/IBM Python 01/Course02/ML Python Sharing.ipynb | brianshen1990/KeepLearning |
dcicison tree | drugTree = DecisionTreeClassifier(criterion="entropy", max_depth = 6)
drugTree.fit(X_train,y_train)
yhat = drugTree.predict(test_Feature)
DT_f1_acc = f1_score(test_y, yhat, average='weighted')
DT_jaccard_acc = jaccard_similarity_score(test_y, yhat)
DT_f1_acc, DT_jaccard_acc | _____no_output_____ | MIT | Coursera/IBM Python 01/Course02/ML Python Sharing.ipynb | brianshen1990/KeepLearning |
SVM | clf = svm.SVC(kernel='rbf')
clf.fit(X_train_SVM, y_train_SVM)
yhat = clf.predict(test_X_SVM)
SVM_f1_acc = f1_score(test_y_SVM, yhat, average='weighted')
SVM_jaccard_acc = jaccard_similarity_score(test_y_SVM, yhat)
SVM_f1_acc, SVM_jaccard_acc | /opt/conda/envs/Python36/lib/python3.6/site-packages/sklearn/svm/base.py:196: FutureWarning: The default value of gamma will change from 'auto' to 'scale' in version 0.22 to account better for unscaled features. Set gamma explicitly to 'auto' or 'scale' to avoid this warning.
"avoid this warning.", FutureWarning)
| MIT | Coursera/IBM Python 01/Course02/ML Python Sharing.ipynb | brianshen1990/KeepLearning |
Logistic Regression | LR = LogisticRegression(C=0.01, solver='liblinear').fit(X_train,y_train)
yhat = LR.predict(test_Feature)
LR_f1_acc = f1_score(test_y, yhat, average='weighted')
LR_jaccard_acc = jaccard_similarity_score(test_y, yhat)
from sklearn.metrics import log_loss
yhat_prob = LR.predict_proba(test_Feature)
LR_log_loss = log_los... | /opt/conda/envs/Python36/lib/python3.6/site-packages/sklearn/metrics/classification.py:1143: UndefinedMetricWarning: F-score is ill-defined and being set to 0.0 in labels with no predicted samples.
'precision', 'predicted', average, warn_for)
| MIT | Coursera/IBM Python 01/Course02/ML Python Sharing.ipynb | brianshen1990/KeepLearning |
2 - Análise Exploratória de Séries Temporais - Faturamento TotalProjeto para a disciplina de **Estatística** (Módulo 4) do Data Science Degree (turma de julho de 2020) Equipe* Felipe Lima de Oliveira* Mário Henrique Romagna Cesa* Tsuyioshi Valentim Fukuda* Fernando Raineri MonariLink para [projeto no Github](https://... | # importação de bibliotecas
import datetime as dt
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
import json
# importação de bibliotecas de análise
from statsmodels.tsa.seasonal import seasonal_decompose
from statsmodels.graphics.tsaplots import plot_acf, plot_pacf
from st... | _____no_output_____ | MIT | notebooks_exploration/2-faturamento_total.ipynb | flimao/case-previsao-faturamento |
Importação dos dados | ts_raw = pd.read_csv(r'../data/sim_ts_limpo.csv')
tsd, tswide = py_scripts.transform.pipeline(ts_raw)
fat_total = tswide.sum(axis = 'columns').dropna()
fat_total
fat_total.plot(linestyle = '', marker = 'o')
plt.title('Faturamento (R$ bi)')
plt.show() | _____no_output_____ | MIT | notebooks_exploration/2-faturamento_total.ipynb | flimao/case-previsao-faturamento |
Análise ExploratóriaVamos primeiramente analisar o faturamento total contido na série histórica: | fat_total = tsd['total']
fat_total.describe()
sns.scatterplot(data = fat_total)
plt.title('Série histórica (últimos 4 anos)')
plt.show() | _____no_output_____ | MIT | notebooks_exploration/2-faturamento_total.ipynb | flimao/case-previsao-faturamento |
Parece haver um salto entre 2014 e 2015 no faturamento total. Esse salto é devido ao lançamento de um outro produto, `transporte`. O faturamento deste novo produto é uma ordem de magnitude menor que o faturamento do produto `alimenticio` (como vimos brevemente no gráfico de dados faltantes e veremos com detalhes mais a... | fig = plt.figure(figsize = (6, 8))
sns.boxplot(y = fat_total)
plt.ylabel('Faturamento total (R$ bi)')
plt.title('Boxplot - Série Histórica completa')
plt.show()
sns.histplot(fat_total)
plt.xlabel('Faturamento total (R$ bi)')
plt.title('Histograma - Série Histórica completa')
plt.show() | _____no_output_____ | MIT | notebooks_exploration/2-faturamento_total.ipynb | flimao/case-previsao-faturamento |
No entanto, medidas descritivas de séries temporais devem ser tomadas em relação ao tempo. Vamos separar essas medidas ano a ano: | n_anos = 4
anos_recentes = fat_total[fat_total.index >= dt.datetime.now() - dt.timedelta(days = n_anos * 365) + pd.tseries.offsets.YearBegin()]
anos_recentes.describe()
sns.scatterplot(data = anos_recentes)
plt.title(f'Série histórica (últimos {n_anos} anos)')
plt.show()
sns.boxplot(y = fat_total, x = fat_total.index.y... | _____no_output_____ | MIT | notebooks_exploration/2-faturamento_total.ipynb | flimao/case-previsao-faturamento |
Parece haver alguns *outliers* em 2021.No entanto, a série de 2021 está incompleta (vai somente até outubro). Historicamente, há um salto no faturamento em agosto, o que pode estar causando essa deturpação das medidas descritivas. Excluindo o ano de 2021... | anos_recentes_exc2021 = fat_total[(fat_total.index >= '2016') & (fat_total.index < '2021')]
sns.boxplot(y = anos_recentes_exc2021, x = anos_recentes_exc2021.index.year)
plt.ylabel('Faturamento total (R$ bi)')
plt.title(f'Boxplot - Série Histórica (2016-2020)')
plt.show() | _____no_output_____ | MIT | notebooks_exploration/2-faturamento_total.ipynb | flimao/case-previsao-faturamento |
A pandemia se faz notar nos dados apenas com o aumento ligeiro da mediana em relação à distância entre o Q1 e o Q3. | sns.histplot(x = anos_recentes, hue = anos_recentes.index.year, multiple = 'dodge', shrink = .8, common_norm = False, palette = sns.color_palette()[:4])
plt.xlabel('Faturamento total (R$ bi)')
plt.title(f'Histograma - Série Histórica (últimos {n_anos} anos)')
plt.show() | _____no_output_____ | MIT | notebooks_exploration/2-faturamento_total.ipynb | flimao/case-previsao-faturamento |
Os histogramas ano a ano estão melhor comportados que o histograma da série histórica completa. Fazendo uma análise mês a mês para cada ano... | hue = fat_total.index.year
palette = []
for i, year in enumerate(hue.unique()):
if year not in [2014, 2015]:
palette += ['lightgray']
else:
palette += [sns.color_palette()[i]]
ax = sns.lineplot(
y = fat_total, x = fat_total.index.month,
hue = fat_total.index.year,
palette = palett... | _____no_output_____ | MIT | notebooks_exploration/2-faturamento_total.ipynb | flimao/case-previsao-faturamento |
... nota-se claramente o salto dado de 2014 para 2015 com a entrada do novo produto. Estacionariedade Para que a série de faturamentos mensais totais possa ser decomposta, é necessário que ela seja estacionária. Não parece ser, mas vamos testar através do teste estatístico de Dickey-Fuller.A hipótese nula do teste de ... | testedf = adfuller(fat_total)
pvalor = testedf[1]
alpha = 0.05
print(f'Valor-p: {pvalor:.3%}', end = '')
if pvalor < alpha:
print(f' < {alpha:.0%}')
print(' Série de faturamentos mensais é estacionária. Rejeita-se a hipótese de a série ser um passeio aleatório.')
else:
print(f' > {alpha:.0%}')
prin... | Valor-p: 98.342% > 5%
Série de faturamentos mensais é um passeio aleatório. Não podemos rejeitar a hipótese nula.
| MIT | notebooks_exploration/2-faturamento_total.ipynb | flimao/case-previsao-faturamento |
Isso é evidenciado pela decomposição da série temporal. Decomposição em séries de Fourier | decomp_total = seasonal_decompose(fat_total)
# plot
fig, axs = plt.subplots(nrows = 4, figsize = (10, 8), sharex = True)
sns.lineplot(data = fat_total, ax = axs[0])
axs[0].set_title('Faturamento total')
sns.lineplot(data = decomp_total.trend, ax = axs[1])
axs[1].set_ylabel('Tendência')
sns.lineplot(data = dec... | _____no_output_____ | MIT | notebooks_exploration/2-faturamento_total.ipynb | flimao/case-previsao-faturamento |
Como mostrado anteriormente, esta série temporal não é estacionária, o que podemos ver através dos resíduos padronizados do último quadro (onde há um padrão claro oscilatório). Modelo autorregressivo - Faturamento total Para analisar e prever essa série temporal, é necessário um modelo mais completo. Utilizaremos aqui... | # excluindo o período pré-2015
test_begin = '2020-01-01'
fat_modelo = fat_total['2015-01-01':]
total_train = fat_modelo[:test_begin].iloc[:-1]
total_test = fat_modelo[test_begin:]
train_test_split_idx = int(fat_modelo.shape[0] * 0.8 + 1)
total_train = fat_modelo[:train_test_split_idx]
total_test = fat_modelo[train_... | _____no_output_____ | MIT | notebooks_exploration/2-faturamento_total.ipynb | flimao/case-previsao-faturamento |
O modelo SARIMA contém alguns parâmetros, `S(P, D, Q, S)`, `AR(p)`, `I(d)` e `MA(q)`.Para determinarmos o parâmetro `d`, uma boa indicação é o gráfico de autocorrelação: | fig = plt.figure()
ax = fig.gca()
plot_pacf(fat_modelo, lags = 20, method = 'ywm', ax = ax)
ax.set_xlabel('Lags')
ax.set_title('Autocorrelação parcial - Série de faturamento total')
plt.show() | _____no_output_____ | MIT | notebooks_exploration/2-faturamento_total.ipynb | flimao/case-previsao-faturamento |
Neste caso, uma boa estimativa para o parâmetro `d` é 1 subtraído do número de *lags* em que a correlação é estatisticamente significativa. Neste caso, $d \sim 1$. | arimas = {}
arimas['total'] = auto_arima(
y = total_train,
start_p = 1, max_p = 3,
d = 2, max_d = 4,
start_q = 1, max_q = 3,
start_P = 1, max_P = 3,
D = None, max_D = 4,
start_Q = 1, max_Q = 3,
#max_order = 6,
m = 12,
seasonal = True,
alpha = 0.05,
stepwise = True,
tr... | _____no_output_____ | MIT | notebooks_exploration/2-faturamento_total.ipynb | flimao/case-previsao-faturamento |
Métricas para o modelo autorregressivo SARIMAX Primeiramente, podemos avaliar o ajuste visualmente: | n_test_periods = total_test.shape[0]
arr_preds = arimas['total'].predict(n_test_periods)
idx = pd.date_range(freq = 'MS', start = total_test.index[0], periods = n_test_periods)
preds = pd.Series(arr_preds, index = idx)
preds.name = 'yearly_preds'
preds.plot(label = 'Predição')
total_test.plot(label = 'Conjunto de tes... | _____no_output_____ | MIT | notebooks_exploration/2-faturamento_total.ipynb | flimao/case-previsao-faturamento |
Vamos aplicar algumas métricas quantitativas ao modelo: | kwargs_total = dict(
y_true = total_test,
y_pred = preds,
n = total_train.shape[0],
dof = arimas['total'].df_model()
)
py_scripts.metrics.mostrar_metricas(**kwargs_total)
arimas['total'].arima_res_.data.endog
fat_total['2019-06':'2020-06'] | _____no_output_____ | MIT | notebooks_exploration/2-faturamento_total.ipynb | flimao/case-previsao-faturamento |
Task of muscle Modeling | import numpy as np
import math
import matplotlib.pyplot as plt
%matplotlib notebook
#inline | _____no_output_____ | MIT | courses/modsim2018/tasks/Tasks_ForLectures10and11/.ipynb_checkpoints/Tasks_During_Lecture10-checkpoint.ipynb | raissabthibes/bmc |
Nova Proposta Normalizando a Força pela Força máxima Propriedades do vasto medialUmax = 0.04Lslack = 0.223Lce = 0.087Lceopt = 0.093width = 0.63 * LceoptFmax = 7400;a = 0.25 * Fmaxb = 0.25*10 * Lceopt Condições Iniciaisphi = np.pi/2phid = 0Lce = 0.31 - Lslackt0 = 0tend = 2.99h = 0.001 t = np.arange(t0,tend,h)Lce_2 = ... | # Propriedades do vasto medial
Umax = 0.04
Lslack = 0.223
Lceopt = 0.093
LceNorm = 0.087 / Lceopt
width = 0.63
Fmax = 7400;
a = 0.25 # * Fmax
b = 0.25*10
# Condições Iniciais
phi = np.pi/2
phid = 0
#Lce = 0.31 - Lslack
t0 = 0
tend = 2.99
h = 0.001
# Inicializar
t = np.arange(t0,tend,h)
Lce_2 = np.empty_like(t); ... | _____no_output_____ | MIT | courses/modsim2018/tasks/Tasks_ForLectures10and11/.ipynb_checkpoints/Tasks_During_Lecture10-checkpoint.ipynb | raissabthibes/bmc |
Python in Action Part 1: Python Fundamentals 22 — Variable scope rules in Python> scope and lifecycle of variables in Python When you declare a variable outside of any function in Python, the variable will be visible to any code after the declaration. That is called a global variable.Note that you will be able t... | name = 'Jason'
def say_hello():
print(f'Hello, {name}')
say_hello()
print('Your name is ' + name) | Hello, Jason
Your name is Jason
| MIT | 01-python-basics/22-variable-scope-python.ipynb | sergiofgonzalez/python-in-action |
When you define a variable inside a function, that function will only be visible within that function. That is called a local variable: | name = 'Jason'
def say_hello():
name = 'Idris'
print(f'Hello, {name}!')
say_hello()
print(name) | Hello, Idris!
Jason
| MIT | 01-python-basics/22-variable-scope-python.ipynb | sergiofgonzalez/python-in-action |
The `global` keywordThere might be situations on which you would like to modify the value of a global variable within the scope of a function.When that happens, you will be required to use the `global` keyword: | name = 'Jason'
def say_hello():
print(f'Hi, {name}!')
def holler_hello():
global name
name = name.upper()
print(f'HI, {name}!')
say_hello()
holler_hello()
print(name) | Hi, Jason!
HI, JASON!
JASON
| MIT | 01-python-basics/22-variable-scope-python.ipynb | sergiofgonzalez/python-in-action |
open the FITS file | #read image into a 2-D numpy array
fname = "image.fits"
hdu_list = fits.open(fname)
hdu_list.info()
#access image by indexing hdu_list
image_data = hdu_list[0].data
#data is stored as a 2D numpy array. Show the shape of the array
print(type(image_data))
print(image_data.shape) | _____no_output_____ | MIT | final_project_1.ipynb | ashleyparrilla/astro-detection |
show data | #show the image
m,s = np.mean(image_data), np.std(image_data)
plt.imshow(image_data, interpolation='nearest', cmap='gray', vmin=m-s, vmax=m+s, origin='lower',)
plt.colorbar();
plt.savefig('image_1.png') | _____no_output_____ | MIT | final_project_1.ipynb | ashleyparrilla/astro-detection |
background subtraction | #measure spatially varying background on image
bkg = sep.Background(image_data)
bkg = sep.Background(image_data, bw=64, bh=64, fw=3, fh=3)
#get global mean and noise of image's background
print(bkg.globalback)
print(bkg.globalrms)
#evaluate background as 2-D array but same size as original image
bkg_image = bkg.back()
... | _____no_output_____ | MIT | final_project_1.ipynb | ashleyparrilla/astro-detection |
object detection | #set detection threshold to be a constant value of 1.5*sigma
#sigma=global background rms
objects = sep.extract(image_data_sub, 1.5, err=bkg.globalrms)
#number of objects detected
len(objects)
#over-plot the object coordinates with some parameters on the image
#this will check where the detected objects are
from matplo... | _____no_output_____ | MIT | final_project_1.ipynb | ashleyparrilla/astro-detection |
aperture photometry | #perform circular aperture photometry
#with a 3 pixel radius at locations of the objects
flux, fluxerr, flag = sep.sum_circle(image_data_sub,objects['x'], objects['y'],
3.0, err=bkg.globalrms, gain=1.0)
#show the first 10 objects results:
for i in range(10):
print("object {:d}:... | _____no_output_____ | MIT | final_project_1.ipynb | ashleyparrilla/astro-detection |
How to use Amazon ForecastHelps advanced users start with Amazon Forecast quickly. The demo notebook runs through a typical end to end usecase for a simple timeseries forecasting scenario. Prerequisites: [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/installing.html) . For more informations about APIs, ple... | import sys
import os
import time
import boto3
# importing forecast notebook utility from notebooks/common directory
sys.path.insert( 0, os.path.abspath("../../common") )
import util | _____no_output_____ | MIT-0 | notebooks/advanced/Getting_started_with_AutoML/Getting_started_with_AutoML.ipynb | yinti/forecast-sagemaker |
Configure the S3 bucket name and region name for this lesson.- If you don't have an S3 bucket, create it first on S3.- Although we have set the region to us-west-2 as a default value below, you can choose any of the regions that the service is available in. | text_widget_bucket = util.create_text_widget( "bucketName", "input your S3 bucket name" )
text_widget_region = util.create_text_widget( "region", "input region name.", default_value="us-west-2" )
bucketName = text_widget_bucket.value
assert bucketName, "bucket_name not set."
region = text_widget_region.value
assert re... | _____no_output_____ | MIT-0 | notebooks/advanced/Getting_started_with_AutoML/Getting_started_with_AutoML.ipynb | yinti/forecast-sagemaker |
Forecasting with Amazon Forecast Preparing your Data In Amazon Forecast , a dataset is a collection of file(s) which contain data that is relevant for a forecasting task. A dataset must conform to a schema provided by Amazon Forecast. For this exercise, we use the individual household electric power consumption datas... | import pandas as pd
df = pd.read_csv("../../common/data/item-demand-time.csv", dtype = object)
df.head(3) | _____no_output_____ | MIT-0 | notebooks/advanced/Getting_started_with_AutoML/Getting_started_with_AutoML.ipynb | yinti/forecast-sagemaker |
Now upload the data to S3. But before doing that, go into your AWS Console, select S3 for the service and create a new bucket inside the `Oregon` or `us-west-2` region. Use that bucket name convention of `amazon-forecast-unique-value-data`. The name must be unique, if you get an error, just adjust until your name works... | s3 = session.client('s3')
key="elec_data/item-demand-time.csv"
s3.upload_file(Filename="../../common/data/item-demand-time.csv", Bucket=bucketName, Key=key)
# Create the role to provide to Amazon Forecast.
role_name = "ForecastNotebookRole-AutoML"
role_arn = util.get_or_create_iam_role( role_name = role_name ) | _____no_output_____ | MIT-0 | notebooks/advanced/Getting_started_with_AutoML/Getting_started_with_AutoML.ipynb | yinti/forecast-sagemaker |
CreateDataset More details about `Domain` and dataset type can be found on the [documentation](https://docs.aws.amazon.com/forecast/latest/dg/howitworks-domains-ds-types.html) . For this example, we are using [CUSTOM](https://docs.aws.amazon.com/forecast/latest/dg/custom-domain.html) domain with 3 required attributes ... | DATASET_FREQUENCY = "H"
TIMESTAMP_FORMAT = "yyyy-MM-dd hh:mm:ss"
project = 'workshop_forecastdemo_1' # Replace this with a unique name here, make sure the entire name is < 30 characters.
datasetName= project+'_ds'
datasetGroupName= project +'_gp'
s3DataPath = "s3://"+bucketName+"/"+key
datasetName | _____no_output_____ | MIT-0 | notebooks/advanced/Getting_started_with_AutoML/Getting_started_with_AutoML.ipynb | yinti/forecast-sagemaker |
Schema Definition We are defining the attributes for the model | # Specify the schema of your dataset here. Make sure the order of columns matches the raw data files.
schema ={
"Attributes":[
{
"AttributeName":"timestamp",
"AttributeType":"timestamp"
},
{
"AttributeName":"target_value",
"AttributeType":"float"
},
{... | _____no_output_____ | MIT-0 | notebooks/advanced/Getting_started_with_AutoML/Getting_started_with_AutoML.ipynb | yinti/forecast-sagemaker |
If you have an existing datasetgroup, you can update it using **update_dataset_group** to update dataset group. | forecast.describe_dataset_group(DatasetGroupArn=datasetGroupArn) | _____no_output_____ | MIT-0 | notebooks/advanced/Getting_started_with_AutoML/Getting_started_with_AutoML.ipynb | yinti/forecast-sagemaker |
Create Data Import JobBrings the data into Amazon Forecast system ready to forecast from raw data. | datasetImportJobName = 'EP_AML_DSIMPORT_JOB_TARGET'
ds_import_job_response=forecast.create_dataset_import_job(DatasetImportJobName=datasetImportJobName,
DatasetArn=datasetArn,
DataSource= {
... | _____no_output_____ | MIT-0 | notebooks/advanced/Getting_started_with_AutoML/Getting_started_with_AutoML.ipynb | yinti/forecast-sagemaker |
Check the status of dataset, when the status change from **CREATE_IN_PROGRESS** to **ACTIVE**, we can continue to next steps. Depending on the data size. It can take 10 mins to be **ACTIVE**. This process will take 5 to 10 minutes. | status_indicator = util.StatusIndicator()
while True:
status = forecast.describe_dataset_import_job(DatasetImportJobArn=ds_import_job_arn)['Status']
status_indicator.update(status)
if status in ('ACTIVE', 'CREATE_FAILED'): break
time.sleep(10)
status_indicator.end()
forecast.describe_dataset_import_jo... | _____no_output_____ | MIT-0 | notebooks/advanced/Getting_started_with_AutoML/Getting_started_with_AutoML.ipynb | yinti/forecast-sagemaker |
Create Predictor with customer forecast horizon Forecast horizon is the number of number of time points to predicted in the future. For weekly data, a value of 12 means 12 weeks. Our example is hourly data, we try forecast the next day, so we can set to 24. If we are not sure which recipe will perform best, we can uti... | predictorName = project+'_autoML'
forecastHorizon = 24
algorithmArn = 'arn:aws:forecast:::algorithm/ETS'
create_predictor_response=forecast.create_predictor(PredictorName=predictorName,
ForecastHorizon=forecastHorizon,
... | _____no_output_____ | MIT-0 | notebooks/advanced/Getting_started_with_AutoML/Getting_started_with_AutoML.ipynb | yinti/forecast-sagemaker |
Check the status of the predictor. When the status change from **CREATE_IN_PROGRESS** to **ACTIVE**, we can continue to next steps. Depending on data size, model selection and hyper parameters,it can take 10 mins to more than one hour to be **ACTIVE**. | status_indicator = util.StatusIndicator()
while True:
status = forecast.describe_predictor(PredictorArn=predictorArn)['Status']
status_indicator.update(status)
if status in ('ACTIVE', 'CREATE_FAILED'): break
time.sleep(10)
status_indicator.end() | _____no_output_____ | MIT-0 | notebooks/advanced/Getting_started_with_AutoML/Getting_started_with_AutoML.ipynb | yinti/forecast-sagemaker |
Get Error Metrics Let's get the accuracy metrics of the predicto we just created using Auto ML. The response will be a dictionary with all available recipes. Auto ML works out the best one for our predictor. | forecast.get_accuracy_metrics(PredictorArn=predictorArn) | _____no_output_____ | MIT-0 | notebooks/advanced/Getting_started_with_AutoML/Getting_started_with_AutoML.ipynb | yinti/forecast-sagemaker |
Create Forecast Now create a forecast using the model that was trained. | forecastName= project+'_aml_forecast'
create_forecast_response=forecast.create_forecast(ForecastName=forecastName,
PredictorArn=predictorArn)
forecastArn = create_forecast_response['ForecastArn'] | _____no_output_____ | MIT-0 | notebooks/advanced/Getting_started_with_AutoML/Getting_started_with_AutoML.ipynb | yinti/forecast-sagemaker |
Check the status of the forecast process, when the status change from **CREATE_IN_PROGRESS** to **ACTIVE**, we can continue to next steps. Depending on data size, model selection and hyper parameters,it can take 10 mins to more than one hour to be **ACTIVE**. There's no output here, but that is fine as long as the * is... | status_indicator = util.StatusIndicator()
while True:
status = forecast.describe_forecast(ForecastArn=forecastArn)['Status']
status_indicator.update(status)
if status in ('ACTIVE', 'CREATE_FAILED'): break
time.sleep(10)
status_indicator.end() | _____no_output_____ | MIT-0 | notebooks/advanced/Getting_started_with_AutoML/Getting_started_with_AutoML.ipynb | yinti/forecast-sagemaker |
Get Forecast Once created, the forecast results are ready and you view them. | forecastResponse = forecastquery.query_forecast(
ForecastArn=forecastArn,
Filters={"item_id":"client_12"}
)
print(forecastResponse) | _____no_output_____ | MIT-0 | notebooks/advanced/Getting_started_with_AutoML/Getting_started_with_AutoML.ipynb | yinti/forecast-sagemaker |
Export Forecast You can export forecast to s3 bucket. To do so an role with s3 put access is needed, but this has already been created. | forecastExportName= project+'_aml_forecast_export'
outputPath="s3://"+bucketName+"/output"
forecast_export_response = forecast.create_forecast_export_job(
ForecastExportJobName = forecastExportName,
... | _____no_output_____ | MIT-0 | notebooks/advanced/Getting_started_with_AutoML/Getting_started_with_AutoML.ipynb | yinti/forecast-sagemaker |
Check s3 bucket for results | s3.list_objects(Bucket=bucketName,Prefix="output") | _____no_output_____ | MIT-0 | notebooks/advanced/Getting_started_with_AutoML/Getting_started_with_AutoML.ipynb | yinti/forecast-sagemaker |
CleanupOnce we have completed the above steps, we can start to cleanup the resources we created. All delete jobs, except for `delete_dataset_group` are asynchronous, so we have added the helpful `wait_till_delete` function. Resource Limits documented here. | # Delete forecast export for both algorithms
util.wait_till_delete(lambda: forecast.delete_forecast_export_job(ForecastExportJobArn = forecastExportJobArn))
# Delete forecast
util.wait_till_delete(lambda: forecast.delete_forecast(ForecastArn = forecastArn))
# Delete predictor
util.wait_till_delete(lambda: forecast.dele... | _____no_output_____ | MIT-0 | notebooks/advanced/Getting_started_with_AutoML/Getting_started_with_AutoML.ipynb | yinti/forecast-sagemaker |
MODELOS DE CATEGORIZACION 1. Introducción | import IPython.display as ipd
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import sklearn as skl
import sklearn.utils, sklearn.preprocessing, sklearn.decomposition, sklearn.svm
data = pd.read_pickle("clean_data/track.pkl")
unpickled_df_features = pd.read_pickle("clean_da... | _____no_output_____ | MIT | Modelizacion Coti.ipynb | constanzasilvestre/digital-house-challenge-3 |
(Copiado de Data Analysis) Analisis de FeaturesLos features fueron generados utilizando la libreria de librosa sobre mp3 de extractos de cada cancion.(Del data esta es la primera agrupacion)Los features generados son:- mfcc: Mel-frequency cepstral coefficients (MFCCs). The Mel frequency cepstral coefficients (MFCCs) of... | unpickled_df_features.head(5).style.format('{:.2f}')
features_columns = ['mfcc', 'chroma_cens', 'spectral_centroid',"spectral_bandwidth", 'spectral_rolloff', "zcr"]
clean_features = unpickled_df_features[features_columns]
clean_features.shape
clean_features_spectral_centroid= unpickled_df_features["spectral_centroid"]... | _____no_output_____ | MIT | Modelizacion Coti.ipynb | constanzasilvestre/digital-house-challenge-3 |
Preparamos los datos del modelo | from matplotlib import offsetbox
import joblib
#from PIL import Image
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.model_selection import train_test_split
from sklearn import linear_model
from sklearn import metrics
import matplotlib.pyplot as plt
| _____no_output_____ | MIT | Modelizacion Coti.ipynb | constanzasilvestre/digital-house-challenge-3 |
Observamos la media y varianza de las variables: | #Obtenemos las variables numericas del data:
print (data.columns)
print(data.info())
#dropeo location porque tiene muchos nulos
data_complete = data_full.drop(labels="location",axis=1)
print("Media de las variables: ")
print(data_complete.mean(axis=0))
print('\n')
print("Varianza de las variables: ")
print(data_c... | Media de las variables:
duration 2.054668e-17
acousticness 8.022849e-17
album_tracks 5.641946e-16
danceability 2.689316e-16
energy 6.707861e-17
instrumentalness -2.376314e-16
liveness 1.595708e-16
speechiness -1.208808e-16
tempo ... | MIT | Modelizacion Coti.ipynb | constanzasilvestre/digital-house-challenge-3 |
Features del modeloX_test_numerical_scaled / X_train_numerical_scaled / Y_train, Y_test 1. Reduccion de dimensionalidad -> PCA | model_pca = PCA().fit(X_train_numerical_scaled)
X_train_PCA = model_pca.transform(X_train_numerical_scaled)
X_test_PCA = model_pca.transform(X_test_numerical_scaled)
componentes=model_pca.n_components_
print("Componentes del modelo", model_pca.n_components_)
def plot_explained_variance(components_count, X):
mode... | _____no_output_____ | MIT | Modelizacion Coti.ipynb | constanzasilvestre/digital-house-challenge-3 |
PCA para features musicales | lista_features=['spectral_rolloff', 'spectral_bandwidth', 'spectral_centroid', 'zcr', 'mfcc', 'chroma' ]
std_sclr = StandardScaler()
std_sclr_trained = std_sclr.fit(X_train[lista_features])
X_train_numerical = std_sclr_trained.transform(X_train[lista_features])
X_train_numerical_scaled = pd.DataFrame(X_train_numerical... | _____no_output_____ | MIT | Modelizacion Coti.ipynb | constanzasilvestre/digital-house-challenge-3 |
con la regla del codo notamos que con 3 variables de PCA podemos explicar más de 95% y con 2 podemos explicar el 95% Representacion grafica con 2 variables | pca_digits_vis = PCA(n_components=2)
data_numero = pca_digits_vis.fit_transform(data_complete[lista_features])
print(data_complete[lista_features].shape)
print(data_numero.shape)
def plot_digits_pca(projection, generos):
colors = ["#476A2A", "#7851B8", "#BD3430", "#4A2D4E", "#875525",
"#A83683", "#4E... | _____no_output_____ | MIT | Modelizacion Coti.ipynb | constanzasilvestre/digital-house-challenge-3 |
2. NAIVE BAYES | from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import accuracy_score
from sklearn.metrics import recall_score
from sklearn.metrics import precision_score
from sklearn.metrics import confusion_matrix
import seaborn as sns
gnb = GaussianNB()
gnb.fit(X_train_numerical_scaled, Y_train)
Y_pred = gnb.predic... | _____no_output_____ | MIT | Modelizacion Coti.ipynb | constanzasilvestre/digital-house-challenge-3 |
3. KNN | # Importamos la clase KNeighborsClassifier de módulo neighbors
from sklearn.neighbors import KNeighborsClassifier
knn = KNeighborsClassifier()
knn.fit(X_train, Y_train)
y_pred = knn.predict(X_test)
from sklearn.metrics import accuracy_score
accuracy_score(Y_test, y_pred).round(2)
from sklearn.model_selection import cro... | _____no_output_____ | MIT | Modelizacion Coti.ipynb | constanzasilvestre/digital-house-challenge-3 |
KNN con 11 neighbors -> El modelo esta under fiteando- Acurr en train -> 0.72 - Acurr en test -> 0.67 | # Obtenemos la matriz de confusión
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(Y_test, y_pred)
cm
from sklearn.metrics import confusion_matrix
from sklearn.metrics import plot_confusion_matrix
sns.set(rc={'figure.figsize':(30,30)})
# Graficamos la matriz de confusión
print(confusion_matrix(Y_te... | _____no_output_____ | MIT | Modelizacion Coti.ipynb | constanzasilvestre/digital-house-challenge-3 |
GridSearch & Pipeline | from sklearn.model_selection import GridSearchCV
from sklearn.model_selection import StratifiedKFold
from sklearn.pipeline import Pipeline
folds=StratifiedKFold(n_splits=5,shuffle=True, random_state=42)
pasos = [('scaler', StandardScaler()), ('knn', KNeighborsClassifier())]
pipe_grid = Pipeline(pasos)
param_grid = {'k... | _____no_output_____ | MIT | Modelizacion Coti.ipynb | constanzasilvestre/digital-house-challenge-3 |
Validating the 10m Sahel Africa Cropland Mask DescriptionPreviously, in the `6_Accuracy_assessment_20m.ipynb` notebook, we were doing preliminary validations on 20m resolution testing crop-masks. The crop-mask was stored on disk as a geotiff. The final cropland extent mask, produced at 10m resolution, is stored in th... | import os
import sys
import glob
import rasterio
import datacube
import pandas as pd
import numpy as np
import seaborn as sn
import matplotlib.pyplot as plt
import geopandas as gpd
from sklearn.metrics import f1_score
from rasterstats import zonal_stats | _____no_output_____ | Apache-2.0 | testing/sahel_cropmask/6_Accuracy_assessment_10m.ipynb | digitalearthafrica/crop-mask |
Analysis Parameters* `product` : name of crop-mask we're validating* `bands`: the bands of the crop-mask we want to load and validate. Can one of either `'mask'` or `'filtered'`* `grd_truth` : a shapefile containing crop/no-crop points to serve as the "ground-truth" dataset | product = "crop_mask_sahel"
band = 'mask'
grd_truth = 'data/validation_samples.shp'
| _____no_output_____ | Apache-2.0 | testing/sahel_cropmask/6_Accuracy_assessment_10m.ipynb | digitalearthafrica/crop-mask |
Load the datasets`the cropland extent mask` | #connect to the datacube
dc = datacube.Datacube(app='feature_layers')
#load 10m cropmask
ds = dc.load(product=product, measurements=[band], resolution=(-10,10)).squeeze()
print(ds) | <xarray.Dataset>
Dimensions: (y: 364800, x: 672000)
Coordinates:
time datetime64[ns] 2019-07-02T11:59:59.999999
* y (y) float64 3.36e+06 3.36e+06 3.36e+06 ... -2.88e+05 -2.88e+05
* x (x) float64 -1.728e+06 -1.728e+06 ... 4.992e+06 4.992e+06
spatial_ref int32 6933
Data var... | Apache-2.0 | testing/sahel_cropmask/6_Accuracy_assessment_10m.ipynb | digitalearthafrica/crop-mask |
`Ground truth points` | #ground truth shapefile
ground_truth = gpd.read_file(grd_truth).to_crs('EPSG:6933')
# rename the class column to 'actual'
ground_truth = ground_truth.rename(columns={'Class':'Actual'})
# reclassifer into int
ground_truth['Actual'] = np.where(ground_truth['Actual']=='non-crop', 0, ground_truth['Actual'])
ground_truth[... | _____no_output_____ | Apache-2.0 | testing/sahel_cropmask/6_Accuracy_assessment_10m.ipynb | digitalearthafrica/crop-mask |
Convert points into polygonsWhen the validation data was collected, 40x40m polygons were evaluated as either crop/non-crop rather than points, so we want to sample the raster using the same small polygons. We'll find the majority or 'mode' statistic within the polygon and use that to compare with the validation datase... | #set radius (in metres) around points
radius = 20
#create circle buffer around points, then find envelope
ground_truth['geometry'] = ground_truth['geometry'].buffer(radius).envelope | _____no_output_____ | Apache-2.0 | testing/sahel_cropmask/6_Accuracy_assessment_10m.ipynb | digitalearthafrica/crop-mask |
Calculate zonal statisticsWe want to know what the majority pixel value is inside each validation polygon. | def custom_majority(x):
a=np.ma.MaskedArray.count(x)
b=np.sum(x)
c=b/a
if c>0.5:
return 1
if c<=0.5:
return 0
#calculate stats
stats = zonal_stats(ground_truth.geometry,
ds[band].values,
affine=ds.geobox.affine,
add_stats={'... | _____no_output_____ | Apache-2.0 | testing/sahel_cropmask/6_Accuracy_assessment_10m.ipynb | digitalearthafrica/crop-mask |
*** Create a confusion matrix | confusion_matrix = pd.crosstab(ground_truth['Actual'],
ground_truth['Prediction'],
rownames=['Actual'],
colnames=['Prediction'],
margins=True)
confusion_matrix | _____no_output_____ | Apache-2.0 | testing/sahel_cropmask/6_Accuracy_assessment_10m.ipynb | digitalearthafrica/crop-mask |
Calculate User's and Producer's Accuracy `Producer's Accuracy` | confusion_matrix["Producer's"] = [confusion_matrix.loc[0, 0] / confusion_matrix.loc[0, 'All'] * 100,
confusion_matrix.loc[1, 1] / confusion_matrix.loc[1, 'All'] * 100,
np.nan] | _____no_output_____ | Apache-2.0 | testing/sahel_cropmask/6_Accuracy_assessment_10m.ipynb | digitalearthafrica/crop-mask |
`User's Accuracy` | users_accuracy = pd.Series([confusion_matrix[0][0] / confusion_matrix[0]['All'] * 100,
confusion_matrix[1][1] / confusion_matrix[1]['All'] * 100]
).rename("User's")
confusion_matrix = confusion_matrix.append(users_accuracy) | _____no_output_____ | Apache-2.0 | testing/sahel_cropmask/6_Accuracy_assessment_10m.ipynb | digitalearthafrica/crop-mask |
`Overall Accuracy` | confusion_matrix.loc["User's","Producer's"] = (confusion_matrix.loc[0, 0] +
confusion_matrix.loc[1, 1]) / confusion_matrix.loc['All', 'All'] * 100 | _____no_output_____ | Apache-2.0 | testing/sahel_cropmask/6_Accuracy_assessment_10m.ipynb | digitalearthafrica/crop-mask |
`F1 Score`The F1 score is the harmonic mean of the precision and recall, where an F1 score reaches its best value at 1 (perfect precision and recall), and is calculated as:$$\begin{aligned}\text{Fscore} = 2 \times \frac{\text{UA} \times \text{PA}}{\text{UA} + \text{PA}}.\end{aligned}$$Where UA = Users Accuracy, and PA ... | fscore = pd.Series([(2*(confusion_matrix.loc["User's", 0]*confusion_matrix.loc[0, "Producer's"]) / (confusion_matrix.loc["User's", 0]+confusion_matrix.loc[0, "Producer's"])) / 100,
f1_score(ground_truth['Actual'].astype(np.int8), ground_truth['Prediction'].astype(np.int8), average='binary')]
... | _____no_output_____ | Apache-2.0 | testing/sahel_cropmask/6_Accuracy_assessment_10m.ipynb | digitalearthafrica/crop-mask |
Tidy Confusion Matrix* Limit decimal places,* Add readable class names* Remove non-sensical values | # round numbers
confusion_matrix = confusion_matrix.round(decimals=2)
# rename booleans to class names
confusion_matrix = confusion_matrix.rename(columns={0:'Non-crop', 1:'Crop', 'All':'Total'},
index={0:'Non-crop', 1:'Crop', 'All':'Total'})
#remove the nonsensical values in ... | _____no_output_____ | Apache-2.0 | testing/sahel_cropmask/6_Accuracy_assessment_10m.ipynb | digitalearthafrica/crop-mask |
Export csv | confusion_matrix.to_csv('results/Sahel_10m_accuracy_assessment_confusion_matrix.csv') | _____no_output_____ | Apache-2.0 | testing/sahel_cropmask/6_Accuracy_assessment_10m.ipynb | digitalearthafrica/crop-mask |
Recommendations with IBMIn this notebook, you will be putting your recommendation skills to use on real data from the IBM Watson Studio platform. You may either submit your notebook through the workspace here, or you may work from your local machine and submit through the next page. Either way assure that your code p... | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import project_tests as t
import pickle
%matplotlib inline
df = pd.read_csv('data/user-item-interactions.csv') # Import the user item interactions dataframe
df_content = pd.read_csv('data/articles_community.csv') # Import the articles database dat... | _____no_output_____ | MIT | Recommendations_with_IBM.ipynb | Anirudh-Kulkarni/IBM_article_recommendations |
Part I : Exploratory Data AnalysisUse the dictionary and cells below to provide some insight into the descriptive statistics of the data.`1.` What is the distribution of how many articles a user interacts with in the dataset? Provide a visual and descriptive statistics to assist with giving a look at the number of ti... | df_email = df.set_index('email') # Set index to the email
df_email_count = df_email.groupby('email')['article_id'].count()
# Group articles by email and extract article_id's count: this gives
# the number of articles each user interacted with
df_email_countunique = df_email.groupby('email')['article_id'].unique()
#... | _____no_output_____ | MIT | Recommendations_with_IBM.ipynb | Anirudh-Kulkarni/IBM_article_recommendations |
`2.` Explore and remove duplicate articles from the **df_content** dataframe. | # Find and explore duplicate articles
df_content[df_content['article_id'].duplicated() == True]
# The above shows the duplicate entries
# Remove any rows that have the same article_id - only keep the first
df_content1 = df_content.drop_duplicates(subset =['article_id'])
df_content1.head()
| _____no_output_____ | MIT | Recommendations_with_IBM.ipynb | Anirudh-Kulkarni/IBM_article_recommendations |
`3.` Use the cells below to find:**a.** The number of unique articles that have an interaction with a user. **b.** The number of unique articles in the dataset (whether they have any interactions or not).**c.** The number of unique users in the dataset. (excluding null values) **d.** The number of user-article interac... | df4 = df.set_index('article_id')
df5 = df4.groupby('article_id')['title']
df4.describe()
unique_articles = 714# The number of unique articles that have at least one interaction
total_articles = 1051 # The number of unique articles on the IBM platform
unique_users = 5148 # The number of unique users
user_article_interac... | _____no_output_____ | MIT | Recommendations_with_IBM.ipynb | Anirudh-Kulkarni/IBM_article_recommendations |
`4.` Use the cells below to find the most viewed **article_id**, as well as how often it was viewed. After talking to the company leaders, the `email_mapper` function was deemed a reasonable way to map users to ids. There were a small number of null values, and it was found that all of these null values likely belong... | df_id_art = df4.groupby(['article_id']) # Create a dataframe grouped
# by article_id and having the index of article_id
value_counts = df['article_id'].value_counts(dropna=True, sort=True)
# Create a value_count series with number of times the article is
# interacted with. Then sort it with highest count values on th... | It looks like you have everything right here! Nice job!
| MIT | Recommendations_with_IBM.ipynb | Anirudh-Kulkarni/IBM_article_recommendations |
Part II: Rank-Based RecommendationsUnlike in the earlier lessons, we don't actually have ratings for whether a user liked an article or not. We only know that a user has interacted with an article. In these cases, the popularity of an article can really only be based on how often an article was interacted with.`1.` ... | def get_top_articles(n, df=df):
'''
INPUT:
n - (int) the number of top articles to return
df - (pandas dataframe) df as defined at the top of the notebook
OUTPUT:
top_articles - (list) A list of the top 'n' article titles
'''
value_counts = df['article_id'].value_counts(dropn... | Your top_5 looks like the solution list! Nice job.
Your top_10 looks like the solution list! Nice job.
Your top_20 looks like the solution list! Nice job.
| MIT | Recommendations_with_IBM.ipynb | Anirudh-Kulkarni/IBM_article_recommendations |
Part III: User-User Based Collaborative Filtering`1.` Use the function below to reformat the **df** dataframe to be shaped with users as the rows and articles as the columns. * Each **user** should only appear in each **row** once.* Each **article** should only show up in one **column**. * **If a user has interacted... | # create the user-article matrix with 1's and 0's
def create_user_item_matrix(df):
'''
INPUT:
df - pandas dataframe with article_id, title, user_id columns
OUTPUT:
user_item - user item matrix
Description:
Return a matrix with user ids as rows and article ids on the columns with ... | You have passed our quick tests! Please proceed!
| MIT | Recommendations_with_IBM.ipynb | Anirudh-Kulkarni/IBM_article_recommendations |
`2.` Complete the function below which should take a user_id and provide an ordered list of the most similar users to that user (from most similar to least similar). The returned result should not contain the provided user_id, as we know that each user is similar to him/herself. Because the results for each user here ... | def find_similar_users(user_id, user_item=user_item):
'''
INPUT:
user_id - (int) a user_id
user_item - (pandas dataframe) matrix of users by articles:
1's when a user has interacted with an article, 0 otherwise
OUTPUT:
similar_users - (list) an ordered list where the closes... | The 10 most similar users to user 1 are: [3933, 23, 3782, 203, 4459, 131, 3870, 46, 4201, 5041]
The 5 most similar users to user 3933 are: [1, 23, 3782, 4459, 203]
The 3 most similar users to user 46 are: [4201, 23, 3782]
| MIT | Recommendations_with_IBM.ipynb | Anirudh-Kulkarni/IBM_article_recommendations |
`3.` Now that you have a function that provides the most similar users to each user, you will want to use these users to find articles you can recommend. Complete the functions below to return the articles you would recommend to each user. | def get_article_names(article_ids, df=df):
'''
INPUT:
article_ids - (list) a list of article ids
df - (pandas dataframe) df as defined at the top of the notebook
OUTPUT:
article_names - (list) a list of article names associated with the list of article ids
(this is iden... | If this is all you see, you passed all of our tests! Nice job!
| MIT | Recommendations_with_IBM.ipynb | Anirudh-Kulkarni/IBM_article_recommendations |
`4.` Now we are going to improve the consistency of the **user_user_recs** function from above. * Instead of arbitrarily choosing when we obtain users who are all the same closeness to a given user - choose the users that have the most total article interactions before choosing those with fewer article interactions.* ... | def get_top_sorted_users(user_id, df=df, user_item=user_item):
'''
INPUT:
user_id - (int)
df - (pandas dataframe) df as defined at the top of the notebook
user_item - (pandas dataframe) matrix of users by articles:
1's when a user has interacted with an article, 0 otherwise
... | _____no_output_____ | MIT | Recommendations_with_IBM.ipynb | Anirudh-Kulkarni/IBM_article_recommendations |
`5.` Use your functions from above to correctly fill in the solutions to the dictionary below. Then test your dictionary against the solution. Provide the code you need to answer each following the comments below. | ### Tests with a dictionary of results
user1_most_sim = neighbors_df.iloc[0].neighbor_id # Find the user that is most similar to user 1
user131_10th_sim = neighbors_df.iloc[9].neighbor_id# Find the 10th most similar user to user 131
## Dictionary Test Here
sol_5_dict = {
'The user that is most similar to user 1.'... | This all looks good! Nice job!
| MIT | Recommendations_with_IBM.ipynb | Anirudh-Kulkarni/IBM_article_recommendations |
`6.` If we were given a new user, which of the above functions would you be able to use to make recommendations? Explain. Can you think of a better way we might make recommendations? Use the cell below to explain a better method for new users. The above method only works by finding other similar users, so user-bsed ... | new_user = '0.0'
# What would your recommendations be for this new user '0.0'? As a new user, they have no observed articles.
# Provide a list of the top 10 article ids you would give to
new_user_recs = list(str(x) for x in get_top_article_ids(10)) # Your recommendations here
new_user_recs
assert set(new_user_recs)... | That's right! Nice job!
| MIT | Recommendations_with_IBM.ipynb | Anirudh-Kulkarni/IBM_article_recommendations |
Part IV: Content Based Recommendations (EXTRA - NOT REQUIRED)Another method we might use to make recommendations is to perform a ranking of the highest ranked articles associated with some term. You might consider content to be the **doc_body**, **doc_description**, or **doc_full_name**. There isn't one way to creat... | def make_content_recs(article_id, m):
'''
INPUT:
article_id - (str with a number) one article id that the user has interacted with
m - (int) the number of recommendations you want for the user
OUTPUT:
recs - (list) a list of recommendations for the user by article id
rec_names - (list)... | _____no_output_____ | MIT | Recommendations_with_IBM.ipynb | Anirudh-Kulkarni/IBM_article_recommendations |
`2.` Now that you have put together your content-based recommendation system, use the cell below to write a summary explaining how your content based recommender works. Do you see any possible improvements that could be made to your function? Is there anything novel about your content based recommender? This part is ... | # make recommendations for a brand new user
new_user_recs = list(str(x) for x in get_top_article_ids(10)) # Your recommendations here
new_user_recs
# make a recommendations for a user who only has interacted with article id '1427.0'
user_rec_ids, user_rec_titles = make_content_recs('1427.0', 5)
user_rec_ids | _____no_output_____ | MIT | Recommendations_with_IBM.ipynb | Anirudh-Kulkarni/IBM_article_recommendations |
Part V: Matrix FactorizationIn this part of the notebook, you will build use matrix factorization to make article recommendations to the users on the IBM Watson Studio platform.`1.` You should have already created a **user_item** matrix above in **question 1** of **Part III** above. This first question here will just... | # Load the matrix here
user_item_matrix = pd.read_pickle('user_item_matrix.p')
# quick look at the matrix
user_item_matrix.head() | _____no_output_____ | MIT | Recommendations_with_IBM.ipynb | Anirudh-Kulkarni/IBM_article_recommendations |
`2.` In this situation, you can use Singular Value Decomposition from [numpy](https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.linalg.svd.html) on the user-item matrix. Use the cell to perform SVD, and explain why this is different than in the lesson. | # Perform SVD on the User-Item Matrix Here
u, s, vt = np.linalg.svd(user_item_matrix)# use the built in to get the three matrices | _____no_output_____ | MIT | Recommendations_with_IBM.ipynb | Anirudh-Kulkarni/IBM_article_recommendations |
This matrix has only binary values, so it is different in that sense from the rating matrix used in the lesson. This matrix has nonempty values for every cell, therefore we need not use FunkSVD on it but can do with SVD. `3.` Now for the tricky part, how do we choose the number of latent features to use? Running the b... | num_latent_feats = np.arange(10,700+10,20)
sum_errs = []
for k in num_latent_feats:
# restructure with k latent features
s_new, u_new, vt_new = np.diag(s[:k]), u[:, :k], vt[:k, :]
# take dot product
user_item_est = np.around(np.dot(np.dot(u_new, s_new), vt_new))
# compute error for each p... | _____no_output_____ | MIT | Recommendations_with_IBM.ipynb | Anirudh-Kulkarni/IBM_article_recommendations |
`4.` From the above, we can't really be sure how many features to use, because simply having a better way to predict the 1's and 0's of the matrix doesn't exactly give us an indication of if we are able to make good recommendations. Instead, we might split our dataset into a training and test set of data, as shown in ... | df_train = df.head(40000)
df_test = df.tail(5993)
# Create matrices for training and testing separately
user_item_train = create_user_item_matrix(df_train)
user_item_test = create_user_item_matrix(df_test)
# Find users in test that are not in train and articles in test that are not in train
len(set(user_item_test.in... | _____no_output_____ | MIT | Recommendations_with_IBM.ipynb | Anirudh-Kulkarni/IBM_article_recommendations |
`5.` Now use the **user_item_train** dataset from above to find U, S, and V transpose using SVD. Then find the subset of rows in the **user_item_test** dataset that you can predict using this matrix decomposition with different numbers of latent features to see how many features makes sense to keep based on the accurac... | # fit SVD on the user_item_train matrix
u_train, s_train, vt_train = np.linalg.svd(user_item_train)# fit svd similar to above then use the cells below
# Print all the shapes for understanding what the matrices represent
print(np.shape(u_train))
print(np.shape(s_train))
print(np.shape(vt_train))
print(np.shape(user_ite... | _____no_output_____ | MIT | Recommendations_with_IBM.ipynb | Anirudh-Kulkarni/IBM_article_recommendations |
`6.` Use the cell below to comment on the results you found in the previous question. Given the circumstances of your results, discuss what you might do to determine if the recommendations you make with any of the above recommendation systems are an improvement to how users currently find articles? It seems that the a... | from subprocess import call
call(['python', '-m', 'nbconvert', 'Recommendations_with_IBM.ipynb']) | _____no_output_____ | MIT | Recommendations_with_IBM.ipynb | Anirudh-Kulkarni/IBM_article_recommendations |
Residual NetworksWelcome to the second assignment of this week! You will learn how to build very deep convolutional networks, using Residual Networks (ResNets). In theory, very deep networks can represent very complex functions; but in practice, they are hard to train. Residual Networks, introduced by [He et al.](http... | import numpy as np
from keras import layers
from keras.layers import Input, Add, Dense, Activation, ZeroPadding2D, BatchNormalization, Flatten, Conv2D, AveragePooling2D, MaxPooling2D, GlobalMaxPooling2D
from keras.models import Model, load_model
from keras.preprocessing import image
from keras.utils import layer_utils
... | Using TensorFlow backend.
| MIT | Convolutional Neural Networks/Residual_Networks_v2a.ipynb | joyfinder/Deep_Learning_Specialisation |
1 - The problem of very deep neural networksLast week, you built your first convolutional neural network. In recent years, neural networks have become deeper, with state-of-the-art networks going from just a few layers (e.g., AlexNet) to over a hundred layers.* The main benefit of a very deep network is that it can re... | # GRADED FUNCTION: identity_block
def identity_block(X, f, filters, stage, block):
"""
Implementation of the identity block as defined in Figure 4
Arguments:
X -- input tensor of shape (m, n_H_prev, n_W_prev, n_C_prev)
f -- integer, specifying the shape of the middle CONV's window for the main... | out = [ 0.94822985 0. 1.16101444 2.747859 0. 1.36677003]
| MIT | Convolutional Neural Networks/Residual_Networks_v2a.ipynb | joyfinder/Deep_Learning_Specialisation |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.