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 |
|---|---|---|---|---|---|
Create or Attach existing AmlComputeYou will need to create a compute target for your AutoML run. In this tutorial, you create AmlCompute as your training compute resource. Creation of AmlCompute takes approximately 5 minutes. If the AmlCompute with that name is already in your workspace this code will skip the creati... | from azureml.core.compute import AmlCompute
from azureml.core.compute import ComputeTarget
# Choose a name for your cluster.
amlcompute_cluster_name = "automlcl"
found = False
# Check if this compute target already exists in the workspace.
cts = ws.compute_targets
if amlcompute_cluster_name in cts and cts[amlcompute_... | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/regression-hardware-performance/auto-ml-regression-hardware-performance.ipynb | wamartin-aml/MachineLearningNotebooks |
DataHere load the data in the get_data script to be utilized in azure compute. To do this, first load all the necessary libraries and dependencies to set up paths for the data and to create the conda_run_config. | if not os.path.isdir('data'):
os.mkdir('data')
if not os.path.exists(project_folder):
os.makedirs(project_folder)
from azureml.core.runconfig import RunConfiguration
from azureml.core.conda_dependencies import CondaDependencies
import pkg_resources
# create a new RunConfig object
conda_run_config = RunCon... | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/regression-hardware-performance/auto-ml-regression-hardware-performance.ipynb | wamartin-aml/MachineLearningNotebooks |
Load DataHere create the script to be run in azure compute for loading the data, load the hardware dataset into the X and y variables. Next split the data using train_test_split and return X_train and y_train for training the model. | data = "https://automlsamplenotebookdata.blob.core.windows.net/automl-sample-notebook-data/machineData.csv"
dflow = dprep.read_csv(data, infer_column_types=True)
dflow.get_profile()
X = dflow.drop_columns(columns=['ERP'])
y = dflow.keep_columns(columns=['ERP'], validate_column_exists=True)
X_train, X_test = X.random_sp... | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/regression-hardware-performance/auto-ml-regression-hardware-performance.ipynb | wamartin-aml/MachineLearningNotebooks |
TrainInstantiate an `AutoMLConfig` object to specify the settings and data used to run the experiment.|Property|Description||-|-||**task**|classification or regression||**primary_metric**|This is the metric that you want to optimize. Regression supports the following primary metrics: spearman_correlationnormalized_roo... | automl_settings = {
"iteration_timeout_minutes": 5,
"iterations": 10,
"n_cross_validations": 5,
"primary_metric": 'spearman_correlation',
"preprocess": True,
"max_concurrent_iterations": 5,
"verbosity": logging.INFO,
}
automl_config = AutoMLConfig(task = 'regression',
... | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/regression-hardware-performance/auto-ml-regression-hardware-performance.ipynb | wamartin-aml/MachineLearningNotebooks |
Results Widget for Monitoring RunsThe widget will first report a "loading" status while running the first iteration. After completing the first iteration, an auto-updating graph and table will be shown. The widget will refresh once per minute, so you should see the graph update as child runs complete.**Note:** The wi... | from azureml.widgets import RunDetails
RunDetails(remote_run).show()
# Wait until the run finishes.
remote_run.wait_for_completion(show_output = True) | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/regression-hardware-performance/auto-ml-regression-hardware-performance.ipynb | wamartin-aml/MachineLearningNotebooks |
Retrieve All Child RunsYou can also use SDK methods to fetch all the child runs and see individual metrics that we log. | children = list(remote_run.get_children())
metricslist = {}
for run in children:
properties = run.get_properties()
metrics = {k: v for k, v in run.get_metrics().items() if isinstance(v, float)}
metricslist[int(properties['iteration'])] = metrics
rundata = pd.DataFrame(metricslist).sort_index(1)
rundata | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/regression-hardware-performance/auto-ml-regression-hardware-performance.ipynb | wamartin-aml/MachineLearningNotebooks |
Retrieve the Best ModelBelow we select the best pipeline from our iterations. The get_output method returns the best run and the fitted model. The Model includes the pipeline and any pre-processing. Overloads on get_output allow you to retrieve the best run and fitted model for any logged metric or for a particular it... | best_run, fitted_model = remote_run.get_output()
print(best_run)
print(fitted_model) | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/regression-hardware-performance/auto-ml-regression-hardware-performance.ipynb | wamartin-aml/MachineLearningNotebooks |
Best Model Based on Any Other MetricShow the run and the model that has the smallest `root_mean_squared_error` value (which turned out to be the same as the one with largest `spearman_correlation` value): | lookup_metric = "root_mean_squared_error"
best_run, fitted_model = remote_run.get_output(metric = lookup_metric)
print(best_run)
print(fitted_model)
iteration = 3
third_run, third_model = remote_run.get_output(iteration = iteration)
print(third_run)
print(third_model) | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/regression-hardware-performance/auto-ml-regression-hardware-performance.ipynb | wamartin-aml/MachineLearningNotebooks |
Register the Fitted Model for DeploymentIf neither metric nor iteration are specified in the register_model call, the iteration with the best primary metric is registered. | description = 'AutoML Model'
tags = None
model = remote_run.register_model(description = description, tags = tags)
print(remote_run.model_id) # This will be written to the script file later in the notebook. | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/regression-hardware-performance/auto-ml-regression-hardware-performance.ipynb | wamartin-aml/MachineLearningNotebooks |
Create Scoring ScriptThe scoring script is required to generate the image for deployment. It contains the code to do the predictions on input data. | %%writefile score.py
import pickle
import json
import numpy
import azureml.train.automl
from sklearn.externals import joblib
from azureml.core.model import Model
def init():
global model
model_path = Model.get_model_path(model_name = '<<modelid>>') # this name is model.id of model that we want to deploy
# ... | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/regression-hardware-performance/auto-ml-regression-hardware-performance.ipynb | wamartin-aml/MachineLearningNotebooks |
Create a YAML File for the Environment To ensure the fit results are consistent with the training results, the SDK dependency versions need to be the same as the environment that trains the model. Details about retrieving the versions can be found in notebook [12.auto-ml-retrieve-the-training-sdk-versions](12.auto-ml-... | dependencies = remote_run.get_run_sdk_dependencies(iteration = 1)
for p in ['azureml-train-automl', 'azureml-sdk', 'azureml-core']:
print('{}\t{}'.format(p, dependencies[p]))
myenv = CondaDependencies.create(conda_packages=['numpy','scikit-learn'], pip_packages=['azureml-sdk[automl]'])
conda_env_file_name = 'myenv... | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/regression-hardware-performance/auto-ml-regression-hardware-performance.ipynb | wamartin-aml/MachineLearningNotebooks |
Create a Container ImageNext use Azure Container Instances for deploying models as a web service for quickly deploying and validating your modelor when testing a model that is under development. | from azureml.core.image import Image, ContainerImage
image_config = ContainerImage.image_configuration(runtime= "python",
execution_script = script_file_name,
conda_file = conda_env_file_name,
tags = {'area': "digits", '... | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/regression-hardware-performance/auto-ml-regression-hardware-performance.ipynb | wamartin-aml/MachineLearningNotebooks |
Deploy the Image as a Web Service on Azure Container InstanceDeploy an image that contains the model and other assets needed by the service. | from azureml.core.webservice import AciWebservice
aciconfig = AciWebservice.deploy_configuration(cpu_cores = 1,
memory_gb = 1,
tags = {'area': "digits", 'type': "automl_regression"},
... | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/regression-hardware-performance/auto-ml-regression-hardware-performance.ipynb | wamartin-aml/MachineLearningNotebooks |
Delete a Web ServiceDeletes the specified web service. | #aci_service.delete() | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/regression-hardware-performance/auto-ml-regression-hardware-performance.ipynb | wamartin-aml/MachineLearningNotebooks |
Get Logs from a Deployed Web ServiceGets logs from a deployed web service. | #aci_service.get_logs() | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/regression-hardware-performance/auto-ml-regression-hardware-performance.ipynb | wamartin-aml/MachineLearningNotebooks |
TestNow that the model is trained, split the data in the same way the data was split for training (The difference here is the data is being split locally) and then run the test data through the trained model to get the predicted values. | X_test = X_test.to_pandas_dataframe()
y_test = y_test.to_pandas_dataframe()
y_test = np.array(y_test)
y_test = y_test[:,0]
X_train = X_train.to_pandas_dataframe()
y_train = y_train.to_pandas_dataframe()
y_train = np.array(y_train)
y_train = y_train[:,0] | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/regression-hardware-performance/auto-ml-regression-hardware-performance.ipynb | wamartin-aml/MachineLearningNotebooks |
Predict on training and test set, and calculate residual values. | y_pred_train = fitted_model.predict(X_train)
y_residual_train = y_train - y_pred_train
y_pred_test = fitted_model.predict(X_test)
y_residual_test = y_test - y_pred_test | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/regression-hardware-performance/auto-ml-regression-hardware-performance.ipynb | wamartin-aml/MachineLearningNotebooks |
Calculate metrics for the predictionNow visualize the data on a scatter plot to show what our truth (actual) values are compared to the predicted values from the trained model that was returned. | %matplotlib inline
from sklearn.metrics import mean_squared_error, r2_score
# Set up a multi-plot chart.
f, (a0, a1) = plt.subplots(1, 2, gridspec_kw = {'width_ratios':[1, 1], 'wspace':0, 'hspace': 0})
f.suptitle('Regression Residual Values', fontsize = 18)
f.set_figheight(6)
f.set_figwidth(16)
# Plot residual values... | _____no_output_____ | MIT | how-to-use-azureml/automated-machine-learning/regression-hardware-performance/auto-ml-regression-hardware-performance.ipynb | wamartin-aml/MachineLearningNotebooks |
Word Embeddings: Encoding Lexical Semantics===========================================Word embeddings are dense vectors of real numbers, one per word in yourvocabulary. In NLP, it is almost always the case that your features arewords! But how should you represent a word in a computer? You couldstore its ascii character... | # Author: Robert Guthrie
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
torch.manual_seed(1)
word_to_ix = {"hello": 0, "world": 1}
embeds = nn.Embedding(2, 5) # 2 words in vocab, 5 dimensional embeddings
lookup_tensor_hello = torch.tensor([word_to_ix["hello"]], dtype=t... | hello_embed: tensor([[-0.8923, -0.0583, -0.1955, -0.9656, 0.4224]], grad_fn=<EmbeddingBackward>)
worlds_embed: tensor([[ 0.2673, -0.4212, -0.5107, -1.5727, -0.1232]], grad_fn=<EmbeddingBackward>)
| Apache-2.0 | pytorch_tutorials/pytorch_tutorial_NLP3_word_embeddings_tutorial.ipynb | adam-dziedzic/time-series-ml |
An Example: N-Gram Language Modeling~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~Recall that in an n-gram language model, given a sequence of words$w$, we want to compute\begin{align}P(w_i | w_{i-1}, w_{i-2}, \dots, w_{i-n+1} )\end{align}Where $w_i$ is the ith word of the sequence.In this example, we will compute the loss funct... | CONTEXT_SIZE = 5
EMBEDDING_DIM = 10
# We will use Shakespeare Sonnet 2
test_sentence = """When forty winters shall besiege thy brow,
And dig deep trenches in thy beauty's field,
Thy youth's proud livery so gazed on now,
Will be a totter'd weed of small worth held:
Then being asked, where all thy beauty lies,
Where all ... | the first 3 ngrams, just so you can see what they look like:
[(['When', 'forty', 'winters', 'shall', 'besiege'], 'thy'), (['forty', 'winters', 'shall', 'besiege', 'thy'], 'brow,'), (['winters', 'shall', 'besiege', 'thy', 'brow,'], 'And')]
the last 3 ngrams:
[(['thy', 'blood', 'warm', 'when', 'thou'], "feel'st"), (['b... | Apache-2.0 | pytorch_tutorials/pytorch_tutorial_NLP3_word_embeddings_tutorial.ipynb | adam-dziedzic/time-series-ml |
Exercise: Computing Word Embeddings: Continuous Bag-of-Words~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~The Continuous Bag-of-Words model (CBOW) is frequently used in NLP deeplearning. It is a model that tries to predict words given the context ofa few words before and a few words after the target word.... | CONTEXT_SIZE = 2 # 2 words to the left, 2 to the right
EMBEDDING_DIM = 10
raw_text = """We are about to study the idea of a computational process.
Computational processes are abstract beings that inhabit computers.
As they evolve, processes manipulate other abstract things called data.
The evolution of a process is di... | [(['We', 'are', 'to', 'study'], 'about'), (['are', 'about', 'study', 'the'], 'to'), (['about', 'to', 'the', 'idea'], 'study'), (['to', 'study', 'idea', 'of'], 'the'), (['study', 'the', 'of', 'a'], 'idea')]
context vector: tensor([41, 15, 12, 30])
[256.88402342796326, 253.96123218536377, 251.09937977790833, 248.2958543... | Apache-2.0 | pytorch_tutorials/pytorch_tutorial_NLP3_word_embeddings_tutorial.ipynb | adam-dziedzic/time-series-ml |
This notebook will hopefully contain timeseries that plot continuous data from moorings alongside model output. | import sys
sys.path.append('/ocean/kflanaga/MEOPAR/analysis-keegan/notebooks/Tools')
import numpy as np
import matplotlib.pyplot as plt
import os
import pandas as pd
import netCDF4 as nc
import xarray as xr
import datetime as dt
from salishsea_tools import evaltools as et, viz_tools
import gsw
import matplotlib.gridsp... | _____no_output_____ | Apache-2.0 | notebooks/Evaluations/Continuous_Timeseries/King_County/Hourly_Timeseries/PointWilliams/2018_PointWilliams_Timeseries.ipynb | SalishSeaCast/analysis-keegan |
Online prediction for radon-smallIn online mode, the model is learning as soon as a new data arrives.It means that when we want our prediction we don't need to provide feature vector, since all data was already processed by the model.Explore the following models: * Constant model - The same value for all future point... | import datetime
import calendar
import pprint
import json
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import rcParams
rcParams['figure.figsize'] = 12, 4 | _____no_output_____ | Apache-2.0 | notebooks/radon-small/[prediction] On-line learning.ipynb | carldata/argo |
Load project | project_folder = '../../datasets/radon-small/'
with open(project_folder + 'project.json', 'r') as file:
project = json.load(file)
pprint.pprint(project)
print('Flow1')
flow = pd.read_csv(project_folder + 'flow1.csv', parse_dates=['time'])
flow = flow.set_index('time')['flow'].fillna(0)
flow = flow.resample('5T').pa... | {'end-date': '2017-11-09',
'flows': ['flow1'],
'name': 'radon-small',
'rainfalls': [],
'split-date': '2016-11-09',
'start-date': '2013-10-01'}
Flow1
| Apache-2.0 | notebooks/radon-small/[prediction] On-line learning.ipynb | carldata/argo |
Helper functionsHelper functions for building training and test sets and calculating score | class PredictionModel:
def fit(self, data_points):
pass
def predict(self, prediction_day):
pass
def mae(y_hat, y):
"""
Calculate Mean Absolute Error
This metric is better here since serries have quite big outliers
"""
return np.sum(np.absolute(y_hat-y))/y... | _____no_output_____ | Apache-2.0 | notebooks/radon-small/[prediction] On-line learning.ipynb | carldata/argo |
Models ConstMeanModel | class ConstantMeanModel(PredictionModel):
def __init__(self):
self.mu = 0
def fit(self, xs):
self.mu = np.mean(xs)
def predict(self, day):
return np.ones(12*24) * self.mu
score, costs = evaluate_model(ConstantMeanModel(), pd.Timestamp('2016-11-11'))
print... | ConstantMeanModel score: 18.86
| Apache-2.0 | notebooks/radon-small/[prediction] On-line learning.ipynb | carldata/argo |
Previous Day ModelUses values from last day | class LastDayModel(PredictionModel):
def fit(self, xs):
self.y = xs.values[-288:]
def predict(self, day):
return self.y
score, costs = evaluate_model(LastDayModel(), pd.Timestamp('2016-11-11'))
print('LastDayModel score: {:.2f}'.format(score)) | LastDayModel score: 11.99
| Apache-2.0 | notebooks/radon-small/[prediction] On-line learning.ipynb | carldata/argo |
Model for single day. Easy case | evaluate_day(LastDayModel(), pd.Timestamp('2016-11-11')) | _____no_output_____ | Apache-2.0 | notebooks/radon-small/[prediction] On-line learning.ipynb | carldata/argo |
And when next day is kind of outlier | evaluate_day(LastDayModel(), pd.Timestamp('2017-05-01')) | _____no_output_____ | Apache-2.0 | notebooks/radon-small/[prediction] On-line learning.ipynb | carldata/argo |
Daily Pattern modelCreate pattern of daily usage based on historical data. Use this pattern to predict next values(This can take up to 10 minutes to calculate) | class DailyPatternModel(PredictionModel):
def fit(self, xs):
df = flow.to_frame().reset_index()
self.daily_pattern = df.groupby(by=[df.time.map(lambda x : (x.hour, x.minute))]).flow.mean().values
def predict(self, day):
return self.daily_pattern
score, costs = evaluat... | DailyPatternModel score: 9.61
| Apache-2.0 | notebooks/radon-small/[prediction] On-line learning.ipynb | carldata/argo |
Daily Pattern Median ModelCalculate median value for each time. Use it as a prediction for the next day. | class DayMedianModel(PredictionModel):
def fit(self, xs):
df = flow.to_frame().reset_index()
self.daily_pattern = df.groupby(by=[df.time.map(lambda x : (x.hour, x.minute))]).flow.median().values
def predict(self, day):
return self.daily_pattern
score, costs = evaluate... | DayModel score: 9.73
| Apache-2.0 | notebooks/radon-small/[prediction] On-line learning.ipynb | carldata/argo |
classificate speaking_audio files |
# 균형있게 구성하기
# 1. 성별 50:50
# 2. 지역 25:25:25:25
# 각 지역별로 남 10, 여 10명
# 총 80명.
import os
import shutil
import random
from typing_extensions import final
A = [] # 강원
B = [] # 서울/경기
C = [] # 경상
D = [] # 전라
E = [] # 제주(현재 없음)
F = [] # 충청(현재 없음)
G = [] # 기타(현재 없음)
region = ['A', 'B', 'C', 'D', 'E', 'F', 'G'... | _____no_output_____ | MIT | preprocessing/1.SpeakingSound_audio_classification.ipynb | kyle-bong/Realtime_Voice_Activity_Detection |
ASSIGNMEN 1) Replticate the lesson code. I recommend that you [do not copy-paste](https://docs.google.com/document/d/1ubOw9B3Hfip27hF2ZFnW3a3z9xAgrUDRReOEo-FHCVs/edit).Get caught up to where we got our example in class and then try and take things further. How close to "pixel perfect" can you make the lecture graph?O... | import matplotlib.pyplot as plt
import matplotlib.ticker as mtick
plt.style.use('fivethirtyeight')
import numpy as np
import pandas as pd
fake = pd.Series([38,3,2,1,2,4,6,5,5,33])
fig = plt.figure()
fig.patch.set(facecolor='white')
ax = ax=fake.plot.bar(color='C1', width=0.9)
ax.set(facecolor='White')
plt.xlabel... | _____no_output_____ | MIT | module3-make-explanatory-visualizations/LS_DS_123_Make_Explanatory_Visualizations_Assignment.ipynb | maiormarso/DS-Unit-1-Sprint-2-Data-Wrangling-and-Storytelling |
STRETCH OPTIONS 1) Reproduce one of the following using the matplotlib or seaborn libraries:- [thanksgiving-2015](https://fivethirtyeight.com/features/heres-what-your-part-of-america-eats-on-thanksgiving/) - [candy-power-ranking](https://fivethirtyeight.com/features/the-ultimate-halloween-candy-power-ranking/) - or an... | _____no_output_____ | MIT | module3-make-explanatory-visualizations/LS_DS_123_Make_Explanatory_Visualizations_Assignment.ipynb | maiormarso/DS-Unit-1-Sprint-2-Data-Wrangling-and-Storytelling | |
Exploratory data analysis of Dranse discharge dataSummary: The data is stationary even without differencing, but ACF and PACF plots show that an hourly first order difference and a periodic 24h first order difference is needed for SARIMA fitting.Note: Final fitting done in Google Colab due to memory constraints - this... | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
from river_forecast.training_data_access import get_combined_flow
flow_df = get_combined_flow()
plt.plot(flow_df.index, flow_df) | _____no_output_____ | MIT | jupyter-notebooks/exploratory_analysis_and_SARIMAX_fitting.ipynb | maxnolte/river_forecast |
Exploratory Analysis | subset_df = flow_df.loc[:]
subset_df['year'] = subset_df.index.year
subset_df['offset_datetime'] = subset_df.index + pd.DateOffset(year=2019)
sns.set(style="whitegrid")
sns.set(rc={'figure.figsize':(15, 8)})
ax = sns.lineplot(x='offset_datetime', y='discharge', hue='year', data=subset_df, markers='')
import matplotlib.... | _____no_output_____ | MIT | jupyter-notebooks/exploratory_analysis_and_SARIMAX_fitting.ipynb | maxnolte/river_forecast |
train-test split | import statsmodels.api as sm
train = flow_df.loc[flow_df.index < pd.to_datetime('2019-01-01 00:00:00')]
test = flow_df.loc[(flow_df.index >= pd.to_datetime('2019-01-01 00:00:00')) & (flow_df.index < pd.to_datetime('2019-07-01 00:00:00'))]
fig, ax = plt.subplots()
train.plot(ax=ax, label='train')
test.plot(ax=ax, label=... | _____no_output_____ | MIT | jupyter-notebooks/exploratory_analysis_and_SARIMAX_fitting.ipynb | maxnolte/river_forecast |
Time series stationarity analysis | import statsmodels.formula.api as smf
import statsmodels.tsa.api as smt
import statsmodels.api as sm
import scipy.stats as scs
def tsplot(y, lags=None, figsize=(12, 7), style='bmh'):
"""
Plot time series, its ACF and PACF, calculate Dickey–Fuller test
-> Adapted from https://gist.github.com... | _____no_output_____ | MIT | jupyter-notebooks/exploratory_analysis_and_SARIMAX_fitting.ipynb | maxnolte/river_forecast |
Augmenteded Dicky-Fuller to check for stationarity | flow = flow_df['discharge']
flow_diff_1 = (flow - flow.shift(1)).dropna()
flow_diff_1_24 = (flow_diff_1 - flow_diff_1.shift(24)).dropna()
flow_diff_24 = (flow - flow.shift(24)).dropna()
tsplot(flow, lags=24*5, figsize=(12, 7))
tsplot(flow_diff_1, lags=24*5, figsize=(12, 7))
tsplot(flow_diff_1_24, lags=24*7, figsize=... | _____no_output_____ | MIT | jupyter-notebooks/exploratory_analysis_and_SARIMAX_fitting.ipynb | maxnolte/river_forecast |
Fitting SARIMAX | train['discharge'].plot()
from statsmodels.tsa.statespace.sarimax import SARIMAX
### Crashed again upon completion, make sure the time series is ok -> computation moved to Colab
# Create a SARIMAX model
model = SARIMAX(train['discharge'], order=(4,1,1), seasonal_order=(0,1,1,24))
# p - try 0, 1, 2, 3, 4; q is cleary o... | _____no_output_____ | MIT | jupyter-notebooks/exploratory_analysis_and_SARIMAX_fitting.ipynb | maxnolte/river_forecast |
Plotting the forecast | # Generate predictions
one_step_forecast = results.get_prediction(start=-48)
# Extract prediction mean
mean_forecast = one_step_forecast.predicted_mean
# Get confidence intervals of predictions
confidence_intervals = one_step_forecast.conf_int()
# Select lower and upper confidence limits
lower_limits = confidence_in... | _____no_output_____ | MIT | jupyter-notebooks/exploratory_analysis_and_SARIMAX_fitting.ipynb | maxnolte/river_forecast |
Finding the best model manually | # Create empty list to store search results
order_aic_bic=[]
# Loop over p values from 0-2
for p in range(0, 5):
print(p)
# create and fit ARMA(p,q) model
model = SARIMAX(train['discharge'], order=(p,1,1), seasonal_order=(0,1,1,24))
# p - try 0, 1, 2, 3, 4; q is cleary one. Q is clearly 1, P is taperin... | _____no_output_____ | MIT | jupyter-notebooks/exploratory_analysis_and_SARIMAX_fitting.ipynb | maxnolte/river_forecast |
Forecasting | results.forecast(steps=6)
resB.forecast(steps=6)
import river_forecast.api_data_access
import importlib, sys
importlib.reload(river_forecast.api_data_access)
rivermap_data = river_forecast.api_data_access.RivermapDataRetriever()
recent_flow_df = rivermap_data.get_latest_river_flow(n_days=3, station='Dranse')
recent_flo... | _____no_output_____ | MIT | jupyter-notebooks/exploratory_analysis_and_SARIMAX_fitting.ipynb | maxnolte/river_forecast |
Isotonic RegressionAn illustration of the isotonic regression on generated data. Theisotonic regression finds a non-decreasing approximation of a functionwhile minimizing the mean squared error on the training data. The benefitof such a model is that it does not assume any form for the targetfunction such as linearity... | print(__doc__)
# Author: Nelle Varoquaux <nelle.varoquaux@gmail.com>
# Alexandre Gramfort <alexandre.gramfort@inria.fr>
# License: BSD
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
from sklearn.linear_model import LinearRegression
from sklearn.isotonic i... | _____no_output_____ | MIT | jhub-spawner-client/plot_isotonic_regression.ipynb | zach-schoenberger/CS6460 |
M5_Idol_lyrics/SongTidy 폴더의 전처리 ipnb을 총정리하고, 잘못된 코드를 수정한 노트북 가사 데이터(song_tidy01) 전처리**df = pd.read_csv('rawdata/song_data_raw_ver01.csv')****!!!!!!!!!!!!!순서로 df(번호)로 지정!!!!!!!!!!!!!**1. Data20180915/song_data_raw_ver01.csv 데이터로 시작함 (키스있는지체크) - 제목에 리믹스,라이브,inst,영일중,ver 인 행 - 앨범에 나가수, 불명, 복면인 행 - 타이틀, 가사, 앨범에 ... | import pandas as pd
import re
df1 = pd.read_csv('C:/Users/pje17/Desktop/Lyricsis/M5_Idol_lyrics/Data/Data20180921/song_data_raw_20180921_ver02.csv')
df1.head()
# 키스없음확인
df1[df1['artist'] == '키스']
df1.shape
# 인덱스칼럼 드랍
df1 = df1.drop(df1.columns[0], axis=1)
df1
# 가사 정보 없는 행 드랍
df1 = df1[df1.lyrics.notnull()]
df1.shape
# ... | <class 'pandas.core.frame.DataFrame'>
Int64Index: 13569 entries, 0 to 18091
Data columns (total 9 columns):
title 13569 non-null object
artist 13569 non-null object
album 13569 non-null object
release_date 13569 non-null object
song_genre 13569 non-null object
is_title 13569 ... | MIT | SongTidy/FinalTidy/final_tidy_yewon_ver02.ipynb | jyw7664/M5_Idol_lyrics |
--------------------2번 전처리 시작-------------------- | # 히라가나/가타카나를 제거한 후에도 일본어 가사가 한글로 포함되어 있는 경우 전처리
df2 = df1[df1.lyrics.str.contains(r'(와타시|혼토|아노히|혼또|마센|에가이|히토츠|후타츠|마치노|몬다이|마에노|아메가)') == False]
df2= df2[df2.lyrics.str.contains(r'(히카리|미라이|오나지|춋|카라다|큥|즛또|나캇|토나리|못또|뎅와|코이|히토리|맛스구|후타리|케시키|쟈나이|잇슌|이츠모|아타라|덴샤|즈쿠|에가오|소라오|난테|고멘네|아이시테|다키시|유메|잇탄다|소레|바쇼)') == False]
df2= df2[df2.ly... | <class 'pandas.core.frame.DataFrame'>
Int64Index: 13119 entries, 0 to 18091
Data columns (total 9 columns):
title 13119 non-null object
artist 13119 non-null object
album 13119 non-null object
release_date 13119 non-null object
song_genre 13119 non-null object
is_title 13119 ... | MIT | SongTidy/FinalTidy/final_tidy_yewon_ver02.ipynb | jyw7664/M5_Idol_lyrics |
--------------------3번 전처리 시작-------------------- | # 한글이 한글자라도 나오는 것만 저장합니다.
# 469곡 제거
df3 = df2[df2.lyrics.str.contains(r'[가-힣]+') == True]
df3.info() | <class 'pandas.core.frame.DataFrame'>
Int64Index: 12667 entries, 0 to 18091
Data columns (total 9 columns):
title 12667 non-null object
artist 12667 non-null object
album 12667 non-null object
release_date 12667 non-null object
song_genre 12667 non-null object
is_title 12667 ... | MIT | SongTidy/FinalTidy/final_tidy_yewon_ver02.ipynb | jyw7664/M5_Idol_lyrics |
--------------------4번 전처리 시작-------------------- | # creator칼럼을 lyricist, composer, arranger로 나누기
df4 = df3.copy()
# 리인덱스해줘야 안밀림
df4 = df4.reset_index(drop=True)
# 전처리 함수
def preprocess(text):
splitArr = list(filter(None, re.split("(작사)|(작곡)|(편곡)", text)))
lyricist = []
composer = []
arranger = []
lyricist.clear()
composer.clear()
arra... | _____no_output_____ | MIT | SongTidy/FinalTidy/final_tidy_yewon_ver02.ipynb | jyw7664/M5_Idol_lyrics |
--------------------5번 전처리 시작-------------------- | df5 = df4.copy()
# 발매일이 널값인 곡이 남지 않도록 널값인 것들은 미래의 날짜로 채워준다.
d = {'':'2019.01.01','-':'2019.01.01'}
df5['release_date'] = df5['release_date'].replace(d)
# 확인해보니 크롤링시에 발매일순서대로 담기지 않았음
# !!!!!!sort by 'artist', 'release_date'로 주고 중복제거하기
df5 = df5.sort_values(by=['artist', 'release_date'])
# 중복노래(띄어쓰기,대소문자,피처링에 의한)를 제거
# 제... | _____no_output_____ | MIT | SongTidy/FinalTidy/final_tidy_yewon_ver02.ipynb | jyw7664/M5_Idol_lyrics |
가사 데이터 전처리 끝 ------------------------------ 작사작곡 데이터 전처리 시작--------------------6번 전처리 시작-------------------- | # 위의 df4를 파일로 불러오기 df6 = pd.read_csv('tidydata/tidy01.csv')
df6 = pd.read_csv('tidy03.csv')
df6
# 확인해보니 크롤링시에 발매일순서대로 담기지 않았음
# !!!!!!sort by 'artist', 'release_date'로 주고 시작하기
df6 = df6.sort_values(by=['artist', 'release_date'])
df6
# creator가 없는 행 제거
df6 = df6[pd.notnull(df6['creator'])]
df6 | _____no_output_____ | MIT | SongTidy/FinalTidy/final_tidy_yewon_ver02.ipynb | jyw7664/M5_Idol_lyrics |
--------------------7번 전처리 시작-------------------- | # 중복노래(띄어쓰기,대소문자,피처링에 의한)를 제거 << 위 과정 반복
df7 = df6.copy()
# 제목의 공백(띄어쓰기)를 모두 제거한다
df7['title'] = df7['title'].str.replace(r' ', '')
# 제목의 영어 부분을 전부 소문자로 바꿔준다
df7['title'] = df7['title'].str.lower()
# 그리고 다시 중복값을 제거해준다.
df7 = df7.drop_duplicates(['artist', 'title'], keep='first')
# 제목 열을 새로 만들어서
df7['t'] = df7['title... | _____no_output_____ | MIT | SongTidy/FinalTidy/final_tidy_yewon_ver02.ipynb | jyw7664/M5_Idol_lyrics |
Q1. WAF to compute 5/0 and use try-except to catch exceptions | try:
res=5/0
print(res)
except ZeroDivisionError:
print("Zero Division Error occurred") | Zero Division Error occurred
| MIT | Python/Python - Assignment 5 Exception Handelling.ipynb | harshit-saraswat/DL_CV_NLP-Assignments |
Q2. Implement a Python program to generate all sentences where subject is in ["Americans", "Indians"] and verb is in ["Play", "watch"] and the object is in ["Baseball","cricket"]. Hint: Subject,Verb and Object should be declared in the program as shown below.subjects=["Americans ","Indians"]verbs=["play","watch"]objec... | import itertools
subjects=["Americans","Indians"]
verbs=["play","watch"]
objects=["Baseball","Cricket"]
finalList=[subjects,verbs,objects]
sentenceList=list(itertools.product(*finalList))
for sentence in sentenceList:
print(" ".join(sentence),end='.\n')
lst=[-1,2,3,45,-23]
filt=[x for x in lst if x>0 ]
filt | _____no_output_____ | MIT | Python/Python - Assignment 5 Exception Handelling.ipynb | harshit-saraswat/DL_CV_NLP-Assignments |
Use Sastrawi stemmer | malaya.stem.sastrawi('saya tengah berjalan')
malaya.stem.sastrawi('saya tengah berjalankan sangat-sangat')
malaya.stem.sastrawi('menarik') | _____no_output_____ | MIT | example/stemmer/load-stemmer.ipynb | fossabot/Malaya |
Load deep learning modelI really not suggest you to use this model. Use Sastrawi instead. We are adding our own rules into Sastrawi stemmer | stemmer = malaya.stem.deep_model()
stemmer.stem('saya tengah berjalankan sangat-sangat')
stemmer.stem('saya sangat sukakan awak')
stemmer.stem('saya sangat suakkan awak') | _____no_output_____ | MIT | example/stemmer/load-stemmer.ipynb | fossabot/Malaya |
Style A | # plot
plt.figure(figsize=(6, 4), dpi=160)
plt.errorbar(x, y_means, y_stds, color='xkcd:red')
plt.show() | _____no_output_____ | MIT | matplotlib/show_error.ipynb | subhadarship/visualization |
Style B | # plot
plt.figure(figsize=(6, 4), dpi=160)
plt.plot(x, y_means, color='xkcd:red')
plt.fill_between(x, y_means - y_stds, y_means + y_stds, facecolor='xkcd:red',
edgecolor='None', alpha=0.3)
plt.show()
| _____no_output_____ | MIT | matplotlib/show_error.ipynb | subhadarship/visualization |
Первому семинару приготовиться __Наша цель на сегодня:__ * Запустить анаконду быстрее, чем за 20 минут. * Попробовать python на вкус* Решить пару простых задач и залить их в Яндекс.Контест 0. Куда это я попал? __Jupyter Notebook__ - это штука для интеракктивного запуска кода в браузере. Много где используют. Можно п... | # напиши код прямо тут вместо трёх точек
2+2 | _____no_output_____ | MIT | sem01_intro/sem01_intro.ipynb | Vinley123/dap_2021_spring |
> Ещё у ячеек бывает разный тип. В этой части семинара ваш семинарист немного поучит вас работать в тетрадках с Markdown. Markdown- [10-минутный урок по синтаксису](https://www.markdowntutorial.com/)- [Короткий гайд по синтаксису](https://guides.github.com/features/mastering-markdown/) 1. Python как калькуляторМожно... | 2+2
4 * 7
3 * (2 + 5)
5 ** 1
5 / 2
5 // 2 #Человек против машины: раунд 1, угадайте, что получится?
5 % 2 #а тут? | _____no_output_____ | MIT | sem01_intro/sem01_intro.ipynb | Vinley123/dap_2021_spring |
Как обстоят дела с другими операциями? Попробуем извлечь квадратный корень: | 1+1
sqrt(4) | _____no_output_____ | MIT | sem01_intro/sem01_intro.ipynb | Vinley123/dap_2021_spring |
Извлечение квадратного корня не входит в комплект математических операций, доступных в Python по умолчанию, поэтому вместо ответа мы получили какую-то непонятную ругань. Эта непонятная ругань называется исключением, когда-нибудь мы научимся их обрабатывать, а сейчас обратим внимание на последнюю строчку: `NameError: na... | import math
math.sqrt(4) | _____no_output_____ | MIT | sem01_intro/sem01_intro.ipynb | Vinley123/dap_2021_spring |
После того, как модуль `math` импортирован, вы можете узнать, какие ещё в нём есть функции. В __IPython Notebook__ для этого достаточно ввести имя модуля, поставить точку и нажать кнопку __«Tab»__. Вот, например, синус: | math.sin(0) | _____no_output_____ | MIT | sem01_intro/sem01_intro.ipynb | Vinley123/dap_2021_spring |
Приведенный синтаксис может оказаться неудобным, если вам часто приходится вызывать какие-то математические функции. Чтобы не писать каждый раз слово «math», можно импортировать из модуля конкретные функции. | from math import sqrt
sqrt(4) | _____no_output_____ | MIT | sem01_intro/sem01_intro.ipynb | Vinley123/dap_2021_spring |
Также можно подгрузить какой-нибудь модуль или пакет, но при этом изменить у него название на более короткое и пользоваться им. | import math as mh
mh.sqrt(4) | _____no_output_____ | MIT | sem01_intro/sem01_intro.ipynb | Vinley123/dap_2021_spring |
2. ПеременныеПонятие «переменной» в программировании похоже на аналогичное понятие в математике. Переменная — это ячейка памяти, обозначаемая каким-то именем. В этой ячейке могут храниться числа, строки и более сложные объекты. Мы пока поработаем немножко с числовыми переменными. | x = 4
y=1
y
x
x = x + 2
x
x | _____no_output_____ | MIT | sem01_intro/sem01_intro.ipynb | Vinley123/dap_2021_spring |
А что будет в $x$, если запусстить ячейку ещё раз? 3. ТипыПопробуем записать числа по-разному | 4 * 42
'4' * 42 #Человек против машины: раунд 2, угадайте, что получится? | _____no_output_____ | MIT | sem01_intro/sem01_intro.ipynb | Vinley123/dap_2021_spring |
Для каждого типа арифметика работает по-своему! | a = 'ёж'
b = 'ик'
a + b + a +a
type(4)
c = 3
type (c)
type('4')
type(4.0)
type(True) | _____no_output_____ | MIT | sem01_intro/sem01_intro.ipynb | Vinley123/dap_2021_spring |
- `str` - текстовый- `int` - целочисленный- `float` - число с плавающей запятой (обычное действительное число)- `bool` - булева переменная Иногда можно переходить от одного типа переменной к другому. | x = '42'
print(type(x))
x = int(x)
print(type(x)) | <class 'str'>
<class 'int'>
| MIT | sem01_intro/sem01_intro.ipynb | Vinley123/dap_2021_spring |
А иногда нет. Включайте логику :) | x = 'Люк, я твой отец'
print(type(x))
x = int(x)
print(type(x)) | <class 'str'>
| MIT | sem01_intro/sem01_intro.ipynb | Vinley123/dap_2021_spring |
Булевы переменные возникают при разных сравнениях, их мы будем активно использовать на следующем семинаре. | 2 + 2 == 4
2 + 2 == 5
x = 5
x < 8 | _____no_output_____ | MIT | sem01_intro/sem01_intro.ipynb | Vinley123/dap_2021_spring |
4. Вещественные числа и погрешностиВещественные числа в программировании не так просты. Вот, например, посчитаем синус числа $\pi$: | from math import pi, sin
sin(pi) #думаете, получится 0? Ха-ха! | _____no_output_____ | MIT | sem01_intro/sem01_intro.ipynb | Vinley123/dap_2021_spring |
Непонятный ответ? Во-первых, это так называемая [компьютерная форма экспоненциальной записи чисел.](https://ru.wikipedia.org/wiki/Экспоненциальная_запись.D0.9A.D0.BE.D0.BC.D0.BF.D1.8C.D1.8E.D1.82.D0.B5.D1.80.D0.BD.D1.8B.D0.B9_.D1.81.D0.BF.D0.BE.D1.81.D0.BE.D0.B1_.D1.8D.D0.BA.D1.81.D0.BF.D0.BE.D0.BD.D0.B5.D0.BD.D1.86.D0... | #Человек против машины: раунд 3, угадайте, что получится?
0.4 - 0.3 == 0.1
0.4 - 0.3 | _____no_output_____ | MIT | sem01_intro/sem01_intro.ipynb | Vinley123/dap_2021_spring |
Когда сравниваете вещественные числа будьте осторожнее. 5. Ввод и выводРабота в Jupyter редко требует писать код, который сам по себе запрашивает данные с клавиатуры, но для других приложений (и в частности для домашних работ) это может потребоваться. К тому же, написание интерактивных приложений само по себе забавно... | name = input("Введите ваше имя: ")
print("Привет,",name)
name | _____no_output_____ | MIT | sem01_intro/sem01_intro.ipynb | Vinley123/dap_2021_spring |
Что здесь произшло? В первой строчке мы использовали функцию `input`. Она вывела на экран строчку, которую ей передали (обязательно в кавычках) и запросила ответ с клавиатуры. Я его ввёл, указав своё имя. После чего `input` вернула строчку с именем и присвоила её переменной `name`.После этого во второй строке была вызв... | x = input("Введите какое-нибудь число: ")
y = x * 2
print(y) | _____no_output_____ | MIT | sem01_intro/sem01_intro.ipynb | Vinley123/dap_2021_spring |
Что-то пошло не так. Что именно? Как это исправить? 6. Учимся дружить с поисковиками__Задача:__ я хочу сгенерировать рандомное число, но я не знаю как это сделать. В этом месте ваш семинарист совершит смертельный номер. Он загуглит у вас на глазах как сгенерировать случайное число и найдёт код для этого. | # Местечко для маленького чуда | _____no_output_____ | MIT | sem01_intro/sem01_intro.ipynb | Vinley123/dap_2021_spring |
Увидели чудо? Давайте договоримся, что вы не будете стесняться гуглить нужные вам команды и искать ответы на свои вопросы в интернете. Если уж совсем не выходит, задавайте их в наш чат технической поддержки в Телеграм. 7. КонтестЯндекс.Контест - это система для автоматического тестирования кода. Вы будете сталкиватьс... | ### ╰( ͡° ͜ʖ ͡° )つ▬▬ι═══════ bzzzzzzzzzz
# will the code be with you | _____no_output_____ | MIT | sem01_intro/sem01_intro.ipynb | Vinley123/dap_2021_spring |
8. Дзен Python и PEP-8Как мы увидели выше, команда `import` позволяет подгрузить различные пакеты и модули. Один из модулей, который обязательно нужно подгрузить на первой же паре - это модуль `this` | import this | The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality... | MIT | sem01_intro/sem01_intro.ipynb | Vinley123/dap_2021_spring |
Imports: | from PIL import Image, ImageOps
import cv2
from google_images_download import google_images_download
solicitor = google_images_download.googleimagesdownload()
arguments = {"keywords":"consorcio feliz", "aspect_ratio":"square", "color_type":"transparent", "limit":7,"output_directory":"images", "no_directory":True}
pat... |
Item no.: 1 --> Item name = consorcio feliz
Evaluating...
Starting Download...
Completed Image ====> 1.consorcio_site.banner.b57de633fbb34701.62616e6e6572735f4b415f4d41494f2e706e67.png
Completed Image ====> 2.consorcio_site.banner.948ec30cc8c55333.62616e6e6572735f474f4c5f4d41494f2e706e67.png
URLError on an image...try... | Unlicense | Data Science/Image Processing/Resizer IT.ipynb | Alissonfelipe1234/JupyterNotebooks |
Instantiating the variables | imagePath = "topo.png"
dinamic_image = Image.open(imagePath)
new_width = 386
new_height = 390 | _____no_output_____ | Unlicense | Data Science/Image Processing/Resizer IT.ipynb | Alissonfelipe1234/JupyterNotebooks |
Processing: | image1 = dinamic_image.resize((new_width, new_height), Image.NEAREST) # use nearest neighbour
image2 = dinamic_image.resize((new_width, new_height), Image.BILINEAR) # linear interpolation in a 2x2 environment
image3 = dinamic_image.resize((new_width, new_height), Image.BICUBIC) # cubic spline interpolatio... | _____no_output_____ | Unlicense | Data Science/Image Processing/Resizer IT.ipynb | Alissonfelipe1234/JupyterNotebooks |
Save | ext = ".png"
image1.save("top" + ext) #Bad result for my tests But smaller size
image2.save("top2" + ext) #Averange result and size
image3.save("top3" + ext) #Best result
image4.save("top4" + ext) #Best result too
#dinamic_image.save("original" + ext) #convert original to png
#LESS CODE
imagePath = "original.png"
dinam... | RGBA
(557, 672, 557, 672)
| Unlicense | Data Science/Image Processing/Resizer IT.ipynb | Alissonfelipe1234/JupyterNotebooks |
transform white in transparent | def white_cleaner():
from PIL import Image
img = Image.open('img.png')
img = img.convert("RGBA")
pixdata = img.load()
width, height = image.size
for y in xrange(height):
for x in xrange(width):
if pixdata[x, y] == (255, 255, 255, 255):
pixdata[x, y] = (255,... | _____no_output_____ | Unlicense | Data Science/Image Processing/Resizer IT.ipynb | Alissonfelipe1234/JupyterNotebooks |
Custom Line Color To custom color, just use the `color` argument! Note that you can add **transparency** to the color with the `alpha` argument (0=transparent, 1=opaque). | # Libraries and data
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
df=pd.DataFrame({'x_values': range(1,11), 'y_values': np.random.randn(10) })
# Draw plot
plt.plot( 'x_values', 'y_values', data=df, color='skyblue')
plt.show()
# Draw line chart by modifiying transparency of the line
plt.plot(... | _____no_output_____ | 0BSD | src/notebooks/121-line-chart-customization.ipynb | s-lasch/The-Python-Graph-Gallery |
Custom Line Style You can choose between different **line styles** with the `linestyle` argument. | # Libraries and data
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
df=pd.DataFrame({'x_values': range(1,11), 'y_values': np.random.randn(10) })
# Draw line chart with dashed line
plt.plot( 'x_values', 'y_values', data=df, linestyle='dashed')
# Show graph
plt.show() | _____no_output_____ | 0BSD | src/notebooks/121-line-chart-customization.ipynb | s-lasch/The-Python-Graph-Gallery |
The following examples show different types of line styles. | plt.plot( [1,1.1,1,1.1,1], linestyle='-' , linewidth=4)
plt.text(1.5, 1.3, "linestyle = '-' ", horizontalalignment='left', size='medium', color='C0', weight='semibold')
plt.plot( [2,2.1,2,2.1,2], linestyle='--' , linewidth=4 )
plt.text(1.5, 2.3, "linestyle = '--' ", horizontalalignment='left', size='medium', color='C1'... | _____no_output_____ | 0BSD | src/notebooks/121-line-chart-customization.ipynb | s-lasch/The-Python-Graph-Gallery |
Custom Line Width Finally you can custom the **line width** as well using `linewidth` argument. | # Libraries and data
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
df=pd.DataFrame({'x_values': range(1,11), 'y_values': np.random.randn(10) })
# Modify line width of the graph
plt.plot( 'x_values', 'y_values', data=df, linewidth=22)
# Show graph
plt.show() | _____no_output_____ | 0BSD | src/notebooks/121-line-chart-customization.ipynb | s-lasch/The-Python-Graph-Gallery |
Be sure you've installed the praw and tqdm libraries. If you haven't you can run the line below. Node.js in required to install the jupyter widgets in a few cells. These two cells can take a while to run and won't show progress; you can also run the commands in the command prompt (without the !) to see the progress ... | !conda install tqdm praw nodejs -y | Collecting package metadata (current_repodata.json): ...working... done | MIT | Reddit_Sentiment_Assignment.ipynb | ebayandelger/MSDS600 |
Install the jupyter widget to enable tqdm to work with jupyter lab: | !jupyter labextension install @jupyter-widgets/jupyterlab-manager | An error occured.
ValueError: Please install Node.js and npm before continuing installation. You may be able to install Node.js from your package manager, from conda, or directly from the Node.js website (https://nodejs.org).
See the log file for details: C:\Users\ENKHBA~1\AppData\Local\Temp\jupyterlab-debug-b79fsi1d.... | MIT | Reddit_Sentiment_Assignment.ipynb | ebayandelger/MSDS600 |
Scrape Reddit Comments for a Sentiment Analysis - Assignment Go through the notebook and complete the code where prompted This assignment was adapted from a number of sources including: http://www.storybench.org/how-to-scrape-reddit-with-python/ and https://towardsdatascience.com/scraping-reddit-data-1c0af3040768 | # Import all the necessary libraries
import praw # Import the Praw library: https://praw.readthedocs.io/en/latest/code_overview/reddit_instance.html
import pandas as pd # Import Pandas library: https://pandas.pydata.org/
import datetime as dt # Import datetime library
import matplotlib.pyplot as plt # Import Matplot li... | _____no_output_____ | MIT | Reddit_Sentiment_Assignment.ipynb | ebayandelger/MSDS600 |
Prompt In the cell below, enter your client ID, client secret, user agent, username, and password in the appropitate place withing the quotation marks | reddit = praw.Reddit(client_id = 'A0HZsCKBk-P50g',
client_secret = '9vAJO7D2uhGh-I7wpVNDI2JEwm0',
username = 'baymsds',
password = '2003@@PUujin',
user_agent = 'msds') | _____no_output_____ | MIT | Reddit_Sentiment_Assignment.ipynb | ebayandelger/MSDS600 |
Prompt In the cell below, enter a subreddit you which to compare the sentiment of the post comments, decide how far back to pull posts, and how many posts to pull comments from. We will be comparing two subreddits, so think of a subject where a comparison might be interesting (e.g. if there are two sides to an issue w... | number_of_posts = 200
time_period = 'all' # use posts from all time
# .top() can use the time_period argument
# subreddit = reddit.subreddit('').top(time_filter=time_period, limit=number_of_posts)
subreddit = reddit.subreddit('GlobalWarming').hot(limit=number_of_posts)
# Create an empty list to store the data
subre... | Part
2
would
probably
go
something
like
this
Ok
so
he's
ill
but
the
important
thing
is
that
it's
not
my
fault
| MIT | Reddit_Sentiment_Assignment.ipynb | ebayandelger/MSDS600 |
Now we will use the sentiment file called AFINN-en-165.txt. This file contains a sentiment score for 3382 words. More information can be found here: https://github.com/fnielsen/afinn With the sentiment file we will assign scores to words within the top comments that are found in the AFINN file | # We load the AFINN sentiment table into a Python dictionary
sentimentfile = open("AFINN-en-165.txt", "r") # open sentiment file
scores = {} # an empty dictionary
for line in sentimentfile: # loop over each word / sentiment score
word, score = line.split("\t") # file is tab-delimited
scores[word] = int(sco... | _____no_output_____ | MIT | Reddit_Sentiment_Assignment.ipynb | ebayandelger/MSDS600 |
Prompt We will plot the data so it is easier to visualize. In each of the three cells below, plot the Count, Normalized Count, and Normalized Score vs Sentiment Value. In each plot add the appropriate x-label, y-label, plot title, and color | # Count vs Sentiment Value Plot
plt.bar(comment_sentiment_df['Sentiment_Value'], comment_sentiment_df['Counts'], color='green') # add the y-values and color
plt.xlabel('Sentiment Value') # add x-label
plt.ylabel('Sentiment Count') # add y-label
plt.title('Reddit Global Warming Sentiment Analysis') # add title
plt.s... | _____no_output_____ | MIT | Reddit_Sentiment_Assignment.ipynb | ebayandelger/MSDS600 |
Prompt In the cell below, enter a subreddit you which to compare the sentiment of the post comments, decide how far back to pull posts, and how many posts to pull comments from.Pick a subreddit that can be compared with your first subreddit in terms of sentiment. You may want to go back up to the first subreddit secti... | subreddit_2 = reddit.subreddit('Futurology').hot(limit=number_of_posts)
# Create an empty list to store the data
subreddit_comments_2 = []
# go through each post in our subreddit and put the comment body and id in our dictionary
for post in tqdm(subreddit_2, total=number_of_posts):
submission = reddit.submission... | _____no_output_____ | MIT | Reddit_Sentiment_Assignment.ipynb | ebayandelger/MSDS600 |
Prompt We will plot the data so it is easier to visualize. In each of the three cells below, plot the Count, Normalized Count, and Normalized Score data vs Sentiment Value. In each plot add the appropriate x-label, y-label, plot title , and color | # Count vs Sentiment Value Plot
plt.bar(comment_sentiment_df_2['Sentiment_Value'], comment_sentiment_df_2['Counts'], color='blue') # add the y-values and color
plt.xlabel('Sentiment Value') # add x-label
plt.ylabel('Sentiment Counts') # add y-label
plt.title('Futurology Reddit Sentiment Value Analysis') # add title... | _____no_output_____ | MIT | Reddit_Sentiment_Assignment.ipynb | ebayandelger/MSDS600 |
Prompt Now we will overlay the baseline comment sentiment and the subreddit comment sentiment to help compare. In each of the three cells below, overlay the plots the Count, Normalized Count, and Normalized Score data vs Sentiment Value. In each plot add the appropriate x-label, y-label, plot title, and plot color | # Count vs Sentiment Value Plot
plt.bar(comment_sentiment_df['Sentiment_Value'], comment_sentiment_df['Counts'], color='green', label='Global Warming') # add first subreddit data and color
# add second subreddit with a slight offset of x-axis; alpha is opacity/transparency
plt.bar(comment_sentiment_df_2['Sentiment_Va... | _____no_output_____ | MIT | Reddit_Sentiment_Assignment.ipynb | ebayandelger/MSDS600 |
Stretch goal (bonus-ish) Although this is not formally a bonus for points, it is a learning opportinity. You are not required to complete the following part of this notebook for the assignment.Our sentiment analysis technique above works, but has some shortcomings. The biggest shortcoming is that each word is treate... | !conda install -c conda-forge textblob
!pip install textblob vaderSentiment
sentence = 'This is not a bad thing.'
[(word, scores[word]) for word in sentence.split() if word in scores]
from textblob import TextBlob
tb = TextBlob(sentence)
print(tb.polarity)
print(tb.sentiment_assessments)
from vaderSentiment.vaderSentim... | _____no_output_____ | MIT | Reddit_Sentiment_Assignment.ipynb | ebayandelger/MSDS600 |
Emily Harvey Research question/interestsIt would be cool to see how much of the money made overall in Canada had to do with tourism from BC and the breakdown of which categories within tourism BC makes the most money in. As well as overall growth of tourism in Canada and BC from 2014-2017. | import pandas as pd
pd.read_csv('../data/raw/tourism.csv') | _____no_output_____ | MIT | notebooks/analysis1.ipynb | data301-2021-winter1/group05-project |
Milestone 3: Task 1: EDA | #Importing Libraries
import numpy as np
import seaborn as sns
import matplotlib
import matplotlib.pyplot as plt
import missingno
import pandas as pd
%matplotlib inline
df = pd.read_csv('../data/raw/tourism.csv')
# Simple Preview and Stats of Data
# Shows column names, non-null count, and Dtype
# Shows us that columns... | _____no_output_____ | MIT | notebooks/analysis1.ipynb | data301-2021-winter1/group05-project |
Task 2: Analysis Pipeline Load in data | df = pd.read_csv('../data/raw/tourism.csv')
df | _____no_output_____ | MIT | notebooks/analysis1.ipynb | data301-2021-winter1/group05-project |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.