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
Maybe a few outliers with high GDP do not follow the linear trend that we observed above.
# Data for training Xfull = np.c_[full_country_stats["GDP per capita"]] yfull = np.c_[full_country_stats["Life satisfaction"]] print(Xfull.shape, yfull.shape)
(36, 1) (36, 1)
MIT
reading_assignments/5_Note-ML Methodology.ipynb
biqar/Fall-2020-ITCS-8156-MachineLearning
We can better observe the trend by fitting polynomial regression models by changing the degrees.
# polynomial model to this data for deg in [1, 2, 5, 10, 30]: plt.figure(); full_country_stats.plot(kind='scatter', x="GDP per capita", y='Life satisfaction', figsize=(12,4)); plt.axis([0, 110000, 3, 10]); Xp, mu, sd, wp = poly_regress(Xfull.flatten(), deg, yfull.flatten(), ...
_____no_output_____
MIT
reading_assignments/5_Note-ML Methodology.ipynb
biqar/Fall-2020-ITCS-8156-MachineLearning
What degree do you think the data follow? What is your best pick? Do you see overfitting here? From which one do you see it? As the complexity of model grows, you may have small training errors. However, there is no guarantee that you have a good generalization (you may have very bad generalization error!). This is ca...
# TODO: try to implement your own K-fold CV. # (This will be a part of next assignment (no solution will be provided.))
_____no_output_____
MIT
reading_assignments/5_Note-ML Methodology.ipynb
biqar/Fall-2020-ITCS-8156-MachineLearning
GOOGLE PLAYSTORE ANALYSIS The dataset used in this analysis is taken from [kaggle datasets](https://www.kaggle.com/datasets) In this analysis we took a raw data which is in csv format and then converted it into a dataframe.Performed some operations, cleaning of the data and finally visualizing some necessary conclusio...
import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns
_____no_output_____
MIT
playstore analysis.ipynb
yazalipavan/Playstore_analysis
Convert the csv file into dataframe using pandas
df=pd.read_csv('googleplaystore.csv') df.head(5)
_____no_output_____
MIT
playstore analysis.ipynb
yazalipavan/Playstore_analysis
This is the data we obtained from the csv file.Let's see some info about this dataframe
df.info()
<class 'pandas.core.frame.DataFrame'> RangeIndex: 10841 entries, 0 to 10840 Data columns (total 13 columns): App 10841 non-null object Category 10841 non-null object Rating 9367 non-null float64 Reviews 10841 non-null object Size 10841 non-null object Installs ...
MIT
playstore analysis.ipynb
yazalipavan/Playstore_analysis
This dataframe consists of 10841 entries ie information about 10841 apps.It tells about the category to which the app belongs,rating given by the users,size of the app,number of reviews given,count of number of installs and some other information DATA CLEANING Some columns have in-appropriate data,data types.This colu...
df['Size'] = df['Size'].map(lambda x: x.rstrip('M')) df['Size'] = df['Size'].map(lambda x: str(round((float(x.rstrip('k'))/1024), 1)) if x[-1]=='k' else x) df['Size'] = df['Size'].map(lambda x: np.nan if x.startswith('Varies') else x)
_____no_output_____
MIT
playstore analysis.ipynb
yazalipavan/Playstore_analysis
10472 has in-appropriate data in every column, may due to entry mistake.So we are removing that entry from the table
df.drop(10472,inplace=True)
_____no_output_____
MIT
playstore analysis.ipynb
yazalipavan/Playstore_analysis
By using pd.to_numeric command we are converting into numeric type
df['Size']=df['Size'].apply(pd.to_numeric)
_____no_output_____
MIT
playstore analysis.ipynb
yazalipavan/Playstore_analysis
Installs : The value of installs is in “string” format. It contains numeric values with commas. It should be removed. And also, the ‘+’ sign should be removed from the end of each string.
df['Installs'] = df['Installs'].map(lambda x: x.rstrip('+')) df['Installs'] = df['Installs'].map(lambda x: ''.join(x.split(',')))
_____no_output_____
MIT
playstore analysis.ipynb
yazalipavan/Playstore_analysis
By using pd.to_numeric command we are converting it into numeric data type
df['Installs']=df['Installs'].apply(pd.to_numeric)
_____no_output_____
MIT
playstore analysis.ipynb
yazalipavan/Playstore_analysis
Reviews :The reviews column is in string format and we need to convert it into numeric type
df['Reviews']=df['Reviews'].apply(pd.to_numeric)
_____no_output_____
MIT
playstore analysis.ipynb
yazalipavan/Playstore_analysis
After cleaning some columns and rows we obtained the required format to perform the analysis
df.head(5)
_____no_output_____
MIT
playstore analysis.ipynb
yazalipavan/Playstore_analysis
DATA VISUALIZATION In this we are taking a parameter as reference and checking the trend of another parameter like whether there is a rise or fall,which category are more,what kinds are of more intrest and so on. Basic pie chart to view distribution of apps across various categories
fig, ax = plt.subplots(figsize=(10, 10), subplot_kw=dict(aspect="equal")) number_of_apps = df["Category"].value_counts() labels = number_of_apps.index sizes = number_of_apps.values ax.pie(sizes,labeldistance=2,autopct='%1.1f%%') ax.legend(labels=labels,loc="right",bbox_to_anchor=(0.9, 0, 0.5, 1)) ax.axis("equal") plt.s...
_____no_output_____
MIT
playstore analysis.ipynb
yazalipavan/Playstore_analysis
App count for certain range of Ratings In this we are finding the count of apps for each range from 0 to 5 ie how many apps have more rating,how many are less rated.
bins=pd.cut(df['Rating'],[0.0,1.0,2.0,3.0,4.0,5.0]) rating_df=pd.DataFrame(df.groupby(bins)['App'].count()) rating_df.reset_index(inplace=True) rating_df plt.figure(figsize=(12, 6)) axis=sns.barplot('Rating','App',data=rating_df); axis.set(ylabel= "App count",title='APP COUNT STATISTICS ACCORDING TO RATING');
_____no_output_____
MIT
playstore analysis.ipynb
yazalipavan/Playstore_analysis
We can see that most of the apps are with rating 4 and above and very less apps have rating below 2. Top5 Apps with highest review count In this we are retrieving the top5 apps with more number of reviews and seeing it visually how their review count is changing.
reviews_df=df.sort_values('Reviews').tail(15).drop_duplicates(subset='App')[['App','Reviews','Rating']] reviews_df plt.figure(figsize=(12, 6)) axis=sns.lineplot(x="App",y="Reviews",data=reviews_df) axis.set(title="Top 5 most Reviewed Apps"); sns.set_style('darkgrid')
_____no_output_____
MIT
playstore analysis.ipynb
yazalipavan/Playstore_analysis
Facebook has more reviews compared to other apps in the playstore Which content type Apps are more in playstore In this we are grouping the apps according to their content type and visually observing the result
content_df=pd.DataFrame(df.groupby('Content Rating')['App'].count()) content_df.reset_index(inplace=True) content_df plt.figure(figsize=(12, 6)) plt.bar(content_df['Content Rating'],content_df['App']); plt.xlabel('Content Rating') plt.ylabel('App count') plt.title('App count for different Contents');
_____no_output_____
MIT
playstore analysis.ipynb
yazalipavan/Playstore_analysis
Most of the apps in playstore can be used by everyone irrespective of the age.Only 3 apps are A rated --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Free vs Paid Apps Let's see vari...
Type_df=df.groupby('Type')[['App']].count() Type_df['Rating']=df.groupby('Type')['Rating'].mean() Type_df.reset_index(inplace=True) Type_df
_____no_output_____
MIT
playstore analysis.ipynb
yazalipavan/Playstore_analysis
We found the number of apps that are freely available and their average rating and also number of paid apps and their average rating.
fig, axes = plt.subplots(1, 2, figsize=(18, 6)) axes[0].bar(Type_df.Type,Type_df.App) axes[0].set_title("Number of free and paid apps") axes[0].set_ylabel('App count') axes[1].bar(Type_df.Type,Type_df.Rating) axes[1].set_title('Average Rating of free and paid apps') axes[1].set_ylabel('Average Rating');
_____no_output_____
MIT
playstore analysis.ipynb
yazalipavan/Playstore_analysis
Conclusion Average rating of Paid Apps is more than Free apps.So,we can say that paid apps are trust worthy and we can invest in them ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------...
max_installs=df.loc[df['Installs']==df.Installs.max()][['App','Category','Reviews','Rating','Installs','Content Rating']] max_installs=max_installs.drop_duplicates(subset='App') max_installs
_____no_output_____
MIT
playstore analysis.ipynb
yazalipavan/Playstore_analysis
These are the 20 apps which are with 1B+ downloads Which App has more rating and trend of 20 apps rating
plt.figure(figsize=(12, 6)) sns.barplot('Rating','App',data=max_installs);
_____no_output_____
MIT
playstore analysis.ipynb
yazalipavan/Playstore_analysis
We can see that Google photos,Instagram and Subway Surfers are the most rated Apps which have 1B+ downloads.Though the Apps are used by 1B+ users they have a good rating too Which content Apps are most Installed We will group the most installed apps according to their content and see which content apps are most instal...
content_max_df=pd.DataFrame(max_installs.groupby('Content Rating')['App'].count()) content_max_df.reset_index(inplace=True) content_max_df plt.figure(figsize=(12, 6)) axis=sns.barplot('Content Rating','App',data=content_max_df); axis.set(ylabel= "App count",title='Max Installed APP COUNT STATISTICS ACCORDING TO Content...
_____no_output_____
MIT
playstore analysis.ipynb
yazalipavan/Playstore_analysis
More than 10 apps are of type which can be used by any age group and about 8 apps are teen aged apps.Only 1 app is to used by person with age 10+ Which category Apps are more Installed In this we will group the most installed apps according to their category and see which category are on high demand
category_max_df=pd.DataFrame(max_installs.groupby('Category')['App'].count()) category_max_df.reset_index(inplace=True) category_max_df plt.figure(figsize=(12, 6)) axis=sns.barplot('App','Category',data=category_max_df); plt.plot(category_max_df.App,category_max_df.Category,'o--r') axis.set(ylabel= "App count",title='M...
_____no_output_____
MIT
playstore analysis.ipynb
yazalipavan/Playstore_analysis
_Lambda School Data Science_ Make explanatory visualizationsTody we will reproduce this [example by FiveThirtyEight:](https://fivethirtyeight.com/features/al-gores-new-movie-exposes-the-big-flaw-in-online-movie-ratings/)
from IPython.display import display, Image url = 'https://fivethirtyeight.com/wp-content/uploads/2017/09/mehtahickey-inconvenient-0830-1.png' example = Image(url=url, width=400) display(example)
_____no_output_____
MIT
module3-make-explanatory-visualizations/LS_DS_223_Make_explanatory_visualizations.ipynb
coding-ss/DS-Unit-1-Sprint-3-Data-Storytelling
Using this data: https://github.com/fivethirtyeight/data/tree/master/inconvenient-sequel Objectives- add emphasis and annotations to transform visualizations from exploratory to explanatory- remove clutter from visualizationsLinks- [Strong Titles Are The Biggest Bang for Your Buck](http://stephanieevergreen.com/strong-...
%matplotlib inline import matplotlib.pyplot as plt import numpy as np import pandas as pd plt.style.use('fivethirtyeight') fake = pd.Series([38, 3, 2, 1, 2, 4, 6, 5, 5, 33], index=range(1,11)) # index will start from 0 if not for this fake.plot.bar(color='C1', width=0.9); fake2 = pd.Series( [1...
_____no_output_____
MIT
module3-make-explanatory-visualizations/LS_DS_223_Make_explanatory_visualizations.ipynb
coding-ss/DS-Unit-1-Sprint-3-Data-Storytelling
Annotate with text
display(example) plt.style.use('fivethirtyeight') fake = pd.Series([38, 3, 2, 1, 2, 4, 6, 5, 5, 33], index=range(1,11)) # index will start from 0 if not for this fake.plot.bar(color='C1', width=0.9); # rotate x axis numbers plt.style.use('fivethirtyeight') fake = pd.Series([38, 3, 2, 1, 2, 4, 6, 5...
_____no_output_____
MIT
module3-make-explanatory-visualizations/LS_DS_223_Make_explanatory_visualizations.ipynb
coding-ss/DS-Unit-1-Sprint-3-Data-Storytelling
Reproduce with real data
df = pd.read_csv('https://raw.githubusercontent.com/fivethirtyeight/data/master/inconvenient-sequel/ratings.csv') df.shape df.head() width,height = df.shape width*height pd.options.display.max_columns = 500 df.head() df.sample(1).T df.timestamp.describe() # convert timestamp to date time df.timestamp = pd.to_datetime(...
_____no_output_____
MIT
module3-make-explanatory-visualizations/LS_DS_223_Make_explanatory_visualizations.ipynb
coding-ss/DS-Unit-1-Sprint-3-Data-Storytelling
only interested in IMDb users
df.category == 'IMDb users' # As a filter to select certain rows df[df.category == 'IMDb users'] lastday = df['2017-08-09'] lastday.head(1) lastday[lastday.category =='IMDb users'].tail() lastday[lastday.category =='IMDb users'].respondents.plot(); final = df.tail(1) #columns = ['1_pct','2_pct','3_pct','4_pct','5_pct'...
_____no_output_____
MIT
module3-make-explanatory-visualizations/LS_DS_223_Make_explanatory_visualizations.ipynb
coding-ss/DS-Unit-1-Sprint-3-Data-Storytelling
Exam 2 - Gema Castillo García
%load_ext sql %config SqlMagic.autocommit=True %sql mysql+pymysql://root:root@127.0.0.1:3306/mysql
_____no_output_____
MIT
Exam_2/Exam_2_Answers.ipynb
gcg-99/GitExams
Problem 1: ControlsWrite a Python script that proves that the lines of data in Germplasm.tsv, and LocusGene are in the same sequence, based on the AGI Locus Code (ATxGxxxxxx). (hint: This will help you decide how to load the data into the database)
import pandas as pd import csv gp = pd.read_csv('Germplasm.tsv', sep='\t') matrix2 = gp[gp.columns[0]].to_numpy() germplasm = matrix2.tolist() #print(germplasm) ##to see the first column (AGI Locus Codes) of Germplasm.tsv lg = pd.read_csv('LocusGene.tsv', sep='\t') matrix2 = lg[lg.columns[0]].to_numpy() locus = matri...
lines of data are in the same sequence
MIT
Exam_2/Exam_2_Answers.ipynb
gcg-99/GitExams
**I have only compared the first columns because is where AGI Codes are (they are the same in the two tables).** Problem 2: Design and create the database. * It should have two tables - one for each of the two data files* The two tables should be linked in a 1:1 relationship* you may use either sqlMagic or pymysql t...
##creating a database called germplasm %sql create database germplasm; ##showing the existing databases %sql show databases; ##selecting the new database to interact with it %sql use germplasm; %sql show tables; ##the database is empty (it has not tables as expected) ##showing the structure of the tables I want to ...
* mysql+pymysql://root:***@127.0.0.1:3306/mysql 0 rows affected.
MIT
Exam_2/Exam_2_Answers.ipynb
gcg-99/GitExams
**- I have designed a database with two tables: Germplasm_table for Germplasm.tsv and Locus_table for LocusGene.tsv****- The primary keys to link the two tables in a 1:1 relationship are in the 'locus' column of each table** Problem 3: Fill the databaseUsing pymysql, create a Python script that reads the data from the...
import csv import re with open("Germplasm.tsv", "r") as Germplasm_file: next(Germplasm_file) ##skipping the first row for line in Germplasm_file: line = line.rstrip() ##removing blank spaces created by the \n (newline) character at the end of every line print(line, file=open('Germplasm_wo_heade...
* mysql+pymysql://root:***@127.0.0.1:3306/mysql 32 rows affected.
MIT
Exam_2/Exam_2_Answers.ipynb
gcg-99/GitExams
To do this exercise, I have asked Andrea Álvarez for some help because I did not understand well what you did in the suggested practice to fill databases.**As 'pubmed' and 'protein_length' columns are for INTEGERS, I have created new TSV files without the header (the first row gave me an error in those columns because ...
##creating an empty text file in current directory report = open('exam2_report.txt', 'x') import pymysql.cursors ##connecting to the database (db) germplasm connection = pymysql.connect(host='localhost', user='root', password='root', ...
Problem 4.1 report written in exam2_report.txt file
MIT
Exam_2/Exam_2_Answers.ipynb
gcg-99/GitExams
**I have omitted the locus column from the Locus_table in 4.1 and 4.2 for not repeating information.**
print('\n\nProblem 4.2. Create a joined report that only includes the Genes SKOR and MAA3:', file=open('exam2_report.txt', 'a')) try: with connection.cursor() as cursor: sql = "SELECT Germplasm_table.locus, Germplasm_table.germplasm, Germplasm_table.phenotype, Germplasm_table.pubmed, Locus_table.gene, Locus...
Problem 4.4 report written in exam2_report.txt file
MIT
Exam_2/Exam_2_Answers.ipynb
gcg-99/GitExams
Quick Multi-Processing Tests
import numpy as np import matplotlib.pyplot as plt from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor import time import numba import pandas as pd import pyspark from pyspark.sql import SparkSession
_____no_output_____
Apache-2.0
Multiprocessing.ipynb
pawarbi/snippets
Defining a an arbitrary function for testing. The function doesn't mean anything.
def fun(x): return x * np.sin(10*x) + np.tan(34*x) + np.log(x) #Calcluate a value for testing fun(10) #Plot the function, for testing x = np.arange(0.1,10,0.5) plt.plot(x,fun(x));
_____no_output_____
Apache-2.0
Multiprocessing.ipynb
pawarbi/snippets
Benchmark Without any parallelism, for comparison purposes
%%timeit n = int(1e7) ## Using a large number to iterate def f(n): x = np.random.random(n) y = (x * np.sin(10*x) + np.tan(34*x) + np.log(x)) return y f(n)
652 ms ± 2.79 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
Apache-2.0
Multiprocessing.ipynb
pawarbi/snippets
652 ms without parallel processing ProcessPool Execution [ProcessPoolExecutor](https://docs.python.org/3/library/concurrent.futures.html) uses executes the processes asynchronously by using the number of processors assigned, in parallel.
%%time with ProcessPoolExecutor(max_workers=4) as executor: result = executor.map(f, [int(1e7) for i in range(10)])
Wall time: 312 ms
Apache-2.0
Multiprocessing.ipynb
pawarbi/snippets
Execution time dropped from 652 ms to 312 ms! This can be further optimized by specifying the number of processors to use and the chunk size. I will skip that for now. ThreadPool Execution Similar to `ProcessPool` but uses threads instead of CPU.
%%time with ThreadPoolExecutor(max_workers=4) as texecute: result_t = texecute.map(f, [int(1e7) for i in range(10)])
Wall time: 3.67 s
Apache-2.0
Multiprocessing.ipynb
pawarbi/snippets
Far worse than the benchmark and the `ProcessPool`. I am not entirely sure why, but most lilelt because the interpreter is allowing only 1 thread to run or is creating an I/O bottleneck. Using NUMBA I have used `numba` for JIT compilation for some of my programs for bootstrapping.
%%time @numba.jit(nopython=True, parallel=True) def f2(n): x = np.random.random(n) y = (x * np.sin(10*x) + np.tan(34*x) + np.log(x)) return y f2(int(1e7))
Wall time: 400 ms
Apache-2.0
Multiprocessing.ipynb
pawarbi/snippets
400 ms - so better than the bechmark but almost as good as the `ProcessPool` method Using Spark
spark=( SparkSession.builder.master("local") .appName("processingtest") .getOrCreate() ) from pyspark.sql.types import FloatType from pyspark.sql.functions import udf n = int(1e7) df = pd.DataFrame({"x":np.random.random(n)}) df.head(3) def f3(x): return (x * np.sin(10*x) + np.tan(34*x) + np.l...
_____no_output_____
Apache-2.0
Multiprocessing.ipynb
pawarbi/snippets
Inspecting the Spark job shows execution time as 0.4s (400 ms), as good as numba and `ProcessPool`. Spark would be much more scalable. Th eonly challenge here is the data needs to be converted to a tabular/dataframe format first. For most business process modeling scenarios that's usually not required and is an added s...
spark.stop()
_____no_output_____
Apache-2.0
Multiprocessing.ipynb
pawarbi/snippets
Importing the data
#print(os.listdir('../data')) df = pd.read_csv('../data/NumberConfirmedOfCases.csv') #df = df.set_index('Date', append=False) #df['Date'] = df.apply(lambda x: datetime.strptime(x['Date'], '%d-%m-%Y').date(), axis=1) #convert the date df = df.groupby('Date')['Cases'].sum().reset_index() #group the data df['Date'] = pd.t...
_____no_output_____
MIT
notebooks/Time series analysis.ipynb
AsmaaOmer/CoronavirusCases-in-Sudan
Visualizing the time series dataWe are going to use matplotlib to visualise the dataset.
# Time series data source: fpp pacakge in R. import matplotlib.pyplot as plt df = pd.read_csv('../data/NumberConfirmedOfCases.csv', parse_dates=['Date'], index_col='Date') df = df.groupby('Date')['Cases'].sum().reset_index() #group the data # Draw Plot def plot_df(df, x, y, title="", xlabel='Date', ylabel='Cases', dpi...
_____no_output_____
MIT
notebooks/Time series analysis.ipynb
AsmaaOmer/CoronavirusCases-in-Sudan
Boxplot of Month-wise (Seasonal) and Year-wise (trend) DistributionYou can group the data at seasonal intervals and see how the values are distributed within a given year or month and how it compares over time.The boxplots make the year-wise and month-wise distributions evident. Also, in a month-wise boxplot, the mont...
# Importing the data df = pd.read_csv('../data/NumberConfirmedOfCases.csv', parse_dates=['Date'], index_col='Date') df = df.groupby('Date')['Cases'].sum().reset_index() #group the data df.reset_index(inplace=True) # Prepare data #df['year'] = [d.year for d in df.Date] df['month'] = [d.strftime('%b') for d in df.Date] ...
_____no_output_____
MIT
notebooks/Time series analysis.ipynb
AsmaaOmer/CoronavirusCases-in-Sudan
Autocorrelation and partial autocorrelationAutocorrelation measures the relationship between a variable's current value and its past values.Autocorrelation is simply the correlation of a series with its own lags. If a series is significantly autocorrelated, that means, the previous values of the series (lags) may be h...
from statsmodels.graphics.tsaplots import plot_acf from statsmodels.graphics.tsaplots import plot_pacf df = pd.read_csv('../data/NumberConfirmedOfCases.csv') df = df.groupby('Date')['Cases'].sum().reset_index() #group the data pyplot.figure(figsize=(6,8), dpi= 100) pyplot.subplot(211) plot_acf(df.Cases, ax=pyplot.gc...
_____no_output_____
MIT
notebooks/Time series analysis.ipynb
AsmaaOmer/CoronavirusCases-in-Sudan
Lag PlotsA Lag plot is a scatter plot of a time series against a lag of itself. It is normally used to check for autocorrelation. If there is any pattern existing in the series like the one you see below, the series is autocorrelated. If there is no such pattern, the series is likely to be random white noise.
from pandas.plotting import lag_plot plt.rcParams.update({'ytick.left' : False, 'axes.titlepad':10}) # Import df = pd.read_csv('../data/NumberConfirmedOfCases.csv') df = df.groupby('Date')['Cases'].sum().reset_index() #group the data # Plot fig, axes = plt.subplots(1, 4, figsize=(10,3), sharex=True, sharey=True, dpi=...
_____no_output_____
MIT
notebooks/Time series analysis.ipynb
AsmaaOmer/CoronavirusCases-in-Sudan
Estimating the forecastabilityThe more regular and repeatable patterns a time series has, the easier it is to forecast. Since we have a small dataset, we apply a Sample Entropy to examine that. Put in mind that, The higher the approximate entropy, the more difficult it is to forecast it.
# https://en.wikipedia.org/wiki/Sample_entropy df = pd.read_csv('../data/NumberConfirmedOfCases.csv') df = df.groupby('Date')['Cases'].sum().reset_index() #group the data def SampEn(U, m, r): """Compute Sample entropy""" def _maxdist(x_i, x_j): return max([abs(ua - va) for ua, va in zip(x_i, x_j)]) ...
0.21622310846963594
MIT
notebooks/Time series analysis.ipynb
AsmaaOmer/CoronavirusCases-in-Sudan
Plotting Rolling StatisticsWe observe that the rolling mean and Standard deviation are not constant with respect to time (increasing trend) The time series is hence not stationary
from statsmodels.tsa.stattools import adfuller def test_stationarity(timeseries): #Determing rolling statistics rolmean = pd.Series(timeseries).rolling(window=12).std() rolstd = pd.Series(timeseries).rolling(window=12).mean() #Plot rolling statistics: orig = plt.plot(timeseries, color='blue',l...
_____no_output_____
MIT
notebooks/Time series analysis.ipynb
AsmaaOmer/CoronavirusCases-in-Sudan
The standard deviation and th mean are clearly increasing with time therefore, this is not a stationary series.
from pylab import rcParams df = pd.read_csv('../data/NumberConfirmedOfCases.csv', parse_dates=['Date'], index_col='Date') df = df.groupby('Date')['Cases'].sum().reset_index() #group the data df['Date'] = pd.to_datetime(df['Date'], format='%Y-%m-%d') df = df.set_index('Date') ts_log = np.log(df) plt.plot(ts_log...
_____no_output_____
MIT
notebooks/Time series analysis.ipynb
AsmaaOmer/CoronavirusCases-in-Sudan
Remove Trend - Smoothing
n = int(len(df.Cases)/2) moving_avg = ts_log.rolling(n).mean() plt.plot(ts_log) plt.plot(moving_avg, color='red') ts_log_moving_avg_diff = ts_log.Cases - moving_avg.Cases ts_log_moving_avg_diff.head(n) ts_log_moving_avg_diff.dropna(inplace=True) test_stationarity(ts_log_moving_avg_diff) expwighted_avg = ts_log.ewm(n).m...
_____no_output_____
MIT
notebooks/Time series analysis.ipynb
AsmaaOmer/CoronavirusCases-in-Sudan
Autoregressive Integrated Moving Average (ARIMA)In an ARIMA model there are 3 parameters that are used to help model the major aspects of a times series: seasonality, trend, and noise. These parameters are labeled p,d,and q.Number of AR (Auto-Regressive) terms (p): p is the parameter associated with the auto-regressiv...
# ARMA example from statsmodels.tsa.arima_model import ARMA from random import random # fit model model = ARMA(ts_log_diff, order=(2, 1)) model_fit = model.fit(disp=False) model_fit.summary() plt.plot(ts_log_diff) plt.plot(model_fit.fittedvalues, color='red') plt.title('RSS: %.4f'% np.nansum((model_fit.fittedvalues-ts...
_____no_output_____
MIT
notebooks/Time series analysis.ipynb
AsmaaOmer/CoronavirusCases-in-Sudan
Bayesian Randomized Benchmarking DemoThis is a bayesian pyMC3 implementation on top of frequentist interleaved RB from qiskit experimentsBased on this [WIP tutorial](https://github.com/Qiskit/qiskit-experiments/blob/main/docs/tutorials/rb_example.ipynb) on july 10 2021
import numpy as np import copy import qiskit_experiments as qe import qiskit.circuit.library as circuits rb = qe.randomized_benchmarking # for retrieving gate calibration from datetime import datetime import qiskit.providers.aer.noise.device as dv # import the bayesian packages import pymc3 as pm import arviz as az i...
_____no_output_____
Apache-2.0
02-bayesian-rb-example-hierarchical.ipynb
pdc-quantum/qiskit-advocates-bayes-RB
Running 1-qubit RB
lengths = np.arange(1, 1000, 100) num_samples = 10 seed = 1010 qubits = [0] # Run an RB experiment on qubit 0 exp1 = rb.StandardRB(qubits, lengths, num_samples=num_samples, seed=seed) expdata1 = exp1.run(backend) # View result data print(expdata1) physical_qubits = [0] nQ = len(qubits) scale = (2 ** nQ - 1) / 2 ** nQ ...
_____no_output_____
Apache-2.0
02-bayesian-rb-example-hierarchical.ipynb
pdc-quantum/qiskit-advocates-bayes-RB
Pooled model
#build model pooled_model = bf.get_bayesian_model(model_type="pooled",Y=Y,shots=shots,m_gates=lengths, mu_AB=[popt_fm[0],popt_fm[2]],cov_AB=[perr_fm[0],perr_fm[2]], alpha_ref=popt_fm[1], alph...
mean sd hdi_3% hdi_97% alpha 0.995688 0.000099 0.995500 0.995870 AB[0] 0.476342 0.003614 0.469744 0.483336 AB[1] 0.506909 0.003476 0.500081 0.513033 Model: Frequentist Bayesian _______________________________________ EPC 2.135e-03 2.156e-03 ± sigma ± 1.7...
Apache-2.0
02-bayesian-rb-example-hierarchical.ipynb
pdc-quantum/qiskit-advocates-bayes-RB
Hierarchical model
#build model original_model = bf.get_bayesian_model(model_type="h_sigma",Y=Y,shots=shots,m_gates=lengths, mu_AB=[popt_fm[0],popt_fm[2]],cov_AB=[perr_fm[0],perr_fm[2]], alpha_ref=popt_fm[1], a...
mean sd hdi_3% hdi_97% alpha 0.995677 0.000103 0.995476 0.995860 AB[0] 0.476004 0.003727 0.469408 0.483239 AB[1] 0.507318 0.003578 0.500497 0.513866 sigma_t 0.001005 0.000290 0.000500 0.001439 GSP[0] 0.981185 0.001334 0.978472 0.983521 GSP[1] 0.814874 0.002270 0.8...
Apache-2.0
02-bayesian-rb-example-hierarchical.ipynb
pdc-quantum/qiskit-advocates-bayes-RB
import seaborn as sns import pandas as pd import matplotlib.pyplot as plt from pandas.plotting import parallel_coordinates data = sns.load_dataset("iris")
_____no_output_____
MIT
HW2/HW2.ipynb
DSNortsev/CSE-694-Case-Studies-in-Deep-Learning
**Task 1. Brief description on its value and possible applications.**The IRIS dataset has the following characteristics:* 150 examples of Iris flowers * The first four fields are features that are the characteristics of flower examples. All these fields hold float numbers representing flower measurements. * The last ...
data print(f'CLASS DISTRIBUTION:\n{data.groupby("species").size()}') print(f'\nSHAPE: {data.shape}') print(f'\nTOTAL MISSING VALUES:\n{data.isnull().sum()}\n')
CLASS DISTRIBUTION: species setosa 50 versicolor 50 virginica 50 dtype: int64 SHAPE: (150, 5) TOTAL MISSING VALUES: sepal_length 0 sepal_width 0 petal_length 0 petal_width 0 species 0 dtype: int64
MIT
HW2/HW2.ipynb
DSNortsev/CSE-694-Case-Studies-in-Deep-Learning
_________ **Task 2. Summarize and visually report on the Size of this data set including labeling or non-labeled status** For all three species, the respective values of the mean and median of its features are found to be pretty close. This indicates that data is nearly symmetrically distributed with very less presenc...
data.groupby('species').agg(['mean', 'median'])
_____no_output_____
MIT
HW2/HW2.ipynb
DSNortsev/CSE-694-Case-Studies-in-Deep-Learning
Standard deviation (or variance) is an indication of how widely the data is spread about the mean.
data.groupby('species').std()
_____no_output_____
MIT
HW2/HW2.ipynb
DSNortsev/CSE-694-Case-Studies-in-Deep-Learning
The isolated points for each feature that can be seen in the box-plots below are the outliers in the data. Since these are very few in number, it wouldn't have any significant impact on our analysis.
sns.set(style="ticks") plt.figure(figsize=(12,10)) plt.subplot(2,2,1) sns.boxplot(x='species',y='sepal_length',data=data) plt.subplot(2,2,2) sns.boxplot(x='species',y='sepal_width',data=data) plt.subplot(2,2,3) sns.boxplot(x='species',y='petal_length',data=data) plt.subplot(2,2,4) sns.boxplot(x='species',y='petal_widt...
_____no_output_____
MIT
HW2/HW2.ipynb
DSNortsev/CSE-694-Case-Studies-in-Deep-Learning
Scatter plot helps to analyze the relationship between 2 features on the x and y
sns.pairplot(data)
_____no_output_____
MIT
HW2/HW2.ipynb
DSNortsev/CSE-694-Case-Studies-in-Deep-Learning
Next, we can make a correlation matrix to see how these features are correlated to each other using a heatmap in the seaborn library. It can be observed that petal measurements are highly correlated, while the sepal one are uncorrelated. Also we can see that petal length is highly correlated with speal length, but not ...
plt.figure(figsize=(10,11)) sns.heatmap(data.corr(),annot=True, square = True) plt.plot()
_____no_output_____
MIT
HW2/HW2.ipynb
DSNortsev/CSE-694-Case-Studies-in-Deep-Learning
Another way to visualize the data is by parallel coordinate plot, which represents each row as a line. As we have seen below, petal measurements can separate species better than the sepal ones.
parallel_coordinates(data, "species", color = ['blue', 'red', 'green']);
_____no_output_____
MIT
HW2/HW2.ipynb
DSNortsev/CSE-694-Case-Studies-in-Deep-Learning
Now, we can plot a scatter plot between the sepal length and the sepal width to visualise the iris dataset. We can observe that the blue dots(setosa) are quite clear separated from red(versicolor) and green dots(virginica), while separation between red dots and green dots might be a very difficult task given the two fe...
labels_names = { 'setosa': 'blue', 'versicolor': 'red', 'virginica': 'green'} for species, color in labels_names.items(): x = data.loc[data['species'] == species]['sepal_length'] y = data.loc[data['species'] == species]['sepal_width'] plt.scatter(x, y, c=color) plt.legend(labels_n...
_____no_output_____
MIT
HW2/HW2.ipynb
DSNortsev/CSE-694-Case-Studies-in-Deep-Learning
We can also visualise the data on different features such as petal width and petal length. In this case, the decision boundary between blue, green and red dots can be easily determined, which indicates that using all features for training is a good choice.
labels_names = { 'setosa': 'blue', 'versicolor': 'red', 'virginica': 'green'} for species, color in labels_names.items(): x = data.loc[data['species'] == species]['petal_length'] y = data.loc[data['species'] == species]['petal_width'] plt.scatter(x, y, c=color) plt.legend(labels_n...
_____no_output_____
MIT
HW2/HW2.ipynb
DSNortsev/CSE-694-Case-Studies-in-Deep-Learning
___________ **3. Propose and perform Deep Learning using this data set.**Report on your implementation as follows:* Justify your selection of techniques and platform* Explain your results and their applicability &nbsp;&nbsp;&nbsp;&nbsp;In our project we are using python language. There are two well-known libraries for ...
import pandas as pd from sklearn.preprocessing import LabelBinarizer, LabelEncoder encoder = LabelBinarizer() le=LabelEncoder() seed = 42 data = sns.load_dataset("iris") # Create X variable with four features X = data.drop(['species'],axis=1) # Convert species to int Y_int = le.fit_transform(data['species']) # Conv...
Normalized X_test values: sepal_length sepal_width petal_length petal_width 0 5.1 3.5 1.4 0.2 1 4.9 3.0 1.4 0.2 2 4.7 3.2 1.3 0.2 3 4.6 3.1 1.5 0.2 4 5...
MIT
HW2/HW2.ipynb
DSNortsev/CSE-694-Case-Studies-in-Deep-Learning
Step 2: Create training and testing datasets
from sklearn.model_selection import train_test_split # Split data in train and test with percentage proportion 70%/30% X_train,X_test,y_train,y_test = train_test_split(X, Y, test_size=0.30,random_state=seed) print(f'X_train: {X_train.shape}, y_train: {y_train.shape}') print(f'X_test : {X_test.shape}, y_test : {y_test...
X_train: (105, 4), y_train: (105, 3) X_test : (45, 4), y_test : (45, 3)
MIT
HW2/HW2.ipynb
DSNortsev/CSE-694-Case-Studies-in-Deep-Learning
Step 3: Normalize the feature data, all values should be in a range from 0 to 1
import pandas as pd from sklearn import preprocessing # Normalize X features, make all values between 0 and 1 X_train = pd.DataFrame(preprocessing.normalize(X_train), columns=X_train.columns, index=X_train.index) X_test = pd.DataFrame(preprocessing.norm...
Train sample: sepal_length sepal_width petal_length petal_width 81 0.772429 0.337060 0.519634 0.140442 133 0.723660 0.321627 0.585820 0.172300 137 0.698048 0.338117 0.599885 0.196326 75 0.767857 0.349026 0.511905 0.162879, Shape: (105, 4)...
MIT
HW2/HW2.ipynb
DSNortsev/CSE-694-Case-Studies-in-Deep-Learning
**Phase 2: Model Building** Step 1: Build model&nbsp;&nbsp;&nbsp;&nbsp;The IRIS is a classification problem, we need to classify if an Iris flower is setosa, versicolor or virginia. Softmax activation function is commonly used in multi classification problems in the output layer, that would return the label with the h...
from keras.models import Sequential from keras.layers import Dense def model_with_3_layers(): model = Sequential() model.add(Dense(27, input_dim=4, activation='relu', name='input_layer')) model.add(Dense(9, activation='relu', name='layer_1')) model.add(Dense(3, activation='softmax', name='output_layer')) mo...
_____no_output_____
MIT
HW2/HW2.ipynb
DSNortsev/CSE-694-Case-Studies-in-Deep-Learning
Step 2: Create estimator&nbsp;&nbsp;&nbsp;&nbsp;We can also pass arguments in the construction of the KerasClassifier class that will be passed on to the fit() function internally used to train the neural network. Here, we pass the number of epochs as 200 and batch size as 20 to use when training the model.
from keras.wrappers.scikit_learn import KerasClassifier estimator = KerasClassifier( build_fn=model_with_4_layers, epochs=200, batch_size=20, verbose=0)
_____no_output_____
MIT
HW2/HW2.ipynb
DSNortsev/CSE-694-Case-Studies-in-Deep-Learning
Step 3: Evaluate The Model with k-Fold Cross Validation&nbsp;&nbsp;&nbsp;&nbsp;Now, the neural network model can be evaluated on a training dataset. The scikit-learn has excellent capability to evaluate models using a suite of techniques. The gold standard for evaluating machine learning models is k-fold cross validat...
from sklearn.model_selection import KFold from sklearn.model_selection import cross_val_score import tensorflow as tf # Suppress Tensorflow warning tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR) estimator = KerasClassifier( build_fn=model_with_3_layers, epochs=200, batch_size=20, ...
Model Performance: mean: 98.10 std: 2.33
MIT
HW2/HW2.ipynb
DSNortsev/CSE-694-Case-Studies-in-Deep-Learning
Phase 3 : Model Selection&nbsp;&nbsp;&nbsp;&nbsp; For our illustration, two models have been used. One with 3 layers and another with 4 layers. We can observe that the accuracy are almost the same, but the loss value is much lower in the model with 4 layers. It can be concluded that by adding more layers, it improves ...
md1 = model_with_3_layers() md1.fit(X_train, y_train, epochs=200, shuffle=True, # shuffle data randomly. verbose=0 # this will tell keras to print more detailed info ) # Validate the model with test dateset test_error_rate = md1.evaluate(X_test, y_test, verbose=0) print(f'{md1.metric...
accuracy: 95.56 loss: 11.00
MIT
HW2/HW2.ipynb
DSNortsev/CSE-694-Case-Studies-in-Deep-Learning
STEP 4: Evaluate model performs on the test data
from sklearn.metrics import confusion_matrix def evaluate_performace(actual, expected): """ Function accepts two lists with actual and expected lables """ flowers = {0:'setosa', 1:'versicolor', 2:'virginica'} print(f'Flowers in test set: \nSetosa={y_test["setosa"].sum...
EVALUATION OF MODEL 1 Flowers in test set: Setosa=19 Versicolor=13 Virginica=13 ERROR: versicolor predicted as virginica ERROR: virginica predicted as versicolor EVALUATION OF MODEL 2 Flowers in test set: Setosa=19 Versicolor=13 Virginica=13 ERROR: versicolor predicted as v...
MIT
HW2/HW2.ipynb
DSNortsev/CSE-694-Case-Studies-in-Deep-Learning
&nbsp;&nbsp;&nbsp;&nbsp;From the confusion matrix above we can see that the second model with 4 layers outperformed the model with 3 layers and the prediction was wrong only once for versicolor species. ___ **4. Find a publication or report that uses this same data set and compare it’s methodology and results to what ...
# To convert colab notebook to pdf !apt-get install texlive texlive-xetex texlive-latex-extra pandoc >/dev/null !pip install pypandoc >/dev/null from google.colab import drive drive.mount('/content/drive') !cp drive/My\ Drive/Colab\ Notebooks/HW2.ipynb ./ !jupyter nbconvert --to PDF "HW2.ipynb" 2>/dev/null !cp ./HW2.pd...
_____no_output_____
MIT
HW2/HW2.ipynb
DSNortsev/CSE-694-Case-Studies-in-Deep-Learning
list = [1, 2, 3, 4, 5, 6] for element in list: print(element)
1 2 3 4 5 6
MIT
HolaGitHub.ipynb
andresrivera125/colab-books
Plagiarism Detection, Feature EngineeringIn this project, you will be tasked with building a plagiarism detector that examines an answer text file and performs binary classification; labeling that file as either plagiarized or not, depending on how similar that text file is to a provided, source text. Your first task ...
# NOTE: # you only need to run this cell if you have not yet downloaded the data # otherwise you may skip this cell or comment it out #!wget https://s3.amazonaws.com/video.udacity-data.com/topher/2019/January/5c4147f9_data/data.zip #!unzip data # import libraries import pandas as pd import numpy as np import os
_____no_output_____
MIT
Project_Plagiarism_Detection/2_Plagiarism_Feature_Engineering.ipynb
ubbn/sagemaker-ml-studues
This plagiarism dataset is made of multiple text files; each of these files has characteristics that are is summarized in a `.csv` file named `file_information.csv`, which we can read in using `pandas`.
csv_file = 'data/file_information.csv' plagiarism_df = pd.read_csv(csv_file) # print out the first few rows of data info plagiarism_df.head()
_____no_output_____
MIT
Project_Plagiarism_Detection/2_Plagiarism_Feature_Engineering.ipynb
ubbn/sagemaker-ml-studues
Types of PlagiarismEach text file is associated with one **Task** (task A-E) and one **Category** of plagiarism, which you can see in the above DataFrame. Tasks, A-EEach text file contains an answer to one short question; these questions are labeled as tasks A-E. For example, Task A asks the question: "What is inheri...
# Read in a csv file and return a transformed dataframe def numerical_dataframe(csv_file='data/file_information.csv'): '''Reads in a csv file which is assumed to have `File`, `Category` and `Task` columns. This function does two things: 1) converts `Category` column values to numerical values ...
_____no_output_____
MIT
Project_Plagiarism_Detection/2_Plagiarism_Feature_Engineering.ipynb
ubbn/sagemaker-ml-studues
Test cellsBelow are a couple of test cells. The first is an informal test where you can check that your code is working as expected by calling your function and printing out the returned result.The **second** cell below is a more rigorous test cell. The goal of a cell like this is to ensure that your code is working a...
# informal testing, print out the results of a called function # create new `transformed_df` transformed_df = numerical_dataframe(csv_file ='data/file_information.csv') # check work # check that all categories of plagiarism have a class label = 1 transformed_df.head(20) # test cell that creates `transformed_df`, if te...
Tests Passed! Example data:
MIT
Project_Plagiarism_Detection/2_Plagiarism_Feature_Engineering.ipynb
ubbn/sagemaker-ml-studues
Text Processing & Splitting DataRecall that the goal of this project is to build a plagiarism classifier. At it's heart, this task is a comparison text; one that looks at a given answer and a source text, compares them and predicts whether an answer has plagiarized from the source. To effectively do this comparison, a...
""" DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ import helpers # create a text column text_df = helpers.create_text_column(transformed_df) text_df.head() # after running the cell above # check out the processed text for a single file, by row index row_idx = 0 # feel free to change this index samp...
Sample processed text: inheritance is a basic concept of object oriented programming where the basic idea is to create new classes that add extra detail to existing classes this is done by allowing the new classes to reuse the methods and variables of the existing classes and new methods and classes are added to spec...
MIT
Project_Plagiarism_Detection/2_Plagiarism_Feature_Engineering.ipynb
ubbn/sagemaker-ml-studues
Split data into training and test setsThe next cell will add a `Datatype` column to a given DataFrame to indicate if the record is: * `train` - Training data, for model training.* `test` - Testing data, for model evaluation.* `orig` - The task's original answer from wikipedia. Stratified samplingThe given code uses a ...
random_seed = 1 # can change; set for reproducibility """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ import helpers # create new df with Datatype (train, test, orig) column # pass in `text_df` from above to create a complete dataframe, with all the information you need complete_df = helpers.train_...
_____no_output_____
MIT
Project_Plagiarism_Detection/2_Plagiarism_Feature_Engineering.ipynb
ubbn/sagemaker-ml-studues
Determining PlagiarismNow that you've prepared this data and created a `complete_df` of information, including the text and class associated with each file, you can move on to the task of extracting similarity features that will be useful for plagiarism classification. > Note: The following code exercises, assume that...
complete_df[complete_df['File'] == 'g0pA_taska.txt'].iloc[0]['Text'] 'g0pA_taska.txt'.replace('g0pA','orig') s = 'g0pA_taska.txt' 'orig' + s[4:] from sklearn.feature_extraction.text import CountVectorizer def get_texts(df, filename): answer = df[df['File'] == filename].iloc[0]['Text'] orig_filename = 'orig' + ...
_____no_output_____
MIT
Project_Plagiarism_Detection/2_Plagiarism_Feature_Engineering.ipynb
ubbn/sagemaker-ml-studues
Test cellsAfter you've implemented the containment function, you can test out its behavior. The cell below iterates through the first few files, and calculates the original category _and_ containment values for a specified n and file.>If you've implemented this correctly, you should see that the non-plagiarized have l...
# select a value for n n = 1 # indices for first few files test_indices = range(4) # iterate through files and calculate containment category_vals = [] containment_vals = [] for i in test_indices: # get level of plagiarism for a given file index category_vals.append(complete_df.loc[i, 'Category']) # calcu...
Tests Passed!
MIT
Project_Plagiarism_Detection/2_Plagiarism_Feature_Engineering.ipynb
ubbn/sagemaker-ml-studues
QUESTION 1: Why can we calculate containment features across *all* data (training & test), prior to splitting the DataFrame for modeling? That is, what about the containment calculation means that the test and training data do not influence each other? **Answer:**Bit ambiguous lengthy question. But I think, since cont...
ss = "aas" for i in range(1,len(ss)+1): print(ss[i-1]) d = np.zeros((2, 2)) d[0][0] = 1 d import re def clean_text(sentence): return [re.sub(r'\W+', '', c) for c in sentence.split()] # Compute the normalized LCS given an answer text and a source text def lcs_norm_word(answer_text, source_text): '''Co...
_____no_output_____
MIT
Project_Plagiarism_Detection/2_Plagiarism_Feature_Engineering.ipynb
ubbn/sagemaker-ml-studues
Test cellsLet's start by testing out your code on the example given in the initial description.In the below cell, we have specified strings A (answer text) and S (original source text). We know that these texts have 20 words in common and the submitted answer is 27 words long, so the normalized, longest common subsequ...
# Run the test scenario from above # does your function return the expected value? A = "i think pagerank is a link analysis algorithm used by google that uses a system of weights attached to each element of a hyperlinked set of documents" S = "pagerank is a link analysis algorithm used by the google internet search en...
LCS = 0.7407407407407407 Test passed!
MIT
Project_Plagiarism_Detection/2_Plagiarism_Feature_Engineering.ipynb
ubbn/sagemaker-ml-studues
This next cell runs a more rigorous test.
# run test cell """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ # test lcs implementation # params: complete_df from before, and lcs_norm_word function tests.test_lcs(complete_df, lcs_norm_word)
Tests Passed!
MIT
Project_Plagiarism_Detection/2_Plagiarism_Feature_Engineering.ipynb
ubbn/sagemaker-ml-studues
Finally, take a look at a few resultant values for `lcs_norm_word`. Just like before, you should see that higher values correspond to higher levels of plagiarism.
# test on your own test_indices = range(5) # look at first few files category_vals = [] lcs_norm_vals = [] # iterate through first few docs and calculate LCS for i in test_indices: category_vals.append(complete_df.loc[i, 'Category']) # get texts to compare answer_text = complete_df.loc[i, 'Text'] task...
Original category values: [0, 3, 2, 1, 0] Normalized LCS values: [0.1917808219178082, 0.8207547169811321, 0.8464912280701754, 0.3160621761658031, 0.24257425742574257]
MIT
Project_Plagiarism_Detection/2_Plagiarism_Feature_Engineering.ipynb
ubbn/sagemaker-ml-studues
--- Create All FeaturesNow that you've completed the feature calculation functions, it's time to actually create multiple features and decide on which ones to use in your final model! In the below cells, you're provided two helper functions to help you create multiple features and store those in a DataFrame, `features_...
""" DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ # Function returns a list of containment features, calculated for a given n # Should return a list of length 100 for all files in a complete_df def create_containment_features(df, n, column_name=None): containment_values = [] if(colum...
_____no_output_____
MIT
Project_Plagiarism_Detection/2_Plagiarism_Feature_Engineering.ipynb
ubbn/sagemaker-ml-studues
Creating LCS featuresBelow, your complete `lcs_norm_word` function is used to create a list of LCS features for all the answer files in a given DataFrame (again, this assumes you are passing in the `complete_df`. It assigns a special value for our original, source files, -1.
""" DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ # Function creates lcs feature and add it to the dataframe def create_lcs_features(df, column_name='lcs_word'): lcs_values = [] # iterate through files in dataframe for i in df.index: # Computes LCS_norm words feature using...
_____no_output_____
MIT
Project_Plagiarism_Detection/2_Plagiarism_Feature_Engineering.ipynb
ubbn/sagemaker-ml-studues
EXERCISE: Create a features DataFrame by selecting an `ngram_range`The paper suggests calculating the following features: containment *1-gram to 5-gram* and *longest common subsequence*. > In this exercise, you can choose to create even more features, for example from *1-gram to 7-gram* containment features and *longe...
# Define an ngram range ngram_range = range(1,7) # The following code may take a minute to run, depending on your ngram_range """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ features_list = [] # Create features in a features_df all_features = np.zeros((len(ngram_range)+1, len(complete_df))) # Cal...
_____no_output_____
MIT
Project_Plagiarism_Detection/2_Plagiarism_Feature_Engineering.ipynb
ubbn/sagemaker-ml-studues
Correlated FeaturesYou should use feature correlation across the *entire* dataset to determine which features are ***too*** **highly-correlated** with each other to include both features in a single model. For this analysis, you can use the *entire* dataset due to the small sample size we have. All of our features try...
""" DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ # Create correlation matrix for just Features to determine different models to test corr_matrix = features_df.corr().abs().round(2) # display shows all of a dataframe display(corr_matrix)
_____no_output_____
MIT
Project_Plagiarism_Detection/2_Plagiarism_Feature_Engineering.ipynb
ubbn/sagemaker-ml-studues
EXERCISE: Create selected train/test dataComplete the `train_test_data` function below. This function should take in the following parameters:* `complete_df`: A DataFrame that contains all of our processed text data, file info, datatypes, and class labels* `features_df`: A DataFrame of all calculated features, such as...
# Takes in dataframes and a list of selected features (column names) # and returns (train_x, train_y), (test_x, test_y) def train_test_data(complete_df, features_df, selected_features): '''Gets selected training and test features from given dataframes, and returns tuples for training and test features and ...
_____no_output_____
MIT
Project_Plagiarism_Detection/2_Plagiarism_Feature_Engineering.ipynb
ubbn/sagemaker-ml-studues
Test cellsBelow, test out your implementation and create the final train/test data.
#complete_df.loc(list(features_df)[:2]) [list(features_df)[:2]] features_df[list(features_df)[:2]] features_df[complete_df['Datatype'] == 'train'][list(features_df)[:2]].to_numpy() #list(complete_df[complete_df['Datatype'] == 'train']['Class']) features_df """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE ...
Tests Passed!
MIT
Project_Plagiarism_Detection/2_Plagiarism_Feature_Engineering.ipynb
ubbn/sagemaker-ml-studues
EXERCISE: Select "good" featuresIf you passed the test above, you can create your own train/test data, below. Define a list of features you'd like to include in your final mode, `selected_features`; this is a list of the features names you want to include.
# Select your list of features, this should be column names from features_df # ex. ['c_1', 'lcs_word'] selected_features = ['c_1', 'c_5', 'lcs_word'] """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ (train_x, train_y), (test_x, test_y) = train_test_data(complete_df, features_df, selected_features) ...
0.8809022697353123 1 5
MIT
Project_Plagiarism_Detection/2_Plagiarism_Feature_Engineering.ipynb
ubbn/sagemaker-ml-studues
Question 2: How did you decide on which features to include in your final model? **Answer:**I run correlation analysis between each pair of features, and result shows that c_1 and c_5 are least correlated, therefore I chose them --- Creating Final Data FilesNow, you are almost ready to move on to training a model in ...
fake_x = [ [0.39814815, 0.0001, 0.19178082], [0.86936937, 0.44954128, 0.84649123], [0.44086022, 0., 0.22395833] ] fake_y = [0, 1, 1] a=np.array(fake_x) b=np.array(fake_y).reshape(3,1) np.concatenate((a,b),axis=1) def make_csv(x, y, filename, data_dir): '''Merges features and labels and con...
_____no_output_____
MIT
Project_Plagiarism_Detection/2_Plagiarism_Feature_Engineering.ipynb
ubbn/sagemaker-ml-studues
Test cellsTest that your code produces the correct format for a `.csv` file, given some text features and labels.
""" DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ fake_x = [ [0.39814815, 0.0001, 0.19178082], [0.86936937, 0.44954128, 0.84649123], [0.44086022, 0., 0.22395833] ] fake_y = [0, 1, 1] make_csv(fake_x, fake_y, filename='to_delete.csv', data_dir='test_csv') # read in and test di...
_____no_output_____
MIT
Project_Plagiarism_Detection/2_Plagiarism_Feature_Engineering.ipynb
ubbn/sagemaker-ml-studues
If you've passed the tests above, run the following cell to create `train.csv` and `test.csv` files in a directory that you specify! This will save the data in a local directory. Remember the name of this directory because you will reference it again when uploading this data to S3.
# can change directory, if you want data_dir = 'plagiarism_data' """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ make_csv(train_x, train_y, filename='train.csv', data_dir=data_dir) make_csv(test_x, test_y, filename='test.csv', data_dir=data_dir)
Path created: plagiarism_data/train.csv Path created: plagiarism_data/test.csv
MIT
Project_Plagiarism_Detection/2_Plagiarism_Feature_Engineering.ipynb
ubbn/sagemaker-ml-studues
يرجى القراءة الدفتر التالي هو مثال عن كيفية استخدام Python لتحميل، معالجة وتحليل WaPOR data: * [1 تحميل بيانات WaPOR بالجملة](1_Bulk_download_WaPOR_data.ipynb)* [2 معالجة بيانات WaPOR المحملة](2_Preprocess_WaPOR_data.ipynb)* [3 تحليل بيانات WaPOR](3_Analyse_WaPOR_data.ipynb)تحتاج إلى تحميل الحزم التالية لبدء تش...
import requests import numpy import pandas import matplotlib import shapefile import gdal import osr import ogr
_____no_output_____
CC0-1.0
notebooks_AR/Module1_unit4/0_Start_here.ipynb
LaurenZ-IHE/WAPOROCW
إن لم تحصل في الخلية على أية مخرجات، هذا يعني أن الحزم قد تحملت بشكل صحيح. إن لم يتم التحميل بشكل صحيح، سوف يظهر الخطأ على شكل كود كالتالي
import notinstalledpackage
_____no_output_____
CC0-1.0
notebooks_AR/Module1_unit4/0_Start_here.ipynb
LaurenZ-IHE/WAPOROCW