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
--- 과거작업 [1] Rename
# 1) 경로설정 from google.colab import drive drive.mount('/content/gdrive') %cd /content/gdrive/MyDrive/객체탐지/dataset # 2) 필요한 라이브러리 임포트 import os import torch from IPython.display import Image import os import random import shutil from sklearn.model_selection import train_test_split import xml.etree.ElementTree as E...
_____no_output_____
MIT
yolov5/YOLOv5_Task1.ipynb
sosodoit/yolov5
[2] XmlToTxt- https://github.com/Isabek/XmlToTxt [3] Devide [4] 사진 거르기class 1,2,3,4 하나라도 있으면 살리고 없으면 제거.
# 1) 경로설정 %cd /content/gdrive/MyDrive/객체탐지/dataset # 2) 필요한 라이브러리 임포트 import os from glob import glob img_list = glob('labels/train/*.txt') val_img_list = glob('labels/val/*.txt') print(len(img_list)) print(len(val_img_list)) four = [] #체크를 위한 리스트 생성 ## 여기서 val_img_list / img_list 두개를 변경하면서 내부의 다른 index를 제거해주어야...
_____no_output_____
MIT
yolov5/YOLOv5_Task1.ipynb
sosodoit/yolov5
1806554 Ganesh Bhandarkar (DA LAB RECORD) LAB 1
print("Hello World") date() print(mean(1:5)) x <- 1 x apple <-c('red','green',"yellow") print(apple) print(class(apple)) list1 <-list(c(2,5,3),21.3,sin) M = matrix(c('a','a','b','c','b','a'),nrow=2,ncol=3,byrow =TRUE) apple_colors <-c('green','green','yellow','red','red','red','green') factor_apple <-factor(apple_co...
[1] "Hello World"
MIT
DA Lab/1806554_da_lab_records_all.ipynb
ganeshbhandarkar/College-Labs-And-Projects
Batch processing with Argo WorfklowsIn this notebook we will dive into how you can run batch processing with Argo Workflows and Seldon Core.Dependencies:* Seldon core installed as per the docs with an ingress* Minio running in your cluster to use as local (s3) object storage* Argo Workfklows installed in cluster (and ...
!kubectl get secret minio -n minio-system -o json | jq '{apiVersion,data,kind,metadata,type} | .metadata |= {"annotations", "name"}' | kubectl apply -n default -f -
secret/minio created
Apache-2.0
examples/batch/argo-workflows-batch/README.ipynb
Syakyr/seldon-core
Install Argo WorkflowsYou can follow the instructions from the official [Argo Workflows Documentation](https://github.com/argoproj/argoquickstart).You also need to make sure that argo has permissions to create seldon deployments - for this you can just create a default-admin rolebinding as follows:
!kubectl create rolebinding default-admin --clusterrole=admin --serviceaccount=default:default
rolebinding.rbac.authorization.k8s.io/default-admin created
Apache-2.0
examples/batch/argo-workflows-batch/README.ipynb
Syakyr/seldon-core
Create some input for our modelWe will create a file that will contain the inputs that will be sent to our model
mkdir -p assets/ with open("assets/input-data.txt", "w") as f: for i in range(10000): f.write('[[1, 2, 3, 4]]\n')
_____no_output_____
Apache-2.0
examples/batch/argo-workflows-batch/README.ipynb
Syakyr/seldon-core
Check the contents of the file
!wc -l assets/input-data.txt !head assets/input-data.txt
10000 assets/input-data.txt [[1, 2, 3, 4]] [[1, 2, 3, 4]] [[1, 2, 3, 4]] [[1, 2, 3, 4]] [[1, 2, 3, 4]] [[1, 2, 3, 4]] [[1, 2, 3, 4]] [[1, 2, 3, 4]] [[1, 2, 3, 4]] [[1, 2, 3, 4]]
Apache-2.0
examples/batch/argo-workflows-batch/README.ipynb
Syakyr/seldon-core
Upload the file to our minio
!mc mb minio-seldon/data !mc cp assets/input-data.txt minio-seldon/data/
Bucket created successfully `minio-seldon/data`. ...-data.txt: 146.48 KiB / 146.48 KiB ┃▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓┃ 2.14 MiB/s 0s
Apache-2.0
examples/batch/argo-workflows-batch/README.ipynb
Syakyr/seldon-core
Create Argo WorkflowIn order to create our argo workflow we have made it simple so you can leverage the power of the helm charts.Before we dive into the contents of the full helm chart, let's first give it a try with some of the settings.We will run a batch job that will set up a Seldon Deployment with 10 replicas and...
!helm template seldon-batch-workflow helm-charts/seldon-batch-workflow/ \ --set workflow.name=seldon-batch-process \ --set seldonDeployment.name=sklearn \ --set seldonDeployment.replicas=10 \ --set seldonDeployment.serverWorkers=1 \ --set seldonDeployment.serverThreads=10 \ --set batchWorker.wor...
create-seldon-resource: time="2020-08-06T07:21:48.400Z" level=info msg="Starting Workflow Executor" version=v2.9.3 create-seldon-resource: time="2020-08-06T07:21:48.404Z" level=info msg="Creating a docker executor" create-seldon-resource: time="2020-08-06T07:21:48.404Z" level=info msg="Exec...
Apache-2.0
examples/batch/argo-workflows-batch/README.ipynb
Syakyr/seldon-core
Check output in object storeWe can now visualise the output that we obtained in the object store.First we can check that the file is present:
import json wf_arr = !argo get seldon-batch-process -o json wf = json.loads("".join(wf_arr)) WF_ID = wf["metadata"]["uid"] print(f"Workflow ID is {WF_ID}") !mc ls minio-seldon/data/output-data-"$WF_ID".txt
[2020-08-06 08:23:07 BST]  2.7MiB output-data-401c8bc0-0ff0-4f7b-94ba-347df5c786f9.txt 
Apache-2.0
examples/batch/argo-workflows-batch/README.ipynb
Syakyr/seldon-core
Now we can output the contents of the file created using the `mc head` command.
!mc cp minio-seldon/data/output-data-"$WF_ID".txt assets/output-data.txt !head assets/output-data.txt !argo delete seldon-batch-process
Workflow 'seldon-batch-process' deleted
Apache-2.0
examples/batch/argo-workflows-batch/README.ipynb
Syakyr/seldon-core
Load data Read the csv file (first row contains the column names), specify the data types.
csv_dir = Path.cwd().parent / "data" speeches_path = csv_dir / "all_speeches.txt" dtypes={'title':'string', 'pages':'int64', 'date':'string', 'location':'string', 'highest_speaker_count':'int64', 'content':'string'} df = pd.read_csv(speeches_path, header=0, dtype=dtypes) df.head() df.dtypes
_____no_output_____
MIT
components/notebooks/Clean_Up_Speeches.ipynb
jfsalcedo10/mda-kuwait
Dates Some dates had the year missing. The year for `Community_College_Plan` has a typo.
temp = df.loc[:, ['title','date']] temp['has_year'] = temp.apply(lambda row: row['date'][-4:].isnumeric(), axis=1) temp.loc[temp.has_year==False, :]
_____no_output_____
MIT
components/notebooks/Clean_Up_Speeches.ipynb
jfsalcedo10/mda-kuwait
Edit the dates that need to be corrected.
print(df.loc[df.title=='Community_College_Plan','date']) df.loc[df.title=='Community_College_Plan','date'] = '9 January 2015' print(df.loc[df.title=='Community_College_Plan','date'], '\n') print(df.loc[df.title=='Recovery_and_Reinvestment_Act_2016','date']) df.loc[df.title=='Recovery_and_Reinvestment_Act_2016','date']...
78 9 January 20105 Name: date, dtype: string 78 9 January 2015 Name: date, dtype: string 256 26 February Name: date, dtype: string 256 26 February 2016 Name: date, dtype: string 265 15 July Name: date, dtype: string 265 15 July 2015 Name: date, dtype: string
MIT
components/notebooks/Clean_Up_Speeches.ipynb
jfsalcedo10/mda-kuwait
Parse the dates.
df['date'] = pd.to_datetime(df['date'], dayfirst=True, format="%d %B %Y") df.head()
_____no_output_____
MIT
components/notebooks/Clean_Up_Speeches.ipynb
jfsalcedo10/mda-kuwait
The `date` column now has type `datetime`.
df.dtypes
_____no_output_____
MIT
components/notebooks/Clean_Up_Speeches.ipynb
jfsalcedo10/mda-kuwait
Locations Locations that specify a specific place in the White House can be replaced by `White House, Washington D.C.`.
contains_WH = df.location.str.contains("White House", flags=re.I) df.loc[contains_WH, 'location'] = "White House, Washington D.C."
_____no_output_____
MIT
components/notebooks/Clean_Up_Speeches.ipynb
jfsalcedo10/mda-kuwait
Make a `country`column, values for `White House` can already be filled.
df.loc[contains_WH, 'country'] = "USA" df.loc[~contains_WH, 'country'] = ""
_____no_output_____
MIT
components/notebooks/Clean_Up_Speeches.ipynb
jfsalcedo10/mda-kuwait
Set country to `USA` for locations that contain state names or state abbreviations. In case it contains the abbreviation, replace it by the full state name.
states_full = ['Alabama','Alaska','Arizona','Arkansas','California','Colorado','Connecticut','Delaware','Florida','Georgia','Hawaii','Idaho','Illinois','Indiana','Iowa','Kansas','Kentucky','Louisiana','Maine','Maryland','Massachusetts','Michigan','Minnesota','Mississippi','Missouri','Montana','Nebraska','Nevada','New H...
_____no_output_____
MIT
components/notebooks/Clean_Up_Speeches.ipynb
jfsalcedo10/mda-kuwait
Change `Washington, D.C.` (and some variations) to `Washington D.C.`.
df['location'] = df.location.str.replace("Washington, D.?C.?", repl="Washington D.C.", flags=re.I, regex=True)
_____no_output_____
MIT
components/notebooks/Clean_Up_Speeches.ipynb
jfsalcedo10/mda-kuwait
If `country=='USA'`: We assume the last substring to be the state, the second to last the city and everything before that a more specific locations.If `country!='USA'`: We assume the last substring to be the country, the second to last the city and everything before that a more specific locations.
df.loc[:, 'count_commas'] = df.loc[:, 'location'].str.count(',') df.loc[:,['location','country','count_commas']].sort_values(by='count_commas')
_____no_output_____
MIT
components/notebooks/Clean_Up_Speeches.ipynb
jfsalcedo10/mda-kuwait
USA No commas
print(df.loc[(df.country=="USA") & (df.count_commas == 0), ['title','location']].sort_values(by='location'), '\n') df.loc[df.title=='Ebola_CDC', ['state','city','specific_location']] = ['Georgia', 'Atlanta', 'no_specific_location'] df.loc[df.location=='Washington D.C.', ['state','city','specific_location']] = ['no_sta...
title location 308 Ebola_CDC Atlanta Georgia 258 State_of_the_Union_2012 Washington D.C. 278 Health_Care_Law_Signing Washington D.C. 284 White_House_Correspondents_Dinner_2015 Washington D.C. 285 ...
MIT
components/notebooks/Clean_Up_Speeches.ipynb
jfsalcedo10/mda-kuwait
One comma + `Washington D.C.`
contains_WDC = df.location.str.contains("Washington D.C.", flags=re.I) select = contains_WDC & (df.count_commas == 1) print(df.loc[select, 'location']) locations = df.loc[select, 'location'].str.extract(r"(.+), Washington D.C. *", flags=re.I) df.loc[select, ['state','city']] = ['no_state', 'Washington D.C.'] df.loc[...
1 Washington Hilton, Washington D.C. 5 Washington Hilton Hotel, Washington D.C. 8 White House, Washington D.C. 11 White House, Washington D.C. 12 White House, Washington D.C. ... 414 ...
MIT
components/notebooks/Clean_Up_Speeches.ipynb
jfsalcedo10/mda-kuwait
One comma + other
select = (df.country=="USA") & ~contains_WDC & (df.count_commas == 1) print(df.loc[select, 'location']) states = df.loc[select, 'location'].str.extract(r".+?, *(.+)", flags=re.I) cities = df.loc[select, 'location'].str.extract(r"(.+?), *.+", flags=re.I) df.loc[select, 'state'] = states.values df.loc[select, 'city'] ...
_____no_output_____
MIT
components/notebooks/Clean_Up_Speeches.ipynb
jfsalcedo10/mda-kuwait
Some cities need corrections. Cities that don't have a space in them are all ok, we only need to look at ones with spaces.
contains = df.loc[select, 'city'].str.contains(" ", flags=re.I) df.loc[select & contains, ['title', 'location','state','city','specific_location']].sort_values( by= ['state','city','specific_location']) need_corrections = ['Mayors_Conference_2015','White_House_Correspondents_Dinner_First','Beau_Biden_Eulogy', ...
_____no_output_____
MIT
components/notebooks/Clean_Up_Speeches.ipynb
jfsalcedo10/mda-kuwait
Two commas
select = (df.country=="USA") & (df.count_commas == 2) print(df.loc[select, 'location']) states = df.loc[select, 'location'].str.extract(r".+?,.+?, *(.+)", flags=re.I) cities = df.loc[select, 'location'].str.extract(r".+?, *(.+?),.+", flags=re.I) locations = df.loc[select, 'location'].str.extract(r" *(.+?),.+?,.+", fla...
_____no_output_____
MIT
components/notebooks/Clean_Up_Speeches.ipynb
jfsalcedo10/mda-kuwait
Some cities need corrections.
need_corrections = ['Obama-Romney_-_First_Live_Debate', 'NY_NJ_Explosions', 'Afghanistan_War_Troop_Surge', 'Tucson_Memorial_Address', 'Armed_Forces_Farewell'] states = ['Colorado', 'New York', 'New York', 'Arizona', 'Virginia'] cities = ['Denver', 'New York', 'West Point', 'Tucson', 'Arlington'] l...
_____no_output_____
MIT
components/notebooks/Clean_Up_Speeches.ipynb
jfsalcedo10/mda-kuwait
Result for locations in USA
df.loc[df.country=="USA", ['location','country','state','city','specific_location']].sort_values( by=['state','city','specific_location'])
_____no_output_____
MIT
components/notebooks/Clean_Up_Speeches.ipynb
jfsalcedo10/mda-kuwait
Not USA, but known location Note: some US locations don't have `country=='USA'` yet Zero commas
select = (df.country!="USA") & (df.location!="unknown_location") & (df.count_commas == 0) df.loc[select, ['title','location']] titles = df.loc[select, 'title'] df.loc[df.title=='Joint_Presser_with_President_Benigno_Aquino', ['country','state','city','specific_location']] = ['Philippines', 'no_state', 'Manila', ...
_____no_output_____
MIT
components/notebooks/Clean_Up_Speeches.ipynb
jfsalcedo10/mda-kuwait
One comma
select = (df.country!="USA") & (df.location!="unknown_location") & (df.count_commas == 1) titles = df.loc[select, 'title'] df.loc[select, ['title','location']] countries = df.loc[df.title.isin(titles), 'location'].str.extract(r".+?, *(.+)", flags=re.I) cities = df.loc[df.title.isin(titles), 'location'].str.extract(r" *...
_____no_output_____
MIT
components/notebooks/Clean_Up_Speeches.ipynb
jfsalcedo10/mda-kuwait
some corrections
df.loc[df.title=='2004_DNC_Address', ['country','state','city','specific_location']] = ['USA', 'New York', 'Boston', 'no_specific_location'] df.loc[df.title=='Afghanistan_US_Troops_Bagram', ['country','state','city','specific_location']] = ['Afghanistan', 'no_state', 'Bagram', 'Bagram Air Field'] df.loc...
_____no_output_____
MIT
components/notebooks/Clean_Up_Speeches.ipynb
jfsalcedo10/mda-kuwait
Two commas
select = (df.country!="USA") & (df.location!="unknown_location") & (df.count_commas == 2) titles = df.loc[select, 'title'] df.loc[select, ['title','location']] countries = df.loc[df.title.isin(titles), 'location'].str.extract(r".+?,.+?, *(.+)", flags=re.I) cities = df.loc[df.title.isin(titles), 'location'].str.extract(...
_____no_output_____
MIT
components/notebooks/Clean_Up_Speeches.ipynb
jfsalcedo10/mda-kuwait
Three commas
select = (df.country!="USA") & (df.location!="unknown_location") & (df.count_commas == 3) df.loc[select, ['title','location']] df.loc[df.title=='UK_Young_Leaders', ['country','state','city','specific_location']] = ['England', 'no_state', 'London', 'Lindley Hall, Royal Horticulture Halls']
_____no_output_____
MIT
components/notebooks/Clean_Up_Speeches.ipynb
jfsalcedo10/mda-kuwait
Result for locations not in USA
df.loc[(df.country!="USA") & (df.location!="unknown_location"), ['location','country','state','city','specific_location']].sort_values( by=['country','state','city','specific_location'])
_____no_output_____
MIT
components/notebooks/Clean_Up_Speeches.ipynb
jfsalcedo10/mda-kuwait
Unknown locations
print('There are %i unknown locations.' % len(df.loc[df.location=="unknown_location", :]))
There are 89 unknown locations.
MIT
components/notebooks/Clean_Up_Speeches.ipynb
jfsalcedo10/mda-kuwait
drop location column Make new csv Only known locations
csv_dir = Path.cwd().parent / "speeches_csv" path_only_known = csv_dir / "speeches_loc_known_cleaned.txt" only_known = df.loc[df.location!="unknown_location", :] only_known.to_csv(path_only_known, index=False, header=True, mode='w')
_____no_output_____
MIT
components/notebooks/Clean_Up_Speeches.ipynb
jfsalcedo10/mda-kuwait
15.077: Problem Set 3Alex Berke (aberke)From Rice, J.A., Mathematical Statistics and Data Analysis (with CD Data Sets), 3rd ed., Duxbury, 2007 (ISBN 978-0-534-39942-9).
%config Completer.use_jedi = False # autocomplete import math import numpy as np import pandas as pd import scipy.special from scipy import stats from sklearn.utils import resample import matplotlib.pyplot as plt %matplotlib inline %config InlineBackend.figure_format = 'retina'
_____no_output_____
MIT
pset-3/pset3.ipynb
aberke/mit-stats-15.077
Problems 10.48In 1970, Congress instituted a lottery for the military draft to support the unpopular war in Vietnam. All 366 possible birth dates were placed in plastic capsules in a rotating drum and were selected one by one. Eligible males born on the first day drawn were first in line to be drafted followed by tho...
lottery = pd.read_csv('1970lottery.txt') lottery.columns = [c.replace("'", "") for c in lottery.columns] lottery['Month'] = lottery['Month'].apply(lambda m: m.replace("'", "")) lottery.head()
_____no_output_____
MIT
pset-3/pset3.ipynb
aberke/mit-stats-15.077
A. Plot draft number versus day number. Do you see any trend?No, a trend is not clear from a simple plot with these two variables.
_ = lottery.plot.scatter('Day_of_year', 'Draft_No', title='Day of year vs draft number')
_____no_output_____
MIT
pset-3/pset3.ipynb
aberke/mit-stats-15.077
B. Calculate the Pearson and rank correlation coefficients. What do they suggest?Both correlation coefficcients suggest there could be a relationship that is not immediately visible.
print('Pearson correlation coefficient: %0.4f' % ( stats.pearsonr(lottery['Draft_No'], lottery['Day_of_year'])[0])) print('Spearman rank correlation coefficient: %0.4f' % ( stats.spearmanr(lottery['Draft_No'], lottery['Day_of_year'])[0]))
Pearson correlation coefficient: -0.2260 Spearman rank correlation coefficient: -0.2258
MIT
pset-3/pset3.ipynb
aberke/mit-stats-15.077
C. Is the correlation statistically significant? One way to assess this is via a permutation test. Randomly permute the draft numbers and find the correlation of this random permutation with the day numbers. Do this 100 times and see how many of the resulting correlation coefficients exceed the one observed in the dat...
iterations = 1000 pearson_coefficients = [] rank_coefficients = [] for i in range(iterations): permuted_draft_no = np.random.permutation(lottery['Draft_No']) pearson_coefficients += [stats.pearsonr(permuted_draft_no, lottery['Day_of_year'])[0]] rank_coefficients += [stats.spearmanr(permuted_draft_no, lott...
_____no_output_____
MIT
pset-3/pset3.ipynb
aberke/mit-stats-15.077
D. Make parallel boxplots of the draft numbers by month. Do you see any pattern? The mean draft numbers are lowest in the (later) months of November and December.
pd.DataFrame( {m: lottery[lottery['Month']==m]['Draft_No'] for m in months.values()} ).boxplot(grid=False)
_____no_output_____
MIT
pset-3/pset3.ipynb
aberke/mit-stats-15.077
E. Examine the sampling variability of the two correlation coefficients (Pearson and rank) using the bootstrap (re-sampling pairs with replacement) with 100 (or 1000) bootstrap samples. How does this compare with the permutation approach?The results are drastically different from the results of the permutation ...
pearson_coefficients = [] rank_coefficients = [] for i in range(iterations): resampled = resample(lottery) pearson_coefficients += [stats.pearsonr(resampled['Draft_No'], resampled['Day_of_year'])[0]] rank_coefficients += [stats.spearmanr(resampled['Draft_No'], resampled['Day_of_year'])[0]] print('Pearson ...
Pearson correlation coefficient 95% CI for (1000) bootstrap samples: (-0.2292, -0.2231) Spearman rank correlation coefficient 95% CI for (1000) bootstrap samples: (-0.2285, -0.2224)
MIT
pset-3/pset3.ipynb
aberke/mit-stats-15.077
11.15 Suppose that n measurements are to be taken under a treatment condition and another n measurements are to be taken independently under a control condition. It is thought that the standard deviation of a single observation is about 10 under both conditions. How large should n be so that a 95% confidence interval...
l = "676 88 206 570 230 605 256 617 280 653 433 2913 337 924 466 286 497 1098 512 982 794 2346 428 321 452 615 512 519".split(" ") df = pd.DataFrame({ 'test': l[::2], 'control': l[1::2], }).astype(int) df
_____no_output_____
MIT
pset-3/pset3.ipynb
aberke/mit-stats-15.077
A. Plot the differences versus the control rate and summarize what you see.
differences = df['test'] - df['control'] plt.scatter(df['control'], differences) plt.xlabel('control values') plt.ylabel('difference values') _ = plt.title(' difference vs control values')
_____no_output_____
MIT
pset-3/pset3.ipynb
aberke/mit-stats-15.077
The difference values decrease as the control values increase. This relationship appears linear. B. Calculate the mean difference, its standard deviation, and a confidence interval. Let $D_i$ be the difference value.From Rice Section 11.3.1, a 100(1 − α)% confidence interval for $μ_D$ is$ \bar{D} \pm t_{n-1}(α/2)s_...
mean_D = differences.mean() print('The mean difference ~ %s' % round(mean_D, 2)) n = len(differences) std = np.sqrt((1/((n-1)*(n)))*(((differences - mean_D)**2).sum())) print('The standard deviation ~ %s' % round(std, 2))
The standard deviation ~ 202.53
MIT
pset-3/pset3.ipynb
aberke/mit-stats-15.077
Since $n = 14$ and $t_{13}(0.025) = 2.160$, a 95% confidence interval for the mean difference is$ -461.29 \pm (437.46) = -461.29 \pm (2.160 \times 202.53) = \bar{D} \pm t_{n-1}(α/2)s_{\bar{D}}$
print('95%% CI (%s , %s)' % (round(mean_D - (2.160 * std), 2), round(mean_D + (2.160 * std), 2)))
95% CI (-898.76 , -23.81)
MIT
pset-3/pset3.ipynb
aberke/mit-stats-15.077
C. Calculate the median difference and a confidence interval and compare to the previous result. Based on Rice section 10.4: We can sort the values, and find the median and find confidence intervals around that median by using a binomial distribution.
sorted_differences = sorted(differences) print('sorted difference values:', sorted_differences) median = np.median(sorted_differences) print('η: median value = %s' % median) n = len(sorted_differences) print('n = %s' % n)
sorted difference values: [-2480, -1552, -601, -587, -470, -375, -373, -364, -361, -163, -7, 107, 180, 588] η: median value = -368.5 n = 14
MIT
pset-3/pset3.ipynb
aberke/mit-stats-15.077
We look to form a confidence interval of the following form:(X(k), X(n−k+1))The coverage probability of this interval isP(X(k) ≤ η ≤ X(n−k+1)) = = 1 − P(η X(n−k+1))The distribution of the number of observations greater than the median is binomial with n trials and probability $\frac{1}{2}$ of success on each trial. T...
binomials = [] for i in range(int(n/2)): binomials += [((1/(2**n)) * sum([scipy.special.binom(n, j) for j in range(i+1)]))] pd.Series(binomials).rename('P[X ≤ k]').to_frame()
_____no_output_____
MIT
pset-3/pset3.ipynb
aberke/mit-stats-15.077
P(X n−k+1)We can choose k = 4P(X 11) = 0.0287Since $2 \times 0.0287 = 0.0574$Then we have about a 94% confidence interval for (X(4), X(11)) which is:
print('(%s, %s)' % (sorted_differences[4], sorted_differences[11]))
(-470, 107)
MIT
pset-3/pset3.ipynb
aberke/mit-stats-15.077
In summary, the median vaue is -368.5 with a 94% CI of (-470, 107).In comparison, the mean value is approximately -461.29 with a 95% CI of (-898.76 , -23.81).The mean value is lower than the median value and it has a wider confidence interval due to its larger standard deviation. The mean value and its standard devia...
fig, (ax0, ax1) = plt.subplots(1, 2, figsize=(15,5)) stats.probplot(differences.values, plot=ax0) ax0.set_title('Normal probability plot: difference values') ax1.hist(differences) _ = ax1.set_title('Histogram: difference values')
_____no_output_____
MIT
pset-3/pset3.ipynb
aberke/mit-stats-15.077
Using a t test:The null hypothesis is for no difference, i.e.$H_0: μ_𝐷 = 0 $The test statistic is then$ t = \frac{\bar{D} - μ_𝐷}{s_{\bar{D}}} = \frac{\bar{D}}{s_{\bar{D}}} $ which follows a t distribution with n - 1 degrees of freedom.
t = (np.abs(mean_D)/std) print('t = %s' % round(t, 3))
t = 2.278
MIT
pset-3/pset3.ipynb
aberke/mit-stats-15.077
From the t distribution table:$ t_{13}(0.025) = 2.160$ and $t_{13}(0.01) = 2.650 $ so the p-value of a two-sided test is less than .05 but not less than 0.02. Using The Signed Rank Test:
test_df = differences.rename('difference').to_frame() test_df['|difference|'] = np.abs(test_df['difference']) test_df = test_df.sort_values('|difference|').reset_index().drop('index', axis=1).reset_index().rename( columns={'index':'rank'} )[['difference', '|difference|', 'rank']] test_df['rank'] = test_df['rank'] +...
_____no_output_____
MIT
pset-3/pset3.ipynb
aberke/mit-stats-15.077
We now calculate W+ by summing the positive ranks.
positive_ranks = [w for w in test_df['signed rank'] if w > 0] print('W+ = %s' % sum(positive_ranks))
W+ = 17
MIT
pset-3/pset3.ipynb
aberke/mit-stats-15.077
From Table 9 of Appendix B, the two-sided test is significant at α = .05, but not at α = .02. The findings between the t test and The Unsigned Rank test are consistent. 11.46 The National Weather Bureau’s ACN cloud-seeding project was carried out in the states of Oregon and Washington. Cloud seeding was accomplished ...
control = pd.DataFrame({ 'Type I': [ .0080, .0046, .0549, .1313, .0587, .1723, .3812, .1720, .1182, .1383, .0106, .2126, .1435, ], 'Type II': [ .0000, .0000, .0053, .0920, .0220, .1133, .2880, .0000, .1058, .2050, .0100, .2450, .1529, ], }) seeded = pd.DataFrame({ 'Type I': [ ...
_____no_output_____
MIT
pset-3/pset3.ipynb
aberke/mit-stats-15.077
First we compare the mean values of each sample with boxplots, and check for normality with normal probability plots.
fig, (ax0, ax1, ax2, ax3) = plt.subplots(1, 4, figsize=(20,5)) fig.suptitle('Normal probability plots of values') stats.probplot(control['Type I'], plot=ax0) stats.probplot(control['Type II'], plot=ax1) ax0.set_title('Control Type I') ax1.set_title('Control Type II') stats.probplot(seeded['Type I'], plot=ax2) stats.pro...
_____no_output_____
MIT
pset-3/pset3.ipynb
aberke/mit-stats-15.077
The boxplots do not show significant differences.The means of the seeded samples overlap with the values of their control counterparts. The seeded samples have longer tails.The normal probability plots show that the control data does not follow a normal distribution and the sample sizes are relatively small. ...
n = len(control) m = len(seeded) print('n = %s' % n) print('m = %s' % m)
n = 13 m = 22
MIT
pset-3/pset3.ipynb
aberke/mit-stats-15.077
From Rice Section 11.2.3, a test statistic is calculated in the following way. First, we group all m + n observations together and rank them in order of increasing size.Let $n_1$ be the smaller sample size and let R be the sum of the ranks from that sample. Let $R′ = n_1(m + n + 1) − R$ and $R^* = min(R, R′)$.In our ...
type1 = pd.DataFrame({ 'value': control['Type I'], 'sample': 'control', }).append(pd.DataFrame({ 'value': seeded['Type I'], 'sample': 'seeded', })).sort_values('value').reset_index().drop('index', axis=1).reset_index().rename( columns={'index':'rank'} ) type1['rank'] += 1 R = type1[type1['sample']=...
R = 221 𝑅′= 𝑛1(𝑚+𝑛+1)−𝑅 = 247 𝑅* = 𝑚𝑖𝑛(𝑅,𝑅′) = 221
MIT
pset-3/pset3.ipynb
aberke/mit-stats-15.077
Test for Type II:See computations below.There are 3 tied vaues of 0. We can assign them each the values of (1 + 2 + 3) / 3 = 2. However, since they are all in the same sample (control) this does not make a difference.𝑅* = 𝑚𝑖𝑛(𝑅,𝑅′) = 199From [these Wilcoxon Rank-Sum Tables](https://www.real-statistics.com/statis...
type2 = pd.DataFrame({ 'value': control['Type II'], 'sample': 'control', }).append(pd.DataFrame({ 'value': seeded['Type II'], 'sample': 'seeded', })).sort_values('value').reset_index().drop('index', axis=1).reset_index().rename( columns={'index':'rank'} ) type2['rank'] += 1 R = type2[type2['sample'...
R = 199 𝑅′= 𝑛1(𝑚+𝑛+1)−𝑅 = 269 𝑅* = 𝑚𝑖𝑛(𝑅,𝑅′) = 199
MIT
pset-3/pset3.ipynb
aberke/mit-stats-15.077
In general, there is weak evidence that seeding has an effect on either type of target. 13.24 Is it advantageous to wear the color red in a sporting contest? According to Hill and Barton (2005): Although other colours are also present in animal displays, it is specifically the presence and intensity of red colorat...
sports = pd.DataFrame({ 'Sport': ['Boxing','Freestyle Wrestling', 'Greco Roman Wrestling', 'Tae Kwon Do'], 'Red': [148, 27, 25, 45,], 'Blue': [120, 24, 23, 35], }).set_index('Sport') sports sports['Total'] = sports['Red'] + sports['Blue'] sports.loc['Total'] = sports.sum() sports
_____no_output_____
MIT
pset-3/pset3.ipynb
aberke/mit-stats-15.077
Some supplementary information is given in the file red-blue.txt. a. Let πR denote the probability that the contestant wearing red wins. Test the null hypothesis that πR = ½ versus the alternative hypothesis that πR is the same in each sport, but πR ≠ ½ .The null and alternative hypothesis setup models a game as a Be...
print('(447 choose 245) x (0.5)^447 = %s' % (scipy.special.comb(447, 245) * (0.5 ** 447))) print('Z = %s' % ((245 - 223.5)/(np.sqrt(447*(0.5)*(0.5)))))
Z = 2.033830210313729
MIT
pset-3/pset3.ipynb
aberke/mit-stats-15.077
b. Test the null hypothesis πR = ½ against the alternative hypothesis that allows πR to be different in different sports, but not equal to ½.Again, games are modeled as bernoulli trials, but this time the bernoulli trials are independent across sports. Since the minimum n (total games) from each sport is reasonably la...
t = ( ((sports['Red'] - (0.5 * sports['Total']))**2) / (sports['Total'] * 0.5 * 0.5 )).sum() print('chi-squared = %s' % t)
chi-squared = 8.571642380281773
MIT
pset-3/pset3.ipynb
aberke/mit-stats-15.077
C. Are either of these hypothesis tests equivalent to that which would test the null hypothesis πR = ½ versus the alternative hypothesis πR ≠ ½ using as data the total numbers of wins summed over all the sports?Yes, (A) was equivalent to this. D. Is there any evidence that wearing red is more favorable in so...
sports.drop('Total', axis=0).drop('Total', axis=1) chi2, p, dof, ex = stats.chi2_contingency(sports.drop('Total', axis=0).drop('Total', axis=1)) assert(dof == 3) print('chi-squared test statistic = %s' % chi2) print('p = %s' % p) print('\nexpected frequencies:') pd.DataFrame(ex, columns=['Red','Blue'])
chi-squared test statistic = 0.3015017799642389 p = 0.9597457890114767 expected frequencies:
MIT
pset-3/pset3.ipynb
aberke/mit-stats-15.077
E. From an analysis of the points scored by winners and losers, Hill and Barton concluded that color had the greatest effect in close contests. Data on the points of each match are contained in the file red-blue.xls. Analyze this data and see whether you agree with their conclusion. Here we analyze the sports separate...
def get_red_blue_points_differences(points_fpath): df =pd.read_csv(points_fpath)[ ['Winner','Points Scored by Red', 'Points Scored by Blue'] ].dropna() df['|Difference|'] = np.abs(df['Points Scored by Red'] - df['Points Scored by Blue']) return df def plot_point_differences(df, name): fig, a...
_____no_output_____
MIT
pset-3/pset3.ipynb
aberke/mit-stats-15.077
It does appear that for each of the sports, *excluding* Freestyle Wrestling, the distribution of Red wins are skewed towards the smaller points differences, as compared to the Blue wins. We already saw from previous tests (parts A and B) that Red has a statistically significant higher chance of winning (p > 0.5). Howev...
def get_signed_ranks(df): """ Assigns signed ranks and computes W+ Returns W+, df """ df = df.sort_values('|Difference|').reset_index(drop=True) # get the ranks, handling ties differences = df['|Difference|'] ranks = [] r = [] for index, d in differences.items(): if (ind...
_____no_output_____
MIT
pset-3/pset3.ipynb
aberke/mit-stats-15.077
Tae Kwon Doe
w, tkd = get_signed_ranks(tkd) n = len(tkd) exp_w = (n*(n+1))/4 var_w = (n*(n+1)*((2*n)+1))/24 z = (w - exp_w)/(np.sqrt(var_w)) print('n = %s' % n) print('W+ = %s' % w) print('E(W+) = %s' % exp_w) print('Var(W+) = %s' % var_w) print('Z = %s' % z) tkd.head()
n = 70 W+ = 1292.0 E(W+) = 1242.5 Var(W+) = 29198.75 Z = 0.2896830397843113
MIT
pset-3/pset3.ipynb
aberke/mit-stats-15.077
Boxing
w, boxing = get_signed_ranks(boxing) n = len(boxing) exp_w = (n*(n+1))/4 var_w = (n*(n+1)*((2*n)+1))/24 z = (w - exp_w)/(np.sqrt(var_w)) print('n = %s' % n) print('W+ = %s' % w) print('E(W+) = %s' % exp_w) print('Var(W+) = %s' % var_w) print('Z = %s' % z) boxing.head()
n = 233 W+ = 13854.0 E(W+) = 13630.5 Var(W+) = 1060907.25 Z = 0.2169895498296029
MIT
pset-3/pset3.ipynb
aberke/mit-stats-15.077
Greco Roman Wrestling
w, gr_wrestling = get_signed_ranks(gr_wrestling) n = len(gr_wrestling) exp_w = (n*(n+1))/4 var_w = (n*(n+1)*((2*n)+1))/24 z = (w - exp_w)/(np.sqrt(var_w)) print('n = %s' % n) print('W+ = %s' % w) print('E(W+) = %s' % exp_w) print('Var(W+) = %s' % var_w) print('Z = %s' % z) gr_wrestling.head()
n = 51 W+ = 580.5 E(W+) = 663.0 Var(W+) = 11381.5 Z = -0.773311016598475
MIT
pset-3/pset3.ipynb
aberke/mit-stats-15.077
Freestyle Wrestling
w, fw_wrestling = get_signed_ranks(fw_wrestling) n = len(fw_wrestling) exp_w = (n*(n+1))/4 var_w = (n*(n+1)*((2*n)+1))/24 z = (w - exp_w)/(np.sqrt(var_w)) print('n = %s' % n) print('W+ = %s' % w) print('E(W+) = %s' % exp_w) print('Var(W+) = %s' % var_w) print('Z = %s' % z) fw_wrestling.head()
n = 54 W+ = 835.5 E(W+) = 742.5 Var(W+) = 13488.75 Z = 0.8007502737021251
MIT
pset-3/pset3.ipynb
aberke/mit-stats-15.077
Merge Merging molecular systems A list of molecular systems are merged in to a new molecular system:
molsys_A = msm.build.build_peptide(['AceProNme',{'forcefield':'AMBER14', 'implicit_solvent':'OBC1'}]) molsys_B = msm.build.build_peptide(['AceValNme',{'forcefield':'AMBER14', 'implicit_solvent':'OBC1'}]) molsys_C = msm.build.build_peptide(['AceLysNme',{'forcefield':'AMBER14', 'implicit_solvent':'OBC1'}]) molsys_B = msm...
_____no_output_____
MIT
docs/contents/basic/merge.ipynb
dprada/molsysmt
Converting raster to vectorA cluster of functions that convert raster (.tiff) files generated as part of future scenario pipeline code, to vector (point shapefile) files.**Original code:** [Konstantinos Pegios](https://github.com/kopegios) **Conceptualization & Methodological review :** [Alexandros Korkovelos](https:/...
# Importing necessary modules import geopandas as gpd import rasterio as rio import pandas as pd import fiona import gdal import osr import ogr import rasterio.mask import time import os import ogr, gdal, osr, os import numpy as np import itertools import re from rasterio.warp import calculate_default_transform, repro...
_____no_output_____
MIT
agrodem_preprocessing/Future_Scenarios/Converting raster to vector.ipynb
babakkhavari/agrodem
Raster (Re)projection to target CRSThis step is not necessary if the raster file is already in the target CRS
# Define project function def reproj(input_raster, output_raster, new_crs, factor): dst_crs = new_crs with rio.open(input_raster) as src: transform, width, height = calculate_default_transform( src.crs, dst_crs, src.width*factor, src.height*factor, *src.bounds) kwargs = src.meta.co...
_____no_output_____
MIT
agrodem_preprocessing/Future_Scenarios/Converting raster to vector.ipynb
babakkhavari/agrodem
Converting raster to shapefile
# Define functions def pixelOffset2coord(raster, xOffset,yOffset): geotransform = raster.GetGeoTransform() originX = geotransform[0] originY = geotransform[3] pixelWidth = geotransform[1] pixelHeight = geotransform[5] coordX = originX+pixelWidth*xOffset coordY = originY+pixelHeight*yOffset ...
0 of 3580 rows processed 100 of 3580 rows processed 200 of 3580 rows processed 300 of 3580 rows processed 400 of 3580 rows processed 500 of 3580 rows processed 600 of 3580 rows processed 700 of 3580 rows processed 800 of 3580 rows processed 900 of 3580 rows processed 1000 of 3580 rows processed 1100 of 3580 rows proces...
MIT
agrodem_preprocessing/Future_Scenarios/Converting raster to vector.ipynb
babakkhavari/agrodem
Assigning lat/long columns to the shapefile
# Import as geodataframe path_shp = r"N:\Agrodem\Future_Scenarios\maize_cassava_scenarios\maize_cassava_scenarios\vectorfiles" name_shp = "cassava_SG.shp" future_crop_gdf = gpd.read_file(path_shp + "\\" + name_shp) # Creating lon/lat columns future_crop_gdf['lon'] = future_crop_gdf["geometry"].x future_crop_gdf['lat'] ...
_____no_output_____
MIT
agrodem_preprocessing/Future_Scenarios/Converting raster to vector.ipynb
babakkhavari/agrodem
Exporting file back to shp or gpkg
# Define output path path = r"N:\Agrodem\Future_Scenarios\maize_cassava_scenarios\maize_cassava_scenarios\vectorfiles" name_shp = "cassava_SG.shp" #dshp future_crop_gdf.to_file(os.path.join(path,name_shp), index=False) #gpkg #future_crop_gdf.to_file("maize_BAU.gpkg", layer='Maize_Inputfile_Future', driver="GPKG")
_____no_output_____
MIT
agrodem_preprocessing/Future_Scenarios/Converting raster to vector.ipynb
babakkhavari/agrodem
强化学习第二章的例子的代码,10臂赌博问题,首先建立一个k臂赌博者的类。
class Bandit: '''参数: kArm: int, 赌博臂的个数 epsilon: double, e-贪心算法的概率值 initial: 每个行为的行为的初始化估计 stepSize: double,更加估计值的常数步数 sampleAverages: if ture, 使用简单的均值方法替代stepSize权重更新 UCB: 不是None时,使用UCB算法,(初始值优化算法) gradient: if ture, 使用算法的选择的基础标志(过去的均值作为基准,评价现在的值) grad...
_____no_output_____
BSD-2-Clause
EvaluativeFeedback/TenArmedTestbed.ipynb
xiaorancs/xr-reinforcement-learning
Real Estate Modelling Project -Srini Objective -Build a model to predict house prices based on features provided in the dataset. -One of those parameters include understanding which factors are responsible for higher property value - $650K and above.-The data set consists of information on some 22,000 properties. -T...
import matplotlib.pyplot as plt import seaborn as sns %matplotlib inline import pandas as pd import numpy as np from sklearn.preprocessing import StandardScaler from sklearn.preprocessing import OneHotEncoder from sklearn.preprocessing import QuantileTransformer from sklearn.linear_model import LinearRegression from sk...
_____no_output_____
MIT
source_code/MidTerm_Project_srini.V3_trials.ipynb
Denny-Meyer/IronHack_mid_term_real_state_regression
Fetching the data
df=pd.read_excel("Data_MidTerm_Project_Real_State_Regression.xls" ) # reading the excel file
_____no_output_____
MIT
source_code/MidTerm_Project_srini.V3_trials.ipynb
Denny-Meyer/IronHack_mid_term_real_state_regression
Checking the data type of the features for any corrections
df.info()
<class 'pandas.core.frame.DataFrame'> RangeIndex: 21597 entries, 0 to 21596 Data columns (total 21 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 id 21597 non-null int64 1 date 21597 non-null datetime64[ns] 2 be...
MIT
source_code/MidTerm_Project_srini.V3_trials.ipynb
Denny-Meyer/IronHack_mid_term_real_state_regression
Checking the column headers for case consistency and spacing for any corrections
col_list = df.columns col_list #filtered view of the repetitive house ids repetitive_sales = df.groupby('id').filter(lambda x: len(x) > 1) repetitive_sales
_____no_output_____
MIT
source_code/MidTerm_Project_srini.V3_trials.ipynb
Denny-Meyer/IronHack_mid_term_real_state_regression
Exploring the data
df['zipcode']= df['zipcode'].astype(str) df.zipcode[df.zipcode.isin(["98102", "98103", "98105", "98106", "98107", "98108", "98109", "98112", "98115", "98116", "98117", "98118", "98119", "98122", "98125", "98126", "98133", "98136", "98144", "98177", "98178", "98199"])] = "seattle_zipcode" df.zipcode[df.zipcode.isin(["98...
_____no_output_____
MIT
source_code/MidTerm_Project_srini.V3_trials.ipynb
Denny-Meyer/IronHack_mid_term_real_state_regression
Mapping a new variable called distance from the epicenter to see how far the properties are located to the main areas of Seatlle and Bellevue.
df['lat_long'] = tuple(zip(df.lat,df.long)) # creating one column with a tuple using latitude and longitude coordinates df df['zipcode']= df['zipcode'].astype(str) seattle = [47.6092,-122.3363] bellevue = [47.61555,-122.20392] seattle_dist = [] for i in df['lat_long']: seattle_dist.append(haversine((seattle),(i), u...
_____no_output_____
MIT
source_code/MidTerm_Project_srini.V3_trials.ipynb
Denny-Meyer/IronHack_mid_term_real_state_regression
Applying Box-cox Powertransform
def plots (df, var, t): plt.figure(figsize= (13,5)) plt.subplot(121) sns.kdeplot(df[var]) plt.title('before' + str(t).split('(')[0]) plt.subplot(122) p1 = t.fit_transform(df[[var]]).flatten() sns.kdeplot(p1) plt.title('after' + str(t).split('(')[0]) box_col = [] for item in df.colum...
_____no_output_____
MIT
source_code/MidTerm_Project_srini.V3_trials.ipynb
Denny-Meyer/IronHack_mid_term_real_state_regression
Preparing the data
# x = df.drop("price", axis=1) x = df_zips._get_numeric_data() y = x['price'] x for col in drop_list: x.drop([col],axis=1,inplace=True)
_____no_output_____
MIT
source_code/MidTerm_Project_srini.V3_trials.ipynb
Denny-Meyer/IronHack_mid_term_real_state_regression
Modelling the data
y x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=.2, random_state =1) std_scaler=StandardScaler().fit(x_train) x_train_scaled=std_scaler.transform(x_train) x_test_scaled=std_scaler.transform(x_test) x_train_scaled[0]
_____no_output_____
MIT
source_code/MidTerm_Project_srini.V3_trials.ipynb
Denny-Meyer/IronHack_mid_term_real_state_regression
Modeling using Statsmodels without scaling
x_train_const= sm.add_constant(x_train) # adding a constant model = sm.OLS(y_train, x_train_const).fit() predictions_train = model.predict(x_train_const) x_test_const = sm.add_constant(x_test) # adding a constant predictions_test = model.predict(x_test_const) print_model = model.summary() print(print_model)
OLS Regression Results ============================================================================== Dep. Variable: price R-squared: 0.725 Model: OLS Adj. R-squared: 0.724 Meth...
MIT
source_code/MidTerm_Project_srini.V3_trials.ipynb
Denny-Meyer/IronHack_mid_term_real_state_regression
checking the significant variables
model.params[list(np.where(model.pvalues < 0.05)[0])].iloc[1:].index.tolist() significant_features=x[model.params[list(np.where(model.pvalues < 0.05)[0])].iloc[1:].index.tolist()] model = LinearRegression() model.fit(x_train, y_train) coefficients = list(model.coef_) coefficients
_____no_output_____
MIT
source_code/MidTerm_Project_srini.V3_trials.ipynb
Denny-Meyer/IronHack_mid_term_real_state_regression
with scaling
x_train.columns x_train_const_scaled = sm.add_constant(x_train_scaled) # adding a constant model = sm.OLS(y_train, x_train_const_scaled).fit() predictions_train = model.predict(x_train_const_scaled) x_test_const_scaled = sm.add_constant(x_test_scaled) # adding a constant predictions_test = model.predict(x_test_const...
OLS Regression Results ============================================================================== Dep. Variable: price R-squared: 0.725 Model: OLS Adj. R-squared: 0.724 Meth...
MIT
source_code/MidTerm_Project_srini.V3_trials.ipynb
Denny-Meyer/IronHack_mid_term_real_state_regression
Linear regression
model=LinearRegression() # model model.fit(x_train_scaled, y_train) # model train y y_pred=model.predict(x_test_scaled) # model prediction y_pred_train=model.predict(x_train_scaled) # Make an scatter plot y_pred vs y # What kind of plot you will get if all the all the predictions are ok? # A stright line fig...
_____no_output_____
MIT
source_code/MidTerm_Project_srini.V3_trials.ipynb
Denny-Meyer/IronHack_mid_term_real_state_regression
Model validation
train_mse=mse(y_train,y_pred_train) test_mse=mse(y_test,y_pred) print ('train MSE: {} -- test MSE: {}'.format(train_mse, test_mse))
train MSE: 37602966924.11132 -- test MSE: 34361724727.49398
MIT
source_code/MidTerm_Project_srini.V3_trials.ipynb
Denny-Meyer/IronHack_mid_term_real_state_regression
RMSE
print ('train RMSE: {} -- test RMSE: {}'.format(train_mse**.5, test_mse**.5))
train RMSE: 193914.84451715223 -- test RMSE: 185369.1579726627
MIT
source_code/MidTerm_Project_srini.V3_trials.ipynb
Denny-Meyer/IronHack_mid_term_real_state_regression
MAE
train_mae=mae(y_train,y_pred_train) test_mae=mae(y_test,y_pred) print ('train MAE: {} -- test MAE: {}'.format(train_mse, test_mse))
train MAE: 37602966924.11132 -- test MAE: 34361724727.49398
MIT
source_code/MidTerm_Project_srini.V3_trials.ipynb
Denny-Meyer/IronHack_mid_term_real_state_regression
R2
#R2= model.score(X_test_scaled, y_test) R2_train=r2_score(y_train,y_pred_train) R2_test=r2_score(y_test,y_pred) print (R2_train) print(R2_test) print ('train R2: {} -- test R2: {}'.format(model.score(x_train_scaled, y_train), model.score(x_test_scaled, y_test)))
train R2: 0.7245706790336555 -- test R2: 0.7328942112790509
MIT
source_code/MidTerm_Project_srini.V3_trials.ipynb
Denny-Meyer/IronHack_mid_term_real_state_regression
adjusted rsquare
Adj_R2_train= 1 - (1-R2_train)*(len(y_train)-1)/(len(y_train)-x_train.shape[1]-1) Adj_R2_train Adj_R2_test= 1 - (1-R2_test)*(len(y_test)-1)/(len(y_test)-x_test.shape[1]-1) Adj_R2_test features_importances = pd.DataFrame(data={ 'Attribute': x_train.columns, 'Importance': abs(model.coef_) }) features_importances ...
_____no_output_____
MIT
source_code/MidTerm_Project_srini.V3_trials.ipynb
Denny-Meyer/IronHack_mid_term_real_state_regression
Iteration Example
import pyblp import numpy as np pyblp.__version__
_____no_output_____
MIT
docs/notebooks/api/iteration.ipynb
yusukeaoki1223/pyblp
In this example, we'll build a SQUAREM configuration with a $\ell^2$-norm and use scheme S1 from :ref:`references:Varadhan and Roland (2008)`.
iteration = pyblp.Iteration('squarem', {'norm': np.linalg.norm, 'scheme': 1}) iteration
_____no_output_____
MIT
docs/notebooks/api/iteration.ipynb
yusukeaoki1223/pyblp
Next, instead of using a built-in routine, we'll create a custom method that implements a version of simple iteration, which, for the sake of having a nontrivial example, arbitrarily identifies a major iteration with three objective evaluations.
def custom_method(initial, contraction, callback, max_evaluations, tol, norm): x = initial evaluations = 0 while evaluations < max_evaluations: x0, (x, weights, _) = x, contraction(x) evaluations += 1 if evaluations % 3 == 0: callback() if weights is None: d...
_____no_output_____
MIT
docs/notebooks/api/iteration.ipynb
yusukeaoki1223/pyblp
We can then use this custom method to build a custom iteration configuration.
iteration = pyblp.Iteration(custom_method) iteration
_____no_output_____
MIT
docs/notebooks/api/iteration.ipynb
yusukeaoki1223/pyblp
![redditscore](https://s3.us-east-2.amazonaws.com/redditscore/logo.png) ***A machine learning approach to predicting how badly you'll get roasted for your sub-par reddit comments.***Alex Hartford & Trevor Hacker **Dataset**Reddit comments from September, 2018 (source). This is well over 100gb of data. We will likely...
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from sklearn.linear_model import SGDRegressor from sklearn.metrics import mean_squared_error from sklearn.feature_extraction.text import TfidfTransformer from sklearn.feature_extraction.text import TfidfVectorizer from sklear...
Libraries loaded!
MIT
python/redditscore.ipynb
AlexHartford/redditscore
Import and Clean Data
print('Loading memes...') # df = pd.read_csv('https://s3.us-east-2.amazonaws.com/redditscore/2500rows.csv') df = pd.read_csv('https://s3.us-east-2.amazonaws.com/redditscore/2mrows.csv', error_bad_lines=False, engine='python', encoding='utf-8') print('Memes are fully operational!') print(df.dtypes) print() print(df.sh...
subreddit object body object score float64 dtype: object (1961645, 3)
MIT
python/redditscore.ipynb
AlexHartford/redditscore