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
Setting the index- Now we need to set the index of the data-frame so that it contains the sequence of dates.
googl.set_index(pd.to_datetime(googl['Date']), inplace=True) googl.index[0] type(googl.index[0])
_____no_output_____
CC-BY-4.0
src/main/ipynb/pandas.ipynb
pperezgr/python-bigdata
Plotting series- We can plot a series in a dataframe by invoking its `plot()` method.- Here we plot a time-series of the daily traded volume:
ax = googl['Volume'].plot() plt.show()
_____no_output_____
CC-BY-4.0
src/main/ipynb/pandas.ipynb
pperezgr/python-bigdata
Adjusted closing prices as a time series
googl['Adj Close'].plot() plt.show()
_____no_output_____
CC-BY-4.0
src/main/ipynb/pandas.ipynb
pperezgr/python-bigdata
Slicing series using date/time stamps- We can slice a time series by specifying a range of dates or times.- Date and time stamps are specified strings representing dates in the required format.
googl['Adj Close']['1-1-2016':'1-1-2017'].plot() plt.show()
_____no_output_____
CC-BY-4.0
src/main/ipynb/pandas.ipynb
pperezgr/python-bigdata
Resampling - We can *resample* to obtain e.g. weekly or monthly prices.- In the example below the `'W'` denotes weekly.- See [the documentation](http://pandas.pydata.org/pandas-docs/stable/timeseries.htmloffset-aliases) for other frequencies.- We group data into weeks, and then take the last value in each week.- For d...
weekly_prices = googl['Adj Close'].resample('W').last() weekly_prices.head() weekly_prices.plot() plt.title('Prices for GOOGL sampled at weekly frequency') plt.show()
_____no_output_____
CC-BY-4.0
src/main/ipynb/pandas.ipynb
pperezgr/python-bigdata
Converting prices to log returns
weekly_rets = np.diff(np.log(weekly_prices)) plt.plot(weekly_rets) plt.xlabel('t'); plt.ylabel('$r_t$') plt.title('Weekly log-returns for GOOGL') plt.show()
_____no_output_____
CC-BY-4.0
src/main/ipynb/pandas.ipynb
pperezgr/python-bigdata
Converting the returns to a series- Notice that in the above plot the time axis is missing the dates.- This is because the `np.diff()` function returns an array instead of a data-frame.
type(weekly_rets)
_____no_output_____
CC-BY-4.0
src/main/ipynb/pandas.ipynb
pperezgr/python-bigdata
- We can convert it to a series thus:
weekly_rets_series = pd.Series(weekly_rets, index=weekly_prices.index[1:]) weekly_rets_series.head()
_____no_output_____
CC-BY-4.0
src/main/ipynb/pandas.ipynb
pperezgr/python-bigdata
Plotting with the correct time axis Now when we plot the series we will obtain the correct time axis:
plt.plot(weekly_rets_series) plt.title('GOOGL weekly log-returns'); plt.xlabel('t'); plt.ylabel('$r_t$') plt.show()
_____no_output_____
CC-BY-4.0
src/main/ipynb/pandas.ipynb
pperezgr/python-bigdata
Plotting a return histogram
weekly_rets_series.hist() plt.show() weekly_rets_series.describe()
_____no_output_____
CC-BY-4.0
src/main/ipynb/pandas.ipynb
pperezgr/python-bigdata
Scraping Fantasy Football DataNeed to scrape the following data:- Weekly Player PPR Projections: ESPN, CBS, Fantasy Sharks, Scout Fantasy Sporsts, (and tried Fantasy Football Today but doesn't have defense projections currently, so exclude)- Previous Week Player Actual PPR Results- Weekly Fanduel Player Salary (can ma...
import pandas as pd import numpy as np import requests # import json # from bs4 import BeautifulSoup import time from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC # from se...
_____no_output_____
MIT
data/Scraping Fantasy Football Data - FINAL.ipynb
zgscherrer/Project-Fantasy-Football
Get Weekly Player Actual Fantasy PPR PointsGet from ESPN's Scoring Leaders tablehttp://games.espn.com/ffl/leaders?&scoringPeriodId=1&seasonId=2018&slotCategoryId=0&leagueID=0- scoringPeriodId = week of the season- seasonId = year- slotCategoryId = position, where 'QB':0, 'RB':2, 'WR':4, 'TE':6, 'K':17, 'D/ST':16- leag...
##SCRAPE ESPN SCORING LEADERS TABLE FOR ACTUAL FANTASY PPR POINTS## #input needs to be year as four digit number and week as number #returns dataframe of scraped data def scrape_actual_PPR_player_points_ESPN(week, year): #instantiate the driver driver = instantiate_selenium_driver() #initialize dataf...
Pickle saved to: pickle_archive/Week1_Player_Actual_PPR_messy_scrape_2018-9-16-7-31.pkl Pickle saved to: pickle_archive/Week1_Player_Actual_PPR_2018-9-16-7-31.pkl (1007, 5)
MIT
data/Scraping Fantasy Football Data - FINAL.ipynb
zgscherrer/Project-Fantasy-Football
Get ESPN Player Fantasy Points Projections for Week Get from ESPN's Projections Tablehttp://games.espn.com/ffl/tools/projections?&scoringPeriodId=1&seasonId=2018&slotCategoryId=0&leagueID=0- scoringPeriodId = week of the season- seasonId = year- slotCategoryId = position, where 'QB':0, 'RB':2, 'WR':4, 'TE':6, 'K':17, ...
##SCRAPE ESPN PROJECTIONS TABLE FOR PROJECTED FANTASY PPR POINTS## #input needs to be year as four digit number and week as number #returns dataframe of scraped data def scrape_weekly_player_projections_ESPN(week, year): #instantiate the driver on the ESPN projections page driver = instantiate_selenium_driver...
Pickle saved to: pickle_archive/Week2_PPR_Projections_ESPN_messy_scrape_2018-9-16-7-35.pkl Pickle saved to: pickle_archive/Week2_PPR_Projections_ESPN_2018-9-16-7-35.pkl (1007, 5)
MIT
data/Scraping Fantasy Football Data - FINAL.ipynb
zgscherrer/Project-Fantasy-Football
Get CBS Player Fantasy Points Projections for Week Get from CBS's Projections Tablehttps://www.cbssports.com/fantasy/football/stats/sortable/points/QB/ppr/projections/2018/2?&print_rows=9999- QB is where position goes- 2018 is where season goes- 2 is where week goes- print_rows = 9999 gives all results in one table
##SCRAPE CBS PROJECTIONS TABLE FOR PROJECTED FANTASY PPR POINTS## #input needs to be year as four digit number and week as number #returns dataframe of scraped data def scrape_weekly_player_projections_CBS(week, year): ###GET PROJECTIONS FROM CBS### #CBS has separate tables for each position, so need to cycle...
Pickle saved to: pickle_archive/Week2_PPR_Projections_CBS_messy_scrape_2018-9-16-7-35.pkl Pickle saved to: pickle_archive/Week2_PPR_Projections_CBS_2018-9-16-7-35.pkl (815, 5)
MIT
data/Scraping Fantasy Football Data - FINAL.ipynb
zgscherrer/Project-Fantasy-Football
Get Fantasy Sharks Player Points Projection for WeekThey have a json option that gets updated weekly (don't appear to store previous week projections). The json defaults to PPR (which is lucky for us) and has an all players option.https://www.fantasysharks.com/apps/Projections/WeeklyProjections.php?pos=ALL&format=jso...
##SCRAPE FANTASY SHARKS PROJECTIONS TABLE FOR PROJECTED FANTASY PPR POINTS## #input needs to be week as number (year isn't used, but keep same format as others) #returns dataframe of scraped data def scrape_weekly_player_projections_Sharks(week, year): #fantasy sharks url - segment for 2018 week 1 starts at 628 an...
Pickle saved to: pickle_archive/Week2_PPR_Projections_Sharks_messy_scrape_2018-9-16-7-35.pkl Pickle saved to: pickle_archive/Week2_PPR_Projections_Sharks_2018-9-16-7-35.pkl (992, 5)
MIT
data/Scraping Fantasy Football Data - FINAL.ipynb
zgscherrer/Project-Fantasy-Football
Get Scout Fantasy Sports Player Fantasy Points Projections for Week Get from Scout Fantasy Sports Projections Tablehttps://fftoolbox.scoutfantasysports.com/football/rankings/?pos=rb&week=2&noppr=false- pos is position with options of 'QB','RB','WR','TE', 'K', 'DEF'- week is week of year- noppr is set to false when you...
##SCRAPE Scout PROJECTIONS TABLE FOR PROJECTED FANTASY PPR POINTS## #input needs to be year as four digit number and week as number #returns dataframe of scraped data def scrape_weekly_player_projections_SCOUT(week, year): ###GET PROJECTIONS FROM SCOUT### #SCOUT has separate tables for each position, so need ...
C:\Users\micha\Anaconda3\envs\PythonData\lib\site-packages\urllib3\connectionpool.py:858: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings InsecureRequestWarning) C:\Users...
MIT
data/Scraping Fantasy Football Data - FINAL.ipynb
zgscherrer/Project-Fantasy-Football
Get FanDuel Player Salaries for Week just import the Thurs-Mon game salaries (they differ for each game type, and note they don't include Kickers in the Thurs-Mon)Go to a FanDuel Thurs-Mon competition and Download a csv of players, which we then upload and format in python.
###FORMAT/EXTRACT FANDUEL SALARY INFO### def format_extract_FanDuel(df_fanduel_csv, week, year): #rename columns df_fanduel_csv.rename(columns={'Position':'POS', 'Nickname':'PLAYER', 'Team':'TEAM', 'Sala...
Pickle saved to: pickle_archive/Week2_Salary_FanDuel_2018-9-16-7-35.pkl (669, 5)
MIT
data/Scraping Fantasy Football Data - FINAL.ipynb
zgscherrer/Project-Fantasy-Football
!!!FFtoday apparently doesn't do weekly projections for Defenses, so don't use it for now (can check back in future and see if updated)!!! Get FFtoday Player Fantasy Points Projections for Week Get from FFtoday's Projections Tablehttp://www.fftoday.com/rankings/playerwkproj.php?Season=2018&GameWeek=2&PosID=10&LeagueID...
# ##SCRAPE FFtoday PROJECTIONS TABLE FOR PROJECTED FANTASY PPR POINTS## # #input needs to be year as four digit number and week as number # #returns dataframe of scraped data # def scrape_weekly_player_projections_FFtoday(week, year): # #instantiate selenium driver # driver = instantiate_selenium_driver() ...
_____no_output_____
MIT
data/Scraping Fantasy Football Data - FINAL.ipynb
zgscherrer/Project-Fantasy-Football
Initial Database Stuff
# actual_ppr_df = pd.read_pickle('pickle_archive/Week1_Player_Actual_PPR_2018-9-13-6-41.pkl') # espn_final_df = pd.read_pickle('pickle_archive/Week1_PPR_Projections_ESPN_2018-9-13-6-46.pkl') # cbs_final_df = pd.read_pickle('pickle_archive/Week1_PPR_Projections_CBS_2018-9-13-17-45.pkl') # cbs_final_df.head() # from sqla...
_____no_output_____
MIT
data/Scraping Fantasy Football Data - FINAL.ipynb
zgscherrer/Project-Fantasy-Football
Tutorial 13: Skyrmion in a disk> Interactive online tutorial:> [![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/ubermag/oommfc/master?filepath=docs%2Fipynb%2Findex.ipynb) In this tutorial, we compute and relax a skyrmion in a interfacial-DMI material in a confined disk like geometry.
import discretisedfield as df import micromagneticmodel as mm import oommfc as oc
_____no_output_____
BSD-3-Clause
docs/ipynb/13-tutorial-skyrmion.ipynb
ubermag/mumaxc
We define mesh in cuboid through corner points `p1` and `p2`, and discretisation cell size `cell`.
region = df.Region(p1=(-50e-9, -50e-9, 0), p2=(50e-9, 50e-9, 10e-9)) mesh = df.Mesh(region=region, cell=(5e-9, 5e-9, 5e-9))
_____no_output_____
BSD-3-Clause
docs/ipynb/13-tutorial-skyrmion.ipynb
ubermag/mumaxc
The mesh we defined is:
%matplotlib inline mesh.k3d()
_____no_output_____
BSD-3-Clause
docs/ipynb/13-tutorial-skyrmion.ipynb
ubermag/mumaxc
Now, we can define the system object by first setting up the Hamiltonian:
system = mm.System(name="skyrmion") system.energy = ( mm.Exchange(A=1.6e-11) + mm.DMI(D=4e-3, crystalclass="Cnv") + mm.UniaxialAnisotropy(K=0.51e6, u=(0, 0, 1)) + mm.Demag() + mm.Zeeman(H=(0, 0, 2e5)) )
_____no_output_____
BSD-3-Clause
docs/ipynb/13-tutorial-skyrmion.ipynb
ubermag/mumaxc
Disk geometry is set up be defining the saturation magnetisation (norm of the magnetisation field). For that, we define a function:
Ms = 1.1e6 def Ms_fun(pos): """Function to set magnitude of magnetisation: zero outside cylindric shape, Ms inside cylinder. Cylinder radius is 50nm. """ x, y, z = pos if (x**2 + y**2) ** 0.5 < 50e-9: return Ms else: return 0
_____no_output_____
BSD-3-Clause
docs/ipynb/13-tutorial-skyrmion.ipynb
ubermag/mumaxc
And the second function we need is the function to definr the initial magnetisation which is going to relax to skyrmion.
def m_init(pos): """Function to set initial magnetisation direction: -z inside cylinder (r=10nm), +z outside cylinder. y-component to break symmetry. """ x, y, z = pos if (x**2 + y**2) ** 0.5 < 10e-9: return (0, 0, -1) else: return (0, 0, 1) # create system with above ...
_____no_output_____
BSD-3-Clause
docs/ipynb/13-tutorial-skyrmion.ipynb
ubermag/mumaxc
The geometry is now:
system.m.norm.k3d_nonzero()
_____no_output_____
BSD-3-Clause
docs/ipynb/13-tutorial-skyrmion.ipynb
ubermag/mumaxc
and the initial magnetsation is:
system.m.plane("z").mpl()
_____no_output_____
BSD-3-Clause
docs/ipynb/13-tutorial-skyrmion.ipynb
ubermag/mumaxc
Finally we can minimise the energy and plot the magnetisation.
# minimize the energy md = oc.MinDriver() md.drive(system) # Plot relaxed configuration: vectors in z-plane system.m.plane("z").mpl() # Plot z-component only: system.m.z.plane("z").mpl() # 3d-plot of z-component system.m.z.k3d_voxels(filter_field=system.m.norm)
_____no_output_____
BSD-3-Clause
docs/ipynb/13-tutorial-skyrmion.ipynb
ubermag/mumaxc
Finally we can sample and plot the magnetisation along the line:
system.m.z.line(p1=(-49e-9, 0, 0), p2=(49e-9, 0, 0), n=20).mpl()
_____no_output_____
BSD-3-Clause
docs/ipynb/13-tutorial-skyrmion.ipynb
ubermag/mumaxc
**Author: Avani Gupta Roll: 2019121004** Excercise 2In Excercise 1, we computed the LDA for a multi-class problem, the IRIS dataset. In this excercise, we will now compare the LDA and PCA for the IRIS dataset.To revisit, the iris dataset contains measurements for 150 iris flowers from three different species.The three ...
from sklearn.datasets import make_classification import matplotlib.pyplot as plt import numpy as np import seaborn as sns; sns.set(); import pandas as pd from sklearn.model_selection import train_test_split from numpy import pi
_____no_output_____
MIT
HW9/2019121004_LDAExcercise2.ipynb
avani17101/SMAI-Assignments
Importing the dataset
url = "https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data" names = ['sepal-length', 'sepal-width', 'petal-length', 'petal-width', 'Class'] dataset = pd.read_csv(url, names=names) dataset.tail()
_____no_output_____
MIT
HW9/2019121004_LDAExcercise2.ipynb
avani17101/SMAI-Assignments
Data preprocessingOnce dataset is loaded into a pandas data frame object, the first step is to divide dataset into features and corresponding labels and then divide the resultant dataset into training and test sets. The following code divides data into labels and feature set:
X = dataset.iloc[:, 0:4].values y = dataset.iloc[:, 4].values
_____no_output_____
MIT
HW9/2019121004_LDAExcercise2.ipynb
avani17101/SMAI-Assignments
The above script assigns the first four columns of the dataset i.e. the feature set to X variable while the values in the fifth column (labels) are assigned to the y variable.The following code divides data into training and test sets:
from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
_____no_output_____
MIT
HW9/2019121004_LDAExcercise2.ipynb
avani17101/SMAI-Assignments
Feature ScalingWe will now perform feature scaling as part of data preprocessing too. For this task, we will be using scikit learn `StandardScalar`.
from sklearn.preprocessing import StandardScaler sc = StandardScaler() X_train = sc.fit_transform(X_train) X_test = sc.transform(X_test)
_____no_output_____
MIT
HW9/2019121004_LDAExcercise2.ipynb
avani17101/SMAI-Assignments
Write your code belowWrite your code to compute the PCA and LDA on the IRIS dataset below.
### WRITE YOUR CODE HERE #### from sklearn.preprocessing import LabelEncoder enc = LabelEncoder() label_encoder = enc.fit(y_train) y_train = label_encoder.transform(y_train) + 1 #labels are done in alphabetical order # 1: 'Iris-setosa', 2: 'Iris-versicolor', 3:'Iris-virginica' label_encoder = enc.fit(y_test) y_test = ...
Accuracy on train set 85.0
MIT
HW9/2019121004_LDAExcercise2.ipynb
avani17101/SMAI-Assignments
Exercise 11 - Recurrent Neural Networks========A recurrent neural network (RNN) is a class of neural network that excels when your data can be treated as a sequence - such as text, music, speech recognition, connected handwriting, or data over a time period. RNN's can analyse or predict a word based on the previous wor...
%%capture # Run this! from keras.models import load_model from keras.models import Sequential from keras.layers import Dense, Activation, LSTM from keras.callbacks import LambdaCallback, ModelCheckpoint import numpy as np import random, sys, io, string
_____no_output_____
MIT
11. Recurrent Neural Networks - Python.ipynb
AnneliesseMorales/ms-learn-ml-crash-course-python
Replace the `` with `The Time Machine`
### # REPLACE THE <addFileName> BELOW WITH The Time Machine ### text = io.open('Data/<addFileName>.txt', encoding = 'UTF-8').read() ### # Let's have a look at some of the text print(text[0:198]) # This cuts out punctuation and make all the characters lower case text = text.lower().translate(str.maketrans("", "", stri...
_____no_output_____
MIT
11. Recurrent Neural Networks - Python.ipynb
AnneliesseMorales/ms-learn-ml-crash-course-python
Expected output: ```The Time Traveller (for so it will be convenient to speak of him) was expounding a recondite matter to us. His pale grey eyes shone and twinkled, and his usually pale face was flushed and animated.text length: 174201 charactersunique characters: 39```Step 2-----Next we'll divide the text into seque...
### # REPLACE <sequenceLength> WITH 40 AND <step> WITH 4 ### sequence_length = <sequenceLength> step = <step> ### sequences = [] target_chars = [] for i in range(0, len(text) - sequence_length, step): sequences.append([text[i: i + sequence_length]]) target_chars.append(text[i + sequence_length]) print('number ...
_____no_output_____
MIT
11. Recurrent Neural Networks - Python.ipynb
AnneliesseMorales/ms-learn-ml-crash-course-python
Expected output:`number of training sequences: 43541` Replace `` with `sequences` and run the code.
# One-hot vectorise X = np.zeros((len(sequences), sequence_length, len(charset)), dtype=np.bool) y = np.zeros((len(sequences), len(charset)), dtype=np.bool) ### # REPLACE THE <addSequences> BELOW WITH sequences ### for n, sequence in enumerate(<addSequences>): ### for m, character in enumerate(list(sequence[0])):...
_____no_output_____
MIT
11. Recurrent Neural Networks - Python.ipynb
AnneliesseMorales/ms-learn-ml-crash-course-python
Step 3------Let's build our model, using a single LSTM layer of 128 units. We'll keep the model simple for now, so that training does not take too long. In the cell below replace: 1. `` with `LSTM` 2. `` with `128` 3. `` with `'softmax` and then __run the code__.
model = Sequential() ### # REPLACE THE <addLSTM> BELOW WITH LSTM (use uppercase) AND <addLayerSize> WITH 128 ### model.add(<addLSTM>(<addLayerSize>, input_shape = (X.shape[1], X.shape[2]))) ### ### # REPLACE THE <addSoftmaxFunction> with 'softmax' (INCLUDING THE QUOTES) ### model.add(Dense(y.shape[1], activation = <a...
_____no_output_____
MIT
11. Recurrent Neural Networks - Python.ipynb
AnneliesseMorales/ms-learn-ml-crash-course-python
The code below generates text at the end of an epoch (one training cycle). This allows us to see how the model is performing as it trains. If you're making a large neural network with a long training time it's useful to check in on the model as see if the text generating is legible as it trains, as overtraining may occ...
# Run this, but do not edit. # It helps generate the text and save the model epochs. # Generate new text def on_epoch_end(epoch, _): diversity = 0.5 print('\n### Generating text with diversity %0.2f' %(diversity)) start = random.randint(0, len(text) - sequence_length - 1) seed = text[start: start + se...
_____no_output_____
MIT
11. Recurrent Neural Networks - Python.ipynb
AnneliesseMorales/ms-learn-ml-crash-course-python
The code below will start the model to train. This may take a long time. Feel free to stop the training with the `square stop button` to the right of the `Run button` in the toolbar.Later in the exercise, we will load a pretrained model. In the cell below replace: 1. `` with `print_callback` 2. `` with `checkpoint` and...
### # REPLACE <addPrintCallback> WITH print_callback AND <addCheckpoint> WITH checkpoint ### model.fit(X, y, batch_size = 128, epochs = 3, callbacks = [<addPrintCallback>, <addCheckpoint>]) ###
_____no_output_____
MIT
11. Recurrent Neural Networks - Python.ipynb
AnneliesseMorales/ms-learn-ml-crash-course-python
The output won't appear to be very good. But then, this dataset is small, and we have trained it only for a short time using a rather small RNN. How might it look if we upscaled things?Step 5------We could improve our model by:* Having a larger training set.* Increasing the number of LSTM units.* Training it for longer...
from keras.models import load_model print("loading model... ", end = '') ### # REPLACE <addLoadModel> BELOW WITH load_model ### model = <addLoadModel>('Models/arthur-model-epoch-30.hdf5') ### model.compile(loss = 'categorical_crossentropy', optimizer = 'Adam') ### print("model loaded")
_____no_output_____
MIT
11. Recurrent Neural Networks - Python.ipynb
AnneliesseMorales/ms-learn-ml-crash-course-python
Step 6-------Now let's use this model to generate some new text! Replace `` with `'Data/Arthur tales.txt'`
### # REPLACE <addFilePath> BELOW WITH 'Data/Arthur tales.txt' (INCLUDING THE QUOTATION MARKS) ### text = io.open(<addFilePath>, encoding='UTF-8').read() ### # Cut out punctuation and make lower case text = text.lower().translate(str.maketrans("", "", string.punctuation)) # Character index dictionary charset = sorted...
_____no_output_____
MIT
11. Recurrent Neural Networks - Python.ipynb
AnneliesseMorales/ms-learn-ml-crash-course-python
In the cell below replace: 1. `` with `50` 2. `` with a sentence of your own, at least 50 characters long. 3. `` with the number of characters you want to generate (choose a large number, like 1500) and then __run the code__.
# Generate text diversity = 0.5 print('\n### Generating text with diversity %0.2f' %(diversity)) ### # REPLACE <sequenceLength> BELOW WITH 50 ### sequence_length = <sequenceLength> ### # Next we'll make a starting point for our text generator ### # REPLACE <writeSentence> WITH A SENTENCE OF AT LEAST 50 CHARACTERS #...
_____no_output_____
MIT
11. Recurrent Neural Networks - Python.ipynb
AnneliesseMorales/ms-learn-ml-crash-course-python
Introduction to Python and Natural Language Technologies__Laboratory 10- NLP applications, Dependency parsing____April 22, 2021__During this laboratory you will have to implement various evaluation methods and use them to measure the performance of pretrained models.
import stanza import spacy from gensim.summarization import summarizer as gensim_summarizer from transformers import pipeline import nltk import conllu import os import numpy as np import requests stanza.download('en') stanza_nlp = stanza.Pipeline('en') spacy_nlp = spacy.load("en_core_web_sm")
_____no_output_____
MIT
assignments/10_NLP_applications_lab.ipynb
bmeaut/python_nlp_2021_spring
Let's download the UD treebanks if you do not have them already. We are going to use them for evaluations.
url = "https://lindat.mff.cuni.cz/repository/xmlui/bitstream/handle/11234/1-3424/ud-treebanks-v2.7.tgz" tgz = 'ud-treebanks-v2.7.tgz' directory = 'ud_treebanks' if not os.path.exists(directory): import tarfile response = requests.get(url, stream=True) with open(tgz, 'wb') as ud: ud.write(response.co...
_____no_output_____
MIT
assignments/10_NLP_applications_lab.ipynb
bmeaut/python_nlp_2021_spring
Evaluation Methods 1. F-scoreProbably the most relevant measure we can use when we are evaluating classifiers.Implement the function below. The function takes two iterables and returns a detailed dictionary that contains the True Positive, True Negative, False Positive, Precision, Recall, F-score values for each uniq...
f_dict = { 0: {'tp': 4, 'fp': 0, 'fn': 0, 'precision': 1.0, 'recall': 1.0, 'f': 1.0}, 1: {'tp': 4, 'fp': 0, 'fn': 0, 'precision': 1.0, 'recall': 1.0, 'f': 1.0}, 2: {'tp': 4, 'fp': 0, 'fn': 0, 'precision': 1.0, 'recall': 1.0, 'f': 1.0}, 'MICRO AVG': {'precision': 1.0, 'recall': 1.0, 'f': 1.0}, 'M...
_____no_output_____
MIT
assignments/10_NLP_applications_lab.ipynb
bmeaut/python_nlp_2021_spring
1.1 Evaluate a pretrained POS tagger using the exampleChoose an existing POS tagger (eg. stanza, spacy, nltk) and predict the POS tags of the sentence given below. Compare the results to the refference below using the f_score function above. Keep in mind, that there are different POS formats, and you should compare th...
sentence = trees[0].metadata["text"] upos = [token['upos'] for token in trees[0]] xpos = [token['xpos'] for token in trees[0]] print(f'{sentence}\n{upos}\n{xpos}') # Your solution here
_____no_output_____
MIT
assignments/10_NLP_applications_lab.ipynb
bmeaut/python_nlp_2021_spring
2. ROUGE-N scoreWe usually use the ROUGE score to evaluate summaries, comparing the reference summaries and the generated summaries. Write a function that gets a reference summary, a generated summary and a number N. The number represents the length of n-grams to compare. The function should return a dictionary contai...
n2 = {'precision': 0.75, 'recall': 0.6, 'f': 0.6666666666666665} def get_ngram(text, n): raise NotImplementedError() def rouge_n(reference, generated, n): raise NotImplementedError() reference = 'this cat is absoultely adorable today' generated = 'this cat is adorable today' assert n2 == rouge_n(reference, ge...
_____no_output_____
MIT
assignments/10_NLP_applications_lab.ipynb
bmeaut/python_nlp_2021_spring
2.1 Evaluate a pretraied summarizer using the exampleChoose a summarizer (eg. gensim, huggingface) and summarize the following text (taken from the [CNN-Daily Mail dataset](https://cs.nyu.edu/~kcho/DMQA/)) and calculate the ROUGE-2 score of the summary.
article = """Manchester City starlet Devante Cole, son of Andy Cole, has joined Barnsley on loan until January. City have also confirmed that £3m midfielder Bruno Zuculini has joined Valencia on loan for the rest of the season.  Meanwhile Juventus and Roma remain keen on signing Matija Nastasic. On the move: Manchester...
_____no_output_____
MIT
assignments/10_NLP_applications_lab.ipynb
bmeaut/python_nlp_2021_spring
3. Dependency parse evaluationWe've discussed the two methods used to evaluate dependency parsers.Reminder: - Labeled attachment score (LAS): the percentage of words that are assigned both the correct syntactic head and the correct dependency label - Unlabeled attachment score (UAS): the percentage of words that are a...
def convert_conllu(tree): return {token['id']: (token['head'], token['deprel']) for token in tree} reference_graph = convert_conllu(trees[0]) reference_graph pred = {1: (0, 'root'), 2: (1, 'punct'), 3: (1, 'flat'), 4: (1, 'punct'), 5: (6, 'amod'), 6: (7, 'obj'), 7: (1, 'parataxis'), 8: (7, 'obj'), 9: (8, 'f...
_____no_output_____
MIT
assignments/10_NLP_applications_lab.ipynb
bmeaut/python_nlp_2021_spring
3.2 LAS methodImplement the LAS method as well, similarly to the previous evaluation script.
def las(gold, predicted): raise NotImplementedError() assert 26/29 == uas(reference_graph, pred) assert 24/29 == las(reference_graph, pred)
_____no_output_____
MIT
assignments/10_NLP_applications_lab.ipynb
bmeaut/python_nlp_2021_spring
================ PASSING LEVEL ==================== 3.3 Try out the evaluation methods with stanzaEvaluate the predictions of stanza on the given example! To do so, you will have to convert the output of stanza to be in the same format as the expected input of the uas and las methods. We recomend the stanza [document...
def stanza_converter(stanza_doc): raise NotImplementedError() # Your solution here
_____no_output_____
MIT
assignments/10_NLP_applications_lab.ipynb
bmeaut/python_nlp_2021_spring
3.4 Compare the accuracy of stanza and spacyRun the spacy dependency parser on the same input as before and evaluate the performace. To do so you will have to implement a function, that converts the output of spacy (see the [documentation](https://spacy.io/usage/linguistic-featuresdependency-parse)) to the appropriate...
def spacy_converter(spacy_doc): raise NotImplementedError() # Your solution here
_____no_output_____
MIT
assignments/10_NLP_applications_lab.ipynb
bmeaut/python_nlp_2021_spring
Construction
import numpy as np import matplotlib.pyplot as plt import seaborn as sns def sign(x): return (-1)**(x < 0) def make_standard(X): means = X.mean(0) stds = X.std(0) return (X - means)/stds class RegularizedRegression: def __init__(self, name = None): self.name = name def rec...
_____no_output_____
MIT
content/c2/.ipynb_checkpoints/construction-checkpoint.ipynb
JeffFessler/mlbook
PROBLEM 1 INTRODUCTION
#Say "Hello, World!" With Python print("Hello, World!") #Python If-Else #!/bin/python3 import math import os import random import re import sys if __name__ == '__main__': n = int(input().strip()) if 1 <= n <= 100: if n % 2 != 0 or (n % 2 == 0 and 6<=n<=20): print("Weird") elif n % 2 == 0 and (2<...
_____no_output_____
MIT
scripts.ipynb
giuliacasale/homework1
BASIC DATA TYPES
# List Comprehension if __name__ == '__main__': x = int(input()) y = int(input()) z = int(input()) n = int(input()) lista = [[i,j,k] for i in range(0,x+1) for j in range(0,y+1) for k in range(0,z+1) if i+j+k != n] print(lista) #Find the runner up score! if __name__ == '__main__': n = int(input()...
_____no_output_____
MIT
scripts.ipynb
giuliacasale/homework1
STRINGS
#sWAP cASE def swap_case(s): new = '' for char in s: if char.isupper(): new += char.lower() elif char.islower(): new += char.upper() else: new += char return new if __name__ == '__main__': s = input() result = swap_case(s) print(resul...
_____no_output_____
MIT
scripts.ipynb
giuliacasale/homework1
SETS
#Introduction to sets def average(array): # your code goes here if 1<=len(array)<=100: somma = 0 array1 = [] for elem in array: if elem not in array1: array1.append(elem) somma += elem average = somma/len(array1) return average...
_____no_output_____
MIT
scripts.ipynb
giuliacasale/homework1
COLLECTIONS
#collections.Counter() # Enter your code here. Read input from STDIN. Print output to STDOUT from collections import Counter X = int(input()) #number of shoes shoe_sizes = list(map(int,input().split())) N = int(input()) #number of customers shoe_sizes = Counter(shoe_sizes) total = 0 if 0<X<10**3 and 0<N<=10**3...
_____no_output_____
MIT
scripts.ipynb
giuliacasale/homework1
DATE AND TIME
#Calendar Module # Enter your code here. Read input from STDIN. Print output to STDOUT import calendar month,day,year = map(int,input().split()) if 2000<year<3000: weekdays = ['MONDAY','TUESDAY','WEDNESDAY','THURSDAY','FRIDAY','SATURDAY','SUNDAY'] weekday = calendar.weekday(year,month,day) print(weekdays[...
_____no_output_____
MIT
scripts.ipynb
giuliacasale/homework1
EXCEPTIONS
#Exceptions # Enter your code here. Read input from STDIN. Print output to STDOUT t = int(input()) if 0<t<10: for i in range(t): values = list(input().split()) try: division = int(values[0])//int(values[1]) print(division) except ZeroDivisionError as e: ...
_____no_output_____
MIT
scripts.ipynb
giuliacasale/homework1
BUILT-INS
#Zipped! # Enter your code here. Read input from STDIN. Print output to STDOUT num_students, num_subjects = map(int,input().split()) mark_sheet = [] for i in range(num_subjects): mark_sheet.append(map(float, input().split(' '))) for grades in zip(*mark_sheet): somma = sum(grades) print(somma/num_subjects...
_____no_output_____
MIT
scripts.ipynb
giuliacasale/homework1
PYTHON FUNCTIONALS
#Map and Lambda Functions cube = lambda x: x**3 # complete the lambda function def fibonacci(n): # return a list of fibonacci numbers serie = [] if 0<=n<=15: if n == 1: serie = [0] if n > 1: serie = [0, 1] for i in range(1,n-1): serie.ap...
_____no_output_____
MIT
scripts.ipynb
giuliacasale/homework1
REGEX AND PARSING
#Detect Floating Point Number # Enter your code here. Read input from STDIN. Print output to STDOUT import re t = int(input()) if 0<t<10: for i in range(t): test_case = input() print(bool(re.search(r"^[+-/.]?[0-9]*\.[0-9]+$",test_case))) #Re.split() regex_pattern = r"[,.]" # Do not delete 'r'. ...
_____no_output_____
MIT
scripts.ipynb
giuliacasale/homework1
XML
#XML 1 - Find the score import sys import xml.etree.ElementTree as etree def get_attr_number(node): # your code goes here somma = 0 for elem in node.iter(): diz = elem.attrib somma += len(diz) return somma if __name__ == '__main__': sys.stdin.readline() xml = sys.stdin.read() ...
_____no_output_____
MIT
scripts.ipynb
giuliacasale/homework1
CLOSURES AND DECORATIONS
#Standardize Mobile Number Using Decorators import re def wrapper(f): def fun(l): # complete the function lista = [] for elem in l: if len(elem) == 10: lista.append('+91'+' '+str(elem[0:5]+ ' '+str(elem[5:]))) elif len(elem) == 11: li...
_____no_output_____
MIT
scripts.ipynb
giuliacasale/homework1
NUMPY
#Arrays import numpy def arrays(arr): # complete this function # use numpy.array arr.reverse() return numpy.array(arr, float) arr = input().strip().split(' ') result = arrays(arr) print(result) #Shape and Reshape import numpy x = list(map(int,input().split())) my_array = numpy.array(x) print(nump...
_____no_output_____
MIT
scripts.ipynb
giuliacasale/homework1
PROBLEM 2
#Birthday Cake Candles #!/bin/python3 import math import os import random import re import sys # # Complete the 'birthdayCakeCandles' function below. # # The function is expected to return an INTEGER. # The function accepts INTEGER_ARRAY candles as parameter. # def birthdayCakeCandles(candles): # Write your cod...
_____no_output_____
MIT
scripts.ipynb
giuliacasale/homework1
PRACTICA DE PREDICCION DE SERIES DE TIEMPO CON TENSORFLOW 1. Cargue Librerias y Data Set
# Cargamos las librerias necesarias para el analisis import os import datetime import IPython import IPython.display import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns import tensorflow as tf mpl.rcParams['figure.figsize'] = (8, 6) mpl.rcParams['axes...
Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/jena_climate_2009_2016.csv.zip 13574144/13568290 [==============================] - 0s 0us/step
MIT
Aprendizaje_Time_Series_con_Deep_Learning.ipynb
diegojeda/AdvancedMethodsDataAnalysisClass
2. Limpieza y Preparacion De Datos
df = pd.read_csv(csv_path) df.head() # Ya que el registro esta cada 10 minutos, tomaremos solo el valor correspondiente al valor final de la hora, para tener solo un valor por hora df = pd.read_csv(csv_path) # slice [start:stop:step], starting from index 5 take every 6th record. df = df[5::6] # Convertimos la colum...
_____no_output_____
MIT
Aprendizaje_Time_Series_con_Deep_Learning.ipynb
diegojeda/AdvancedMethodsDataAnalysisClass
Podemos observar que las variables de "wv (m/s)" y "max. wv (m/s)" tienen valors minimos anomalos, estos deben ser erroneos, procederemos a imputarlos con cero.
wv = df['wv (m/s)'] bad_wv = wv == -9999.0 wv[bad_wv] = 0.0 max_wv = df['max. wv (m/s)'] bad_max_wv = max_wv == -9999.0 max_wv[bad_max_wv] = 0.0 df['wv (m/s)'].min()
_____no_output_____
MIT
Aprendizaje_Time_Series_con_Deep_Learning.ipynb
diegojeda/AdvancedMethodsDataAnalysisClass
La ultima variable "wd (deg)" nos indica la direccion del viento en grados. Sin embargo, los grados no son un buen input para el modelo. En este caso las limitaciones son las siguientes:- 0° y 360° deberian estar cerca y cerrarse, eso no se puede apreciar.- Si no hay velocidad del viento, la direccion no debería import...
plt.hist2d(df['wd (deg)'], df['wv (m/s)'], bins=(50, 50), vmax=400) plt.colorbar() plt.xlabel('Wind Direction [deg]') plt.ylabel('Wind Velocity [m/s]');
_____no_output_____
MIT
Aprendizaje_Time_Series_con_Deep_Learning.ipynb
diegojeda/AdvancedMethodsDataAnalysisClass
Para solventar estas dificultadades, convertiremos la direccion y la magnitud de la velocidad del viento en vectores, una medida mas representativa
wv = df.pop('wv (m/s)') max_wv = df.pop('max. wv (m/s)') # Convert to radians. wd_rad = df.pop('wd (deg)')*np.pi / 180 # Calculate the wind x and y components. df['Wx'] = wv*np.cos(wd_rad) df['Wy'] = wv*np.sin(wd_rad) # Calculate the max wind x and y components. df['max Wx'] = max_wv*np.cos(wd_rad) df['max Wy'] = ma...
_____no_output_____
MIT
Aprendizaje_Time_Series_con_Deep_Learning.ipynb
diegojeda/AdvancedMethodsDataAnalysisClass
Revisaremos la distribucion de los componentes de cada vector
plt.hist2d(df['Wx'], df['Wy'], bins=(50, 50), vmax=400) plt.colorbar() plt.xlabel('Wind X [m/s]') plt.ylabel('Wind Y [m/s]') ax = plt.gca() ax.axis('tight') # Transformaremos la fecha a segundos para revisar periodicidiad timestamp_s = date_time.map(datetime.datetime.timestamp) # Definimos los segundos que tiene un di...
_____no_output_____
MIT
Aprendizaje_Time_Series_con_Deep_Learning.ipynb
diegojeda/AdvancedMethodsDataAnalysisClass
Podemos evidenciar que los dos picos se presentan en 1/año y 1/dia, lo que corrobora nuestras suposiciones.
df.head()
_____no_output_____
MIT
Aprendizaje_Time_Series_con_Deep_Learning.ipynb
diegojeda/AdvancedMethodsDataAnalysisClass
3. Split De Los DatosDividiremos los datos de la siguiente manera:- Entrenamiento: 70%- Validacion: 20%- Prueba: 10%
column_indices = {name: i for i, name in enumerate(df.columns)} n = len(df) train_df = df[0:int(n*0.7)] val_df = df[int(n*0.7):int(n*0.9)] test_df = df[int(n*0.9):] num_features = df.shape[1]
_____no_output_____
MIT
Aprendizaje_Time_Series_con_Deep_Learning.ipynb
diegojeda/AdvancedMethodsDataAnalysisClass
4. Normalizacion De Los Datos
# Normalizaremos los conjuntos de entrenamiento, validacion y prueba train_mean = train_df.mean() train_std = train_df.std() train_df = (train_df - train_mean) / train_std val_df = (val_df - train_mean) / train_std test_df = (test_df - train_mean) / train_std df_std = (df - train_mean) / train_std df_std = df_std.melt...
_____no_output_____
MIT
Aprendizaje_Time_Series_con_Deep_Learning.ipynb
diegojeda/AdvancedMethodsDataAnalysisClass
Classification with Python In this notebook we try to practice all the classification algorithms that we learned in this course.We load a dataset using Pandas library, and apply the following algorithms, and find the best one for this specific dataset by accuracy evaluation methods.Lets first load required libraries:
import itertools import numpy as np import matplotlib.pyplot as plt from matplotlib.ticker import NullFormatter import pandas as pd import numpy as np import matplotlib.ticker as ticker from sklearn import preprocessing %matplotlib inline
_____no_output_____
MIT
Coursera/IBM Python 01/Course02/ML Python Sharing.ipynb
brianshen1990/KeepLearning
About dataset This dataset is about past loans. The __Loan_train.csv__ data set includes details of 346 customers whose loan are already paid off or defaulted. It includes following fields:| Field | Description ||----------------|------...
!wget -O loan_train.csv https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/ML0101ENv3/labs/loan_train.csv
--2020-05-22 14:48:38-- https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/ML0101ENv3/labs/loan_train.csv Resolving s3-api.us-geo.objectstorage.softlayer.net (s3-api.us-geo.objectstorage.softlayer.net)... 67.228.254.196 Connecting to s3-api.us-geo.objectstorage.softlayer.net (s3-api.us-ge...
MIT
Coursera/IBM Python 01/Course02/ML Python Sharing.ipynb
brianshen1990/KeepLearning
Load Data From CSV File
df = pd.read_csv('loan_train.csv') df.head() df.shape
_____no_output_____
MIT
Coursera/IBM Python 01/Course02/ML Python Sharing.ipynb
brianshen1990/KeepLearning
Convert to date time object
df['due_date'] = pd.to_datetime(df['due_date']) df['effective_date'] = pd.to_datetime(df['effective_date']) df.head()
_____no_output_____
MIT
Coursera/IBM Python 01/Course02/ML Python Sharing.ipynb
brianshen1990/KeepLearning
Data visualization and pre-processing Let’s see how many of each class is in our data set
df['loan_status'].value_counts()
_____no_output_____
MIT
Coursera/IBM Python 01/Course02/ML Python Sharing.ipynb
brianshen1990/KeepLearning
260 people have paid off the loan on time while 86 have gone into collection Lets plot some columns to underestand data better:
# notice: installing seaborn might takes a few minutes !conda install -c anaconda seaborn -y import seaborn as sns bins = np.linspace(df.Principal.min(), df.Principal.max(), 10) g = sns.FacetGrid(df, col="Gender", hue="loan_status", palette="Set1", col_wrap=2) g.map(plt.hist, 'Principal', bins=bins, ec="k") g.axes[-1...
_____no_output_____
MIT
Coursera/IBM Python 01/Course02/ML Python Sharing.ipynb
brianshen1990/KeepLearning
Pre-processing: Feature selection/extraction Lets look at the day of the week people get the loan
df['dayofweek'] = df['effective_date'].dt.dayofweek bins = np.linspace(df.dayofweek.min(), df.dayofweek.max(), 10) g = sns.FacetGrid(df, col="Gender", hue="loan_status", palette="Set1", col_wrap=2) g.map(plt.hist, 'dayofweek', bins=bins, ec="k") g.axes[-1].legend() plt.show()
_____no_output_____
MIT
Coursera/IBM Python 01/Course02/ML Python Sharing.ipynb
brianshen1990/KeepLearning
We see that people who get the loan at the end of the week dont pay it off, so lets use Feature binarization to set a threshold values less then day 4
df['weekend'] = df['dayofweek'].apply(lambda x: 1 if (x>3) else 0) df.head()
_____no_output_____
MIT
Coursera/IBM Python 01/Course02/ML Python Sharing.ipynb
brianshen1990/KeepLearning
Convert Categorical features to numerical values Lets look at gender:
df.groupby(['Gender'])['loan_status'].value_counts(normalize=True)
_____no_output_____
MIT
Coursera/IBM Python 01/Course02/ML Python Sharing.ipynb
brianshen1990/KeepLearning
86 % of female pay there loans while only 73 % of males pay there loan Lets convert male to 0 and female to 1:
df['Gender'].replace(to_replace=['male','female'], value=[0,1],inplace=True) df.head()
_____no_output_____
MIT
Coursera/IBM Python 01/Course02/ML Python Sharing.ipynb
brianshen1990/KeepLearning
One Hot Encoding How about education?
df.groupby(['education'])['loan_status'].value_counts(normalize=True)
_____no_output_____
MIT
Coursera/IBM Python 01/Course02/ML Python Sharing.ipynb
brianshen1990/KeepLearning
Feature befor One Hot Encoding
df[['Principal','terms','age','Gender','education']].head()
_____no_output_____
MIT
Coursera/IBM Python 01/Course02/ML Python Sharing.ipynb
brianshen1990/KeepLearning
Use one hot encoding technique to conver categorical varables to binary variables and append them to the feature Data Frame
Feature = df[['Principal','terms','age','Gender','weekend']] Feature = pd.concat([Feature,pd.get_dummies(df['education'])], axis=1) Feature.drop(['Master or Above'], axis = 1,inplace=True) Feature.head()
_____no_output_____
MIT
Coursera/IBM Python 01/Course02/ML Python Sharing.ipynb
brianshen1990/KeepLearning
Feature selection Lets defind feature sets, X:
X = Feature X[0:5]
_____no_output_____
MIT
Coursera/IBM Python 01/Course02/ML Python Sharing.ipynb
brianshen1990/KeepLearning
What are our lables?
y = df['loan_status'].values y[0:5]
_____no_output_____
MIT
Coursera/IBM Python 01/Course02/ML Python Sharing.ipynb
brianshen1990/KeepLearning
Normalize Data Data Standardization give data zero mean and unit variance (technically should be done after train test split )
X= preprocessing.StandardScaler().fit(X).transform(X) X[0:5]
/opt/conda/envs/Python36/lib/python3.6/site-packages/sklearn/preprocessing/data.py:645: DataConversionWarning: Data with input dtype uint8, int64 were all converted to float64 by StandardScaler. return self.partial_fit(X, y) /opt/conda/envs/Python36/lib/python3.6/site-packages/ipykernel/__main__.py:1: DataConversionW...
MIT
Coursera/IBM Python 01/Course02/ML Python Sharing.ipynb
brianshen1990/KeepLearning
Classification Now, it is your turn, use the training set to build an accurate model. Then use the test set to report the accuracy of the modelYou should use the following algorithm:- K Nearest Neighbor(KNN)- Decision Tree- Support Vector Machine- Logistic Regression__ Notice:__ - You can go above and change the pre-...
from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=4) print ('Train set:', X_train.shape, y_train.shape) print ('Test set:', X_test.shape, y_test.shape)
Train set: (276, 8) (276,) Test set: (70, 8) (70,)
MIT
Coursera/IBM Python 01/Course02/ML Python Sharing.ipynb
brianshen1990/KeepLearning
Calculate the best K among 1 to 15and plot the result to select
from sklearn.neighbors import KNeighborsClassifier from sklearn import metrics Ks = 15 mean_acc = np.zeros((Ks-1)) std_acc = np.zeros((Ks-1)) ConfustionMx = []; for n in range(1,Ks): #Train Model and Predict neigh = KNeighborsClassifier(n_neighbors = n).fit(X_train,y_train) yhat=neigh.predict(X_test)...
_____no_output_____
MIT
Coursera/IBM Python 01/Course02/ML Python Sharing.ipynb
brianshen1990/KeepLearning
The answerIt seems k = 7 gives the best accuracy Decision Tree Train set adn Test SetJust use the previous one~ And use Decision Tree to build the model (max_depeth from1 - 10 , why? There are only less than 10 kinds of attributes )
from sklearn.tree import DecisionTreeClassifier from sklearn import metrics import matplotlib.pyplot as plt Ks = 10 acc = np.zeros((Ks-1)) for n in range(1,Ks): drugTree = DecisionTreeClassifier(criterion="entropy", max_depth = n) drugTree # it shows the default parameters drugTree.fit(X_train,y_train) ...
_____no_output_____
MIT
Coursera/IBM Python 01/Course02/ML Python Sharing.ipynb
brianshen1990/KeepLearning
And we will use depth 6 with decision tree.??? Why 1 to 2 gives this results? Support Vector Machine Data pre-processing and selectionFor SVM, treat as numbers
Feature.dtypes feature_df = Feature[['Principal', 'terms', 'age', 'Gender', 'weekend', 'Bechalor', 'High School or Below', 'college']] X_SVM = np.asarray(feature_df) X_SVM[0:5] Y_Feature = [ 1 if i == "PAIDOFF" else 0 for i in df['loan_status'].values] y_SVM = np.asarray(Y_Feature) y_SVM [0:5]
_____no_output_____
MIT
Coursera/IBM Python 01/Course02/ML Python Sharing.ipynb
brianshen1990/KeepLearning
Train and Test dataSplit
X_train_SVM, X_test_SVM, y_train_SVM, y_test_SVM = train_test_split( X_SVM, y_SVM, test_size=0.2, random_state=4) print ('Train set:', X_train_SVM.shape, y_train_SVM.shape) print ('Test set:', X_test_SVM.shape, y_test_SVM.shape)
Train set: (276, 8) (276,) Test set: (70, 8) (70,)
MIT
Coursera/IBM Python 01/Course02/ML Python Sharing.ipynb
brianshen1990/KeepLearning