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 |
|---|---|---|---|---|---|
For a quick check of all the regressors, you can use plot_partregress_grid. These plots will not label the points, but you can use them to identify problems and then use plot_partregress to get more information. | fig = sm.graphics.plot_partregress_grid(prestige_model)
fig.tight_layout(pad=1.0) | _____no_output_____ | BSD-3-Clause | examples/notebooks/regression_plots.ipynb | chengevo/statsmodels |
Component-Component plus Residual (CCPR) Plots The CCPR plot provides a way to judge the effect of one regressor on the response variable by taking into account the effects of the other independent variables. The partial residuals plot is defined as $\text{Residuals} + B_iX_i \text{ }\text{ }$ versus $X_i$. The co... | fig = sm.graphics.plot_ccpr(prestige_model, "education")
fig.tight_layout(pad=1.0) | _____no_output_____ | BSD-3-Clause | examples/notebooks/regression_plots.ipynb | chengevo/statsmodels |
As you can see the relationship between the variation in prestige explained by education conditional on income seems to be linear, though you can see there are some observations that are exerting considerable influence on the relationship. We can quickly look at more than one variable by using plot_ccpr_grid. | fig = sm.graphics.plot_ccpr_grid(prestige_model)
fig.tight_layout(pad=1.0) | _____no_output_____ | BSD-3-Clause | examples/notebooks/regression_plots.ipynb | chengevo/statsmodels |
Single Variable Regression Diagnostics The plot_regress_exog function is a convenience function that gives a 2x2 plot containing the dependent variable and fitted values with confidence intervals vs. the independent variable chosen, the residuals of the model vs. the chosen independent variable, a partial regression p... | fig = sm.graphics.plot_regress_exog(prestige_model, "education")
fig.tight_layout(pad=1.0) | _____no_output_____ | BSD-3-Clause | examples/notebooks/regression_plots.ipynb | chengevo/statsmodels |
Fit Plot The plot_fit function plots the fitted values versus a chosen independent variable. It includes prediction confidence intervals and optionally plots the true dependent variable. | fig = sm.graphics.plot_fit(prestige_model, "education")
fig.tight_layout(pad=1.0) | _____no_output_____ | BSD-3-Clause | examples/notebooks/regression_plots.ipynb | chengevo/statsmodels |
Statewide Crime 2009 Dataset Compare the following to http://www.ats.ucla.edu/stat/stata/webbooks/reg/chapter4/statareg_self_assessment_answers4.htmThough the data here is not the same as in that example. You could run that example by uncommenting the necessary cells below. | #dta = pd.read_csv("http://www.stat.ufl.edu/~aa/social/csv_files/statewide-crime-2.csv")
#dta = dta.set_index("State", inplace=True).dropna()
#dta.rename(columns={"VR" : "crime",
# "MR" : "murder",
# "M" : "pctmetro",
# "W" : "pctwhite",
# "H... | _____no_output_____ | BSD-3-Clause | examples/notebooks/regression_plots.ipynb | chengevo/statsmodels |
Partial Regression Plots (Crime Data) | fig = sm.graphics.plot_partregress_grid(crime_model)
fig.tight_layout(pad=1.0)
fig = sm.graphics.plot_partregress("murder", "hs_grad", ["urban", "poverty", "single"], data=dta)
fig.tight_layout(pad=1.0) | _____no_output_____ | BSD-3-Clause | examples/notebooks/regression_plots.ipynb | chengevo/statsmodels |
Leverage-Resid2 Plot Closely related to the influence_plot is the leverage-resid2 plot. | fig = sm.graphics.plot_leverage_resid2(crime_model)
fig.tight_layout(pad=1.0) | _____no_output_____ | BSD-3-Clause | examples/notebooks/regression_plots.ipynb | chengevo/statsmodels |
Influence Plot | fig = sm.graphics.influence_plot(crime_model)
fig.tight_layout(pad=1.0) | _____no_output_____ | BSD-3-Clause | examples/notebooks/regression_plots.ipynb | chengevo/statsmodels |
Using robust regression to correct for outliers. Part of the problem here in recreating the Stata results is that M-estimators are not robust to leverage points. MM-estimators should do better with this examples. | from statsmodels.formula.api import rlm
rob_crime_model = rlm("murder ~ urban + poverty + hs_grad + single", data=dta,
M=sm.robust.norms.TukeyBiweight(3)).fit(conv="weights")
print(rob_crime_model.summary())
#rob_crime_model = rlm("murder ~ pctmetro + poverty + pcths + single", data=dta, M=sm.rob... | _____no_output_____ | BSD-3-Clause | examples/notebooks/regression_plots.ipynb | chengevo/statsmodels |
There is not yet an influence diagnostics method as part of RLM, but we can recreate them. (This depends on the status of [issue 888](https://github.com/statsmodels/statsmodels/issues/808)) | weights = rob_crime_model.weights
idx = weights > 0
X = rob_crime_model.model.exog[idx.values]
ww = weights[idx] / weights[idx].mean()
hat_matrix_diag = ww*(X*np.linalg.pinv(X).T).sum(1)
resid = rob_crime_model.resid
resid2 = resid**2
resid2 /= resid2.sum()
nobs = int(idx.sum())
hm = hat_matrix_diag.mean()
rm = resid2.... | _____no_output_____ | BSD-3-Clause | examples/notebooks/regression_plots.ipynb | chengevo/statsmodels |
Developing an AI applicationGoing forward, AI algorithms will be incorporated into more and more everyday applications. For example, you might want to include an image classifier in a smart phone app. To do this, you'd use a deep learning model trained on hundreds of thousands of images as part of the overall applicat... | # Imports here
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
import matplotlib.pyplot as plt
import torch
from torch import nn
from torch import optim
import torch.nn.functional as F
from torchvision import datasets,transforms,models
from workspace_utils import active_session
from PIL import Image
... | _____no_output_____ | FTL | Image Classifier Project.ipynb | SrikanthGarnipudi/ImageClassifier |
Load the dataHere you'll use `torchvision` to load the data ([documentation](http://pytorch.org/docs/0.3.0/torchvision/index.html)). The data should be included alongside this notebook, otherwise you can [download it here](https://s3.amazonaws.com/content.udacity-data.com/nd089/flower_data.tar.gz). The dataset is spli... | data_dir = 'flowers'
train_dir = data_dir + '/train'
valid_dir = data_dir + '/valid'
test_dir = data_dir + '/test'
# TODO: Define your transforms for the training, validation, and testing sets
train_data_transforms = transforms.Compose([transforms.RandomResizedCrop(224),
trans... | _____no_output_____ | FTL | Image Classifier Project.ipynb | SrikanthGarnipudi/ImageClassifier |
Label mappingYou'll also need to load in a mapping from category label to category name. You can find this in the file `cat_to_name.json`. It's a JSON object which you can read in with the [`json` module](https://docs.python.org/2/library/json.html). This will give you a dictionary mapping the integer encoded categori... | with open('cat_to_name.json', 'r') as f:
cat_to_name = json.load(f) | _____no_output_____ | FTL | Image Classifier Project.ipynb | SrikanthGarnipudi/ImageClassifier |
Building and training the classifierNow that the data is ready, it's time to build and train the classifier. As usual, you should use one of the pretrained models from `torchvision.models` to get the image features. Build and train a new feed-forward classifier using those features.We're going to leave this part up to... | # TODO: Build and train your network
# Use GPU device
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
#using Vgg pre training
model= models.vgg11(pretrained=True)
#Set disable Backdrop property for model parameters
for param in model.parameters():
param.requires_grad= False
model.classifie... | Epoch 1/5.. Train loss: 0.453..Validation loss:8.617..Validation Accuracy :0.057..
Epoch 1/5.. Train loss: 0.448..Validation loss:5.540..Validation Accuracy :0.189..
Epoch 1/5.. Train loss: 0.256..Validation loss:3.558..Validation Accuracy :0.315..
Epoch 1/5.. Train loss: 0.187..Validation loss:2.916..Validation Accura... | FTL | Image Classifier Project.ipynb | SrikanthGarnipudi/ImageClassifier |
Testing your networkIt's good practice to test your trained network on test data, images the network has never seen either in training or validation. This will give you a good estimate for the model's performance on completely new images. Run the test images through the network and measure the accuracy, the same way y... | # TODO: Do validation on the test set
def testModel(model_to_test):
test_loss=0
accuracy =0
test_n="test"
model_to_test.to(device)
with torch.no_grad():
model_to_test.eval()
for inputs,lables in dataloader[test_n]:
inputs,lables = inputs.to(device),lables.to(device)
... | testloss:0.438..Test Accuracy:0.883..
| FTL | Image Classifier Project.ipynb | SrikanthGarnipudi/ImageClassifier |
Save the checkpointNow that your network is trained, save the model so you can load it later for making predictions. You probably want to save other things such as the mapping of classes to indices which you get from one of the image datasets: `image_datasets['train'].class_to_idx`. You can attach this to the model as... | # TODO: Save the checkpoint
#map class to idx
checkpoint_path = "checkpoint.pth"
model.class_to_idx = image_datasets["train"].class_to_idx
checkpoint={"state_dict":model.state_dict(),
"class_to_idx":model.class_to_idx,
"architecture":"vgg11",
"hidden_units":4096,
"learni... | _____no_output_____ | FTL | Image Classifier Project.ipynb | SrikanthGarnipudi/ImageClassifier |
Loading the checkpointAt this point it's good to write a function that can load a checkpoint and rebuild the model. That way you can come back to this project and keep working on it without having to retrain the network. | # TODO: Write a function that loads a checkpoint and rebuilds the model
def load_checkpoint(filepath):
checkpoint = torch.load(filepath)
hidden_units = checkpoint["hidden_units"]
model = models.vgg11(pretrained=True)
for param in model.parameters():
param.requires_grad = False
model.classifi... | testloss:0.438..Test Accuracy:0.883..
| FTL | Image Classifier Project.ipynb | SrikanthGarnipudi/ImageClassifier |
Inference for classificationNow you'll write a function to use a trained network for inference. That is, you'll pass an image into the network and predict the class of the flower in the image. Write a function called `predict` that takes an image and a model, then returns the top $K$ most likely classes along with the... | def process_image(image_Path):
''' Scales, crops, and normalizes a PIL image for a PyTorch model,
returns an Numpy array
'''
# TODO: Process a PIL image for use in a PyTorch model
img = Image.open(image_path)
# Resize
if img.size[0] > img.size[1]:
img.thumbnail((10000, 256))... | _____no_output_____ | FTL | Image Classifier Project.ipynb | SrikanthGarnipudi/ImageClassifier |
To check your work, the function below converts a PyTorch tensor and displays it in the notebook. If your `process_image` function works, running the output through this function should return the original image (except for the cropped out portions). | def imshow(image, ax=None, title=None):
"""Imshow for Tensor."""
if ax is None:
fig, ax = plt.subplots()
if title:
#plt.title(title)
ax.set_title(title)
# PyTorch tensors assume the color channel is the first dimension
# but matplotlib assumes is the third dimension
... | _____no_output_____ | FTL | Image Classifier Project.ipynb | SrikanthGarnipudi/ImageClassifier |
Class PredictionOnce you can get images in the correct format, it's time to write a function for making predictions with your model. A common practice is to predict the top 5 or so (usually called top-$K$) most probable classes. You'll want to calculate the class probabilities then find the $K$ largest values.To get t... | def predict(image_path, model, topk=5):
''' Predict the class (or classes) of an image using a trained deep learning model.
'''
# TODO: Implement the code to predict the class from an image file
image = torch.from_numpy(process_image(image_path)).type(torch.FloatTensor)
#Change the dimensions o... | _____no_output_____ | FTL | Image Classifier Project.ipynb | SrikanthGarnipudi/ImageClassifier |
Sanity CheckingNow that you can use a trained model for predictions, check to make sure it makes sense. Even if the testing accuracy is high, it's always good to check that there aren't obvious bugs. Use `matplotlib` to plot the probabilities for the top 5 classes as a bar graph, along with the input image. It should ... | # TODO: Display an image along with the top 5 classes
image_path = test_dir+"/1/image_06743.jpg"
flower_num = image_path.split('/')[-2]
title = cat_to_name[flower_num]
model = load_checkpoint(checkpoint_path)
top_p,top_class = predict(image_path,model)
top_flowers = [cat_to_name[cl] for cl in top_class]
plt.figure(figs... | _____no_output_____ | FTL | Image Classifier Project.ipynb | SrikanthGarnipudi/ImageClassifier |
初始化 | #@markdown - **挂载**
from google.colab import drive
drive.mount('GoogleDrive')
# #@markdown - **卸载**
# !fusermount -u GoogleDrive | _____no_output_____ | MIT | notebooks(colab)/Classic_models/KNN.ipynb | jswanglp/MyML |
代码区 | #@title K-近邻算法 { display-mode: "both" }
# 该程序实现 k-NN 对三维随机数据的分类
#@markdown [参考程序](https://github.com/wzyonggege/statistical-learning-method/blob/master/KNearestNeighbors/KNN.ipynb)
# coding: utf-8
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
#@markdown - **绑定数据**
class Bun... | _____no_output_____ | MIT | notebooks(colab)/Classic_models/KNN.ipynb | jswanglp/MyML |
Implementing an LSTM RNN Model------------------------Here we implement an LSTM model on all a data set of Shakespeare works.We start by loading the necessary libraries and resetting the default computational graph. | import os
import re
import string
import requests
import numpy as np
import collections
import random
import pickle
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.python.framework import ops
ops.reset_default_graph() | _____no_output_____ | MIT | 09_Recurrent_Neural_Networks/03_Implementing_LSTM/03_implementing_lstm.ipynb | vlalov/tensorflow_cookbook |
We start a computational graph session. | sess = tf.Session() | _____no_output_____ | MIT | 09_Recurrent_Neural_Networks/03_Implementing_LSTM/03_implementing_lstm.ipynb | vlalov/tensorflow_cookbook |
Next, it is important to set the algorithm and data processing parameters.---------Parameter : Descriptions - min_word_freq: Only attempt to model words that appear at least 5 times. - rnn_size: size of our RNN (equal to the embedding size) - epochs: Number of epochs to cycle through the data - batch_size: How many e... | # Set RNN Parameters
min_word_freq = 5 # Trim the less frequent words off
rnn_size = 128 # RNN Model size
embedding_size = 100 # Word embedding size
epochs = 10 # Number of epochs to cycle through data
batch_size = 100 # Train on this many examples at once
learning_rate = 0.001 # Learning rate
training_seq_len = 50 # h... | _____no_output_____ | MIT | 09_Recurrent_Neural_Networks/03_Implementing_LSTM/03_implementing_lstm.ipynb | vlalov/tensorflow_cookbook |
Download the data if we don't have it saved already. The data comes from the [Gutenberg Project](http://www.gutenberg.org]) | print('Loading Shakespeare Data')
# Check if file is downloaded.
if not os.path.isfile(os.path.join(data_dir, data_file)):
print('Not found, downloading Shakespeare texts from www.gutenberg.org')
shakespeare_url = 'http://www.gutenberg.org/cache/epub/100/pg100.txt'
# Get Shakespeare text
response = requ... | Loading Shakespeare Data
Cleaning Text
Done loading/cleaning.
| MIT | 09_Recurrent_Neural_Networks/03_Implementing_LSTM/03_implementing_lstm.ipynb | vlalov/tensorflow_cookbook |
Define a function to build a word processing dictionary (word -> ix) | # Build word vocabulary function
def build_vocab(text, min_word_freq):
word_counts = collections.Counter(text.split(' '))
# limit word counts to those more frequent than cutoff
word_counts = {key:val for key, val in word_counts.items() if val>min_word_freq}
# Create vocab --> index mapping
words = w... | _____no_output_____ | MIT | 09_Recurrent_Neural_Networks/03_Implementing_LSTM/03_implementing_lstm.ipynb | vlalov/tensorflow_cookbook |
Now we can build the index-vocabulary from the Shakespeare data. | # Build Shakespeare vocabulary
print('Building Shakespeare Vocab')
ix2vocab, vocab2ix = build_vocab(s_text, min_word_freq)
vocab_size = len(ix2vocab) + 1
print('Vocabulary Length = {}'.format(vocab_size))
# Sanity Check
assert(len(ix2vocab) == len(vocab2ix))
# Convert text to word vectors
s_text_words = s_text.split('... | Building Shakespeare Vocab
Vocabulary Length = 8009
| MIT | 09_Recurrent_Neural_Networks/03_Implementing_LSTM/03_implementing_lstm.ipynb | vlalov/tensorflow_cookbook |
We define the LSTM model. The methods of interest are the `__init__()` method, which defines all the model variables and operations, and the `sample()` method which takes in a sample word and loops through to generate text. | # Define LSTM RNN Model
class LSTM_Model():
def __init__(self, embedding_size, rnn_size, batch_size, learning_rate,
training_seq_len, vocab_size, infer_sample=False):
self.embedding_size = embedding_size
self.rnn_size = rnn_size
self.vocab_size = vocab_size
self.infe... | _____no_output_____ | MIT | 09_Recurrent_Neural_Networks/03_Implementing_LSTM/03_implementing_lstm.ipynb | vlalov/tensorflow_cookbook |
In order to use the same model (with the same trained variables), we need to share the variable scope between the trained model and the test model. | # Define LSTM Model
lstm_model = LSTM_Model(embedding_size, rnn_size, batch_size, learning_rate,
training_seq_len, vocab_size)
# Tell TensorFlow we are reusing the scope for the testing
with tf.variable_scope(tf.get_variable_scope(), reuse=True):
test_lstm_model = LSTM_Model(embedding_size,... | _____no_output_____ | MIT | 09_Recurrent_Neural_Networks/03_Implementing_LSTM/03_implementing_lstm.ipynb | vlalov/tensorflow_cookbook |
We need to save the model, so we create a model saving operation. | # Create model saver
saver = tf.train.Saver(tf.global_variables()) | _____no_output_____ | MIT | 09_Recurrent_Neural_Networks/03_Implementing_LSTM/03_implementing_lstm.ipynb | vlalov/tensorflow_cookbook |
Let's calculate how many batches are needed for each epoch and split up the data accordingly. | # Create batches for each epoch
num_batches = int(len(s_text_ix)/(batch_size * training_seq_len)) + 1
# Split up text indices into subarrays, of equal size
batches = np.array_split(s_text_ix, num_batches)
# Reshape each split into [batch_size, training_seq_len]
batches = [np.resize(x, [batch_size, training_seq_len]) fo... | _____no_output_____ | MIT | 09_Recurrent_Neural_Networks/03_Implementing_LSTM/03_implementing_lstm.ipynb | vlalov/tensorflow_cookbook |
Initialize all the variables | # Initialize all variables
init = tf.global_variables_initializer()
sess.run(init) | _____no_output_____ | MIT | 09_Recurrent_Neural_Networks/03_Implementing_LSTM/03_implementing_lstm.ipynb | vlalov/tensorflow_cookbook |
Training the model! | # Train model
train_loss = []
iteration_count = 1
for epoch in range(epochs):
# Shuffle word indices
random.shuffle(batches)
# Create targets from shuffled batches
targets = [np.roll(x, -1, axis=1) for x in batches]
# Run a through one epoch
print('Starting Epoch #{} of {}.'.format(epoch+1, epoc... | Starting Epoch #1 of 10.
Iteration: 10, Epoch: 1, Batch: 10 out of 182, Loss: 9.90
| MIT | 09_Recurrent_Neural_Networks/03_Implementing_LSTM/03_implementing_lstm.ipynb | vlalov/tensorflow_cookbook |
Here is a plot of the training loss across the iterations. | # Plot loss over time
plt.plot(train_loss, 'k-')
plt.title('Sequence to Sequence Loss')
plt.xlabel('Iterations')
plt.ylabel('Loss')
plt.show() | _____no_output_____ | MIT | 09_Recurrent_Neural_Networks/03_Implementing_LSTM/03_implementing_lstm.ipynb | vlalov/tensorflow_cookbook |
咱们的基金是否存在着明显的周内效应呢?就是特定周几盈利高一些,让我们来验证一下吧。 | import pandas as pd
from datetime import datetime
import trdb2py
isStaticImg = False
width = 960
height = 768
pd.options.display.max_columns = None
pd.options.display.max_rows = None
trdb2cfg = trdb2py.loadConfig('./trdb2.yaml') | _____no_output_____ | Apache-2.0 | home/trdb2/weekday001.ipynb | zhs007/jupyternotebook.demo |
我们先指定一个特定的基金,特定的时间段来分析吧。 | # 具体基金
# asset = 'jrj.510310'
asset = 'jqdata.000300_XSHG|1d'
# 起始时间,0表示从最开始算起
# tsStart = 0
tsStart = int(trdb2py.str2timestamp('2013-05-01', '%Y-%m-%d'))
# 结束时间,-1表示到现在为止
# tsEnd = -1
tsEnd = int(trdb2py.str2timestamp('2020-09-30', '%Y-%m-%d'))
# 初始资金池
paramsinit = trdb2py.trading2_pb2.InitParams(
money=10000,... | _____no_output_____ | Apache-2.0 | home/trdb2/weekday001.ipynb | zhs007/jupyternotebook.demo |
首先看看这个基金的基准表现,就是在开始时间就直接买入,然后一直持有,看具体的收益率。 | # baseline
s0 = trdb2py.trading2_pb2.Strategy(
name="normal",
asset=trdb2py.str2asset(asset),
)
buy0 = trdb2py.trading2_pb2.CtrlCondition(
name='buyandhold',
)
paramsbuy = trdb2py.trading2_pb2.BuyParams(
perHandMoney=1,
)
paramsinit = trdb2py.trading2_pb2.InitParams(
money=10... | _____no_output_____ | Apache-2.0 | home/trdb2/weekday001.ipynb | zhs007/jupyternotebook.demo |
那么策略基准线大概就是这样了,7年多的时间2.2倍。 接下来,先看看最简单的情况,就是特定周几买入,第二天就卖出,只持有1天。 | lstparams = []
for i in range(0, 5):
buy0 = trdb2py.trading2_pb2.CtrlCondition(
name='weekday',
vals=[lststart[i]],
)
sell0 = trdb2py.trading2_pb2.CtrlCondition(
name='weekday',
vals=[trdb2py.nextWeekDay(lststart[i], 1)],
)
s0 = trdb2py.trading2_pb2.Strategy(
... | _____no_output_____ | Apache-2.0 | home/trdb2/weekday001.ipynb | zhs007/jupyternotebook.demo |
如果看曲线图不是很清楚的话,我们列表看看 | dfpnl1b = trdb2py.buildPNLReport(lstpnl1 + [pnlBaseline])
dfpnl1b[['title', 'maxDrawdown', 'maxDrawdownStart', 'maxDrawdownEnd', 'totalReturns', 'sharpe', 'annualizedReturns', 'annualizedVolatility', 'variance']].sort_values(by='totalReturns', ascending=False) | _____no_output_____ | Apache-2.0 | home/trdb2/weekday001.ipynb | zhs007/jupyternotebook.demo |
我看可以看到,虽然盈利都不如基线,但由于波动率降低了。特别是周一和周五,最大回撤都降低了50%以上,所以夏普都要高于基线。 上面的策略比较简单,因为有些节假日交易日,所以可能会出现买入了,但无法及时卖出的情况,下面我们换一个确定能卖出才买入的策略看看 | def calcweekday2val2(wday, offday):
if offday == 1:
if wday == 5:
return 3
if offday == 2:
if wday >= 4:
return 4
if offday == 3:
if wday >= 3:
return 5
if offday == 4:
if wday >= 2:
return 6
return offday
lstp... | _____no_output_____ | Apache-2.0 | home/trdb2/weekday001.ipynb | zhs007/jupyternotebook.demo |
可以看到,虽然有一些差别,但其实影响有好有坏,下面我们还是按v2版的策略来吧 接下来看看胜率 | # trdb2py.showBarWinRate4Month(lstpnl1t, valtype='abs', valoff=-0.5, toImg=isStaticImg, width=width, height=height)
# trdb2py.showBarWinRate4Month(lstpnl1t, toImg=isStaticImg, width=width, height=height)
trdb2py.showBarWinRateInYears(lstpnl1t, toImg=isStaticImg, width=width, height=height) | _____no_output_____ | Apache-2.0 | home/trdb2/weekday001.ipynb | zhs007/jupyternotebook.demo |
对于这种随机策略,胜率应该均匀分布在0.5左右的,可以分别看看每一条数据,会发现,周五和周一还是要稍高于0.5的,周二周三稍低于0.5。当然,这种策略交易比较频繁,次数足够,按月分布来看,没有明显的趋势,所以我们可以直接看整体汇总胜率。 | wrmt = trdb2py.buildPNLWinRateInMonths(lstpnl1t)
wrmt[0][['title', 'total']] | _____no_output_____ | Apache-2.0 | home/trdb2/weekday001.ipynb | zhs007/jupyternotebook.demo |
这里,我们对比一下纳指、标普、恒指、上证50、中证500、中小盘,可以得出以下结论:1. 和走势曲线关系不大,同样大趋势向上的纳指和中小盘,胜率也是能看出差异来的。2. 除了有明显高于0.5的以外,最好也能有明显低于0.5的,这样避开低于0.5的,持有高于0.5的,才能获得额外收益,最终明显超过基线。3. 纳指、标普、恒指 都没有明显的周内效应。4. A股普遍存在较明显的周内效应。5. 越是小盘股,周内效应越明显。 | trdb2py.showBarWinRate4Month(lstpnl1t, toImg=isStaticImg, width=width, height=height) | _____no_output_____ | Apache-2.0 | home/trdb2/weekday001.ipynb | zhs007/jupyternotebook.demo |
接下来,我们统计一下不同月份的胜率,发现,胜率最突出的还是周五买入持有1天,但这个在4月和9月胜率偏低,特别是4月。接下来看看4月的统计。 | #trdb2py.showBarWinRateInMonths(lstpnl1t, valtype='abs', valoff=-0.5, month=8, toImg=isStaticImg, width=width, height=height)
trdb2py.showBarWinRateInMonths(lstpnl1t, month=4, toImg=isStaticImg, width=width, height=height) | _____no_output_____ | Apache-2.0 | home/trdb2/weekday001.ipynb | zhs007/jupyternotebook.demo |
发现除了2015年和2020年以外,4月确实都是输的。但是,2015年和2020年4月其实都算是牛市了,不能这样简单的筛选。目前看来,没有特别的证据表明有明显的可供配合的月度效应。 如果能把周五、周一的增长叠加起来,是不是结果会更好一些呢干脆把持有1天到4天的情况,也就是从周一买周二卖,一直到 周一买周五卖,看看 | lstparams = []
for day in range(1, 5):
for i in range(0, 5):
buy0 = trdb2py.trading2_pb2.CtrlCondition(
name='weekday2',
vals=[lststart[i], calcweekday2val2(i + 1, day)],
)
sell0 = trdb2py.trading2_pb2.CtrlCondition(
name='weekday',
vals=[trd... | _____no_output_____ | Apache-2.0 | home/trdb2/weekday001.ipynb | zhs007/jupyternotebook.demo |
单看回报率,已经有明显超过基线的了,而且,最好的情况,夏普提升了近3倍 接下来,还能想到的,如果在下降的时候,定投买入,最终会不会也能获得额外收益呢?还是周一到周五一起测一下吧。 | lstparams = []
for i in range(0, 5):
buy0 = trdb2py.trading2_pb2.CtrlCondition(
name='weekday',
vals=[lststart[i]],
)
s0 = trdb2py.trading2_pb2.Strategy(
name="normal",
asset=trdb2py.str2asset(asset),
)
paramsaip = trdb2py.trading2_pb2.AIPParams(
money=... | _____no_output_____ | Apache-2.0 | home/trdb2/weekday001.ipynb | zhs007/jupyternotebook.demo |
我们可以看到5条收益曲线几乎重合在一起,说明,特定周几购买,其实并没有差别。关于定投,后面会有更详细的测试,这里还是回到如何榨取周内效应的最大收益上。 我们还可以考虑加入均线策略,看看在均线上下方买入,是否有区别,其实如果均线粒度够大,一定程度上能将牛市和熊市区分开。这个运算量有点大,大概有24000种,我直接给出结论吧。 | lstparams = []
for ema in range(5, 61):
for sdo in range(1, 5):
for sd in range(1, 6):
buy0 = trdb2py.trading2_pb2.CtrlCondition(
name='weekday2',
vals=[sd, calcweekday2val2(sd, sdo)],
)
buy1 = trdb2py.trading2_pb2.CtrlCondition(
... | _____no_output_____ | Apache-2.0 | home/trdb2/weekday001.ipynb | zhs007/jupyternotebook.demo |
EDA on training dataset | #### check if dataframe has null value, then call KNN Imputer to Impute the appropriate value
#### (Check the nearest 3 value to impute)
objPrediction = Preprocessor(execType)
if Raw_Prediction_Data.isnull().values.any():
log.info("Initiate to Impute null value for the null value columns")
Raw_Prediction_Data ... | _____no_output_____ | MIT | prediction-model-aai.ipynb | dinesh13n/assignment-aai |
Predict the Model | objTraining = prediction(execType)
# X33 data has multicolinearity during preprocessing on traing data, so need to remove from prediction as well
status = objTraining.predictionFromModel(Raw_Prediction_Data[dataColumns],dataColumns, ['X33'])
if status == 1:
print ("Successful End of Training")
else:
print ("Uns... | Successful End of Training
| MIT | prediction-model-aai.ipynb | dinesh13n/assignment-aai |
 [](https://colab.research.google.com/github/JohnSnowLabs/spark-nlp-workshop/blob/master/tutorials/Certification_Trainings/Public/1.SparkNLP_Basics.ipynb) Spark NLP Basics and P... | import os
# Install java
! apt-get update -qq
! apt-get install -y openjdk-8-jdk-headless -qq > /dev/null
os.environ["JAVA_HOME"] = "/usr/lib/jvm/java-8-openjdk-amd64"
os.environ["PATH"] = os.environ["JAVA_HOME"] + "/bin:" + os.environ["PATH"]
! java -version
# Install pyspark
! pip install --ignore-installed -q pys... | openjdk version "1.8.0_265"
OpenJDK Runtime Environment (build 1.8.0_265-8u265-b01-0ubuntu2~18.04-b01)
OpenJDK 64-Bit Server VM (build 25.265-b01, mixed mode)
[K |████████████████████████████████| 133kB 2.8MB/s
[?25h | Apache-2.0 | tutorials/Certification_Trainings/Public/1.SparkNLP_Basics.ipynb | ewbolme/spark-nlp-workshop |
**How to prevent Google Colab from disconnecting?**Google Colab notebooks have an idle timeout of 90 minutes and absolute timeout of 12 hours. This means, if user does not interact with his Google Colab notebook for more than 90 minutes, its instance is automatically terminated. Also, maximum lifetime of a Colab insta... | '''
function ConnectButton(){
console.log("Connect pushed");
document.querySelector("#top-toolbar > colab-connect-button").shadowRoot.querySelector("#connect").click()
}
setInterval(ConnectButton,60000);
''' | _____no_output_____ | Apache-2.0 | tutorials/Certification_Trainings/Public/1.SparkNLP_Basics.ipynb | ewbolme/spark-nlp-workshop |
1. Start Spark Session | import sparknlp
spark = sparknlp.start()
# params =>> gpu=False, spark23=False (start with spark 2.3)
print("Spark NLP version", sparknlp.version())
print("Apache Spark version:", spark.version)
| Spark NLP version 2.6.3-rc1
Apache Spark version: 2.4.4
| Apache-2.0 | tutorials/Certification_Trainings/Public/1.SparkNLP_Basics.ipynb | ewbolme/spark-nlp-workshop |
if you want to work with Spark 2.3 ```import os Install java! apt-get update -qq! apt-get install -y openjdk-8-jdk-headless -qq > /dev/null!wget -q https://archive.apache.org/dist/spark/spark-2.3.0/spark-2.3.0-bin-hadoop2.7.tgz!tar xf spark-2.3.0-bin-hadoop2.7.tgz!pip install -q findsparkos.environ["JAVA_HOME"] = "/u... | # https://github.com/JohnSnowLabs/spark-nlp/blob/master/python/sparknlp/__init__.py
from pyspark.sql import SparkSession
def start(gpu=False, spark23=False):
current_version="2.5.4"
maven_spark24 = "com.johnsnowlabs.nlp:spark-nlp_2.11:{}".format(current_version)
maven_gpu_spark24 = "com.johnsnowlabs.nlp:s... | _____no_output_____ | Apache-2.0 | tutorials/Certification_Trainings/Public/1.SparkNLP_Basics.ipynb | ewbolme/spark-nlp-workshop |
If you want to start `SparkSession` with your own parameters or you need to load the required jars/packages from your local disk, or you have no internet connection (that would be needed to pull the required packages from internet), you can skip `sparknlp.start()` and start your session manually as shown below. | """
from pyspark.sql import SparkSession
spark = SparkSession.builder \
.appName("Spark NLP Enterprise 2.4.5") \
.master("local[8]") \
.config("spark.driver.memory","12G") \
.config("spark.driver.maxResultSize", "2G") \
.config("spark.serializer", "org.apache.spark.serializer.KryoSerializer") \
... | _____no_output_____ | Apache-2.0 | tutorials/Certification_Trainings/Public/1.SparkNLP_Basics.ipynb | ewbolme/spark-nlp-workshop |
CPU on Apache Spark 2.4.x: https://s3.amazonaws.com/auxdata.johnsnowlabs.com/public/spark-nlp-assembly-2.6.2.jarGPU on Apache Spark 2.4.x: https://s3.amazonaws.com/auxdata.johnsnowlabs.com/public/spark-nlp-gpu-assembly-2.6.2.jarCPU on Apache Spark 2.3.x: https://s3.amazonaws.com/auxdata.johnsnowlabs.com/public/spark-nl... | from sparknlp.pretrained import PretrainedPipeline
testDoc = '''
Peter is a very good persn.
My life in Russia is very intersting.
John and Peter are brothrs. However they don't support each other that much.
Lucas Nogal Dunbercker is no longer happy. He has a good car though.
Europe is very culture rich. There are huge... | _____no_output_____ | Apache-2.0 | tutorials/Certification_Trainings/Public/1.SparkNLP_Basics.ipynb | ewbolme/spark-nlp-workshop |
Explain Document ML **Stages**- DocumentAssembler- SentenceDetector- Tokenizer- Lemmatizer- Stemmer- Part of Speech- SpellChecker (Norvig) | pipeline = PretrainedPipeline('explain_document_ml', lang='en')
pipeline.model.stages
# Load pretrained pipeline from local disk:
pipeline_local = PretrainedPipeline.from_disk('/root/cache_pretrained/explain_document_ml_en_2.4.0_2.4_1580252705962')
%%time
result = pipeline.annotate(testDoc)
result.keys()
result['sen... | _____no_output_____ | Apache-2.0 | tutorials/Certification_Trainings/Public/1.SparkNLP_Basics.ipynb | ewbolme/spark-nlp-workshop |
Explain Document DL **Stages**- DocumentAssembler- SentenceDetector- Tokenizer- NER (NER with GloVe 100D embeddings, CoNLL2003 dataset)- Lemmatizer- Stemmer- Part of Speech- SpellChecker (Norvig) | pipeline_dl = PretrainedPipeline('explain_document_dl', lang='en')
pipeline_dl.model.stages
pipeline_dl.model.stages[-2].getStorageRef()
pipeline_dl.model.stages[-2].getClasses()
%%time
result = pipeline_dl.annotate(testDoc)
result.keys()
result.keys()
result['entities']
df = pd.DataFrame({'token':result['token'], '... | _____no_output_____ | Apache-2.0 | tutorials/Certification_Trainings/Public/1.SparkNLP_Basics.ipynb | ewbolme/spark-nlp-workshop |
Recognize Entities DL | recognize_entities = PretrainedPipeline('recognize_entities_dl', lang='en')
testDoc = '''
Peter is a very good persn.
My life in Russia is very intersting.
John and Peter are brothrs. However they don't support each other that much.
Lucas Nogal Dunbercker is no longer happy. He has a good car though.
Europe is very cu... | _____no_output_____ | Apache-2.0 | tutorials/Certification_Trainings/Public/1.SparkNLP_Basics.ipynb | ewbolme/spark-nlp-workshop |
Clean Stop Words | clean_stop = PretrainedPipeline('clean_stop', lang='en')
result = clean_stop.annotate(testDoc)
result.keys()
' '.join(result['cleanTokens']) | _____no_output_____ | Apache-2.0 | tutorials/Certification_Trainings/Public/1.SparkNLP_Basics.ipynb | ewbolme/spark-nlp-workshop |
Clean Slang | clean_slang = PretrainedPipeline('clean_slang', lang='en')
result = clean_slang.annotate(' Whatsup bro, call me ASAP')
' '.join(result['normal']) | clean_slang download started this may take some time.
Approx size to download 21.8 KB
[OK!]
| Apache-2.0 | tutorials/Certification_Trainings/Public/1.SparkNLP_Basics.ipynb | ewbolme/spark-nlp-workshop |
Spell Checker (Norvig Algo)ref: https://norvig.com/spell-correct.html | spell_checker = PretrainedPipeline('check_spelling', lang='en')
testDoc = '''
Peter is a very good persn.
My life in Russia is very intersting.
John and Peter are brothrs. However they don't support each other that much.
Lucas Nogal Dunbercker is no longer happy. He has a good car though.
Europe is very culture rich. ... | _____no_output_____ | Apache-2.0 | tutorials/Certification_Trainings/Public/1.SparkNLP_Basics.ipynb | ewbolme/spark-nlp-workshop |
Spell Checker DLhttps://medium.com/spark-nlp/applying-context-aware-spell-checking-in-spark-nlp-3c29c46963bc | spell_checker_dl = PretrainedPipeline('check_spelling_dl', lang='en')
text = 'We will go to swimming if the ueather is nice.'
result = spell_checker_dl.annotate(text)
list(zip(result['token'], result['checked']))
result.keys()
# check for the different occurrences of the word "ueather"
examples = ['We will go to swi... | [('We', 'We'), ('will', 'will'), ('go', 'go'), ('to', 'to'), ('swimming', 'swimming'), ('if', 'if'), ('the', 'the'), ('ueather', 'weather'), ('is', 'is'), ('nice', 'nice'), ('.', '.')]
[('I', 'I'), ('have', 'have'), ('a', 'a'), ('black', 'black'), ('ueather', 'weather'), ('jacket', 'jacket'), (',', ','), ('so', 'so'), ... | Apache-2.0 | tutorials/Certification_Trainings/Public/1.SparkNLP_Basics.ipynb | ewbolme/spark-nlp-workshop |
Parsing a list of texts | testDoc_list = ['French author who helped pioner the science-fiction genre.',
'Verne wrate about space, air, and underwater travel before navigable aircrast',
'Practical submarines were invented, and before any means of space travel had been devised.']
testDoc_list
pipeline = PretrainedPipeline('explain_document_ml', ... | _____no_output_____ | Apache-2.0 | tutorials/Certification_Trainings/Public/1.SparkNLP_Basics.ipynb | ewbolme/spark-nlp-workshop |
Using fullAnnotate to get more details ```annotatorType: String, begin: Int, end: Int, result: String, (this is what annotate returns)metadata: Map[String, String], embeddings: Array[Float]``` | text = 'Peter Parker is a nice guy and lives in New York'
# pipeline_dl >> explain_document_dl
detailed_result = pipeline_dl.fullAnnotate(text)
detailed_result
detailed_result[0]['entities']
detailed_result[0]['entities'][0].result
chunks=[]
entities=[]
for n in detailed_result[0]['entities']:
chunks.append... | _____no_output_____ | Apache-2.0 | tutorials/Certification_Trainings/Public/1.SparkNLP_Basics.ipynb | ewbolme/spark-nlp-workshop |
Use pretrained match_chunk Pipeline for Individual Noun Phrase **Stages**- DocumentAssembler- SentenceDetector- Tokenizer- Part of Speech- ChunkerPipeline:- The pipeline uses regex `?*+`- which states that whenever the chunk finds an optional determiner (DT) followed by any number of adjectives (JJ) and then a noun (N... | pipeline = PretrainedPipeline('match_chunks', lang='en')
pipeline.model.stages
result = pipeline.annotate("The book has many chapters") # single noun phrase
result
result['chunk']
result = pipeline.annotate("the little yellow dog barked at the cat") #multiple noune phrases
result
result['chunk'] | _____no_output_____ | Apache-2.0 | tutorials/Certification_Trainings/Public/1.SparkNLP_Basics.ipynb | ewbolme/spark-nlp-workshop |
Extract exact dates from referential date phrases | pipeline = PretrainedPipeline('match_datetime', lang='en')
result = pipeline.annotate("I saw him yesterday and he told me that he will visit us next week")
result
detailed_result = pipeline.fullAnnotate("I saw him yesterday and he told me that he will visit us next week")
detailed_result
tuples = []
for x in detail... | _____no_output_____ | Apache-2.0 | tutorials/Certification_Trainings/Public/1.SparkNLP_Basics.ipynb | ewbolme/spark-nlp-workshop |
Sentiment Analysis Vivek algopaper: `Fast and accurate sentiment classification using an enhanced Naive Bayes model`https://arxiv.org/abs/1305.6143code `https://github.com/vivekn/sentiment` | sentiment = PretrainedPipeline('analyze_sentiment', lang='en')
result = sentiment.annotate("The movie I watched today was not a good one")
result['sentiment'] | _____no_output_____ | Apache-2.0 | tutorials/Certification_Trainings/Public/1.SparkNLP_Basics.ipynb | ewbolme/spark-nlp-workshop |
DL version (trained on imdb) | sentiment_imdb = PretrainedPipeline('analyze_sentimentdl_use_imdb', lang='en')
sentiment_imdb_glove = PretrainedPipeline('analyze_sentimentdl_glove_imdb', lang='en')
comment = '''
It's a very scary film but what impressed me was how true the film sticks to the original's tricks; it isn't filled with loud in-your-face j... | _____no_output_____ | Apache-2.0 | tutorials/Certification_Trainings/Public/1.SparkNLP_Basics.ipynb | ewbolme/spark-nlp-workshop |
DL version (trained on twitter dataset) | sentiment_twitter = PretrainedPipeline('analyze_sentimentdl_use_twitter', lang='en')
result = sentiment_twitter.annotate("The movie I watched today was not a good one")
result['sentiment']
| _____no_output_____ | Apache-2.0 | tutorials/Certification_Trainings/Public/1.SparkNLP_Basics.ipynb | ewbolme/spark-nlp-workshop |
Sets in Python Welcome! This notebook will teach you about the sets in the Python Programming Language. By the end of this lab, you'll know the basics set operations in Python, including what it is, operations and logic operations. Table of Contents Sets ... | # Create a set
set1 = {"pop", "rock", "soul", "hard rock", "rock", "R&B", "rock", "disco"}
set1 | _____no_output_____ | MIT | PY0101EN-2-3-Sets.ipynb | vatsal30/Python |
The process of mapping is illustrated in the figure: You can also create a set from a list as follows: | # Convert list to set
album_list = [ "Michael Jackson", "Thriller", 1982, "00:42:19", \
"Pop, Rock, R&B", 46.0, 65, "30-Nov-82", None, 10.0]
album_set = set(album_list)
album_set | _____no_output_____ | MIT | PY0101EN-2-3-Sets.ipynb | vatsal30/Python |
Now let us create a set of genres: | # Convert list to set
music_genres = set(["pop", "pop", "rock", "folk rock", "hard rock", "soul", \
"progressive rock", "soft rock", "R&B", "disco"])
music_genres | _____no_output_____ | MIT | PY0101EN-2-3-Sets.ipynb | vatsal30/Python |
Set Operations Let us go over set operations, as these can be used to change the set. Consider the set A: | # Sample set
A = set(["Thriller", "Back in Black", "AC/DC"])
A | _____no_output_____ | MIT | PY0101EN-2-3-Sets.ipynb | vatsal30/Python |
We can add an element to a set using the add() method: | # Add element to set
A.add("NSYNC")
A | _____no_output_____ | MIT | PY0101EN-2-3-Sets.ipynb | vatsal30/Python |
If we add the same element twice, nothing will happen as there can be no duplicates in a set: | # Try to add duplicate element to the set
A.add("NSYNC")
A | _____no_output_____ | MIT | PY0101EN-2-3-Sets.ipynb | vatsal30/Python |
We can remove an item from a set using the remove method: | # Remove the element from set
A.remove("NSYNC")
A | _____no_output_____ | MIT | PY0101EN-2-3-Sets.ipynb | vatsal30/Python |
We can verify if an element is in the set using the in command: | # Verify if the element is in the set
"AC/DC" in A | _____no_output_____ | MIT | PY0101EN-2-3-Sets.ipynb | vatsal30/Python |
Sets Logic Operations Remember that with sets you can check the difference between sets, as well as the symmetric difference, intersection, and union: Consider the following two sets: | # Sample Sets
album_set1 = set(["Thriller", 'AC/DC', 'Back in Black'])
album_set2 = set([ "AC/DC", "Back in Black", "The Dark Side of the Moon"]) | _____no_output_____ | MIT | PY0101EN-2-3-Sets.ipynb | vatsal30/Python |
# Print two sets
album_set1, album_set2 | _____no_output_____ | MIT | PY0101EN-2-3-Sets.ipynb | vatsal30/Python | |
As both sets contain AC/DC and Back in Black we represent these common elements with the intersection of two circles. You can find the intersect of two sets as follow using &: | # Find the intersections
intersection = album_set1 & album_set2
intersection | _____no_output_____ | MIT | PY0101EN-2-3-Sets.ipynb | vatsal30/Python |
You can find all the elements that are only contained in album_set1 using the difference method: | # Find the difference in set1 but not set2
album_set1.difference(album_set2) | _____no_output_____ | MIT | PY0101EN-2-3-Sets.ipynb | vatsal30/Python |
You only need to consider elements in album_set1; all the elements in album_set2, including the intersection, are not included. The elements in album_set2 but not in album_set1 is given by: | album_set2.difference(album_set1) | _____no_output_____ | MIT | PY0101EN-2-3-Sets.ipynb | vatsal30/Python |
You can also find the intersection of album_list1 and album_list2, using the intersection method: | # Use intersection method to find the intersection of album_list1 and album_list2
album_set1.intersection(album_set2) | _____no_output_____ | MIT | PY0101EN-2-3-Sets.ipynb | vatsal30/Python |
This corresponds to the intersection of the two circles: The union corresponds to all the elements in both sets, which is represented by coloring both circles: The union is given by: | # Find the union of two sets
album_set1.union(album_set2) | _____no_output_____ | MIT | PY0101EN-2-3-Sets.ipynb | vatsal30/Python |
And you can check if a set is a superset or subset of another set, respectively, like this: | # Check if superset
set(album_set1).issuperset(album_set2)
# Check if subset
set(album_set2).issubset(album_set1) | _____no_output_____ | MIT | PY0101EN-2-3-Sets.ipynb | vatsal30/Python |
Here is an example where issubset() and issuperset() return true: | # Check if subset
set({"Back in Black", "AC/DC"}).issubset(album_set1)
# Check if superset
album_set1.issuperset({"Back in Black", "AC/DC"}) | _____no_output_____ | MIT | PY0101EN-2-3-Sets.ipynb | vatsal30/Python |
Quiz on Sets Convert the list ['rap','house','electronic music', 'rap'] to a set: | # Write your code below and press Shift+Enter to execute
set(['rap','house','electronic music','rap']) | _____no_output_____ | MIT | PY0101EN-2-3-Sets.ipynb | vatsal30/Python |
Double-click __here__ for the solution.<!-- Your answer is below:set(['rap','house','electronic music','rap'])--> Consider the list A = [1, 2, 2, 1] and set B = set([1, 2, 2, 1]), does sum(A) = sum(B) | # Write your code below and press Shift+Enter to execute
A=[1,2,2,1]
B=set([1,2,2,1])
print("the sum of A is:",sum(A))
print("the sum of B is:",sum(B))
sum(A)==sum(B) | the sum of A is: 6
the sum of B is: 3
| MIT | PY0101EN-2-3-Sets.ipynb | vatsal30/Python |
Double-click __here__ for the solution.<!-- Your answer is below:A = [1, 2, 2, 1] B = set([1, 2, 2, 1])print("the sum of A is:", sum(A))print("the sum of B is:", sum(B))--> Create a new set album_set3 that is the union of album_set1 and album_set2: | # Write your code below and press Shift+Enter to execute
album_set1 = set(["Thriller", 'AC/DC', 'Back in Black'])
album_set2 = set([ "AC/DC", "Back in Black", "The Dark Side of the Moon"])
album_set3 = album_set1.union(album_set2)
album_set3 | _____no_output_____ | MIT | PY0101EN-2-3-Sets.ipynb | vatsal30/Python |
Double-click __here__ for the solution.<!-- Your answer is below:album_set3 = album_set1.union(album_set2)album_set3--> Find out if album_set1 is a subset of album_set3: | # Write your code below and press Shift+Enter to execute
album_set1.issubset(album_set3) | _____no_output_____ | MIT | PY0101EN-2-3-Sets.ipynb | vatsal30/Python |
To string pdb_text | from molsysmt.tools import openmm_Topology
#openmm_Topology.to_string_pdb_text(item) | _____no_output_____ | MIT | docs/contents/tools/classes/openmm_Topology/to_string_pdb_text.ipynb | dprada/molsysmt |
Exercise 4a 2 Red Cards Study 2.1 Loading and Cleaning the data | #Import libraries
import numpy as np
import pandas as pd
from scipy.sparse.linalg import lsqr
#Load dataset
df = pd.read_csv("CrowdstormingDataJuly1st.csv", sep=",", header=0)
print(df.columns) | Index(['playerShort', 'player', 'club', 'leagueCountry', 'birthday', 'height',
'weight', 'position', 'games', 'victories', 'ties', 'defeats', 'goals',
'yellowCards', 'yellowReds', 'redCards', 'photoID', 'rater1', 'rater2',
'refNum', 'refCountry', 'Alpha_3', 'meanIAT', 'nIAT', 'seIAT',
'meanE... | MIT | ex04a/red-cards.ipynb | Osburg/Fundamentals-of-Machine-Learning |
We sort out (irrelevant) features:- player (playerShort uniquely identifies the player, so player is not needed)- playerShort (the players' names are irrelevant for us, actually...)- photoID (is only needed if we want to classify the skin color by ourselves)- refCountry (we will assume that not the name of the referee ... | df = df.drop(labels=["player", "playerShort", "photoID", "refCountry", "nIAT", "seIAT", "nExp", "seExp", "yellowCards", "club", "birthday", "Alpha_3", "games"], axis=1)
print(df.columns) | Index(['leagueCountry', 'height', 'weight', 'position', 'victories', 'ties',
'defeats', 'goals', 'yellowReds', 'redCards', 'rater1', 'rater2',
'refNum', 'meanIAT', 'meanExp'],
dtype='object')
| MIT | ex04a/red-cards.ipynb | Osburg/Fundamentals-of-Machine-Learning |
Next, we create new features out of existing ones or manipulate them:- rating (we take the mean of rater1 and rater2 as our own rating)- totalReds (we sum up the red and yellow-red cards to the total number of red cards and divide by the number of games, This is our response Y.)- leagueCountry (replace the name of the ... | #take mean of the two skin color ratings
df["rating"] = (df["rater1"] + df["rater2"])/2
df = df.drop(labels=["rater1", "rater2"], axis=1)
#sum up red and yellow-red cards
df["percentageReds"] = (df["redCards"] + df["yellowReds"])/(df["victories"]+df["ties"]+df["defeats"])
df = df.drop(labels=["redCards", "yellowReds"]... | _____no_output_____ | MIT | ex04a/red-cards.ipynb | Osburg/Fundamentals-of-Machine-Learning |
Now we go on with preparing the data set:- remove rows that contain a NaN-value- remove rows where refCount<22 (for explanation see https://nbviewer.jupyter.org/github/mathewzilla/redcard/blob/master/Crowdstorming_visualisation.ipynb. After this we can remove the features "refNum" and "refCount" because these were only... | #remove rows with NaN in "rating"
df = df.dropna(axis=0)
#remove rows where the "refCount"<22
df = df.loc[df["refCount"]>21].reset_index()
df = df.drop(["refNum", "refCount", "index"], axis=1)
#normalize ties, victories and defeats
defeats = df["defeats"]/(df["defeats"]+df["ties"]+df["victories"])
ties = df["ties"]/... | _____no_output_____ | MIT | ex04a/red-cards.ipynb | Osburg/Fundamentals-of-Machine-Learning |
In the following tasks we want to apply the LSQR-algorithm. In the lecture we always assumed centralized features and responses. So our last step is to centralize our data. The responses are given by the values in the column "totalReds" | df_mean = df.apply(np.mean, axis=0)
df = df - df_mean
df | _____no_output_____ | MIT | ex04a/red-cards.ipynb | Osburg/Fundamentals-of-Machine-Learning |
2.2 Model Creation | #solve the problem using the lsqr algorithm (linear regression)
#extract features and responses from the DataFrame
Y = df["percentageReds"].to_numpy()
X = df.drop(labels=["percentageReds"], axis=1).to_numpy()
class LinearRegression():
def __init__(self):
self.beta = None
#use lsqr algorithm
... | 0.0 %
10.0 %
20.0 %
30.0 %
40.0 %
50.0 %
60.0 %
70.0 %
80.0 %
90.0 %
error rate, regression forest:
0.005265575175396048
| MIT | ex04a/red-cards.ipynb | Osburg/Fundamentals-of-Machine-Learning |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.