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
Test on a random sample of accounts
# get a random sample of accounts to look at import os import random accounts = {"charity": [], "company_ixbrl": [], "company_pdf": []} for a in os.listdir("accounts"): if a.startswith("GB-CHC"): accounts["charity"].append(a) elif a.startswith("GB-COH"): if a.endswith(".html"): accou...
_____no_output_____
MIT
2b-pdf-plumber.ipynb
drkane/pdf-accounts
ํ…Œ์ด๋ธ” ๋ฐ์ดํ„ฐ ํ™•์ธ COURSES
courses.head()
_____no_output_____
CC-BY-4.0
0_table data EDA.ipynb
springkind/OULAD
courses ๋ฐ์ดํ„ฐ์—์„œ๋Š” ์‹œ์ž‘ ํ•™๊ธฐ์—๋”ฐ๋ผ B(2์›” ์‹œ์ž‘), J(10์›” ์‹œ์ž‘)๋ฅผ code_presentation์— ๋ถ™์ธ๋‹ค.\๊ฐ™์€ ๊ฐ•์ขŒ๋ผ๋„ ํ•™๊ธฐ๋ณ„๋กœ ๊ตฌ์กฐ๋‚˜ ์„ธ๋ถ€ ๋‚ด์šฉ์ด ๋‹ค๋ฅผ ์ˆ˜ ์žˆ๊ธฐ ๋•Œ๋ฌธ์— ๋”ฐ๋กœ ๋ถ„๋ฆฌํ•ด์„œ ๋ด์•ผํ•˜๋Š”๋ฐ,\code_module์ด CCC, EEE, GGG์ธ ์ฝ”์Šค์˜ ๊ฒฝ์šฐ ์ด์ „ ๊ธฐ์ˆ˜ B, J ์ˆ˜๊ฐ• ๋‚ด์—ญ์ด ์—†๋Š” ๋ฐ์ดํ„ฐ๋กœ ์ด๋ฃจ์–ด์ ธ ์žˆ๋‹ค.
courses[courses['code_module'] == 'CCC']
_____no_output_____
CC-BY-4.0
0_table data EDA.ipynb
springkind/OULAD
ASSESSMENTS ๊ฐ•์ขŒ๋งˆ๋‹ค ํ•™๊ธฐ๋ณ„๋กœ ๋‚˜๊ฐ„ ๊ณผ์ œ์— ๋Œ€ํ•œ ์ •๋ณด.\๋ชจ๋“  ๊ฐ•์ขŒ๋Š” ๋ช‡๊ฐ€์ง€ ๊ณผ์ œ ํ›„ ๊ธฐ๋ง ์‹œํ—˜์„ ์น˜๋ฅด๊ฒŒ ๋œ๋‹ค.- **date** : ์ œ์ถœ์ผ. module-presentation์ด ์‹œ์ž‘๋œ ๋‚ ์งœ ๊ธฐ์ค€ 0์ผ ๋ถ€ํ„ฐ ์‹œ์ž‘. ๊ธฐ๋ง๊ณ ์‚ฌ์˜ date ๊ฐ’์ด ๊ฒฐ์ธก์น˜์ผ ๊ฒฝ์šฐ presentation์˜ ๋งˆ์ง€๋ง‰ week์ž„.- **weight** : ๊ณผ์ œ ๋น„์œจ. Exam์€ ๊ณผ์ œ์™€ ๋ณ„๊ฐœ๋กœ ๋‹ค๋ค„์ง€๊ธฐ ๋•Œ๋ฌธ์— 100%๋กœ ํ‘œ๊ธฐ๋œ๋‹ค. Exam ์ด์™ธ์˜ assessments์˜ weight๋ฅผ ๋ชจ๋‘ ํ•ฉํ•˜๋ฉด 100%๊ฐ€ ๋จ.- **assessment_type** : - Tutor Marked Ass...
assessments.head()
_____no_output_____
CC-BY-4.0
0_table data EDA.ipynb
springkind/OULAD
VLE ์˜จ๋ผ์ธ ํ•™์Šต ํ™˜๊ฒฝ์˜ html page, pdf ํŒŒ์ผ ๋“ฑ์˜ ์ •๋ณด. ๋ฆฌ์†Œ์Šค? ํ•™์Šต์šฉ meterial.- **week_from ~ week_to** : ๋ช‡์ฃผ๋ถ€ํ„ฐ ๋ช‡์ฃผ๊นŒ์ง€ ํ•ด๋‹น meterials๋ฅผ ํ•™์Šตํ•˜๋„๋ก ์„ค๊ณ„๋˜์–ด์žˆ๋Š”์ง€.
vle.head() vle[vle['week_from'].notna()].head()
_____no_output_____
CC-BY-4.0
0_table data EDA.ipynb
springkind/OULAD
studentInfo - **imd_band** : ์ง€์—ญ๋ณ„ ๊ฒฐํ•(๋นˆ๊ณค) ์ง€์ˆ˜. ์†Œ๋“, ๊ณ ์šฉ, ๊ต์œก, ๊ฑด๊ฐ•, ๋ฒ”์ฃ„ ๋“ฑ์œผ๋กœ ๊ณ„์‚ฐ๋จ.\https://en.wikipedia.org/wiki/Multiple_deprivation_index
studentInfo.head()
_____no_output_____
CC-BY-4.0
0_table data EDA.ipynb
springkind/OULAD
studentRegistration module-presentation ๋“ฑ๋ก ๋ฐ์ดํ„ฐ. module-presentation์ด ์‹œ์ž‘๋œ ์‹œ์ ๊ณผ ์—ฐ๊ด€์ด ์žˆ๋‹ค.- **date_registration** : ๋“ฑ๋ก์ผ์ž. -30์ธ ๊ฒฝ์šฐ ํ•ด๋‹น ์ˆ˜๊ฐ•์ƒ์ด module-presentation์ด ์‹œ์ž‘๋˜๊ธฐ 30์ผ ์ „์— ๋“ฑ๋กํ•œ ๊ฒƒ.- **date_unregistration** : ์ˆ˜๊ฐ•์ทจ์†Œ๋ฅผ ํ•œ ๊ฒฝ์šฐ ๊ธฐ๋ก๋จ. 12์ธ ๊ฒฝ์šฐ module-presentation์ด ์‹œ์ž‘๋œ ํ›„ 12์ผ ํ›„์— ๋“ฑ๋ก ์ทจ์†Œํ•œ ๊ฒƒ. ๋นˆ๊ฐ’์ผ ๊ฒฝ์šฐ ์ˆ˜๊ฐ•์„ ๋๊นŒ์ง€ ์ž˜ ๋งˆ์นœ ๊ฒƒ.date_unregistration์ด ๋นˆ ๊ฐ’์ด ์•„๋‹ ๊ฒฝ์šฐ...
studentRegistration.head() studentRegistration[studentRegistration['date_unregistration'].notna()].head()
_____no_output_____
CC-BY-4.0
0_table data EDA.ipynb
springkind/OULAD
studentAssessment ๊ณผ์ œ ์ œ์ถœ ํ˜„ํ™ฉ.๊ณผ์ œ๋ฅผ ์ œ์ถœ ์•ˆํ•œ ๊ฒฝ์šฐ ๊ธฐ๋ก๋˜์ง€ ์•Š๋Š”๋‹ค.\๋งŒ์•ฝ ๊ณผ์ œ ๊ฒฐ๊ณผ๊ฐ€ ์‹œ์Šคํ…œ์—์„œ ๋ˆ„๋ฝ๋  ๊ฒฝ์šฐ ๊ธฐ๋ง๊ณ ์‚ฌ ์ œ์ถœ๋‚ด์—ญ์€ ๊ธฐ๋ก๋˜์ง€ ์•Š์Œ.- **date_submitted** : module-presentation ์‹œ์ž‘ ๋‚ ์งœ ๊ธฐ์ค€, ์ œ์ถœ์ผ.- **is_banked** : a status flag indicating that the assessment result has been transferred from a previous presentation.(์ด์ „ presentation๊ณผ ์—ฐ๊ด€์„ฑ์ด ์žˆ๋Š”์ง€?)- **score** : 0 ~ 100...
studentAssessment.head()
_____no_output_____
CC-BY-4.0
0_table data EDA.ipynb
springkind/OULAD
studentVle ํ•™์ƒ๋“ค์ด VLE์™€ ์ƒํ˜ธ์ž‘์šฉํ•œ ๋ฐ์ดํ„ฐ.- **id_site** : VLE meterial id.- **date** : module-presentation ์‹œ์ž‘ ๋‚ ์งœ ๊ธฐ์ค€, ์ด๋ฒคํŠธ ๋‚ ์งœ.- **sum_click** : ํ•ด๋‹น ๋‚ ์งœ์— ์žˆ์—ˆ๋˜ ํด๋ฆญ ์ˆ˜ ์ง‘๊ณ„.
studentVle.head()
_____no_output_____
CC-BY-4.0
0_table data EDA.ipynb
springkind/OULAD
$$\dot{x}+c{x}=0$$$$V(x)=\frac{1}{2}{x^2}$$
def f(x,t): dx=-x return dx #t = np.linspace(0,20,200) t=np.arange(0,3,.1) x0=-.0043 ys=odeint(f,x0,t) plt.plot(t,ys[:,0])
_____no_output_____
MIT
Apuntes de clases/b04_Clase 13 de marzo_Sistemas de control.ipynb
AlexRojas06/Trabajos_realizados_en_clase
$$\dot{x_1}=-x_1$$$$\dot{x_2}=-2x_2$$$$V(x)=\frac{1}{2}{x^2}$$$$\dot{V}(x) = {x}\dot{x} = [x_1,x_2][{\dot{x}_1}{\dot{x}_2}]^T=x_1\dot{x}_1+x_2\dot{x}_2$$$$\dot{V}(x_1,x_2)=-{x_1}^2-2{x_2}^2$$
def f(x,t): x1,x2=x dx1=-x1 dx2=-2*x2 return [dx1,dx2] #t=np.linspace(0,20,200) t=np.arange(0,3,.1) x0=[4,4] ys=odeint(f,x0,t) y1=np.linspace(-8.0,8.0,20) y2=np.linspace(-8.0,8.0,20) X,Y=np.meshgrid(y1,y2) U,V=f([X,Y],0) plt.figure(figsize=(9,8)) Q=plt.quiver(X,Y,U,V,color='r') plt.plot(ys[:,0],ys[:,1...
_____no_output_____
MIT
Apuntes de clases/b04_Clase 13 de marzo_Sistemas de control.ipynb
AlexRojas06/Trabajos_realizados_en_clase
Mulitscale segregation measures using a KL-divergence based method This is an example notebook to demonstrate the use of this particular python module, segregation_distortion. This particular module from the distortion library can be used to calculate similar variations of a segregation measure, the distortion index o...
#change indexes names and add a quick description of why the index is useful. #unit testing for the class framework #GIO interface for uploading data and plotting the map #make a script for command line from divergence import segregation_distortion as seg import geopandas as gdp import pandas import itertools as it im...
_____no_output_____
MIT
example_distortion.ipynb
ceciledebezenac/segregation_index
Read in and analyse the dataNow let's actually read in some data to work with. The module is designed to run with any geolocated data, provided categorial variables are included as well as a geometry columns used by python for plotting and neighbourhood attribution. We will work with 1950 census data from Chicago. Thi...
geochicago=gdp.read_file('/Users/cdebezenac/Documents/chicago_segregation/data/chicago1950.shp')
_____no_output_____
MIT
example_distortion.ipynb
ceciledebezenac/segregation_index
We will want to get a better look at the raw data (although this set has already been cleaned up a bit) to check for empty, redundant cells or any other flaw that could make running our code difficult.
print('There are ' + str(len(geochicago))+' tracts in Chicago.\n\n',geochicago.head(),geochicago.columns)
There are 937 tracts in Chicago. GISJOIN2 SHAPE_AREA TRACT B0E001 B0E002 B0E003 B0E004 B0E005 \ 0 17003100846 2.614179e+06 0846 460 150 105 110 175 1 17003100867 3.333835e+05 0867 35 35 15 30 85 2 17003100865 6.513552e+05 0865 125 55 ...
MIT
example_distortion.ipynb
ceciledebezenac/segregation_index
After a quick look at the variable dictionary, we can start to understand the data. The first columns represent administrative code for the area, the 'B0...' columns are attributed to income groups and the 'White','Nonwhite','Negro' represent the ethnic affiliation count in each tract. We note that 'Nonwhite' accounts ...
#seperate other from black geochicago['Other']=geochicago['Nonwhite']-geochicago['Negro'] geochicago['% Other']=geochicago['% Nonwhite']-geochicago['% Negro'] #rename a column geochicago.rename(columns={'Negro':'Black'},inplace=True)
_____no_output_____
MIT
example_distortion.ipynb
ceciledebezenac/segregation_index
Create the city framework for segregation analysisLet's now initialise our divergence object used as a city frame for the calculation of the indices. If we want to calculate the local indices for one single unit, we create an instance of the class LocalDivergenceProfile. If we wish to compare measures over all tracts,...
distortion_chicago=seg.DivergenceProfiles(geochicago,['White','Black','Other'])
14 spatial units have been left out because of null values over all groups. Check your data or continue.
MIT
example_distortion.ipynb
ceciledebezenac/segregation_index
Initialise the neighbourhood structure to compute the divergence profilesThe max_distortion index and the excepted_divergence indices are both spatial. Therefore, before calculating anything (see help(LocalDivergenceProfile) for detailed computation of indices) we will need to set up a neighbourhood structure with the...
%time distortion_chicago.set_neighbourhood(path='euclidean')
CPU times: user 12.9 s, sys: 9.62 ms, total: 12.9 s Wall time: 12.9 s
MIT
example_distortion.ipynb
ceciledebezenac/segregation_index
Once the structure is known, the bulk of the work is done! The rest is numpy array operations on population counts (see divergence documentation for more detail). Setting the KL divergence profiles for all 937 units will only take a few seconds more!
%time distortion_chicago.set_profiles()
CPU times: user 6.93 s, sys: 16.8 ms, total: 6.95 s Wall time: 6.95 s
MIT
example_distortion.ipynb
ceciledebezenac/segregation_index
Update the dataNow we could use the raw data included in the DivergenceProfiles object, but we would rather use something we can actually plot easily using the basic geopandas library. So let's update the dataframe we fed into the city object and add columns representing the local variables and check if realistic indi...
distortion_chicago.update_data() #distortion_chicago.dataframe.head()
_____no_output_____
MIT
example_distortion.ipynb
ceciledebezenac/segregation_index
View the resultsEssentially, what the algorithm is doing to compute the local indices is summarise local profiles (described in the divergence documentation: max_index will average the superiour envelope of the profile). These trajectories can hide very relevant information on segregation as well as geographic pattern...
distortion_chicago.plot_profiles([i for i in range(920)],(10,6)) #isolate fewer profiles, here the profile of the unit indexed by 0: distortion_chicago.plot_profiles([0],(10,6))
_____no_output_____
MIT
example_distortion.ipynb
ceciledebezenac/segregation_index
Index distributionAnother good way of getting a quick look at the results is to plot the distribution of the indices into histograms available with maplotlib. We will try to plot something a litle nicer than the default python plot and save it on to our computer. This is done with the plot_distribution() method of the...
distortion_chicago.plot_distribution(variable='max_index')
_____no_output_____
MIT
example_distortion.ipynb
ceciledebezenac/segregation_index
Spatial representation: Chicago mapThe most interesting attribute of local segregation measures are that you can plot them on to the map of the city using the plot_map() method.
distortion_chicago.plot_map(variable='max_index_normal')
_____no_output_____
MIT
example_distortion.ipynb
ceciledebezenac/segregation_index
From this map, we can analyse the segregration trend in Chicago. The red tracts are those that have a high normalised distortion index. The most extreme values reach 45% of the value of the theoretically most segregated Chicago possible! They are visably all clustered in a middle easter area, where the first community ...
distortion_chicago.save_dataframe('distortion_data_chicago')
_____no_output_____
MIT
example_distortion.ipynb
ceciledebezenac/segregation_index
Default mpg
import pandas as pd from pandas_visual_analysis import VisualAnalysis df = pd.read_csv("https://raw.githubusercontent.com/mwaskom/seaborn-data/master/mpg.csv") VisualAnalysis(df)
_____no_output_____
MIT
tests/notebooks/examples.ipynb
rishigarg94/pandas-visual-analysis
DataSource
from pandas_visual_analysis import VisualAnalysis, DataSource ds = DataSource(df) VisualAnalysis(ds)
_____no_output_____
MIT
tests/notebooks/examples.ipynb
rishigarg94/pandas-visual-analysis
Categorical Columns
VisualAnalysis(df, categorical_columns=["name", "origin", "model_year", "cylinders"])
_____no_output_____
MIT
tests/notebooks/examples.ipynb
rishigarg94/pandas-visual-analysis
Layout
VisualAnalysis(df, layout=[["Scatter", "Scatter"], ["ParallelCoordinates"]])
_____no_output_____
MIT
tests/notebooks/examples.ipynb
rishigarg94/pandas-visual-analysis
Get all Widgets
VisualAnalysis.widgets()
_____no_output_____
MIT
tests/notebooks/examples.ipynb
rishigarg94/pandas-visual-analysis
Neural Network Fundamentals This blog post is a guide to help readers build a neural network from the very basics. It starts with an introduction to the concept of a neural networks concept and its early development. A step-by-step coding tutorial follows, through which relevant concepts are illustrated. Later in the ...
# Load the package to work with numbers: import numpy as np # Determine the structure of the NN: i_n = 3 h_n = 5 o_n = 2
_____no_output_____
MIT
Neural_Network_Fundamentals/1_NN_from_scratch.ipynb
romanarion/InformationSystemsWS1718
**Weights.** In order to transfer an input data point to the next layer, a predetermined number (called weight) is stored in each connection from the sender node to the receiver node. Each weight accounts for the impact between the interconnected nodes.Initially, we assign weights between nodes in neighboring layers ra...
# Randomly define the weights between the layers: w_i_h = np.random.rand(h_n, i_n) # create an array of the given shape and populate it with random values. w_h_o = np.random.rand(o_n, h_n) # Show matrices of randomly assigned weights: w_i_h # w_h_o # uncomment this line in order to see the values for w_h_o. # Use Cmd...
_____no_output_____
MIT
Neural_Network_Fundamentals/1_NN_from_scratch.ipynb
romanarion/InformationSystemsWS1718
**Activation Function.** The remaining element of the NN's structure is an activation function - a function which transforms an input data point that it receives from the previous nodes to an output value which will be the input for the nodes in the next layer. The activation function plays an important role in the eff...
# Determine activation function: def sigmoid(x): # np.exp() calculates the exponential # of all elements in the input array. return 1 / (1 + np.exp(-x)) # Draw activation function: import matplotlib.pyplot as plt # return 100 evenly spaced numbers over an interval from -10 to 10. x = np.linspace(-10, 10,...
_____no_output_____
MIT
Neural_Network_Fundamentals/1_NN_from_scratch.ipynb
romanarion/InformationSystemsWS1718
Data InspectionBy now we have collected all the elements of the NN. Can we use this structure in order to solve the classification problem stated in the beginning? In order to answer this question we need first to get a better understanding of the data at our disposal. We are trying to check whether NN is able to solv...
# Load the data: raw_data = open("data/mnist_train_100.csv", 'r') # "r" stands for "read only" mode. data = raw_data.readlines() # read all the lines of a file in a list. raw_data.close() # remove temporal file from the environment in order to save memory. # Inspect the data - check the number of observations: len(data...
_____no_output_____
MIT
Neural_Network_Fundamentals/1_NN_from_scratch.ipynb
romanarion/InformationSystemsWS1718
* A particular observation looks like a string of 785 elements (label of the image + 784 elements for each pixels of a 28x28 image). * Each element representing a pixel is a number from 0 to 255 (from white to black color).* The first element in the line is the label of the image and therefore is a number from 0 to 9.U...
# Load the package to plot the data: import matplotlib.pyplot as mpp %matplotlib inline # Plot the data: observation = data[0].split(',') # break down observation number 0 (comma is used to identify each element). image = np.asfarray(observation[1:]).reshape((28,28)) # take all the elements starting from the element 1 ...
_____no_output_____
MIT
Neural_Network_Fundamentals/1_NN_from_scratch.ipynb
romanarion/InformationSystemsWS1718
Fitting the structure of the NN to the Data Let's take a look once again at the NN's structure we have created at the beginning of the tutorial. After inspecting the data, we can conclude that the structure with 3-5-2 nodes is probably not optimal and therefore should be updated in order to fit the data we have and p...
# Determine the new structure of the NN: i_n = 784 h_n = 90 o_n = 10
_____no_output_____
MIT
Neural_Network_Fundamentals/1_NN_from_scratch.ipynb
romanarion/InformationSystemsWS1718
As we have new structure of the NN we should reassign the weights - now the size of each weight matrix will increase as we have more nodes in each layer.
# Determine the weights: w_i_h = np.random.rand(h_n, i_n) w_h_o = np.random.rand(o_n, h_n)
_____no_output_____
MIT
Neural_Network_Fundamentals/1_NN_from_scratch.ipynb
romanarion/InformationSystemsWS1718
So far we have not used the first element of our observation - the label. It will be necessary to compare the predictions of the NN to the real state of the world and to train the NN to make correct predictions. The target should therefore have the same shape as the output layer of the NN, so that they could be compara...
# Create target array: target = np.array(np.zeros(o_n), ndmin=2).T target[int(observation[0])] = 1 # int() method returns an integer object from any number or string. # Inspect how the target looks like (remember that the label of observations is 5): target # Show the sizes of matrices of weights, input and target vect...
_____no_output_____
MIT
Neural_Network_Fundamentals/1_NN_from_scratch.ipynb
romanarion/InformationSystemsWS1718
Feedforwarding Once we have the structure of the NN updated for the specific task of classifying the numbers depicted on the images, we can run our network in order to get the first predictions that will be represented by a vector of 10 elements. This vector in its turn can be compared to the target.To run the NN, i.e...
# Calculate the output of hidden and output layers of our NN: h_input = np.dot(w_i_h, input) # dot() performs matrix multiplication; "h_input" stands for "Hidden_Input". h_output = sigmoid(h_input) # "Hidden_Output" - result after activation function. o_input = np.dot(w_h_o, h_output) # "Output_Input" - input used for ...
_____no_output_____
MIT
Neural_Network_Fundamentals/1_NN_from_scratch.ipynb
romanarion/InformationSystemsWS1718
Data treatment good practices Once we check the output of the NN and the results of each performed step, we can observe that already at the stage of the h_output all the data converts to a vector in which all the values are equal to 1. Such a vector does not provide us with any helpful insight. Apparently, something i...
x = np.linspace(-10, 10, 100) plt.plot(x, sigmoid(x)) plt.show()
_____no_output_____
MIT
Neural_Network_Fundamentals/1_NN_from_scratch.ipynb
romanarion/InformationSystemsWS1718
As we can see the output of the sigmoid function will be almost identical once we feed a number bigger than 2. Similarly there is no significant difference between the outputs if numbers used are smaller than -2. Hence the application of sigmoid function to the original data leads to a loss of valuable information. The...
# Good practice transformation of the input values: input = np.array((np.asfarray(observation[1:])/255.0*0.99) + 0.01, ndmin=2).T # Our values in our input vector are in the range from 0 to 255. Therefore we should divide input vector by 255, # multiply it by 0,99 and add 0,01 in order to get values in the range from...
_____no_output_____
MIT
Neural_Network_Fundamentals/1_NN_from_scratch.ipynb
romanarion/InformationSystemsWS1718
**Secondly, we can check our way to randomly assign initial weights:** Let's take a look once at the function we used to randomly assign weights:
np.random.rand(3, 5)
_____no_output_____
MIT
Neural_Network_Fundamentals/1_NN_from_scratch.ipynb
romanarion/InformationSystemsWS1718
As we can see, all the weights are positive, while the actual relationship between the features in the data and the values of the output vector can be negative. Hence, the way we employ to assign random weights should allow for negative weights too.Below there are too alternatives how this can be implemented in Python.
# Good practice for initial weights assignment: alternative1 = np.random.rand(3, 5) - 0.5 # or alternative2 = np.random.normal(0.0, pow(3, -0.5), (3, 5)) # arguments: Mean of the distribution, Standard deviation of the distribution, Output shape. # Second approach is better as it takes in account the standard de...
_____no_output_____
MIT
Neural_Network_Fundamentals/1_NN_from_scratch.ipynb
romanarion/InformationSystemsWS1718
Now that we have all the elements assigned in accordance with good practices, we can feedforward the data once again.
# Run NN to get new classification of the particular observation: h_input = np.dot(w_i_h, input) h_output = sigmoid(h_input) o_input = np.dot(w_h_o, h_output) o_output = sigmoid(o_input) o_output
_____no_output_____
MIT
Neural_Network_Fundamentals/1_NN_from_scratch.ipynb
romanarion/InformationSystemsWS1718
First evaluation of the results Once we have obtained the output of the NN, we can compare it to the target.
# Calculate the errors of the classification: o_errors = target - o_output o_errors
_____no_output_____
MIT
Neural_Network_Fundamentals/1_NN_from_scratch.ipynb
romanarion/InformationSystemsWS1718
The result we would like to achieve should look like as a vector of values where almost all values are negligibly small except for the one value that has the position in the vector corresponding to the index of the true label. It is not the case now. Nevertheless one should remember that so far all the weights have bee...
# Find the errors associated with hidden layer output: h_errors = np.dot(w_h_o.T, o_errors) h_errors[0:10] # errors in the hidden layer - show the first 10 nodes out of 90.
_____no_output_____
MIT
Neural_Network_Fundamentals/1_NN_from_scratch.ipynb
romanarion/InformationSystemsWS1718
Gradient descent Gradient descent is one the most popular algorithms to optimize the neural networks. The name gradient descent is rooted in the procedure where the gradient is repeatedly evaluated to update the parameters. The objective of the gradient descent is to find weight parameters that will minimize the cost ...
%%html <iframe src="https://giphy.com/embed/8tvzvXhB3wcmI" width="1000" height="400" frameBorder="0" class="giphy-embed" allowFullScreen></iframe> <p><a href="https://giphy.com/gifs/deep-learning-8tvzvXhB3wcmI">[Source: Giphy.com]</a></p>
_____no_output_____
MIT
Neural_Network_Fundamentals/1_NN_from_scratch.ipynb
romanarion/InformationSystemsWS1718
Mathematically the differentiation process can be illustrated on the example of weights between output and hidden layers (who). The same process but with corresponding values should be applied for the weights between input and hidden layers (wih).As it can be seen from the formulas below the error we want to minimize (...
# Update the matrix for weights between hidden and output layers: w_h_o += np.dot((o_errors * o_output * (1.0 - o_output)), np.transpose(h_output)) # Update the matrix for weights between input and hidden layers: w_i_h += np.dot((h_errors * h_output * (1.0 - h_output)), np.transpose(input))
_____no_output_____
MIT
Neural_Network_Fundamentals/1_NN_from_scratch.ipynb
romanarion/InformationSystemsWS1718
Learning Rate Now, there is something else, we should add in the weights updating procedure. If we completely change our weights with every new observation - our model learns to predict only the last input. Instead of updating weights 100 % every time we can change them only partially - this way every new observation ...
# Define the learning rate: l_r = 0.3 # Update the weights for the links between the hidden and output layers: w_h_o += l_r * np.dot((o_errors * o_output * (1.0 - o_output)), np.transpose(h_output)) # Update the weights for the links between the input and hidden layers: w_i_h += l_r * np.dot((h_errors * h_output * (1....
_____no_output_____
MIT
Neural_Network_Fundamentals/1_NN_from_scratch.ipynb
romanarion/InformationSystemsWS1718
Training So far we have been working with one particular observation. Let's put all the steps done before in a for-loop, so that we can perform them for all observations in our training set. More observations will allow the NN to learn from more information. Every time a new observation is feedforwarded, the error ter...
for i in data: observation = i.split(',') input = np.array((np.asfarray(observation[1:])/255.0*0.99) + 0.01, ndmin=2).T target = np.array(np.zeros(o_n) + 0.01, ndmin=2).T target[int(observation[0])] = 0.99 h_input = np.dot(w_i_h, input) h_output = sigmoid(h_input) o_input = np.dot(w_h_o, h_...
_____no_output_____
MIT
Neural_Network_Fundamentals/1_NN_from_scratch.ipynb
romanarion/InformationSystemsWS1718
Second evaluation of the results Once we have trained the model with 100 observations we can test it with new data it has never seen. After loading the test set we can first work with a particular observation to get an intuition about how good our NN can solve considered classification problem.
# Load the mnist test data CSV file: raw_data_test = open("data/mnist_test.csv", 'r') data_test = raw_data_test.readlines() raw_data_test.close() # Check a particular observation: observation = data_test[0].split(',') # Print the label: print(observation[0]) # Image the number: image = np.asfarray(observation[1:]).resh...
_____no_output_____
MIT
Neural_Network_Fundamentals/1_NN_from_scratch.ipynb
romanarion/InformationSystemsWS1718
After working with a particular observation from the testset we can label all of them and evaluate the accuracy of our NN.
# Test the neural network using all test dataset: score = [] # create a list in which the predictions of the network will we saved. # Go through all the observations in the test data set: for i in data_test: observation = i.split(',') expected = int(observation[0]) input = np.array((np.asfarray(observatio...
performance = 0.4363
MIT
Neural_Network_Fundamentals/1_NN_from_scratch.ipynb
romanarion/InformationSystemsWS1718
It is several times better than naive, which would be 0.1 (given that we have 10 levels of the categorical variable we have to classify). Can we do better? Further Improvements **Training with several epochs** One way to improve the results of the NN is to train it more. For instance we can feedforward the same 100 ob...
epochs = 5 # The "big loop" with epochs: for e in range(epochs): for i in data: observation = i.split(',') input = np.array((np.asfarray(observation[1:])/255.0*0.99) + 0.01, ndmin=2).T target = np.array(np.zeros(o_n) + 0.01, ndmin=2).T target[int(observation[0])] = 0.99 h_in...
performance = 0.6904
MIT
Neural_Network_Fundamentals/1_NN_from_scratch.ipynb
romanarion/InformationSystemsWS1718
** Training with other l_r** The smaller the learning rate the more capable the network to optimize the weights in a more accurate way. At the same time one should keep in mind that small l_r also means additional loss of information extracted from each particular observation. Hence, there should be many training obser...
l_r = 0.1 # run the "big loop" with epochs again to get measure accuracy for new settings.
_____no_output_____
MIT
Neural_Network_Fundamentals/1_NN_from_scratch.ipynb
romanarion/InformationSystemsWS1718
**A more complicated structure** As you may remember in the beginning we have assigned the number of nodes in the hidden layer based on some rule of thumb assumptions. Now we can test if the NN will perform better if we increase the number of hidden nodes.
h_n = 150 # Determine the weights for a bigger matrices w_i_h = np.random.normal(0.0, pow(h_n, -0.5), (h_n, i_n)) w_h_o = np.random.normal(0.0, pow(o_n, -0.5), (o_n, h_n)) # run the "big loop" with epochs again to get measure accuracy for new settings.
_____no_output_____
MIT
Neural_Network_Fundamentals/1_NN_from_scratch.ipynb
romanarion/InformationSystemsWS1718
It is always possible to train neural networks where the number of neurons is larger. But, with a smaller number of neurons the neural network has much better generalization abilities. **Overfitting.** To many nodes is one of the reasons that leads to a problem when the neural network is over trained which would mean t...
# Load the data raw_data = open("data/mnist_train.csv", 'r') data = raw_data.readlines() raw_data.close() # Settings epochs = 2 l_r = 0.1 h_n = 90 w_i_h = np.random.normal(0.0, pow(h_n, -0.5), (h_n, i_n)) w_h_o = np.random.normal(0.0, pow(o_n, -0.5), (o_n, h_n)) # run the "big loop" with epochs again to get measure a...
_____no_output_____
MIT
Neural_Network_Fundamentals/1_NN_from_scratch.ipynb
romanarion/InformationSystemsWS1718
p-value computation and conversion: one-sided, two-sided?This is an attempt to clear up the confusion around p-value computation and based on the authorative source on that matter:[G. Cowan, K. Cranmer, E. Gross, O. Vitells, Eur.Phys.J.C 71 (2011) 1554](https://inspirehep.net/literature/860907)The point of that paper ...
import numpy as np from iminuit import Minuit from iminuit.cost import ExtendedUnbinnedNLL from numba_stats import uniform_pdf, norm_pdf import matplotlib.pyplot as plt import boost_histogram as bh rng = np.random.default_rng(1) def model(x, mu, theta): return mu + theta, mu * norm_pdf(x, 0, 0.1) + theta * uniform...
_____no_output_____
MIT
p-value conversion.ipynb
HDembinski/essays
Let's look at the two most extreme deviations from $H_0$, the ones with the largest and smallest signal.
fig, ax = plt.subplots(1, 2, figsize=(14, 5), sharex=True, sharey=True) for (t0i, h, par, cov), axi in zip((negative, positive), ax): plt.sca(axi) scale = 1/h.axes[0].widths plt.errorbar(h.axes[0].centers, h.values() * scale, h.variances()**0.5 * scale, fmt="ok", label="data") scale = 1 / h.axes[0].widt...
_____no_output_____
MIT
p-value conversion.ipynb
HDembinski/essays
Both upward and downward fluctuations are unlikely events if $H_0$ is true and therefore both get a large value of our test statistic $t_0$, which does not know in which way the deviation went. Searches with $\mu > 0$ (for a new particle, new decay mode, etc.)In most cases we look for a positive peak (new particle, ne...
plt.hist(t0, alpha=0.5, bins=20, range=(0, 20), label="$t_0$") q0 = t0.copy() q0 = np.where(mu < 0, 0, t0) plt.hist(q0, alpha=0.5, bins=20, range=(0, 20), label="$q_0$") plt.legend() plt.axhline() plt.xlabel("$t_0, q_0$") plt.semilogy();
_____no_output_____
MIT
p-value conversion.ipynb
HDembinski/essays
If we observed $t_0 = q_0 = 15$ in a real experiment, we need to compare it with the $q_0$ distribution and not with the $t_0$ distribution to compute the p-value.
print(f"Wrong: p-value based on t0-distribution {np.mean(t0 > 15)}") print(f"Right: p-value based on q0-distribution {np.mean(q0 > 15)}")
Wrong: p-value based on t0-distribution 0.006 Right: p-value based on q0-distribution 0.004
MIT
p-value conversion.ipynb
HDembinski/essays
As we can see, the p-value is enhanced in this case, because we do not need to consider the negative fluctuations at all. The conversion to significance $Z$ is done with a normal distribution.
from scipy.stats import norm p = np.mean(q0 > 15) print(f"Z = {norm.ppf(1 - p):.2f}")
Z = 2.65
MIT
p-value conversion.ipynb
HDembinski/essays
Searches for deviations where the sign of $\mu$ is not known a prioriIf cannot exclude a priori that our signal has $\mu < 0$, we need to use the $t_0$ distribution instead of $q_0$.If we observed $t_0 = 15$ in a real experiment, we need to compare it with $t_0$ distribution to compute the p-value.
print(f"Right: p-value based on t0-distribution {np.mean(t0 > 15)}")
Right: p-value based on t0-distribution 0.006
MIT
p-value conversion.ipynb
HDembinski/essays
As we can see, the p-value is diluted in this case, because we need to consider fluctuations in both directions. In other words, the Look-Elsewhere Effect is larger in this case, because more kinds of fluctuations in the background can be confused with a signal.
from scipy.stats import norm p = np.mean(t0 > 15) print(f"Z = {norm.ppf(1 - p):.2f}")
Z = 2.51
MIT
p-value conversion.ipynb
HDembinski/essays
Analysis of Sphere packing efficeincy
import numpy as np import matplotlib.pyplot as plt from scipy.spatial.distance import cdist # For calculating QPSK decoding import dill from itertools import product, cycle import tensorflow.keras.backend as K
_____no_output_____
MIT
RBF/analysis_spherepacking.ipynb
v-i-s-h/dl-vi-comm
System Configuration
blkSize = 4 chDim = 2 # Input inVecDim = 2 ** blkSize # 1-hot vector length for block encDim = 2*chDim SNR_range_dB = np.arange( 0.0, 11.0, 1.0 ) one_hot_code = np.eye(inVecDim)
_____no_output_____
MIT
RBF/analysis_spherepacking.ipynb
v-i-s-h/dl-vi-comm
Traditional Systems QAM
qam_map = np.array(list(map(list, product([-1, +1], repeat=blkSize)))) qam_sym_pow = np.mean(np.sum(qam_map*qam_map,axis=1)) print( "QAM Avg. Tx Power:", qam_sym_pow ) noisePower = qam_sym_pow * 10.0**(-SNR_range_dB/10.0) n0_per_comp = noisePower/(2*chDim)
QAM Avg. Tx Power: 4.0
MIT
RBF/analysis_spherepacking.ipynb
v-i-s-h/dl-vi-comm
Agrell Map
agrell_map = [] if blkSize==2 and chDim==1: agrell_map = np.array([ [ -1.0, -1.0 ], [ -1.0, 1.0 ], [ 1.0, -1.0 ], [ 1.0, 1.0 ] ]) elif blkSize==4 and chDim==2: agrell_map = np.array([ [2.148934030042627, 0.0, 0.0, 0.0], [0.7347204676695321, 1.4142135623730951,...
Agrell Avg. Tx Power: 3.095200273238941
MIT
RBF/analysis_spherepacking.ipynb
v-i-s-h/dl-vi-comm
Compute Metrics QAM
qam_map = np.array(list(map(list, product([-1, +1], repeat=blkSize)))) qam_sym_pow = np.mean(np.sum(qam_map*qam_map,axis=1)) print( "QAM Avg. Tx Power:", qam_sym_pow ) qam_d_min = np.unique(cdist(qam_map,qam_map))[1] print("d_min:", qam_d_min ) qam_en = qam_sym_pow / (qam_d_min**2) print("En:", qam_en)
QAM Avg. Tx Power: 4.0 d_min: 2.0 En: 1.0
MIT
RBF/analysis_spherepacking.ipynb
v-i-s-h/dl-vi-comm
Agrell
agrell_sym_pow = np.mean(np.sum(agrell_map*agrell_map,axis=1)) print( "Agrell Avg. Tx Power:", agrell_sym_pow ) agrell_dmin = np.unique(cdist(agrell_map,agrell_map))[1] print("d_min:", agrell_dmin ) agrell_en = agrell_sym_pow / (agrell_dmin**2) print("En:", agrell_en)
Agrell Avg. Tx Power: 3.095200273238941 d_min: 1.9999999999999998 En: 0.7738000683097355
MIT
RBF/analysis_spherepacking.ipynb
v-i-s-h/dl-vi-comm
Deep Learning Model
from CommVAE import CommVAE1hot from AEOshea import AEOshea1hot
_____no_output_____
MIT
RBF/analysis_spherepacking.ipynb
v-i-s-h/dl-vi-comm
Specify models to analyze
model_summary = {} results = {} # if blkSize==8 and chDim==4: # model_summary = { # "AWGN ($\sigma_n^2=0.4$)": "./models_08x04/rbf_awgn_64_32_16_n040_summary.dil", # "AWGN ($\sigma_n^2=0.8$)": "./models_08x04/rbf_awgn_64_32_16_n080_summary.dil", # "AWGN ($\sigma_n^2=1.2$)": "./models_08x04...
_____no_output_____
MIT
RBF/analysis_spherepacking.ipynb
v-i-s-h/dl-vi-comm
For each of the model, compute $E_n$
for (model_exp,summary_file) in model_summary.items(): summary_data = {} file_prefix = None # Load file results[model_exp] = {} with open(summary_file, "rb") as file: file_prefix = summary_file.split("_summary.dil")[0] summary_data = dill.load(file) for (modelid,(sym_pow,bler)) i...
./models_04x02/rbf_oshea_64_32_16_10dB_20190321021005.dil AEOshea WARNING:tensorflow:Output "postnoise_dec_out" missing from loss dictionary. We assume this was done on purpose. The fit and evaluate APIs will not be expecting any data to be passed to "postnoise_dec_out". sym_pow: 4.0103226 Model: 4.0103226 1.8...
MIT
RBF/analysis_spherepacking.ipynb
v-i-s-h/dl-vi-comm
Plot $E_n$ distribution
# colors = cycle(['b', 'g', 'r', 'c', 'm', 'y']) # plt.figure(figsize=(8,6)) # selected_max_en = [] # for (model_exp,density_data) in results.items(): # d = np.array([ en for (_,en) in density_data.items() ]) # # if np.max(d) < 1.4*qam_en: # Avoid un-necessary models # plt.hist(d, bins=100, cumulative=True,...
[1] Min: 1.0957113758453254 Max: 1.4242162083206868 Proposed: Trained with (19) Min: 0.9442138580261565 Max: 1.1523691471870963 Proposed: Trained with (23) Min: 1.0544938823083154 Max: 1.2040457387710786
MIT
RBF/analysis_spherepacking.ipynb
v-i-s-h/dl-vi-comm
Plot constellation for best models
for (model_exp,density_data) in results.items(): file_prefix = model_summary[model_exp].split("_summary.dil")[0] modelid = min(density_data, key=density_data.get) config_file = file_prefix + "_" + modelid + ".dil" config = {} model = None with open(config_file, "rb") as cfg_file: config ...
WARNING:tensorflow:Output "postnoise_dec_out" missing from loss dictionary. We assume this was done on purpose. The fit and evaluate APIs will not be expecting any data to be passed to "postnoise_dec_out". WARNING:tensorflow:Output "postnoise_dec_out" missing from loss dictionary. We assume this was done on purpose. Th...
MIT
RBF/analysis_spherepacking.ipynb
v-i-s-h/dl-vi-comm
๋ช…์‚ฌ์™€ ์กฐ์‚ฌ๋ฅผ ๋ถ„๋ฆฌํ•˜๊ณ  ์กฐ์‚ฌ์™€ ํ•„์š”์—†๋Š” ๋‹จ์–ด๋ฅผ stopword์— ๋„ฃ์–ด ์ œ๊ฑฐํ•˜๋Š” ๊ฒƒ์ด ํ•„์š”
import konlpy okt = konlpy.tag.Okt() stopwords = ['์˜','๊ฐ€','์ด','์€','๋“ค','๋Š”','์ข€','์ž˜','๊ฑ','๊ณผ','๋„','๋ฅผ','์œผ๋กœ','์ž','์—','์™€','ํ•œ','ํ•˜๋‹ค'] !curl -O https://raw.githubusercontent.com/konlpy/konlpy/master/scripts/mecab.sh !bash ./mecab.sh article.replace('[^๊ฐ€-ํžฃใ„ฑ-ใ…Žใ… ]',' ') from konlpy.tag import Mecab mecab = Mecab() x_train = list() o...
_____no_output_____
Apache-2.0
wordcloud.ipynb
tecktonik08/test_deeplearning
Python String Exercises to Pull Question 1 Given a string of odd length greater than 7, return a new string made of the middle three characters of a given String
#---- Examples ------------------------- input_string = "JhonDipPetaJhonDipPetaJhonDipPetaJhonDipPetaJhonDipPetaJhonDipPetaJhonDipPeta" # expected_output: "Dip" # input_string = "JaSonAy" # expected_output: "Son" #--------------------------------------- # Your Solution Here mid = int(len(input_string)/2) mid3...
Dip
MIT
Week 1/.ipynb_checkpoints/Lesson_1_Python_Strings_Fundamentals_Assignment-checkpoint.ipynb
KingsleyNA/UESTC-Python-Walkthroughs
Question 2 Given two strings, s1 and s2, create a new string by appending s2 in the middle of s1
#---- Examples ------------------------- # s1 = "Ault" # s2 = "Kelly" # expected_output: "AuKellylt" #--------------------------------------- # Your Solution Here string1 = "abcdefg" part = string1[4:] print(part)
efg
MIT
Week 1/.ipynb_checkpoints/Lesson_1_Python_Strings_Fundamentals_Assignment-checkpoint.ipynb
KingsleyNA/UESTC-Python-Walkthroughs
Question 3Given two strings, s1, and s2 return a new string made of the first, middle, and last characters each input string
#---- Examples ------------------------- s1 = "AmericaAmericaAmericaAmericaAmericaAmericaAmericaAmericaAmerica" s2 = "JapanAmericaAmericaAmericaAmericaAmericaAmericaAmericaAmericaAmerica" # expected_output: "AJrpan" #--------------------------------------- # Your Solution Here first = s1[0] + s2[0] mid = s1[int(l...
AJrmaa
MIT
Week 1/.ipynb_checkpoints/Lesson_1_Python_Strings_Fundamentals_Assignment-checkpoint.ipynb
KingsleyNA/UESTC-Python-Walkthroughs
Question 4Count all digits from a given string
#---- Examples ------------------------- # s1 = "a1b2c3d4e5" # s2 = "Japan" # expected_output: "There are 5 digits in the string." #--------------------------------------- # Your Solution Here
_____no_output_____
MIT
Week 1/.ipynb_checkpoints/Lesson_1_Python_Strings_Fundamentals_Assignment-checkpoint.ipynb
KingsleyNA/UESTC-Python-Walkthroughs
Question 5Find all occurrences of a given word in a given string
#---- Examples ------------------------- word = "UESTC" s1 = "UESTC is young.UESTC is in Sichuan.UESTC is fun." # expected_output: "There are 3 occurences of UESTC." #--------------------------------------- # Your Solution Here s1 = s1.split() print(s1) count = 0 for _ in s1: if _ == word: count = ...
['UESTC', 'is', 'young.UESTC', 'is', 'in', 'Sichuan.UESTC', 'is', 'fun.'] There are 1 Uestc(s)in the sentence
MIT
Week 1/.ipynb_checkpoints/Lesson_1_Python_Strings_Fundamentals_Assignment-checkpoint.ipynb
KingsleyNA/UESTC-Python-Walkthroughs
Question 6Given a string, find the sum of all the numbers in the string.
#---- Examples ------------------------- s1 = "1 potato, 20001 potatoes, 3 potatoes 4 5 ..." # expected_output: "The sum of the numbers in the string is 6" # s2 = "On the tenth day of Christmas my true love sent to me: # 10 Lords a Leaping, 9 Ladies Dancing, 8 Maids a Milking, # 7 Swans a Swimming, 6 G...
['1', 'potato,', '20001', 'potatoes,', '3', 'potatoes', '4', '5', '...']
MIT
Week 1/.ipynb_checkpoints/Lesson_1_Python_Strings_Fundamentals_Assignment-checkpoint.ipynb
KingsleyNA/UESTC-Python-Walkthroughs
Question 7:Reverse the stringNote, do not use any special functions like "reverse".
#---- Examples ------------------------- # s1 = "Delali adniL" # expected_output: "Linda Delali" #--------------------------------------- s1 = "My very eye may just see" s2 = "eye".reverse() s2 == "eye" # Your Solution Here #isdigit, isnumeric, isdecimal num = "23" print(num.isdigit()) print(num.isnumeric()) ...
_____no_output_____
MIT
Week 1/.ipynb_checkpoints/Lesson_1_Python_Strings_Fundamentals_Assignment-checkpoint.ipynb
KingsleyNA/UESTC-Python-Walkthroughs
Great Methods with Strings capitalize() Converts the first character to upper case casefold() Converts string into lower case center() Returns a centered string count() Returns the number of times a specified value occurs in a string encode() Returns an encoded version of the string endswith() Returns true if the str...
s1 = "Great" print(num.isdigit()) print(num.isnumeric()) print(num.isdecimal())
_____no_output_____
MIT
Week 1/.ipynb_checkpoints/Lesson_1_Python_Strings_Fundamentals_Assignment-checkpoint.ipynb
KingsleyNA/UESTC-Python-Walkthroughs
Decision TreesEstaimted time needed: **15** minutes ObjectivesAfter completing this lab you will be able to:- Develop a classification model using Decision Tree Algorithm In this lab exercise, you will learn a popular machine learning algorithm, Decision Tree. You will use this classification algorithm to build a mo...
import numpy as np import pandas as pd from sklearn.tree import DecisionTreeClassifier
_____no_output_____
MIT
Drug Prescription via Decision Tree Classifier/ML0101EN-Clas-Decision-Trees-drug-py-v1.ipynb
Syed-Sherjeel/Classification-Problems
About the dataset Imagine that you are a medical researcher compiling data for a study. You have collected data about a set of patients, all of whom suffered from the same illness. During their course of treatment, each patient responded to one of 5 medications, Drug A, Drug B, Drug c, Drug x and y. ...
!wget -O drug200.csv https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/ML0101ENv3/labs/drug200.csv
--2020-10-11 10:54:57-- https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/ML0101ENv3/labs/drug200.csv Resolving s3-api.us-geo.objectstorage.softlayer.net (s3-api.us-geo.objectstorage.softlayer.net)... 67.228.254.196 Connecting to s3-api.us-geo.objectstorage.softlayer.net (s3-api.us-geo.o...
MIT
Drug Prescription via Decision Tree Classifier/ML0101EN-Clas-Decision-Trees-drug-py-v1.ipynb
Syed-Sherjeel/Classification-Problems
**Did you know?** When it comes to Machine Learning, you will likely be working with large datasets. As a business, where can you host your data? IBM is offering a unique opportunity for businesses, with 10 Tb of IBM Cloud Object Storage: [Sign up now for free](http://cocl.us/ML0101EN-IBM-Offer-CC) now, read data using...
my_data = pd.read_csv("drug200.csv", delimiter=",") my_data[0:5]
_____no_output_____
MIT
Drug Prescription via Decision Tree Classifier/ML0101EN-Clas-Decision-Trees-drug-py-v1.ipynb
Syed-Sherjeel/Classification-Problems
Practice What is the size of data?
# write your code here my_data.size
_____no_output_____
MIT
Drug Prescription via Decision Tree Classifier/ML0101EN-Clas-Decision-Trees-drug-py-v1.ipynb
Syed-Sherjeel/Classification-Problems
Pre-processing Using my_data as the Drug.csv data read by pandas, declare the following variables: X as the Feature Matrix (data of my_data) y as the response vector (target) Remove the column containing the target name since it doesn't contain numeric values.
X = my_data[['Age', 'Sex', 'BP', 'Cholesterol', 'Na_to_K']].values X[0:5]
_____no_output_____
MIT
Drug Prescription via Decision Tree Classifier/ML0101EN-Clas-Decision-Trees-drug-py-v1.ipynb
Syed-Sherjeel/Classification-Problems
As you may figure out, some features in this dataset are categorical such as **Sex** or **BP**. Unfortunately, Sklearn Decision Trees do not handle categorical variables. But still we can convert these features to numerical values. **pandas.get_dummies()**Convert categorical variable into dummy/indicator variables.
from sklearn import preprocessing le_sex = preprocessing.LabelEncoder() le_sex.fit(['F','M']) X[:,1] = le_sex.transform(X[:,1]) le_BP = preprocessing.LabelEncoder() le_BP.fit([ 'LOW', 'NORMAL', 'HIGH']) X[:,2] = le_BP.transform(X[:,2]) le_Chol = preprocessing.LabelEncoder() le_Chol.fit([ 'NORMAL', 'HIGH']) X[:,3] ...
_____no_output_____
MIT
Drug Prescription via Decision Tree Classifier/ML0101EN-Clas-Decision-Trees-drug-py-v1.ipynb
Syed-Sherjeel/Classification-Problems
Now we can fill the target variable.
y = my_data["Drug"] y[0:5]
_____no_output_____
MIT
Drug Prescription via Decision Tree Classifier/ML0101EN-Clas-Decision-Trees-drug-py-v1.ipynb
Syed-Sherjeel/Classification-Problems
Setting up the Decision Tree We will be using train/test split on our decision tree. Let's import train_test_split from sklearn.cross_validation.
from sklearn.model_selection import train_test_split
_____no_output_____
MIT
Drug Prescription via Decision Tree Classifier/ML0101EN-Clas-Decision-Trees-drug-py-v1.ipynb
Syed-Sherjeel/Classification-Problems
Now train_test_split will return 4 different parameters. We will name them:X_trainset, X_testset, y_trainset, y_testset The train_test_split will need the parameters: X, y, test_size=0.3, and random_state=3. The X and y are the arrays required before the split, the test_size represents the ratio of the testing da...
X_trainset, X_testset, y_trainset, y_testset = train_test_split(X, y, test_size=0.3, random_state=3)
_____no_output_____
MIT
Drug Prescription via Decision Tree Classifier/ML0101EN-Clas-Decision-Trees-drug-py-v1.ipynb
Syed-Sherjeel/Classification-Problems
PracticePrint the shape of X_trainset and y_trainset. Ensure that the dimensions match
# your code X_trainset.shape,y_trainset.shape
_____no_output_____
MIT
Drug Prescription via Decision Tree Classifier/ML0101EN-Clas-Decision-Trees-drug-py-v1.ipynb
Syed-Sherjeel/Classification-Problems
Print the shape of X_testset and y_testset. Ensure that the dimensions match
# your code X_testset.shape,y_testset.shape
_____no_output_____
MIT
Drug Prescription via Decision Tree Classifier/ML0101EN-Clas-Decision-Trees-drug-py-v1.ipynb
Syed-Sherjeel/Classification-Problems
Modeling We will first create an instance of the DecisionTreeClassifier called drugTree. Inside of the classifier, specify criterion="entropy" so we can see the information gain of each node.
drugTree = DecisionTreeClassifier(criterion="entropy", max_depth = 4) drugTree # it shows the default parameters
_____no_output_____
MIT
Drug Prescription via Decision Tree Classifier/ML0101EN-Clas-Decision-Trees-drug-py-v1.ipynb
Syed-Sherjeel/Classification-Problems
Next, we will fit the data with the training feature matrix X_trainset and training response vector y_trainset
drugTree.fit(X_trainset,y_trainset)
_____no_output_____
MIT
Drug Prescription via Decision Tree Classifier/ML0101EN-Clas-Decision-Trees-drug-py-v1.ipynb
Syed-Sherjeel/Classification-Problems
Prediction Let's make some predictions on the testing dataset and store it into a variable called predTree.
predTree = drugTree.predict(X_testset)
_____no_output_____
MIT
Drug Prescription via Decision Tree Classifier/ML0101EN-Clas-Decision-Trees-drug-py-v1.ipynb
Syed-Sherjeel/Classification-Problems
You can print out predTree and y_testset if you want to visually compare the prediction to the actual values.
print (predTree [0:5]) print (y_testset [0:5])
['drugY' 'drugX' 'drugX' 'drugX' 'drugX'] 40 drugY 51 drugX 139 drugX 197 drugX 170 drugX Name: Drug, dtype: object
MIT
Drug Prescription via Decision Tree Classifier/ML0101EN-Clas-Decision-Trees-drug-py-v1.ipynb
Syed-Sherjeel/Classification-Problems
Evaluation Next, let's import metrics from sklearn and check the accuracy of our model.
from sklearn import metrics import matplotlib.pyplot as plt print("DecisionTrees's Accuracy: ", metrics.accuracy_score(y_testset, predTree))
DecisionTrees's Accuracy: 0.9833333333333333
MIT
Drug Prescription via Decision Tree Classifier/ML0101EN-Clas-Decision-Trees-drug-py-v1.ipynb
Syed-Sherjeel/Classification-Problems
**Accuracy classification score** computes subset accuracy: the set of labels predicted for a sample must exactly match the corresponding set of labels in y_true. In multilabel classification, the function returns the subset accuracy. If the entire set of predicted labels for a sample strictly match with the true set ...
# your code here from sklearn import tree from sklearn import metrics,model_selection
_____no_output_____
MIT
Drug Prescription via Decision Tree Classifier/ML0101EN-Clas-Decision-Trees-drug-py-v1.ipynb
Syed-Sherjeel/Classification-Problems
Declare and play with model
model=tree.DecisionTreeClassifier(criterion='entropy') model.fit(X_trainset,y_trainset) yhat=model.predict(X_testset) metrics.classification_report(y_testset,yhat) model
_____no_output_____
MIT
Drug Prescription via Decision Tree Classifier/ML0101EN-Clas-Decision-Trees-drug-py-v1.ipynb
Syed-Sherjeel/Classification-Problems
USE Grid Search for best parameters
model=tree.DecisionTreeClassifier(criterion='entropy') scorer=metrics.make_scorer(metrics.f1_score,average='weighted') param={'criterion':['entropy'],'max_depth':[2,4,6,8,10,12,14,16], 'min_samples_leaf':[2,4,6,8,10,12,14,16],'min_samples_split':[2,4,6,8,10,12,14,16]} Grid1=model_selection.GridSearchCV(model,par...
/home/jupyterlab/conda/envs/python/lib/python3.6/site-packages/sklearn/model_selection/_split.py:2053: FutureWarning: You should specify a value for 'cv' instead of relying on the default value. The default value will change from 3 to 5 in version 0.22. warnings.warn(CV_WARNING, FutureWarning) /home/jupyterlab/conda/...
MIT
Drug Prescription via Decision Tree Classifier/ML0101EN-Clas-Decision-Trees-drug-py-v1.ipynb
Syed-Sherjeel/Classification-Problems